Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replaced numpy.testing.assert_almost_equal to numpy.testing.assert_allclose #4438

Merged
merged 20 commits into from
Feb 24, 2024
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions package/MDAnalysis/visualization/streamlines_3D.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,10 +245,11 @@
cube_half_side_length = scipy.spatial.distance.pdist(array_cube_vertices, 'euclidean').min() / 2.0
array_cube_vertex_distances_from_centroid = scipy.spatial.distance.cdist(array_cube_vertices,
cube_centroid[np.newaxis, :])
np.testing.assert_almost_equal(array_cube_vertex_distances_from_centroid.min(),
array_cube_vertex_distances_from_centroid.max(), decimal=4,
np.testing.assert_allclose(array_cube_vertex_distances_from_centroid.min(),

Check warning on line 248 in package/MDAnalysis/visualization/streamlines_3D.py

View check run for this annotation

Codecov / codecov/patch

package/MDAnalysis/visualization/streamlines_3D.py#L248

Added line #L248 was not covered by tests
array_cube_vertex_distances_from_centroid.max(), rtol=0, atol=1.5*(1e-4),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Write floats as 1.5e-4 and not as 1.5*(1e-4).

This applies to all floats with powers of ten throughout.

err_msg="not all cube vertex to centroid distances are the same, "
"so not a true cube")

absolute_delta_coords = np.absolute(np.subtract(array_point_coordinates, cube_centroid))
absolute_delta_x_coords = absolute_delta_coords[..., 0]
indices_delta_x_acceptable = np.where(absolute_delta_x_coords <= cube_half_side_length)
Expand Down
96 changes: 51 additions & 45 deletions testsuite/MDAnalysisTests/analysis/test_align.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def test_subselection_alignto(self, universe, reference, subselection, expectati

with expectation:
rmsd = align.alignto(universe, reference, subselection=subselection)
assert_almost_equal(rmsd[1], 0.0, decimal=9)
assert_allclose(rmsd[1], 0.0, rtol=0, atol=1.5*1e-9)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can remove the commented old version


def test_no_atom_masses(self, universe):
#if no masses are present
Expand Down Expand Up @@ -199,25 +199,31 @@ def test_rmsd(self, universe, reference):
first_frame = bb.positions
universe.trajectory[-1]
last_frame = bb.positions
assert_almost_equal(rms.rmsd(first_frame, first_frame), 0.0, 5,
err_msg="error: rmsd(X,X) should be 0")

assert_allclose(rms.rmsd(first_frame, first_frame), 0.0, rtol=0, atol=1.5*1e-5,
err_msg="error: rmsd(X,X) should be 0")


# rmsd(A,B) = rmsd(B,A) should be exact but spurious failures in the
# 9th decimal have been observed (see Issue 57 comment #1) so we relax
# the test to 6 decimals.
rmsd = rms.rmsd(first_frame, last_frame, superposition=True)
assert_almost_equal(
rms.rmsd(last_frame, first_frame, superposition=True), rmsd, 6,

assert_allclose(
rms.rmsd(last_frame, first_frame, superposition=True), rmsd, rtol=0, atol=1.5*1e-6,
err_msg="error: rmsd() is not symmetric")
assert_almost_equal(rmsd, 6.820321761927005, 5,
err_msg="RMSD calculation between 1st and last AdK frame gave wrong answer")

assert_allclose(rmsd, 6.820321761927005, rtol=0, atol=1.5*(1e-5),
err_msg="RMSD calculation between 1st and last AdK frame gave wrong answer")

# test masses as weights
last_atoms_weight = universe.atoms.masses
A = universe.trajectory[0]
B = reference.trajectory[-1]
rmsd = align.alignto(universe, reference, weights='mass')
rmsd_sup_weight = rms.rmsd(A, B, weights=last_atoms_weight, center=True,
superposition=True)
assert_almost_equal(rmsd[1], rmsd_sup_weight, 6)
assert_allclose(rmsd[1], rmsd_sup_weight, rtol=0, atol=1.5*(1e-6))

def test_rmsd_custom_mass_weights(self, universe, reference):
last_atoms_weight = universe.atoms.masses
Expand All @@ -227,15 +233,15 @@ def test_rmsd_custom_mass_weights(self, universe, reference):
weights=reference.atoms.masses)
rmsd_sup_weight = rms.rmsd(A, B, weights=last_atoms_weight, center=True,
superposition=True)
assert_almost_equal(rmsd[1], rmsd_sup_weight, 6)
assert_allclose(rmsd[1], rmsd_sup_weight, rtol=0, atol=1.5*(1e-6))

def test_rmsd_custom_weights(self, universe, reference):
weights = np.zeros(universe.atoms.n_atoms)
ca = universe.select_atoms('name CA')
weights[ca.indices] = 1
rmsd = align.alignto(universe, reference, select='name CA')
rmsd_weights = align.alignto(universe, reference, weights=weights)
assert_almost_equal(rmsd[1], rmsd_weights[1], 6)
assert_allclose(rmsd[1], rmsd_weights[1], rtol=0, atol=1.5*(1e-6))

def test_AlignTraj_outfile_default(self, universe, reference, tmpdir):
with tmpdir.as_cwd():
Expand Down Expand Up @@ -285,8 +291,8 @@ def test_AlignTraj(self, universe, reference, tmpdir):
x = align.AlignTraj(universe, reference, filename=outfile).run()
fitted = mda.Universe(PSF, outfile)

assert_almost_equal(x.results.rmsd[0], 6.9290, decimal=3)
assert_almost_equal(x.results.rmsd[-1], 5.2797e-07, decimal=3)
assert_allclose(x.results.rmsd[0], 6.9290, rtol=0, atol=1.5*(1e-3))
assert_allclose(x.results.rmsd[-1], 5.2797e-07, rtol=0, atol=1.5*(1e-3))

# RMSD against the reference frame
# calculated on Mac OS X x86 with MDA 0.7.2 r689
Expand All @@ -299,8 +305,8 @@ def test_AlignTraj_weighted(self, universe, reference, tmpdir):
x = align.AlignTraj(universe, reference,
filename=outfile, weights='mass').run()
fitted = mda.Universe(PSF, outfile)
assert_almost_equal(x.results.rmsd[0], 0, decimal=3)
assert_almost_equal(x.results.rmsd[-1], 6.9033, decimal=3)
assert_allclose(x.results.rmsd[0], 0, rtol=0, atol=1.5*(1e-3))
assert_allclose(x.results.rmsd[-1], 6.9033, rtol=0, atol=1.5*(1e-3))

self._assert_rmsd(reference, fitted, 0, 0.0,
weights=universe.atoms.masses)
Expand All @@ -327,13 +333,13 @@ def test_AlignTraj_custom_mass_weights(self, universe, reference, tmpdir):
filename=outfile,
weights=reference.atoms.masses).run()
fitted = mda.Universe(PSF, outfile)
assert_almost_equal(x.results.rmsd[0], 0, decimal=3)
assert_almost_equal(x.results.rmsd[-1], 6.9033, decimal=3)
assert_allclose(x.results.rmsd[0], 0, rtol=0, atol=1.5*(1e-3))
assert_allclose(x.results.rmsd[-1], 6.9033, rtol=0, atol=1.5*(1e-3))

self._assert_rmsd(reference, fitted, 0, 0.0,
weights=universe.atoms.masses)
weights=universe.atoms.masses)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

undo indent

self._assert_rmsd(reference, fitted, -1, 6.929083032629219,
weights=universe.atoms.masses)
weights=universe.atoms.masses)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

undo indent


def test_AlignTraj_partial_fit(self, universe, reference, tmpdir):
outfile = str(tmpdir.join('align_test.dcd'))
Expand All @@ -348,20 +354,21 @@ def test_AlignTraj_in_memory(self, universe, reference, tmpdir):
x = align.AlignTraj(universe, reference, filename=outfile,
in_memory=True).run()
assert x.filename is None
assert_almost_equal(x.results.rmsd[0], 6.9290, decimal=3)
assert_almost_equal(x.results.rmsd[-1], 5.2797e-07, decimal=3)
assert_allclose(x.results.rmsd[0], 6.9290, rtol=0, atol=1.5*(1e-3))
assert_allclose(x.results.rmsd[-1], 5.2797e-07, rtol=0, atol=1.5*(1e-3))

# check in memory trajectory
self._assert_rmsd(reference, universe, 0, 6.929083044751061)
self._assert_rmsd(reference, universe, -1, 0.0)

def _assert_rmsd(self, reference, fitted, frame, desired, weights=None):
fitted.trajectory[frame]
rmsd = rms.rmsd(reference.atoms.positions, fitted.atoms.positions,
superposition=True)
assert_almost_equal(rmsd, desired, decimal=5,
err_msg="frame {0:d} of fit does not have "
"expected RMSD".format(frame))
fitted.trajectory[frame]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You still have unwanted whitespace changes here and elsewhere, please re-read the entire diff line-by-line and make sure those changes are not present (since I'm spending time doing the same).

rmsd = rms.rmsd(reference.atoms.positions, fitted.atoms.positions,
superposition=True)
np.testing.assert_allclose(rmsd, desired, rtol=0, atol=1.5*(1e-5),
err_msg="frame {0:d} of fit does not have "
"expected RMSD".format(frame))


def test_alignto_checks_selections(self, universe, reference):
"""Testing that alignto() fails if selections do not
Expand All @@ -388,7 +395,6 @@ def test_alignto_partial_universe(self, universe, reference):
u_bound = mda.Universe(ALIGN_BOUND)
u_free = mda.Universe(ALIGN_UNBOUND)
selection = 'segid B'

segB_bound = u_bound.select_atoms(selection)
segB_free = u_free.select_atoms(selection)
segB_free.translate(segB_bound.centroid() - segB_free.centroid())
Expand All @@ -398,6 +404,7 @@ def test_alignto_partial_universe(self, universe, reference):
decimal=3)



def _get_aligned_average_positions(ref_files, ref, select="all", **kwargs):
u = mda.Universe(*ref_files, in_memory=True)
prealigner = align.AlignTraj(u, ref, select=select, **kwargs).run()
Expand Down Expand Up @@ -438,31 +445,30 @@ def test_average_structure_deprecated_attrs(self, universe, reference):
def test_average_structure(self, universe, reference):
ref, rmsd = _get_aligned_average_positions(self.ref_files, reference)
avg = align.AverageStructure(universe, reference).run()
assert_almost_equal(avg.results.universe.atoms.positions, ref,
decimal=4)
assert_almost_equal(avg.results.rmsd, rmsd)
assert_allclose(avg.results.universe.atoms.positions, ref, rtol=0, atol=1.5*(1e-4))
assert_allclose(avg.results.rmsd, rmsd, rtol=0, atol=1.5*(1e-7))

orbeckst marked this conversation as resolved.
Show resolved Hide resolved
def test_average_structure_mass_weighted(self, universe, reference):
ref, rmsd = _get_aligned_average_positions(self.ref_files, reference, weights='mass')
avg = align.AverageStructure(universe, reference, weights='mass').run()
assert_almost_equal(avg.results.universe.atoms.positions, ref,
decimal=4)
assert_almost_equal(avg.results.rmsd, rmsd)
assert_allclose(avg.results.universe.atoms.positions, ref,
rtol=0, atol=1.5*(1e-4))
assert_allclose(avg.results.rmsd, rmsd, rtol=0, atol=1.5*(1e-7))

def test_average_structure_select(self, universe, reference):
select = 'protein and name CA and resid 3-5'
ref, rmsd = _get_aligned_average_positions(self.ref_files, reference, select=select)
avg = align.AverageStructure(universe, reference, select=select).run()
assert_almost_equal(avg.results.universe.atoms.positions, ref,
decimal=4)
assert_almost_equal(avg.results.rmsd, rmsd)
assert_allclose(avg.results.universe.atoms.positions, ref,
rtol=0, atol=1.5*(1e-4))
assert_allclose(avg.results.rmsd, rmsd, rtol=0, atol=1.5*(1e-7))

def test_average_structure_no_ref(self, universe):
ref, rmsd = _get_aligned_average_positions(self.ref_files, universe)
avg = align.AverageStructure(universe).run()
assert_almost_equal(avg.results.universe.atoms.positions, ref,
decimal=4)
assert_almost_equal(avg.results.rmsd, rmsd)
assert_allclose(avg.results.universe.atoms.positions, ref,
rtol=0, atol=1.5*(1e-4))
assert_allclose(avg.results.rmsd, rmsd, rtol=0, atol=1.5*(1e-7))

def test_average_structure_no_msf(self, universe):
avg = align.AverageStructure(universe).run()
Expand All @@ -485,15 +491,15 @@ def test_average_structure_ref_frame(self, universe):
universe.trajectory[0]
ref, rmsd = _get_aligned_average_positions(self.ref_files, u)
avg = align.AverageStructure(universe, ref_frame=ref_frame).run()
assert_almost_equal(avg.results.universe.atoms.positions, ref,
decimal=4)
assert_almost_equal(avg.results.rmsd, rmsd)
assert_allclose(avg.results.universe.atoms.positions, ref,
rtol=0, atol=1.5*(1e-4))
assert_allclose(avg.results.rmsd, rmsd, rtol=0, atol=1.5*(1e-7))

def test_average_structure_in_memory(self, universe):
avg = align.AverageStructure(universe, in_memory=True).run()
reference_coordinates = universe.trajectory.timeseries().mean(axis=1)
assert_almost_equal(avg.results.universe.atoms.positions,
reference_coordinates, decimal=4)
assert_allclose(avg.results.universe.atoms.positions,
reference_coordinates, rtol=0, atol=1.5*(1e-4))
assert avg.filename is None


Expand Down Expand Up @@ -603,4 +609,4 @@ def test_alignto_reorder_atomgroups():
mobile = u.atoms[:4]
ref = u.atoms[[3, 2, 1, 0]]
rmsd = align.alignto(mobile, ref, select='bynum 1-4')
assert_allclose(rmsd, (0.0, 0.0))
assert_allclose(rmsd, (0.0, 0.0))
8 changes: 4 additions & 4 deletions testsuite/MDAnalysisTests/analysis/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

import numpy as np

from numpy.testing import assert_equal, assert_almost_equal
from numpy.testing import assert_equal, assert_almost_equal, assert_allclose
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove assert_almost_equal: the whole point of the PR is to get rid of it :-)


import MDAnalysis as mda
from MDAnalysis.analysis import base
Expand Down Expand Up @@ -194,7 +194,7 @@ def test_start_stop_step(u, run_kwargs, frames):
assert an.n_frames == len(frames)
assert_equal(an.found_frames, frames)
assert_equal(an.frames, frames, err_msg=FRAMES_ERR)
assert_almost_equal(an.times, frames+1, decimal=4, err_msg=TIMES_ERR)
assert_allclose(an.times, frames+1, rtol=0, atol=1.5*(1e-4), err_msg=TIMES_ERR)


@pytest.mark.parametrize('run_kwargs, frames', [
Expand Down Expand Up @@ -251,7 +251,7 @@ def test_frames_times():
assert an.n_frames == len(frames)
assert_equal(an.found_frames, frames)
assert_equal(an.frames, frames, err_msg=FRAMES_ERR)
assert_almost_equal(an.times, frames*100, decimal=4, err_msg=TIMES_ERR)
assert_allclose(an.times, frames*100, rtol=0, atol=1.5*(1e-4), err_msg=TIMES_ERR)


def test_verbose(u):
Expand Down Expand Up @@ -372,7 +372,7 @@ def test_AnalysisFromFunction_args_content(u):
ans = base.AnalysisFromFunction(mass_xyz, protein, another, masses)
assert len(ans.args) == 3
result = np.sum(ans.run().results.timeseries)
assert_almost_equal(result, -317054.67757345125, decimal=6)
assert_allclose(result, -317054.67757345125, rtol=0, atol=1.5*(1e-6))
assert (ans.args[0] is protein) and (ans.args[1] is another)
assert ans._trajectory is protein.universe.trajectory

Expand Down
45 changes: 29 additions & 16 deletions testsuite/MDAnalysisTests/analysis/test_bat.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from __future__ import absolute_import

import numpy as np
from numpy.testing import assert_equal, assert_almost_equal
from numpy.testing import assert_equal, assert_almost_equal, assert_allclose
import pytest
import copy

Expand Down Expand Up @@ -66,36 +66,46 @@ def test_bat_number_of_frames(self, bat):

def test_bat_coordinates(self, bat):
test_bat = np.load(BATArray)
assert_almost_equal(
np.testing.assert_allclose(
bat,
test_bat,
5,
err_msg="error: BAT coordinates should match test values")
rtol=0,
atol=1.5*(1e-5),
err_msg="error: BAT coordinates should match test values"
)

def test_bat_coordinates_single_frame(self, selected_residues):
bat = BAT(selected_residues).run(start=1, stop=2).results.bat
test_bat = [np.load(BATArray)[1]]
assert_almost_equal(
np.testing.assert_allclose(
bat,
test_bat,
5,
err_msg="error: BAT coordinates should match test values")
rtol=0,
atol=1.5*(1e-5),
err_msg="error: BAT coordinates should match test values"
)

def test_bat_reconstruction(self, selected_residues, bat):
R = BAT(selected_residues)
XYZ = R.Cartesian(bat[0])
assert_almost_equal(XYZ, selected_residues.positions, 5,
err_msg="error: Reconstructed Cartesian coordinates " + \
"don't match original")
np.testing.assert_allclose(
XYZ,
selected_residues.positions,
rtol=0,
atol=1.5*(1e-5),
err_msg="error: Reconstructed Cartesian coordinates don't match original"
)

def test_bat_IO(self, bat_npz, selected_residues, bat):
R2 = BAT(selected_residues, filename=bat_npz)
test_bat = R2.results.bat
assert_almost_equal(
np.testing.assert_allclose(
bat,
test_bat,
5,
err_msg="error: Loaded BAT coordinates should match test values")
rtol=0,
atol=1.5*(1e-5),
err_msg="error: Loaded BAT coordinates should match test values"
)

def test_bat_nobonds(self):
u = mda.Universe(XYZ_mini)
Expand All @@ -106,7 +116,7 @@ def test_bat_nobonds(self):
def test_bat_bad_initial_atom(self, selected_residues):
errmsg = 'Initial atom is not a terminal atom'
with pytest.raises(ValueError, match=errmsg):
R = BAT(selected_residues, initial_atom = selected_residues[0])
R = BAT(selected_residues, initial_atom=selected_residues[0])

def test_bat_disconnected_atom_group(self):
u = mda.Universe(PSF, DCD)
Expand All @@ -133,7 +143,10 @@ def test_Cartesian_does_not_modify_input(self, selected_residues, bat):
R = BAT(selected_residues)
pre_transformation = copy.deepcopy(bat[0])
R.Cartesian(bat[0])
assert_almost_equal(
pre_transformation, bat[0],
np.testing.assert_allclose(
pre_transformation,
bat[0],
rtol=0,
atol=1.5*(1e-7),
err_msg="BAT.Cartesian modified input data"
)
Loading
Loading