diff --git a/testsuite/python/actor.py b/testsuite/python/actor.py index ee7398dd905..bdb93800891 100644 --- a/testsuite/python/actor.py +++ b/testsuite/python/actor.py @@ -103,9 +103,9 @@ def test_deactivation(self): self.assertFalse(a.is_active()) params = a.get_params() - self.assertTrue(params["a"]) - self.assertFalse(params["b"]) - self.assertTrue(params["c"]) + self.assertEqual(params["a"], True) + self.assertEqual(params["b"], False) + self.assertEqual(params["c"], True) if __name__ == "__main__": diff --git a/testsuite/python/analyze_distance.py b/testsuite/python/analyze_distance.py index f1e5f37bd83..c26b3cafa88 100644 --- a/testsuite/python/analyze_distance.py +++ b/testsuite/python/analyze_distance.py @@ -92,18 +92,18 @@ def test_nbhood(self): for i in range(1, 10, 2): self.system.part[:].pos = np.random.random( (len(self.system.part), 3)) * BOX_L - self.assertTrue( - np.allclose(self.system.analysis.nbhood([i, i, i], i * 2), - self.nbhood([i, i, i], i * 2))) + np.testing.assert_allclose( + self.system.analysis.nbhood([i, i, i], i * 2), + self.nbhood([i, i, i], i * 2)) def test_dist_to_pos(self): # try five times for i in range(5): self.system.part[:].pos = np.random.random( (len(self.system.part), 3)) * BOX_L - self.assertTrue( - np.allclose(self.system.analysis.dist_to(pos=[i, i, i]), - self.dist_to_pos([i, i, i]))) + np.testing.assert_allclose( + self.system.analysis.dist_to(pos=[i, i, i]), + self.dist_to_pos([i, i, i])) def test_dist_to_id(self): # try five times diff --git a/testsuite/python/analyze_distribution.py b/testsuite/python/analyze_distribution.py index d0699c93084..a85fc88f8e6 100644 --- a/testsuite/python/analyze_distribution.py +++ b/testsuite/python/analyze_distribution.py @@ -64,7 +64,7 @@ def test_rdf(self): bin_width = (r_max - r_min) / r_bins bins = np.arange(r_min, r_max + bin_width, bin_width) bin_volume = 4. / 3. * np.pi * (bins[1:]**3 - bins[:-1]**3) - box_volume = np.prod(self.system.box_l) + box_volume = np.prod(np.copy(self.system.box_l)) # all the same type core_rdf = self.system.analysis.rdf(rdf_type='rdf', type_list_a=[0], @@ -75,11 +75,11 @@ def test_rdf(self): num_pair = 0.5 * (self.num_part) * (self.num_part - 1) r = self.system.part[:].pos # bins - self.assertTrue(np.allclose(core_rdf[0], (bins[1:] + bins[:-1]) * 0.5)) + np.testing.assert_allclose(core_rdf[0], (bins[1:] + bins[:-1]) * 0.5) # rdf - self.assertTrue( - np.allclose(core_rdf[1] * bin_volume * num_pair / box_volume, - self.calc_rdf(r, bins))) + np.testing.assert_allclose( + core_rdf[1] * bin_volume * num_pair / box_volume, + self.calc_rdf(r, bins)) # change one type self.system.part[0].type = 1 r = self.system.part[1:].pos @@ -90,9 +90,9 @@ def test_rdf(self): r_max=r_max, r_bins=r_bins) num_pair = 0.5 * (self.num_part - 1) * (self.num_part - 2) - self.assertTrue( - np.allclose(core_rdf[1] * bin_volume * num_pair / box_volume, - self.calc_rdf(r, bins))) + np.testing.assert_allclose( + core_rdf[1] * bin_volume * num_pair / box_volume, + self.calc_rdf(r, bins)) # compare with type core_rdf = self.system.analysis.rdf(rdf_type='rdf', @@ -105,9 +105,8 @@ def test_rdf(self): dist = np.sqrt( np.sum((self.system.part[1:].pos - self.system.part[0].pos)**2, axis=1)) hist = np.histogram(dist, bins=bins, density=False)[0] - self.assertTrue( - np.allclose(core_rdf[1] * bin_volume * num_pair / box_volume, - hist)) + np.testing.assert_allclose( + core_rdf[1] * bin_volume * num_pair / box_volume, hist) # restore PBC self.system.box_l = self.system.box_l / 2. self.system.part[:].pos = old_pos @@ -131,11 +130,11 @@ def test_distribution_lin(self): log_flag=0, int_flag=0) # bins - self.assertTrue(np.allclose(core_rdf[0], (bins[1:] + bins[:-1]) * 0.5)) + np.testing.assert_allclose(core_rdf[0], (bins[1:] + bins[:-1]) * 0.5) # rdf - self.assertTrue(np.allclose(core_rdf[1], - self.calc_min_distribution(bins))) + np.testing.assert_allclose(core_rdf[1], + self.calc_min_distribution(bins)) # with int flag core_rdf = self.system.analysis.distribution(type_list_a=[0], type_list_b=[0], @@ -144,8 +143,8 @@ def test_distribution_lin(self): r_bins=r_bins, log_flag=0, int_flag=1) - self.assertTrue(np.allclose(core_rdf[1], - np.cumsum(self.calc_min_distribution(bins)))) + np.testing.assert_allclose(core_rdf[1], + np.cumsum(self.calc_min_distribution(bins))) if __name__ == "__main__": diff --git a/testsuite/python/analyze_gyration_tensor.py b/testsuite/python/analyze_gyration_tensor.py index 5eee645dfcc..304bf4151a5 100644 --- a/testsuite/python/analyze_gyration_tensor.py +++ b/testsuite/python/analyze_gyration_tensor.py @@ -50,10 +50,10 @@ def test_gyration_tensor_cube(self): res = self.system.analysis.gyration_tensor(p_type=self.type_cube) rg = self.system.analysis.calc_rg( chain_start=0, number_of_chains=1, chain_length=self.cube_len**3)[0] - # make sure all eigenvalues (for the cube) are identical - self.assertTrue( - np.allclose(np.abs(res['eva0'][0]), np.abs(res['eva1'][0]), np.abs(res['eva2'][0]), atol=1e-6)) - self.assertTrue(np.allclose(rg**2, res['Rg^2'], atol=1e-6)) + # check eigenvalues are identical + np.testing.assert_allclose( + [np.abs(res['eva' + x][0]) for x in '012'], 3 * [1.25], atol=1e-6) + np.testing.assert_allclose(rg**2, res['Rg^2'], atol=1e-6) def test_gyration_tensor(self): # get results @@ -61,25 +61,24 @@ def test_gyration_tensor(self): p_type=[self.type_stick, self.type_cube]) rg = self.system.analysis.calc_rg( chain_start=0, number_of_chains=1, chain_length=len(self.system.part[:]))[0] - # test if principal and secondary axis is [0,0,1] and [0,1,0] - self.assertTrue( - np.allclose(np.abs(res['eva0'][1]), [0., 0., 1.], atol=1e-6)) - self.assertTrue( - np.allclose(np.abs(res['eva1'][1]), [0., 1., 0.], atol=1e-6)) - self.assertTrue( - np.allclose(np.abs(res['eva2'][1]), [1., 0., 0.], atol=1e-6)) - self.assertTrue(np.allclose(rg**2, res['Rg^2'], atol=1e-6)) + # check eigenvectors + np.testing.assert_allclose( + np.abs(res['eva0'][1]), [0., 0., 1.], atol=1e-6) + np.testing.assert_allclose( + np.abs(res['eva1'][1]), [0., 1., 0.], atol=1e-6) + np.testing.assert_allclose( + np.abs(res['eva2'][1]), [1., 0., 0.], atol=1e-6) + np.testing.assert_allclose(rg**2, res['Rg^2'], atol=1e-6) def test_mom_intertia(self): - sqr_dist = np.sum( (self.system.analysis.center_of_mass(p_type=0) - self.system.part.select(type=0).pos)**2, axis=0) mom_I = self.system.analysis.moment_of_inertia_matrix(p_type=0) - # the cube case should have zero as off- diagonal components - self.assertTrue( - np.allclose([mom_I[0, 1], mom_I[0, 2], mom_I[1, 2], mom_I[1, 0], mom_I[2, 0], mom_I[2, 1]], np.zeros(6), atol=1e-6)) - self.assertTrue(np.allclose([mom_I[0, 0], mom_I[1, 1], mom_I[2, 2]], - [sqr_dist[1] + sqr_dist[2], sqr_dist[0] + sqr_dist[2], sqr_dist[1] + sqr_dist[2]], atol=1e-6)) + # the cube case should have zero as off-diagonal components + np.testing.assert_allclose( + mom_I, np.diag(np.diag(mom_I)), rtol=0, atol=1e-6) + np.testing.assert_allclose( + np.diag(mom_I), sqr_dist[(1, 0, 1), ] + sqr_dist[2], atol=1e-6) if __name__ == "__main__": diff --git a/testsuite/python/analyze_mass_related.py b/testsuite/python/analyze_mass_related.py index 22643682d81..66941a5f7e3 100644 --- a/testsuite/python/analyze_mass_related.py +++ b/testsuite/python/analyze_mass_related.py @@ -73,13 +73,12 @@ def test_itensor(self): # Particles of type 0 I0 = self.i_tensor(self.system.part.select( lambda p: (not p.virtual) and p.type == 0).id) - np.testing.assert_allclose( I0, self.system.analysis.moment_of_inertia_matrix(p_type=0), atol=1E-9) - # type=1 + # Particles of type 1 I1 = self.i_tensor(self.system.part.select(type=1).id) - self.assertTrue( - np.allclose(I1, self.system.analysis.moment_of_inertia_matrix(p_type=1), atol=1E-9)) + np.testing.assert_allclose( + I1, self.system.analysis.moment_of_inertia_matrix(p_type=1), atol=1E-9) def test_center_of_mass(self): no_virtual_type_0 = self.system.part.select( diff --git a/testsuite/python/array_properties.py b/testsuite/python/array_properties.py index 31ae5e34477..b1cf344c5a6 100644 --- a/testsuite/python/array_properties.py +++ b/testsuite/python/array_properties.py @@ -60,8 +60,8 @@ def test_unlocked_operators(self): add = v + w sub = v - w - self.assertTrue(isinstance(add, np.ndarray)) - self.assertTrue(isinstance(sub, np.ndarray)) + self.assertIsInstance(add, np.ndarray) + self.assertIsInstance(sub, np.ndarray) self.assertTrue(add.flags.writeable) self.assertTrue(sub.flags.writeable) @@ -136,17 +136,20 @@ def test_common(self): # Check (allowed) setter # Particle self.system.part[0].pos = [2, 2, 2] - self.assertTrue((self.system.part[0].pos == [2, 2, 2]).all()) + np.testing.assert_array_equal( + np.copy(self.system.part[0].pos), [2, 2, 2]) self.system.part[0].v = [2, 2, 2] - self.assertTrue((self.system.part[0].v == [2, 2, 2]).all()) + np.testing.assert_array_equal( + np.copy(self.system.part[0].v), [2, 2, 2]) self.system.part[0].f = [2, 2, 2] - self.assertTrue((self.system.part[0].f == [2, 2, 2]).all()) + np.testing.assert_array_equal( + np.copy(self.system.part[0].f), [2, 2, 2]) # System self.system.box_l = [2, 2, 2] - self.assertTrue((self.system.box_l == [2, 2, 2]).all()) + np.testing.assert_array_equal(np.copy(self.system.box_l), [2, 2, 2]) # Check if copy is settable # Particle @@ -175,25 +178,28 @@ def test_rotation(self): # Check (allowed) setter # Particle self.system.part[0].quat = [0.5, 0.5, 0.5, 0.5] - self.assertTrue( - (self.system.part[0].quat == [0.5, 0.5, 0.5, 0.5]).all()) + np.testing.assert_array_equal( + np.copy(self.system.part[0].quat), [0.5, 0.5, 0.5, 0.5]) self.system.part[0].omega_lab = [2, 2, 2] - self.assertTrue((self.system.part[0].omega_lab == [2, 2, 2]).all()) + np.testing.assert_array_equal( + np.copy(self.system.part[0].omega_lab), [2, 2, 2]) - self.system.part[0].rotation = [1, 1, 1] - self.assertTrue((self.system.part[0].rotation == [1, 1, 1]).all()) + self.system.part[0].rotation = [True, True, True] + self.assertEqual(list(self.system.part[0].rotation), 3 * [True]) self.system.part[0].omega_body = [2, 2, 2] - self.assertTrue((self.system.part[0].omega_body == [2, 2, 2]).all()) + np.testing.assert_array_equal( + np.copy(self.system.part[0].omega_body), [2, 2, 2]) self.system.part[0].torque_lab = [2, 2, 2] - self.assertTrue((self.system.part[0].torque_lab == [2, 2, 2]).all()) + np.testing.assert_array_equal( + np.copy(self.system.part[0].torque_lab), [2, 2, 2]) if espressomd.has_features("EXTERNAL_FORCES"): self.system.part[0].ext_torque = [2, 2, 2] - self.assertTrue( - (self.system.part[0].ext_torque == [2, 2, 2]).all()) + np.testing.assert_array_equal( + np.copy(self.system.part[0].ext_torque), [2, 2, 2]) # Check if copy is settable # Particle @@ -215,7 +221,8 @@ def test_rotational_inertia(self): # Check (allowed) setter # Particle self.system.part[0].rinertia = [2, 2, 2] - self.assertTrue((self.system.part[0].rinertia == [2, 2, 2]).all()) + np.testing.assert_array_equal( + np.copy(self.system.part[0].rinertia), [2, 2, 2]) # Check if copy is settable # Particle @@ -232,10 +239,11 @@ def test_external_forces(self): # Check (allowed) setter # Particle self.system.part[0].ext_force = [2, 2, 2] - self.assertTrue((self.system.part[0].ext_force == [2, 2, 2]).all()) + np.testing.assert_array_equal( + np.copy(self.system.part[0].ext_force), [2, 2, 2]) - self.system.part[0].fix = [1, 1, 1] - self.assertTrue((self.system.part[0].fix == [1, 1, 1]).all()) + self.system.part[0].fix = [True, True, True] + self.assertEqual(list(self.system.part[0].fix), [True, True, True]) # Check if copy is settable # Particle @@ -252,7 +260,8 @@ def test_rot_aniso(self): # Check (allowed) setter # Particle self.system.part[0].gamma_rot = [2, 2, 2] - self.assertTrue((self.system.part[0].gamma_rot == [2, 2, 2]).all()) + np.testing.assert_array_equal( + np.copy(self.system.part[0].gamma_rot), [2, 2, 2]) # Check if copy is settable # Particle @@ -277,7 +286,8 @@ def test_langevinpp_aniso(self): # Check (allowed) setter # Particle self.system.part[0].gamma = [2, 2, 2] - self.assertTrue((self.system.part[0].gamma == [2, 2, 2]).all()) + np.testing.assert_array_equal( + np.copy(self.system.part[0].gamma), [2, 2, 2]) # Check if copy is settable # Particle @@ -294,7 +304,7 @@ def test_dipoles(self): # Particle self.system.part[0].dip = [2, 2, 2] np.testing.assert_allclose( - [2, 2, 2], np.copy(self.system.part[0].dip), atol=1E-15) + np.copy(self.system.part[0].dip), [2, 2, 2], atol=1E-15) # Check if copy is settable # Particle @@ -315,8 +325,8 @@ def test_partial_periodic(self): # Check (allowed) setter # System - self.system.periodicity = [1, 0, 0] - self.assertTrue((self.system.periodicity == [1, 0, 0]).all()) + self.system.periodicity = [True, False, False] + self.assertEqual(list(self.system.periodicity), [True, False, False]) # Check if copy is settable # System diff --git a/testsuite/python/auto_exclusions.py b/testsuite/python/auto_exclusions.py index e2ebc0d7cec..183775ac42e 100644 --- a/testsuite/python/auto_exclusions.py +++ b/testsuite/python/auto_exclusions.py @@ -45,16 +45,16 @@ def test_linear(self): for p in range(1, 9): excl = s.part[p].exclusions self.assertEqual(len(excl), 2) - self.assertTrue((p - 1) in excl) - self.assertTrue((p + 1) in excl) + self.assertIn(p - 1, excl) + self.assertIn(p + 1, excl) excl = s.part[0].exclusions self.assertEqual(len(excl), 1) - self.assertTrue(1 in excl) + self.assertIn(1, excl) excl = s.part[9].exclusions self.assertEqual(len(excl), 1) - self.assertTrue(8 in excl) + self.assertIn(8, excl) def test_ring(self): bond = espressomd.interactions.Virtual() @@ -73,8 +73,8 @@ def test_ring(self): excl = s.part[p].exclusions self.assertEqual(len(excl), 4) for i in range(1, 3): - self.assertTrue((p - i) % 10 in excl) - self.assertTrue((p + i) % 10 in excl) + self.assertIn((p - i) % 10, excl) + self.assertIn((p + i) % 10, excl) if __name__ == "__main__": diff --git a/testsuite/python/cluster_analysis.py b/testsuite/python/cluster_analysis.py index f223b919fe1..0188a019684 100644 --- a/testsuite/python/cluster_analysis.py +++ b/testsuite/python/cluster_analysis.py @@ -130,11 +130,11 @@ def test_zz_single_cluster_analysis(self): self.assertLess(np.linalg.norm(c.center_of_mass()), 1E-8) # Longest distance - self.assertLess( - abs(c.longest_distance() - - self.es.distance(self.es.part[0], - self.es.part[len(self.es.part) - 1])), - 1E-8) + self.assertAlmostEqual( + c.longest_distance(), + self.es.distance(self.es.part[0], + self.es.part[len(self.es.part) - 1]), + delta=1E-8) # Radius of gyration rg = 0. @@ -143,11 +143,11 @@ def test_zz_single_cluster_analysis(self): rg += self.es.distance(p, com_particle)**2 rg /= len(self.es.part) rg = np.sqrt(rg) - self.assertTrue(abs(c.radius_of_gyration() - rg) <= 1E-6) + self.assertAlmostEqual(c.radius_of_gyration(), rg, delta=1E-6) # Fractal dimension calc require gsl if not espressomd.has_features("GSL"): - print("Skipping fractal dimension tests for lack of GSL") + print("Skipping fractal dimension tests due to missing GSL dependency") return # The fractal dimension of a line should be 1 diff --git a/testsuite/python/collision_detection.py b/testsuite/python/collision_detection.py index 685a07a9090..89b69b9f86a 100644 --- a/testsuite/python/collision_detection.py +++ b/testsuite/python/collision_detection.py @@ -162,7 +162,7 @@ def verify_state_after_bind_at_poc(self, expected_np): # get partner p2 = self.s.part[p.bonds[0][1]] # Is that really a vs - self.assertEqual(p2.virtual, True) + self.assertTrue(p2.virtual) # Get base particles base_p1 = self.s.part[p.vs_relative[0]] base_p2 = self.s.part[p2.vs_relative[0]] @@ -173,7 +173,7 @@ def verify_state_after_bind_at_poc(self, expected_np): # Check particle that did not take part in collision. self.assertEqual(len(parts_not_accounted_for), 1) p = self.s.part[parts_not_accounted_for[0]] - self.assertEqual(p.virtual, False) + self.assertFalse(p.virtual) self.assertEqual(p.bonds, ()) parts_not_accounted_for.remove(p.id) self.assertEqual(parts_not_accounted_for, []) @@ -190,8 +190,8 @@ def verify_bind_at_poc_pair(self, p1, p2, vs1, vs2): self.assertTrue(vs1.bonds == bond_vs1 or vs2.bonds == bond_vs2) # Vs properties - self.assertEqual(vs1.virtual, True) - self.assertEqual(vs2.virtual, True) + self.assertTrue(vs1.virtual) + self.assertTrue(vs2.virtual) # vs_relative properties seen = [] @@ -200,7 +200,7 @@ def verify_bind_at_poc_pair(self, p1, p2, vs1, vs2): rel_to = r[0] dist = r[1] # Vs is related to one of the particles - self.assertTrue(rel_to in (p1.id, p2.id)) + self.assertIn(rel_to, (p1.id, p2.id)) # The two vs relate to two different particles self.assertNotIn(rel_to, seen) seen.append(rel_to) @@ -298,7 +298,7 @@ def test_bind_at_point_of_collision_random(self): vs_pairs = [] for p in virtual_sites: # 0 or 1 bond on vs? - self.assertTrue(len(p.bonds) in [0, 1]) + self.assertIn(len(p.bonds), [0, 1]) if len(p.bonds) == 1: vs_pairs.append((p.id, p.bonds[0][1])) @@ -314,7 +314,7 @@ def test_bind_at_point_of_collision_random(self): self.s.part[vs_pair[1]].vs_relative[0]])) # Is there a corresponding bond? - self.assertTrue(base_particles in bonds) + self.assertIn(base_particles, bonds) # Tidy self.s.non_bonded_inter[0, 0].lennard_jones.set_params( @@ -406,7 +406,7 @@ def verify_state_after_glue_to_surface(self, expected_np): # Check particle that did not take part in collision. self.assertEqual(len(parts_not_accounted_for), 1) p = self.s.part[parts_not_accounted_for[0]] - self.assertEqual(p.virtual, False) + self.assertFalse(p.virtual) self.assertEqual(p.type, self.other_type) self.assertEqual(p.bonds, ()) parts_not_accounted_for.remove(p.id) @@ -431,7 +431,7 @@ def verify_glue_to_surface_pair(self, base_p, vs, bound_p): self.assertEqual(vs.bonds, ()) # Vs properties - self.assertEqual(vs.virtual, True) + self.assertTrue(vs.virtual) self.assertEqual(vs.vs_relative[0], base_p.id) # Distance vs,bound_p @@ -527,7 +527,7 @@ def test_glue_to_surface_random(self): # part_type_after_glueing can have a bond to a vs or to a # non_virtual particle if p.type == self.part_type_after_glueing: - self.assertTrue(bond[0] in (self.H, self.H2)) + self.assertIn(bond[0], (self.H, self.H2)) # Bonds to virtual sites: if bond[0] == self.H2: self.assertEqual( @@ -655,9 +655,9 @@ def verify_triangle_binding(self, distance, first_bond, angle_res): d_ij = np.copy(p_j.pos - p_i.pos) d_ik = np.copy(p_k.pos - p_i.pos) d_jk = np.copy(p_k.pos - p_j.pos) - d_ij /= np.sqrt(np.sum(d_ij**2)) - d_ik /= np.sqrt(np.sum(d_ik**2)) - d_jk /= np.sqrt(np.sum(d_jk**2)) + d_ij /= np.linalg.norm(d_ij) + d_ik /= np.linalg.norm(d_ik) + d_jk /= np.linalg.norm(d_jk) if self.s.distance(p_i, p_j) <= distance and self.s.distance( p_i, p_k) <= distance: diff --git a/testsuite/python/coulomb_cloud_wall.py b/testsuite/python/coulomb_cloud_wall.py index 611d8ffaca7..74e80b668d7 100644 --- a/testsuite/python/coulomb_cloud_wall.py +++ b/testsuite/python/coulomb_cloud_wall.py @@ -76,27 +76,15 @@ def compare(self, method_name, energy=True, prefactor=None): p.f / prefactor - self.forces[p.id]) force_abs_diff /= len(self.S.part) - print(method_name, "force difference", force_abs_diff) - # Energy if energy: - energy_abs_diff = abs(self.S.analysis.energy()["total"] / prefactor - - self.reference_energy) - print(method_name, "energy difference", energy_abs_diff) - self.assertLessEqual( - energy_abs_diff, - self.tolerance, - "Absolute energy difference " + - str(energy_abs_diff) + - " too large for " + - method_name) + self.assertAlmostEqual( + self.S.analysis.energy()["total"] / prefactor, + self.reference_energy, delta=self.tolerance, + msg="Absolute energy difference too large for " + method_name) self.assertLessEqual( - force_abs_diff, - self.tolerance, - "Absolute force difference " + - str(force_abs_diff) + - " too large for method " + - method_name) + force_abs_diff, self.tolerance, + "Absolute force difference too large for method " + method_name) # Tests for individual methods diff --git a/testsuite/python/coulomb_cloud_wall_duplicated.py b/testsuite/python/coulomb_cloud_wall_duplicated.py index 02bf2504007..ff367c4a26c 100644 --- a/testsuite/python/coulomb_cloud_wall_duplicated.py +++ b/testsuite/python/coulomb_cloud_wall_duplicated.py @@ -29,8 +29,8 @@ @utx.skipIfMissingFeatures("ELECTROSTATICS") class CoulombCloudWall(ut.TestCase): - """This compares p3m, p3m_gpu, scafacos_p3m and scafacos_p2nfft - electrostatic forces and energy against stored data.""" + """This compares p3m, p3m_gpu electrostatic forces and energy against + stored data.""" S = espressomd.System(box_l=[1.0, 1.0, 1.0]) S.seed = S.cell_system.get_state()['n_nodes'] * [1234] np.random.seed(S.seed) @@ -65,6 +65,7 @@ def setUp(self): def compare(self, method_name, energy=True): # Compare forces and energy now in the system to stored ones + # Force force_abs_diff = 0. for p in self.S.part: @@ -73,12 +74,13 @@ def compare(self, method_name, energy=True): # Energy if energy: - energy_abs_diff = abs( - self.S.analysis.energy()["total"] - self.reference_energy) - self.assertTrue(energy_abs_diff <= self.tolerance, "Absolute energy difference " + - str(energy_abs_diff) + " too large for " + method_name) - self.assertTrue(force_abs_diff <= self.tolerance, "Absolute force difference " + - str(force_abs_diff) + " too large for method " + method_name) + self.assertAlmostEqual( + self.S.analysis.energy()["total"], self.reference_energy, + delta=self.tolerance, + msg="Absolute energy difference too large for " + method_name) + self.assertLess( + force_abs_diff, self.tolerance, + msg="Absolute force difference too large for method " + method_name) # Tests for individual methods @@ -106,8 +108,8 @@ def test_p3m_gpu(self): self.compare("p3m_gpu", energy=False) def test_zz_deactivation(self): - # Is the energy 0, if no methods active - self.assertTrue(self.S.analysis.energy()["total"] == 0.0) + # The energy is 0 if no method is active + self.assertEqual(self.S.analysis.energy()["total"], 0.0) if __name__ == "__main__": diff --git a/testsuite/python/coulomb_mixed_periodicity.py b/testsuite/python/coulomb_mixed_periodicity.py index e7e950b876f..20a342efa9c 100644 --- a/testsuite/python/coulomb_mixed_periodicity.py +++ b/testsuite/python/coulomb_mixed_periodicity.py @@ -71,28 +71,15 @@ def compare(self, method_name, energy=True): rms_force_diff += np.sum((p.f - self.forces[p.id])**2) rms_force_diff = np.sqrt(rms_force_diff / len(self.S.part)) - print(method_name, "rms force difference", rms_force_diff) - # Energy if energy: - energy_abs_diff = abs( - self.S.analysis.energy()["total"] - self.reference_energy) - print(method_name, "energy", self.S.analysis.energy()["total"]) - print(method_name, "energy difference", energy_abs_diff) - self.assertLessEqual( - energy_abs_diff, - self.tolerance_energy, - "Absolute energy difference " + - str(energy_abs_diff) + - " too large for " + - method_name) + self.assertAlmostEqual( + self.S.analysis.energy()["total"], + self.reference_energy, delta=self.tolerance_energy, + msg="Absolute energy difference too large for " + method_name) self.assertLessEqual( - rms_force_diff, - self.tolerance_force, - "Absolute force difference " + - str(rms_force_diff) + - " too large for method " + - method_name) + rms_force_diff, self.tolerance_force, + "Absolute force difference too large for method " + method_name) # Tests for individual methods diff --git a/testsuite/python/coulomb_tuning.py b/testsuite/python/coulomb_tuning.py index cfd198e95fc..2250356f72d 100644 --- a/testsuite/python/coulomb_tuning.py +++ b/testsuite/python/coulomb_tuning.py @@ -60,12 +60,8 @@ def compare(self, method_name): force_abs_diff += np.linalg.norm(p.f - self.forces[p.id]) force_abs_diff /= len(self.system.part) self.assertLessEqual( - force_abs_diff, - self.tolerance, - "Absolute force difference " + - str(force_abs_diff) + - " too large for method " + - method_name) + force_abs_diff, self.tolerance, + "Absolute force difference too large for method " + method_name) # Tests for individual methods @utx.skipIfMissingFeatures(["P3M"]) diff --git a/testsuite/python/dpd.py b/testsuite/python/dpd.py index 5c2886cdb40..7acf8391cc0 100644 --- a/testsuite/python/dpd.py +++ b/testsuite/python/dpd.py @@ -58,18 +58,16 @@ def check_velocity_distribution(self, vel, minmax, n_bins, error_tol, kT): for j in range(n_bins): found = data[j] expected = single_component_maxwell(bins[j], bins[j + 1], kT) - self.assertLessEqual(abs(found - expected), error_tol) + self.assertAlmostEqual(found, expected, delta=error_tol) def test_aa_verify_single_component_maxwell(self): """Verifies the normalization of the analytical expression.""" - self.assertLessEqual( - abs(single_component_maxwell(-10, 10, 4.) - 1.), 1E-4) + self.assertAlmostEqual( + single_component_maxwell(-10, 10, 4.), 1., delta=1E-4) def check_total_zero(self): v_total = np.sum(self.s.part[:].v, axis=0) - self.assertLess(v_total[0], 1e-11) - self.assertLess(v_total[1], 1e-11) - self.assertLess(v_total[2], 1e-11) + np.testing.assert_allclose(v_total, np.zeros(3), atol=1e-11) def single(self, with_langevin=False): """Test velocity distribution of a dpd fluid with a single type.""" @@ -162,7 +160,7 @@ def test_disable(self): # Check that there was neither noise nor friction for v in s.part[:].v: for i in range(3): - self.assertTrue(v[i] == float(i + 1)) + self.assertEqual(v[i], float(i + 1)) # Turn back on s.thermostat.set_dpd(kT=kT, seed=42) @@ -194,16 +192,14 @@ def test_const_weight_function(self): trans_weight_function=0, trans_gamma=gamma, trans_r_cut=1.4) s.part.add(id=0, pos=[5, 5, 5], type=0, v=[0, 0, 0]) - v = [.5, .8, .3] + v = np.array([.5, .8, .3]) s.part.add(id=1, pos=[3, 5, 5], type=0, v=v) s.integrator.run(0) # Outside of both cutoffs, forces should be 0 for f in s.part[:].f: - self.assertTrue(f[0] == 0.) - self.assertTrue(f[1] == 0.) - self.assertTrue(f[2] == 0.) + np.testing.assert_array_equal(f, [0., 0., 0.]) # Only trans s.part[1].pos = [5. - 1.3, 5, 5] @@ -212,25 +208,20 @@ def test_const_weight_function(self): # Only trans, so x component should be zero self.assertLess(abs(s.part[0].f[0]), 1e-16) - # f = gamma * v_ij - self.assertLess(abs(s.part[0].f[1] - gamma * v[1]), 1e-11) - self.assertLess(abs(s.part[0].f[2] - gamma * v[2]), 1e-11) - # Momentum conservation - self.assertLess(abs(s.part[1].f[0]), 1e-16) - self.assertLess(abs(s.part[1].f[1] + gamma * v[1]), 1e-11) - self.assertLess(abs(s.part[1].f[2] + gamma * v[2]), 1e-11) + np.testing.assert_allclose( + np.copy(s.part[0].f[1:2]), gamma * v[1:2], rtol=0, atol=1e-11) + np.testing.assert_array_equal( + np.copy(s.part[0].f), -np.copy(s.part[1].f)) # Trans and parallel s.part[1].pos = [5. - 1.1, 5, 5] s.integrator.run(0) - self.assertLess(abs(s.part[0].f[0] - gamma * v[0]), 1e-11) - self.assertLess(abs(s.part[0].f[1] - gamma * v[1]), 1e-11) - self.assertLess(abs(s.part[0].f[2] - gamma * v[2]), 1e-11) - self.assertLess(abs(s.part[1].f[0] + gamma * v[0]), 1e-11) - self.assertLess(abs(s.part[1].f[1] + gamma * v[1]), 1e-11) - self.assertLess(abs(s.part[1].f[2] + gamma * v[2]), 1e-11) + np.testing.assert_allclose( + np.copy(s.part[0].f), gamma * v, rtol=0, atol=1e-11) + np.testing.assert_array_equal( + np.copy(s.part[0].f), -np.copy(s.part[1].f)) def test_linear_weight_function(self): s = self.s @@ -241,20 +232,18 @@ def test_linear_weight_function(self): weight_function=1, gamma=gamma, r_cut=1.2, trans_weight_function=1, trans_gamma=gamma, trans_r_cut=1.4) - def omega(dist, r_cut): + def calc_omega(dist, r_cut): return 1. - dist / r_cut s.part.add(id=0, pos=[5, 5, 5], type=0, v=[0, 0, 0]) - v = [.5, .8, .3] + v = np.array([.5, .8, .3]) s.part.add(id=1, pos=[3, 5, 5], type=0, v=v) s.integrator.run(0) # Outside of both cutoffs, forces should be 0 for f in s.part[:].f: - self.assertTrue(f[0] == 0.) - self.assertTrue(f[1] == 0.) - self.assertTrue(f[2] == 0.) + np.testing.assert_array_equal(f, [0., 0., 0.]) # Only trans s.part[1].pos = [5. - 1.3, 5, 5] @@ -263,53 +252,33 @@ def omega(dist, r_cut): # Only trans, so x component should be zero self.assertLess(abs(s.part[0].f[0]), 1e-16) - # f = gamma * v_ij - self.assertLess( - abs(s.part[0].f[1] - omega(1.3, 1.4)**2 * gamma * v[1]), 1e-11) - self.assertLess( - abs(s.part[0].f[2] - omega(1.3, 1.4)**2 * gamma * v[2]), 1e-11) - # Momentum conservation - self.assertLess(abs(s.part[1].f[0]), 1e-16) - self.assertLess( - abs(s.part[1].f[1] + omega(1.3, 1.4)**2 * gamma * v[1]), 1e-11) - self.assertLess( - abs(s.part[1].f[2] + omega(1.3, 1.4)**2 * gamma * v[2]), 1e-11) + omega = calc_omega(1.3, 1.4)**2 + np.testing.assert_allclose( + np.copy(s.part[0].f[1:2]), omega * gamma * v[1:2], rtol=0, atol=1e-11) + np.testing.assert_array_equal( + np.copy(s.part[0].f), -np.copy(s.part[1].f)) # Trans and parallel s.part[1].pos = [5. - 1.1, 5, 5] s.integrator.run(0) - self.assertLess( - abs(s.part[0].f[0] - omega(1.1, 1.2)**2 * gamma * v[0]), 1e-11) - self.assertLess( - abs(s.part[0].f[1] - omega(1.1, 1.4)**2 * gamma * v[1]), 1e-11) - self.assertLess( - abs(s.part[0].f[2] - omega(1.1, 1.4)**2 * gamma * v[2]), 1e-11) - self.assertLess( - abs(s.part[1].f[0] + omega(1.1, 1.2)**2 * gamma * v[0]), 1e-11) - self.assertLess( - abs(s.part[1].f[1] + omega(1.1, 1.4)**2 * gamma * v[1]), 1e-11) - self.assertLess( - abs(s.part[1].f[2] + omega(1.1, 1.4)**2 * gamma * v[2]), 1e-11) + omega = np.array([calc_omega(1.1, x)**2 for x in [1.2, 1.4, 1.4]]) + np.testing.assert_allclose( + np.copy(s.part[0].f), omega * gamma * v, rtol=0, atol=1e-11) + np.testing.assert_array_equal( + np.copy(s.part[0].f), -np.copy(s.part[1].f)) # Trans and parallel 2nd point s.part[1].pos = [5. - 0.5, 5, 5] s.integrator.run(0) - self.assertLess( - abs(s.part[0].f[0] - omega(0.5, 1.2)**2 * gamma * v[0]), 1e-11) - self.assertLess( - abs(s.part[0].f[1] - omega(0.5, 1.4)**2 * gamma * v[1]), 1e-11) - self.assertLess( - abs(s.part[0].f[2] - omega(0.5, 1.4)**2 * gamma * v[2]), 1e-11) - self.assertLess( - abs(s.part[1].f[0] + omega(0.5, 1.2)**2 * gamma * v[0]), 1e-11) - self.assertLess( - abs(s.part[1].f[1] + omega(0.5, 1.4)**2 * gamma * v[1]), 1e-11) - self.assertLess( - abs(s.part[1].f[2] + omega(0.5, 1.4)**2 * gamma * v[2]), 1e-11) + omega = np.array([calc_omega(0.5, x)**2 for x in [1.2, 1.4, 1.4]]) + np.testing.assert_allclose( + np.copy(s.part[0].f), omega * gamma * v, rtol=0, atol=1e-11) + np.testing.assert_array_equal( + np.copy(s.part[0].f), -np.copy(s.part[1].f)) def test_ghosts_have_v(self): s = self.s @@ -429,32 +398,31 @@ def calc_stress(dist, vel_diff): s.part.add(pos=pos) s.integrator.run(10) - s.thermostat.set_dpd(kT=0.0) + for kT in [0., 2.]: + s.thermostat.set_dpd(kT=kT) + # run 1 integration step to get velocities + s.part[:].v = np.zeros((n_part, 3)) + s.integrator.run(steps=1) - s.integrator.run(steps=0, recalc_forces=True) + pairs = s.part.pairs() - pairs = s.part.pairs() + stress = np.zeros([3, 3]) - stress = np.zeros([3, 3]) + for pair in pairs: + dist = s.distance_vec(pair[0], pair[1]) + if np.linalg.norm(dist) < r_cut: + vel_diff = pair[1].v - pair[0].v + stress += calc_stress(dist, vel_diff) - for pair in pairs: - dist = s.distance_vec(pair[0], pair[1]) - if np.linalg.norm(dist) < r_cut: - vel_diff = pair[1].v - pair[0].v - stress += calc_stress(dist, vel_diff) + stress /= np.prod(np.copy(s.box_l)) - stress /= s.box_l[0] ** 3.0 + dpd_stress = s.analysis.dpd_stress() - dpd_stress = s.analysis.dpd_stress() + dpd_obs = DPDStress() + obs_stress = np.array(dpd_obs.calculate()).reshape((3, 3)) - dpd_obs = DPDStress() - obs_stress = dpd_obs.calculate() - obs_stress = np.array([[obs_stress[0], obs_stress[1], obs_stress[2]], - [obs_stress[3], obs_stress[4], obs_stress[5]], - [obs_stress[6], obs_stress[7], obs_stress[8]]]) - - np.testing.assert_array_almost_equal(np.copy(dpd_stress), stress) - np.testing.assert_array_almost_equal(np.copy(obs_stress), stress) + np.testing.assert_array_almost_equal(np.copy(dpd_stress), stress) + np.testing.assert_array_almost_equal(np.copy(obs_stress), stress) def test_momentum_conservation(self): r_cut = 1.0 diff --git a/testsuite/python/ek_charged_plate.py b/testsuite/python/ek_charged_plate.py index 09bac464366..e84efafd798 100644 --- a/testsuite/python/ek_charged_plate.py +++ b/testsuite/python/ek_charged_plate.py @@ -91,7 +91,6 @@ def test(self): if abs(expected_force - particle_force[0]) > force_difference: force_difference = abs(expected_force - particle_force[0]) - print("Force deviation: {}".format(force_difference)) self.assertLess(force_difference, 1.0e-04, "Force accuracy in X not achieved, allowed deviation: " "1.0e-04, measured: {}".format(force_difference)) @@ -123,7 +122,6 @@ def test(self): if abs(expected_force - particle_force[1]) > force_difference: force_difference = abs(expected_force - particle_force[1]) - print("Force deviation: {}".format(force_difference)) self.assertLess(force_difference, 1.0e-04, "Force accuracy in Y not achieved, allowed deviation: " "1.0e-04, measured: {}".format(force_difference)) @@ -155,7 +153,6 @@ def test(self): if abs(expected_force - particle_force[2]) > force_difference: force_difference = abs(expected_force - particle_force[2]) - print("Force deviation: {}".format(force_difference)) self.assertLess(force_difference, 1.0e-04, "Force accuracy in Z not achieved, allowed deviation: " "1.0e-04, measured: {}".format(force_difference)) diff --git a/testsuite/python/elc_and_mmm2d_vs_analytic.py b/testsuite/python/elc_and_mmm2d_vs_analytic.py index 6a0d60b1cb5..e322fa5dbef 100644 --- a/testsuite/python/elc_and_mmm2d_vs_analytic.py +++ b/testsuite/python/elc_and_mmm2d_vs_analytic.py @@ -97,11 +97,11 @@ def test_elc_and_mmm2d(self): analytic_results = np.dstack((analytic_force, analytic_energy)) - self.assertTrue(np.testing.assert_allclose( - mmm2d_results, analytic_results, rtol=0, atol=self.check_accuracy) is None) + np.testing.assert_allclose( + mmm2d_results, analytic_results, rtol=0, atol=self.check_accuracy) - self.assertTrue(np.testing.assert_allclose( - elc_results, analytic_results, rtol=0, atol=self.check_accuracy) is None) + np.testing.assert_allclose( + elc_results, analytic_results, rtol=0, atol=self.check_accuracy) def scan(self): result_array = np.empty((len(self.q), len(self.zPos), 2)) diff --git a/testsuite/python/elc_vs_mmm2d_neutral.py b/testsuite/python/elc_vs_mmm2d_neutral.py index 8ea062cd90e..bdc8ac515a1 100644 --- a/testsuite/python/elc_vs_mmm2d_neutral.py +++ b/testsuite/python/elc_vs_mmm2d_neutral.py @@ -148,8 +148,8 @@ def test_elc_vs_mmm2d(self): elc_res["const_pot_m1"] = self.scan() for run in elc_res: - self.assertTrue(np.testing.assert_allclose( - mmm2d_res[run], elc_res[run], rtol=0, atol=1e-4) is None) + np.testing.assert_allclose( + mmm2d_res[run], elc_res[run], rtol=0, atol=1e-4) def scan(self): n = 10 diff --git a/testsuite/python/elc_vs_mmm2d_nonneutral.py b/testsuite/python/elc_vs_mmm2d_nonneutral.py index 6ed78d64a02..b1355b7ed86 100644 --- a/testsuite/python/elc_vs_mmm2d_nonneutral.py +++ b/testsuite/python/elc_vs_mmm2d_nonneutral.py @@ -135,8 +135,8 @@ def test_elc_vs_mmm2d(self): # elc_res["const_pot_m1"] = self.scan() for run in elc_res: - self.assertTrue(np.testing.assert_allclose( - mmm2d_res[run], elc_res[run], rtol=0, atol=1e-4) is None) + np.testing.assert_allclose( + mmm2d_res[run], elc_res[run], rtol=0, atol=1e-4) def scan(self): n = 10 diff --git a/testsuite/python/exclusions.py b/testsuite/python/exclusions.py index 8ea7eb3f3dd..023ca82b26f 100644 --- a/testsuite/python/exclusions.py +++ b/testsuite/python/exclusions.py @@ -40,9 +40,9 @@ def test_add_remove(self): self.s.part[0].add_exclusion(1) self.s.part[0].add_exclusion(2) - self.assertTrue((self.s.part[0].exclusions == [1, 2]).all()) + self.assertEqual(list(self.s.part[0].exclusions), [1, 2]) self.s.part[0].delete_exclusion(1) - self.assertEqual(self.s.part[0].exclusions, [2]) + self.assertEqual(list(self.s.part[0].exclusions), [2]) self.s.part[0].delete_exclusion(2) self.assertEqual(list(self.s.part[0].exclusions), []) @@ -56,7 +56,7 @@ def test_transfer(self): for _ in range(15): self.s.integrator.run(100) - self.assertTrue((self.s.part[0].exclusions == [1, 2, 3]).all()) + self.assertEqual(list(self.s.part[0].exclusions), [1, 2, 3]) @utx.skipIfMissingFeatures(['LENNARD_JONES']) def test_particle_property(self): diff --git a/testsuite/python/h5md.py b/testsuite/python/h5md.py index 3657677acd4..370ef83151d 100644 --- a/testsuite/python/h5md.py +++ b/testsuite/python/h5md.py @@ -83,32 +83,32 @@ def test_metadata(self): def test_pos(self): """Test if positions have been written properly.""" - self.assertTrue(np.allclose( + np.testing.assert_allclose( np.array([3 * [float(i) % self.box_l] for i in range(npart)]), - np.array([x for (_, x) in sorted(zip(self.py_id, self.py_pos))]))) + np.array([x for (_, x) in sorted(zip(self.py_id, self.py_pos))])) def test_img(self): """Test if images have been written properly.""" images = np.append(np.zeros((int(npart / 2), 3)), np.ones((int(npart / 2), 3))) images = images.reshape(npart, 3) - self.assertTrue((np.allclose(np.array( - [x for (_, x) in sorted(zip(self.py_id, self.py_img))]), images))) + np.testing.assert_allclose( + [x for (_, x) in sorted(zip(self.py_id, self.py_img))], images) def test_vel(self): """Test if velocities have been written properly.""" - self.assertTrue(np.allclose( + np.testing.assert_allclose( np.array([[1.0, 2.0, 3.0] for _ in range(npart)]), - np.array([x for (_, x) in sorted(zip(self.py_id, self.py_vel))])), - msg="Velocities not written correctly by H5md!") + np.array([x for (_, x) in sorted(zip(self.py_id, self.py_vel))]), + err_msg="Velocities not written correctly by H5md!") @utx.skipIfMissingFeatures(['EXTERNAL_FORCES']) def test_f(self): """Test if forces have been written properly.""" - self.assertTrue(np.allclose( + np.testing.assert_allclose( np.array([[0.1, 0.2, 0.3] for _ in range(npart)]), - np.array([x for (_, x) in sorted(zip(self.py_id, self.py_f))])), - msg="Forces not written correctly by H5md!") + np.array([x for (_, x) in sorted(zip(self.py_id, self.py_f))]), + err_msg="Forces not written correctly by H5md!") def test_bonds(self): """Test if bonds have been written properly.""" @@ -156,8 +156,8 @@ def tearDownClass(cls): def test_ids(self): """Test if ids have been written properly.""" - self.assertTrue(np.allclose(np.array(range(npart)), self.py_id), - msg="ids incorrectly ordered and written by H5md!") + np.testing.assert_allclose(np.array(range(npart)), self.py_id, + err_msg="ids incorrectly ordered and written by H5md!") @utx.skipIfMissingFeatures(['H5MD']) diff --git a/testsuite/python/interactions_bonded_interface.py b/testsuite/python/interactions_bonded_interface.py index a9df7e0d85a..d5d3309a24c 100644 --- a/testsuite/python/interactions_bonded_interface.py +++ b/testsuite/python/interactions_bonded_interface.py @@ -17,6 +17,8 @@ # along with this program. If not, see . # import unittest as ut +from tests_common import assert_params_match + import espressomd @@ -26,24 +28,13 @@ class ParticleProperties(ut.TestCase): # Particle id to work on pid = 17 - # Error tolerance when comparing arrays/tuples... - tol = 1E-9 - - def bondsMatch(self, inType, outType, inParams, outParams): + def bondsMatch(self, inType, outBond, inParams, outParams, msg_long): """Check, if the bond type set and gotten back as well as the bond parameters set and gotten back match. Only check keys present in ``inParams``. """ - if inType != outType: - return False - - for k in list(inParams.keys()): - if k not in outParams: - return False - if outParams[k] != inParams[k]: - return False - - return True + self.assertEqual(outBond, inType, msg="Bonded interaction mismatch") + assert_params_match(self, inParams, outParams, msg_long) def parameterKeys(self, bondObject): """ @@ -114,19 +105,10 @@ def func(self): tnIn = bondClass(**params).type_number() tnOut = outBond.type_number() outParams = outBond.params - self.assertTrue( - self.bondsMatch( - tnIn, - tnOut, - params, - outParams), - bondClass(**params).type_name() + - ": value set and value gotten back differ for bond id " + - str(bondId) + - ": " + - params.__str__() + - " vs. " + - outParams.__str__()) + self.bondsMatch( + tnIn, tnOut, params, outParams, + "{}: value set and value gotten back differ for bond id {}: {} vs. {}" + .format(bondClass(**params).type_name(), bondId, params, outParams)) self.parameterKeys(outBond) return func diff --git a/testsuite/python/interactions_non-bonded.py b/testsuite/python/interactions_non-bonded.py index 804ed735a99..c5d69dd16fe 100644 --- a/testsuite/python/interactions_non-bonded.py +++ b/testsuite/python/interactions_non-bonded.py @@ -92,8 +92,8 @@ def test_lj_generic(self): E_sim = self.system.analysis.energy()["non_bonded"] # Calculate forces - f0_sim = self.system.part[0].f - f1_sim = self.system.part[1].f + f0_sim = np.copy(self.system.part[0].f) + f1_sim = np.copy(self.system.part[1].f) f1_ref = self.axis * tests_common.lj_generic_force( espressomd, r=(i + 1) * self.step_width, eps=lj_eps, sig=lj_sig, cutoff=lj_cut, offset=lj_off, b1=lj_b1, b2=lj_b2, e1=lj_e1, @@ -102,7 +102,7 @@ def test_lj_generic(self): # Check that energies match, ... self.assertFractionAlmostEqual(E_sim, E_ref[i]) # force equals minus the counter-force ... - self.assertTrue((f0_sim == -f1_sim).all()) + np.testing.assert_array_equal(f0_sim, -f1_sim) # and has correct value. self.assertItemsFractionAlmostEqual(f1_sim, f1_ref) @@ -133,15 +133,15 @@ def test_wca(self): E_sim = self.system.analysis.energy()["non_bonded"] # Calculate forces - f0_sim = self.system.part[0].f - f1_sim = self.system.part[1].f + f0_sim = np.copy(self.system.part[0].f) + f1_sim = np.copy(self.system.part[1].f) f1_ref = self.axis * tests_common.lj_generic_force( espressomd, r=(i + 1) * self.step_width, eps=wca_eps, sig=wca_sig, cutoff=wca_cutoff) # Check that energies match, ... self.assertFractionAlmostEqual(E_sim, E_ref[i]) # force equals minus the counter-force ... - self.assertTrue((f0_sim == -f1_sim).all()) + np.testing.assert_array_equal(f0_sim, -f1_sim) # and has correct value. self.assertItemsFractionAlmostEqual(f1_sim, f1_ref) @@ -180,8 +180,8 @@ def test_lj_generic_softcore(self): e2=lj_e2, shift=lj_shift, delta=lj_delta, lam=lj_lam) # Calculate forces - f0_sim = self.system.part[0].f - f1_sim = self.system.part[1].f + f0_sim = np.copy(self.system.part[0].f) + f1_sim = np.copy(self.system.part[1].f) f1_ref = self.axis * tests_common.lj_generic_force( espressomd, r=(i + 1) * self.step_width, eps=lj_eps, sig=lj_sig, cutoff=lj_cut, offset=lj_off, b1=lj_b1, b2=lj_b2, e1=lj_e1, @@ -190,7 +190,7 @@ def test_lj_generic_softcore(self): # Check that energies match, ... self.assertFractionAlmostEqual(E_sim, E_ref) # force equals minus the counter-force ... - self.assertTrue((f0_sim == -f1_sim).all()) + np.testing.assert_array_equal(f0_sim, -f1_sim) # and has correct value. self.assertItemsFractionAlmostEqual(f1_sim, f1_ref) @@ -220,8 +220,8 @@ def test_lj(self): shift=lj_shift) # Calculate forces - f0_sim = self.system.part[0].f - f1_sim = self.system.part[1].f + f0_sim = np.copy(self.system.part[0].f) + f1_sim = np.copy(self.system.part[1].f) f1_ref = self.axis * \ tests_common.lj_force(espressomd, r=(i + 1) * self.step_width, eps=lj_eps, sig=lj_sig, cutoff=lj_cut) @@ -229,7 +229,7 @@ def test_lj(self): # Check that energies match, ... self.assertFractionAlmostEqual(E_sim, E_ref) # force equals minus the counter-force ... - self.assertTrue((f0_sim == -f1_sim).all()) + np.testing.assert_array_equal(f0_sim, -f1_sim) # and has correct value. self.assertItemsFractionAlmostEqual(f1_sim, f1_ref) @@ -259,8 +259,8 @@ def test_lj_cos(self): cutoff=ljcos_cut, offset=ljcos_offset) # Calculate forces - f0_sim = self.system.part[0].f - f1_sim = self.system.part[1].f + f0_sim = np.copy(self.system.part[0].f) + f1_sim = np.copy(self.system.part[1].f) f1_ref = self.axis * tests_common.lj_cos_force( espressomd, (i + 1) * self.step_width, eps=ljcos_eps, sig=ljcos_sig, cutoff=ljcos_cut, offset=ljcos_offset) @@ -268,7 +268,7 @@ def test_lj_cos(self): # Check that energies match, ... self.assertFractionAlmostEqual(E_sim, E_ref) # force equals minus the counter-force ... - self.assertTrue((f0_sim == -f1_sim).all()) + np.testing.assert_array_equal(f0_sim, -f1_sim) # and has correct value. self.assertItemsFractionAlmostEqual(f1_sim, f1_ref) @@ -299,8 +299,8 @@ def test_lj_cos2(self): offset=ljcos2_offset, width=ljcos2_width) # Calculate forces - f0_sim = self.system.part[0].f - f1_sim = self.system.part[1].f + f0_sim = np.copy(self.system.part[0].f) + f1_sim = np.copy(self.system.part[1].f) f1_ref = self.axis * tests_common.lj_cos2_force( espressomd, r=(i + 1) * self.step_width, eps=ljcos2_eps, sig=ljcos2_sig, offset=ljcos2_offset, width=ljcos2_width) @@ -308,7 +308,7 @@ def test_lj_cos2(self): # Check that energies match, ... self.assertFractionAlmostEqual(E_sim, E_ref) # force equals minus the counter-force ... - self.assertTrue((f0_sim == -f1_sim).all()) + np.testing.assert_array_equal(f0_sim, -f1_sim) # and has correct value. self.assertItemsFractionAlmostEqual(f1_sim, f1_ref) @@ -341,8 +341,8 @@ def test_smooth_step(self): cutoff=sst_cut, d=sst_d, n=sst_n, k0=sst_k0) # Calculate forces - f0_sim = self.system.part[0].f - f1_sim = self.system.part[1].f + f0_sim = np.copy(self.system.part[0].f) + f1_sim = np.copy(self.system.part[1].f) f1_ref = self.axis * tests_common.smooth_step_force( r=(i + 1) * self.step_width, eps=sst_eps, sig=sst_sig, cutoff=sst_cut, d=sst_d, n=sst_n, k0=sst_k0) @@ -350,7 +350,7 @@ def test_smooth_step(self): # Check that energies match, ... self.assertFractionAlmostEqual(E_sim, E_ref) # force equals minus the counter-force ... - self.assertTrue((f0_sim == -f1_sim).all()) + np.testing.assert_array_equal(f0_sim, -f1_sim) # and has correct value. self.assertItemsFractionAlmostEqual(f1_sim, f1_ref) @@ -382,8 +382,8 @@ def test_bmhtf(self): d=bmhtf_d, sig=bmhtf_sig, cutoff=bmhtf_cut) # Calculate forces - f0_sim = self.system.part[0].f - f1_sim = self.system.part[1].f + f0_sim = np.copy(self.system.part[0].f) + f1_sim = np.copy(self.system.part[1].f) f1_ref = self.axis * tests_common.bmhtf_force( r=(i + 1) * self.step_width, a=bmhtf_a, b=bmhtf_b, c=bmhtf_c, d=bmhtf_d, sig=bmhtf_sig, cutoff=bmhtf_cut) @@ -391,7 +391,7 @@ def test_bmhtf(self): # Check that energies match, ... self.assertFractionAlmostEqual(E_sim, E_ref) # force equals minus the counter-force ... - self.assertTrue((f0_sim == -f1_sim).all()) + np.testing.assert_array_equal(f0_sim, -f1_sim) # and has correct value. self.assertItemsFractionAlmostEqual(f1_sim, f1_ref) @@ -420,8 +420,8 @@ def test_morse(self): cutoff=m_cut, rmin=m_rmin) # Calculate forces - f0_sim = self.system.part[0].f - f1_sim = self.system.part[1].f + f0_sim = np.copy(self.system.part[0].f) + f1_sim = np.copy(self.system.part[1].f) f1_ref = self.axis * tests_common.morse_force( r=(i + 1) * self.step_width, eps=m_eps, alpha=m_alpha, cutoff=m_cut, rmin=m_rmin) @@ -429,7 +429,7 @@ def test_morse(self): # Check that energies match, ... self.assertFractionAlmostEqual(E_sim, E_ref) # force equals minus the counter-force ... - self.assertTrue((f0_sim == -f1_sim).all()) + np.testing.assert_array_equal(f0_sim, -f1_sim) # and has correct value. self.assertItemsFractionAlmostEqual(f1_sim, f1_ref) @@ -462,8 +462,8 @@ def test_buckingham(self): discont=b_disc, cutoff=b_cut, shift=b_shift) # Calculate forces - f0_sim = self.system.part[0].f - f1_sim = self.system.part[1].f + f0_sim = np.copy(self.system.part[0].f) + f1_sim = np.copy(self.system.part[1].f) f1_ref = self.axis * tests_common.buckingham_force( r=(i + 1) * self.step_width, a=b_a, b=b_b, c=b_c, d=b_d, discont=b_disc, cutoff=b_cut, shift=b_shift) @@ -471,7 +471,7 @@ def test_buckingham(self): # Check that energies match, ... self.assertFractionAlmostEqual(E_sim, E_ref) # force equals minus the counter-force ... - self.assertTrue((f0_sim == -f1_sim).all()) + np.testing.assert_array_equal(f0_sim, -f1_sim) # and has correct value. self.assertItemsFractionAlmostEqual(f1_sim, f1_ref) @@ -502,8 +502,8 @@ def test_soft_sphere(self): offset=ss_off) # Calculate forces - f0_sim = self.system.part[0].f - f1_sim = self.system.part[1].f + f0_sim = np.copy(self.system.part[0].f) + f1_sim = np.copy(self.system.part[1].f) f1_ref = self.axis * tests_common.soft_sphere_force( r=(i + 13) * self.step_width, a=ss_a, n=ss_n, cutoff=ss_cut, offset=ss_off) @@ -511,7 +511,7 @@ def test_soft_sphere(self): # Check that energies match, ... self.assertFractionAlmostEqual(E_sim, E_ref) # force equals minus the counter-force ... - self.assertTrue((f0_sim == -f1_sim).all()) + np.testing.assert_array_equal(f0_sim, -f1_sim) # and has correct value. self.assertItemsFractionAlmostEqual(f1_sim, f1_ref) @@ -537,15 +537,15 @@ def test_hertzian(self): r=(i + 1) * self.step_width, eps=h_eps, sig=h_sig) # Calculate forces - f0_sim = self.system.part[0].f - f1_sim = self.system.part[1].f + f0_sim = np.copy(self.system.part[0].f) + f1_sim = np.copy(self.system.part[1].f) f1_ref = self.axis * tests_common.hertzian_force( r=(i + 1) * self.step_width, eps=h_eps, sig=h_sig) # Check that energies match, ... self.assertFractionAlmostEqual(E_sim, E_ref) # force equals minus the counter-force ... - self.assertTrue((f0_sim == -f1_sim).all()) + np.testing.assert_array_equal(f0_sim, -f1_sim) # and has correct value. self.assertItemsFractionAlmostEqual(f1_sim, f1_ref) @@ -572,15 +572,15 @@ def test_gaussian(self): r=(i + 1) * self.step_width, eps=g_eps, sig=g_sig, cutoff=g_cut) # Calculate forces - f0_sim = self.system.part[0].f - f1_sim = self.system.part[1].f + f0_sim = np.copy(self.system.part[0].f) + f1_sim = np.copy(self.system.part[1].f) f1_ref = self.axis * tests_common.gaussian_force( r=(i + 1) * self.step_width, eps=g_eps, sig=g_sig, cutoff=g_cut) # Check that energies match, ... self.assertFractionAlmostEqual(E_sim, E_ref) # force equals minus the counter-force ... - self.assertTrue((f0_sim == -f1_sim).all()) + np.testing.assert_array_equal(f0_sim, -f1_sim) # and has correct value. self.assertItemsFractionAlmostEqual(f1_sim, f1_ref) @@ -696,12 +696,12 @@ def get_reference_torque(gb_params, r, dir1, dir2): self.assertAlmostEqual(E_sim, E_ref, delta=delta) # Calc forces - f1_sim = p1.f - f2_sim = p2.f + f1_sim = np.copy(p1.f) + f2_sim = np.copy(p2.f) f2_ref = get_reference_force(gb_params, r, director1, director2) # Test forces # force equals minus the counter-force - self.assertTrue((f1_sim == -f2_sim).all()) + np.testing.assert_array_equal(f1_sim, -f2_sim) # compare force to reference force for i in range(3): self.assertAlmostEqual(f2_sim[i], f2_ref[i], delta=delta) diff --git a/testsuite/python/interactions_non-bonded_interface.py b/testsuite/python/interactions_non-bonded_interface.py index 680625f0260..c354993d663 100644 --- a/testsuite/python/interactions_non-bonded_interface.py +++ b/testsuite/python/interactions_non-bonded_interface.py @@ -17,6 +17,7 @@ # along with this program. If not, see . # import unittest as ut +from tests_common import assert_params_match import espressomd import espressomd.interactions @@ -25,24 +26,13 @@ class Non_bonded_interactionsTests(ut.TestCase): system = espressomd.System(box_l=[20.0, 20.0, 20.0]) - def intersMatch(self, inType, outType, inParams, outParams): + def intersMatch(self, inType, outInter, inParams, outParams, msg_long): """Check, if the interaction type set and gotten back as well as the bond parameters set and gotten back match. Only check keys present in ``inParams``. """ - if inType != outType: - print("Type mismatch:", inType, outType) - return False - - for k in list(inParams.keys()): - if k not in outParams: - print(k, "missing from returned parameters") - return False - if outParams[k] != inParams[k]: - print("Mismatch in parameter ", k, inParams[k], outParams[k]) - return False - - return True + self.assertIsInstance(outInter, inType) + assert_params_match(self, inParams, outParams, msg_long) def parameterKeys(self, interObject): """ @@ -116,21 +106,11 @@ def func(self): self.system.non_bonded_inter[partType1, partType2], interName) outParams = outInter.get_params() - self.assertTrue( - self.intersMatch( - interClass, - type(outInter), - params, - outParams), - interClass(**params).type_name() + - ": value set and value gotten back differ for particle types " + - str(partType1) + - " and " + - str(partType2) + - ": " + - params.__str__() + - " vs. " + - outParams.__str__()) + self.intersMatch( + interClass, outInter, params, outParams, + "{}: value set and value gotten back differ for particle types {} and {}: {} vs. {}" + .format(interClass(**params).type_name(), partType1, partType2, + params, outParams)) self.parameterKeys(outInter) return func diff --git a/testsuite/python/langevin_thermostat.py b/testsuite/python/langevin_thermostat.py index eb39a2c84e1..f75296b5f09 100644 --- a/testsuite/python/langevin_thermostat.py +++ b/testsuite/python/langevin_thermostat.py @@ -53,12 +53,12 @@ def check_velocity_distribution(self, vel, minmax, n_bins, error_tol, kT): for j in range(n_bins): found = data[j] expected = single_component_maxwell(bins[j], bins[j + 1], kT) - self.assertLessEqual(abs(found - expected), error_tol) + self.assertAlmostEqual(found, expected, delta=error_tol) def test_00_verify_single_component_maxwell(self): """Verifies the normalization of the analytical expression.""" - self.assertLessEqual( - abs(single_component_maxwell(-10, 10, 4.) - 1.), 1E-4) + self.assertAlmostEqual( + single_component_maxwell(-10, 10, 4.), 1., delta=1E-4) def test_01__langevin_seed(self): """Test for RNG seed consistency.""" diff --git a/testsuite/python/lb_boundary.py b/testsuite/python/lb_boundary.py index 8f9c139d893..2e4c7033026 100644 --- a/testsuite/python/lb_boundary.py +++ b/testsuite/python/lb_boundary.py @@ -46,8 +46,8 @@ def test_remove(self): lbb.remove(b1) - self.assertFalse(b1 in lbb) - self.assertTrue(b2 in lbb) + self.assertNotIn(b1, lbb) + self.assertIn(b2, lbb) def test_size(self): lbb = self.system.lbboundaries diff --git a/testsuite/python/lb_thermostat.py b/testsuite/python/lb_thermostat.py index 31c6c9de82e..10712a0776a 100644 --- a/testsuite/python/lb_thermostat.py +++ b/testsuite/python/lb_thermostat.py @@ -76,7 +76,7 @@ def test_velocity_distribution(self): for j in range(n_bins): found = data[j] expected = single_component_maxwell(bins[j], bins[j + 1], KT) - self.assertLessEqual(abs(found - expected), error_tol) + self.assertAlmostEqual(found, expected, delta=error_tol) class LBCPUThermostat(ut.TestCase, LBThermostatCommon): diff --git a/testsuite/python/mass-and-rinertia_per_particle.py b/testsuite/python/mass-and-rinertia_per_particle.py index b1f2f21146c..036877bc0cf 100644 --- a/testsuite/python/mass-and-rinertia_per_particle.py +++ b/testsuite/python/mass-and-rinertia_per_particle.py @@ -252,11 +252,17 @@ def check_dissipation(self, n): # reference while gamma_tr is defined in the body one. # Hence, only isotropic gamma_tran_p_validate could be # tested here. - self.assertLess(abs( - self.system.part[ind].v[j] - math.exp(- self.gamma_tran_p_validate[k, j] * self.system.time / self.mass)), tol) + self.assertAlmostEqual( + self.system.part[ind].v[j], + math.exp(- self.gamma_tran_p_validate[k, j] + * self.system.time / self.mass), + delta=tol) if espressomd.has_features("ROTATION"): - self.assertLess(abs( - self.system.part[ind].omega_body[j] - math.exp(- self.gamma_rot_p_validate[k, j] * self.system.time / self.J[j])), tol) + self.assertAlmostEqual( + self.system.part[ind].omega_body[j], + math.exp(- self.gamma_rot_p_validate[k, j] + * self.system.time / self.J[j]), + delta=tol) def check_fluctuation_dissipation(self, n): """ diff --git a/testsuite/python/mmm1d.py b/testsuite/python/mmm1d.py index 4768ff15b5a..94d1e3ff6c9 100644 --- a/testsuite/python/mmm1d.py +++ b/testsuite/python/mmm1d.py @@ -58,26 +58,24 @@ def setUp(self): def tearDown(self): self.system.part.clear() - self.system.actors.clear() # tear down previous actors + self.system.actors.clear() def test_forces(self): measured_f = self.system.part[:].f for i in range(self.num_particles): for comp in range(3): - abs_deviation = abs(measured_f[i, comp] - - self.vec_f_target[i, comp]) - self.assertLess(abs_deviation, - self.allowed_error, - msg="Measured force has a deviation of {} which is too big for " - "particle {} in component {}".format(abs_deviation, i, comp)) + self.assertAlmostEqual( + measured_f[i, comp], self.vec_f_target[i, comp], + delta=self.allowed_error, + msg="Measured force deviates too much " + "for particle {} in component {}".format(i, comp)) def test_energy(self): measured_el_energy = self.system.analysis.energy()["total"] \ - self.system.analysis.energy()["kinetic"] - self.assertLess( - abs(measured_el_energy - self.energy_target), - self.allowed_error, - msg="Measured energy has a deviation which is too big compared to stored result") + self.assertAlmostEqual( + measured_el_energy, self.energy_target, delta=self.allowed_error, + msg="Measured energy deviates too much from stored result") def test_with_analytical_result(self, prefactor=1.0, accuracy=1e-4): self.system.part.clear() @@ -90,27 +88,22 @@ def test_with_analytical_result(self, prefactor=1.0, accuracy=1e-4): target_energy_config = 1.00242505606 * prefactor target_force_z_config = -0.99510759 * prefactor - self.assertLess( - abs(f_measured[0] - 0), - self.allowed_error, - msg="Measured force in x has a deviation which is too big compared to analytical result") - self.assertLess( - abs(f_measured[1] - 0), - self.allowed_error, - msg="Measured force in y has a deviation which is too big compared to analytical result") - self.assertLess( - abs(f_measured[2] - target_force_z_config), - accuracy, - msg="Measured force in z has a deviation which is too big compared to analytical result " - + str(abs(f_measured[2] - target_force_z_config))) - self.assertLess( - abs(energy_measured - target_energy_config), - self.allowed_error, - msg="Measured energy has a deviation which is too big compared to analytical result") + self.assertAlmostEqual( + f_measured[0], 0, delta=self.allowed_error, + msg="Measured force in x deviates too much from analytical result") + self.assertAlmostEqual( + f_measured[1], 0, delta=self.allowed_error, + msg="Measured force in y deviates too much from analytical result") + self.assertAlmostEqual( + f_measured[2], target_force_z_config, delta=accuracy, + msg="Measured force in z deviates too much from analytical result") + self.assertAlmostEqual( + energy_measured, target_energy_config, delta=self.allowed_error, + msg="Measured energy deviates too much from analytical result") def test_bjerrum_length_change(self): self.system.part.clear() - self.system.actors.clear() # tear down previous actors + self.system.actors.clear() prefactor = 2 mmm1d = self.MMM1D(prefactor=prefactor, maxPWerror=1e-20) self.system.actors.add(mmm1d) diff --git a/testsuite/python/nsquare.py b/testsuite/python/nsquare.py index d2bfc123138..00987092aec 100644 --- a/testsuite/python/nsquare.py +++ b/testsuite/python/nsquare.py @@ -44,7 +44,7 @@ def test_load_balancing(self): # Check that the particles are evenly distributed for node_parts in part_dist: - self.assertLess(abs(node_parts - n_part_avg), 2) + self.assertAlmostEqual(node_parts, n_part_avg, delta=2) # Check that we can still access all the particles # This basically checks if part_node and local_particles diff --git a/testsuite/python/p3m_gpu.py b/testsuite/python/p3m_gpu.py index be4367d5983..8da8f1b2295 100644 --- a/testsuite/python/p3m_gpu.py +++ b/testsuite/python/p3m_gpu.py @@ -19,7 +19,7 @@ import espressomd import unittest as ut import unittest_decorators as utx -from tests_common import params_match +from tests_common import assert_params_match @utx.skipIfMissingGPU() @@ -43,7 +43,7 @@ def test(self): p3m = P3MGPU(**test_params) es.actors.add(p3m) - self.assertTrue(params_match(test_params, p3m.get_params())) + assert_params_match(self, test_params, p3m.get_params()) if __name__ == "__main__": diff --git a/testsuite/python/pairs.py b/testsuite/python/pairs.py index 4341f2559d4..ad93290a664 100644 --- a/testsuite/python/pairs.py +++ b/testsuite/python/pairs.py @@ -64,7 +64,7 @@ def check(self): self.assertEqual(len(pairs), len(epairs)) for p in pairs: - self.assertTrue(p in epairs) + self.assertIn(p, epairs) def test_nsquare(self): self.s.cell_system.set_n_square() diff --git a/testsuite/python/particle_slice.py b/testsuite/python/particle_slice.py index 11155a5a4ba..b905d15bc89 100644 --- a/testsuite/python/particle_slice.py +++ b/testsuite/python/particle_slice.py @@ -34,35 +34,39 @@ def __init__(self, *args, **kwargs): if has_features(["EXTERNAL_FORCES"]): self.system.part[1].fix = self.state[1] - self.assertTrue(np.array_equal( - self.system.part[0].fix, self.state[0])) - self.assertTrue(np.array_equal( - self.system.part[1].fix, self.state[1])) - self.assertTrue(np.array_equal( - self.system.part[:2].fix, self.state)) + np.testing.assert_array_equal( + np.copy(self.system.part[0].fix), self.state[0]) + np.testing.assert_array_equal( + np.copy(self.system.part[1].fix), self.state[1]) + np.testing.assert_array_equal( + np.copy(self.system.part[:2].fix), self.state) xs = self.system.part[:].pos for i in range(len(xs)): - self.assertTrue(np.array_equal(xs[i], self.system.part[i].pos)) + np.testing.assert_array_equal( + xs[i], np.copy(self.system.part[i].pos)) @utx.skipIfMissingFeatures(["EXTERNAL_FORCES"]) def test_1_set_different_values(self): self.state[0] = [1, 0, 0] self.state[1] = [1, 0, 0] self.system.part[:2].fix = self.state - self.assertTrue(np.array_equal(self.system.part[:2].fix, self.state)) + np.testing.assert_array_equal( + np.copy(self.system.part[:2].fix), self.state) @utx.skipIfMissingFeatures(["EXTERNAL_FORCES"]) def test_2_set_same_value(self): self.state[0] = [0, 1, 0] self.state[1] = [0, 1, 0] self.system.part[:2].fix = self.state[1] - self.assertTrue(np.array_equal(self.system.part[:2].fix, self.state)) + np.testing.assert_array_equal( + np.copy(self.system.part[:2].fix), self.state) @utx.skipIfMissingFeatures(["EXTERNAL_FORCES"]) def test_3_set_one_value(self): self.state[1] = [0, 0, 1] self.system.part[1:2].fix = self.state[1] - self.assertTrue(np.array_equal(self.system.part[:2].fix, self.state)) + np.testing.assert_array_equal( + np.copy(self.system.part[:2].fix), self.state) @utx.skipIfMissingFeatures(["EXTERNAL_FORCES"]) def test_4_str(self): @@ -235,55 +239,48 @@ def test_bonds(self): self.system.part[:].delete_all_bonds() self.assertEqual(self.system.part[:].bonds, [(), (), (), ()]) - def cmp_array_like(self, A, B): - return all(a.tolist() == b for a, b in zip(A, B)) - @utx.skipIfMissingFeatures(["EXCLUSIONS"]) def test_exclusions(self): + def assert_exclusions_equal(B): + A = self.system.part[:].exclusions + self.assertEqual([x.tolist() for x in A], B) + # Setter # int self.system.part[:].exclusions = [] b = 1 self.system.part[2].exclusions = b - self.assertTrue(self.cmp_array_like( - self.system.part[:].exclusions, [[], [2], [1], []])) + assert_exclusions_equal([[], [2], [1], []]) # single list self.system.part[:].exclusions = [] b = [1] self.system.part[2].exclusions = b - self.assertTrue(self.cmp_array_like( - self.system.part[:].exclusions, [[], [2], [1], []])) + assert_exclusions_equal([[], [2], [1], []]) # tuple self.system.part[:].exclusions = [] b = (0, 1) self.system.part[2].exclusions = b - self.assertTrue( - self.cmp_array_like(self.system.part[:].exclusions, [[2], [2], [0, 1], []])) + assert_exclusions_equal([[2], [2], [0, 1], []]) # list self.system.part[:].exclusions = [] b = [0, 1] self.system.part[2].exclusions = b - self.assertTrue( - self.cmp_array_like(self.system.part[:].exclusions, [[2], [2], [0, 1], []])) + assert_exclusions_equal([[2], [2], [0, 1], []]) # Add/Del exclusions self.system.part[:].exclusions = [] self.system.part[2].add_exclusion(1) - self.assertTrue(self.cmp_array_like( - self.system.part[:].exclusions, [[], [2], [1], []])) + assert_exclusions_equal([[], [2], [1], []]) self.system.part[2].add_exclusion(0) - self.assertTrue( - self.cmp_array_like(self.system.part[:].exclusions, [[2], [2], [1, 0], []])) + assert_exclusions_equal([[2], [2], [1, 0], []]) self.system.part[2].delete_exclusion(0) - self.assertTrue(self.cmp_array_like( - self.system.part[:].exclusions, [[], [2], [1], []])) + assert_exclusions_equal([[], [2], [1], []]) self.system.part[2].delete_exclusion(1) - self.assertTrue(self.cmp_array_like( - self.system.part[:].exclusions, [[], [], [], []])) + assert_exclusions_equal([[], [], [], []]) # Slices @@ -291,44 +288,36 @@ def test_exclusions(self): self.system.part[:].exclusions = [] b = [1] self.system.part[2:].exclusions = b - self.assertTrue(self.cmp_array_like( - self.system.part[:].exclusions, [[], [2, 3], [1], [1]])) + assert_exclusions_equal([[], [2, 3], [1], [1]]) # list for all self.system.part[:].exclusions = [] b = [0, 1] self.system.part[2:].exclusions = b - self.assertTrue( - self.cmp_array_like(self.system.part[:].exclusions, [[2, 3], [2, 3], [0, 1], [0, 1]])) + assert_exclusions_equal([[2, 3], [2, 3], [0, 1], [0, 1]]) # single list for each self.system.part[:].exclusions = [] b = [[0], [0]] self.system.part[2:].exclusions = b - self.assertTrue( - self.cmp_array_like(self.system.part[:].exclusions, [[2, 3], [], [0], [0]])) + assert_exclusions_equal([[2, 3], [], [0], [0]]) # multi list for each self.system.part[:].exclusions = [] b = [[0, 1], [0, 1]] self.system.part[2:].exclusions = b - self.assertTrue( - self.cmp_array_like(self.system.part[:].exclusions, [[2, 3], [2, 3], [0, 1], [0, 1]])) + assert_exclusions_equal([[2, 3], [2, 3], [0, 1], [0, 1]]) # Add/Del exclusions self.system.part[:].exclusions = [] self.system.part[2:].add_exclusion(1) - self.assertTrue(self.cmp_array_like( - self.system.part[:].exclusions, [[], [2, 3], [1], [1]])) + assert_exclusions_equal([[], [2, 3], [1], [1]]) self.system.part[2:].add_exclusion(0) - self.assertTrue( - self.cmp_array_like(self.system.part[:].exclusions, [[2, 3], [2, 3], [1, 0], [1, 0]])) + assert_exclusions_equal([[2, 3], [2, 3], [1, 0], [1, 0]]) self.system.part[2:].delete_exclusion(0) - self.assertTrue(self.cmp_array_like( - self.system.part[:].exclusions, [[], [2, 3], [1], [1]])) + assert_exclusions_equal([[], [2, 3], [1], [1]]) self.system.part[2:].delete_exclusion(1) - self.assertTrue(self.cmp_array_like( - self.system.part[:].exclusions, [[], [], [], []])) + assert_exclusions_equal([[], [], [], []]) @utx.skipIfMissingFeatures("VIRTUAL_SITES_RELATIVE") def test_vs_relative(self): @@ -385,7 +374,7 @@ def test_multiadd(self): self.assertEqual(self.system.part[1].type, 1) def test_empty(self): - self.assertTrue(np.array_equal(self.system.part[0:0].pos, np.empty(0))) + np.testing.assert_array_equal(self.system.part[0:0].pos, np.empty(0)) def test_len(self): self.assertEqual(len(self.system.part[0:0]), 0) diff --git a/testsuite/python/random_pairs.py b/testsuite/python/random_pairs.py index 5f0e00867e2..136cfee5016 100644 --- a/testsuite/python/random_pairs.py +++ b/testsuite/python/random_pairs.py @@ -51,7 +51,7 @@ def setUp(self): self.all_pairs.append((pair[0].id, pair[1].id)) self.all_pairs = set(self.all_pairs) - self.assertTrue(len(self.all_pairs)) + self.assertGreater(len(self.all_pairs), 0) def tearDown(self): self.system.part.clear() @@ -75,7 +75,7 @@ def check_duplicates(self, l): def check_pairs(self, n2_pairs): cs_pairs = self.system.cell_system.get_pairs_(1.5) self.check_duplicates(cs_pairs) - self.assertTrue(len(cs_pairs)) + self.assertGreater(len(cs_pairs), 0) self.assertEqual(n2_pairs ^ set(cs_pairs), set()) def check_dd(self, n2_pairs): diff --git a/testsuite/python/rdf.py b/testsuite/python/rdf.py index 376003310b3..ffc21a3edb7 100644 --- a/testsuite/python/rdf.py +++ b/testsuite/python/rdf.py @@ -60,7 +60,7 @@ def test_single_type(self): parts_in_bin = rdf[1] * rv * rho # All but the last bin should contain 2 particles - self.assertTrue(np.allclose(parts_in_bin[:-1], 2.0)) + np.testing.assert_allclose(parts_in_bin[:-1], 2.0) def test_mixed(self): s = self.s @@ -84,16 +84,16 @@ def test_mixed(self): parts_in_bin = rdf01[1] * rv * rho # Every odd bin should contain two parts - self.assertTrue(np.allclose(parts_in_bin[0:-1:2], 2.0, rtol=1e-1)) + np.testing.assert_allclose(parts_in_bin[0:-1:2], 2.0, rtol=1e-1) # Every odd bin should contain zero parts - self.assertTrue(np.allclose(parts_in_bin[1:-1:2], 0.0)) + np.testing.assert_allclose(parts_in_bin[1:-1:2], 0.0) # Check symmetry rdf10 = s.analysis.rdf( rdf_type='rdf', type_list_a=[1], type_list_b=[0], r_min=r_min, r_max=r_max, r_bins=r_bins) - self.assertTrue(np.allclose(rdf10, rdf01)) + np.testing.assert_allclose(rdf10, rdf01) def test_av(self): s = self.s @@ -113,7 +113,7 @@ def test_av(self): rdf_av = s.analysis.rdf(rdf_type='', type_list_a=[0, 1, 2], r_min=r_min, r_max=r_max, r_bins=r_bins) - self.assertTrue(np.allclose(rdf[1], rdf_av[1])) + np.testing.assert_allclose(rdf[1], rdf_av[1]) if __name__ == "__main__": diff --git a/testsuite/python/rigid_bond.py b/testsuite/python/rigid_bond.py index 0a5adba5a1d..a711a690661 100644 --- a/testsuite/python/rigid_bond.py +++ b/testsuite/python/rigid_bond.py @@ -46,7 +46,7 @@ def test(self): for i in range(1, 5): d = s.distance(s.part[i], s.part[i - 1]) v_d = s.distance_vec(s.part[i], s.part[i - 1]) - self.assertLess(abs(d - 1.2), tol) + self.assertAlmostEqual(d, 1.2, delta=tol) # Velocity projection on distance vector vel_proj = np.dot(s.part[i].v - s.part[i - 1].v, v_d) / d self.assertLess(vel_proj, tol) diff --git a/testsuite/python/rotational_inertia.py b/testsuite/python/rotational_inertia.py index 13d833de641..f3f08d8bd45 100644 --- a/testsuite/python/rotational_inertia.py +++ b/testsuite/python/rotational_inertia.py @@ -75,14 +75,14 @@ def test_stability(self): for i in range(100): self.set_L(0) for k in range(3): - self.assertLessEqual( - abs(self.L_lab[k] - self.L_0_lab[k]), tol, + self.assertAlmostEqual( + self.L_lab[k], self.L_0_lab[k], delta=tol, msg='Inertial motion around stable axis J1: Deviation in ' 'angular momentum is too large. Step {0}, coordinate ' '{1}, expected {2}, got {3}'.format( i, k, self.L_0_lab[k], self.L_lab[k])) - self.assertLessEqual( - abs(self.system.part[0].omega_body[1] - stable_omega), tol, + self.assertAlmostEqual( + self.system.part[0].omega_body[1], stable_omega, delta=tol, msg='Inertial motion around stable axis J1: Deviation in omega ' 'is too large. Step {0}, coordinate 1, expected {1}, got {2}' .format(i, stable_omega, self.system.part[0].omega_body[1])) @@ -100,14 +100,14 @@ def test_stability(self): for i in range(100): self.set_L(0) for k in range(3): - self.assertLessEqual( - abs(self.L_lab[k] - self.L_0_lab[k]), tol, + self.assertAlmostEqual( + self.L_lab[k], self.L_0_lab[k], delta=tol, msg='Inertial motion around stable axis J2: Deviation in ' 'angular momentum is too large. Step {0}, coordinate ' '{1}, expected {2}, got {3}'.format( i, k, self.L_0_lab[k], self.L_lab[k])) - self.assertLessEqual( - abs(self.system.part[0].omega_body[2] - stable_omega), tol, + self.assertAlmostEqual( + self.system.part[0].omega_body[2], stable_omega, delta=tol, msg='Inertial motion around stable axis J2: Deviation in omega ' 'is too large. Step {0}, coordinate 2, expected {1}, got {2}' .format(i, stable_omega, self.system.part[0].omega_body[2])) @@ -125,8 +125,8 @@ def test_stability(self): for i in range(100): self.set_L(0) for k in range(3): - self.assertLessEqual( - abs(self.L_lab[k] - self.L_0_lab[k]), tol, + self.assertAlmostEqual( + self.L_lab[k], self.L_0_lab[k], delta=tol, msg='Inertial motion around stable axis J0: Deviation in ' 'angular momentum is too large. Step {0}, coordinate ' '{1}, expected {2}, got {3}'.format( diff --git a/testsuite/python/sigint.py b/testsuite/python/sigint.py index b22217cb7e3..b7fc0cd0d2c 100644 --- a/testsuite/python/sigint.py +++ b/testsuite/python/sigint.py @@ -33,7 +33,7 @@ def test_signal_handling(self): self.process.send_signal(signal.SIGINT) # Wait for the signal to arrive and one integration step to be finished time.sleep(1) - self.assertFalse(self.process.poll() is None) + self.assertIsNotNone(self.process.poll()) if __name__ == '__main__': diff --git a/testsuite/python/stress.py b/testsuite/python/stress.py index 770ceb64a73..43e9224c447 100644 --- a/testsuite/python/stress.py +++ b/testsuite/python/stress.py @@ -30,35 +30,32 @@ # allowed deviation from analytical results tol = 1.0e-13 -# analytical result for convective stress - def stress_kinetic(vel): - return np.einsum('ij,ik->jk', vel, vel) / np.prod(system.box_l) - -# analytical result for stress originating from bond force + '''Analytical result for convective stress''' + return np.einsum('ij,ik->jk', vel, vel) / np.prod(np.copy(system.box_l)) def stress_bonded(pos): + '''Analytical result for stress originating from bonded forces''' stress = np.zeros([3, 3]) for p1, p2 in zip(pos[0::2], pos[1::2]): r = p1 - p2 f = -1.0e4 * r - stress += np.einsum('i,j', f, r) / np.prod(system.box_l) + stress += np.einsum('i,j', f, r) / np.prod(np.copy(system.box_l)) return stress -# analytical result for stress originating from non-bonded force - def stress_nonbonded(particle_pairs): + '''Analytical result for stress originating from non-bonded forces''' stress = np.zeros([3, 3]) for p1, p2 in particle_pairs: if (p1.type == 0 and p2.type == 0) or (p1.type == 1 and p2.type == 2): d = p1.pos - p2.pos - r = np.sqrt(np.sum(d**2)) + r = np.linalg.norm(d) r_hat = d / r f = (24.0 * 1.0 * (2.0 * 1.0**12 / r**13 - 1.0**6 / r**7)) * r_hat - stress += np.einsum('i,j', f, d) / np.prod(system.box_l) + stress += np.einsum('i,j', f, d) / np.prod(np.copy(system.box_l)) return stress @@ -67,10 +64,10 @@ def stress_nonbonded_inter(particle_pairs): for p1, p2 in particle_pairs: if p1.type == 1 and p2.type == 2 and p1.mol_id != p2.mol_id: r = p1.pos - p2.pos - d = np.sqrt(np.sum(r**2)) + d = np.linalg.norm(r) r_hat = r / d f = (24.0 * 1.0 * (2.0 * 1.0**12 / d**13 - 1.0**6 / d**7)) * r_hat - stress += np.einsum('i,j', f, r) / np.prod(system.box_l) + stress += np.einsum('i,j', f, r) / np.prod(np.copy(system.box_l)) return stress @@ -79,10 +76,10 @@ def stress_nonbonded_intra(particle_pairs): for p1, p2 in particle_pairs: if p1.type == 0 and p2.type == 0 and p1.mol_id == p2.mol_id: r = p1.pos - p2.pos - d = np.sqrt(np.sum(r**2)) + d = np.linalg.norm(r) r_hat = r / d f = (24.0 * 1.0 * (2.0 * 1.0**12 / d**13 - 1.0**6 / d**7)) * r_hat - stress += np.einsum('i,j', f, r) / np.prod(system.box_l) + stress += np.einsum('i,j', f, r) / np.prod(np.copy(system.box_l)) return stress @@ -130,20 +127,22 @@ def test(self): pos = system.part[:].pos vel = system.part[:].v - sim_stress_kinetic = system.analysis.stress_tensor()['kinetic'] - sim_stress_bonded = system.analysis.stress_tensor()['bonded'] - sim_stress_bonded_harmonic = system.analysis.stress_tensor()[ - 'bonded', len(system.bonded_inter) - 1] - sim_stress_nonbonded = system.analysis.stress_tensor()['non_bonded'] - sim_stress_nonbonded_inter = system.analysis.stress_tensor()[ - 'non_bonded_inter'] - sim_stress_nonbonded_inter12 = system.analysis.stress_tensor()[ - 'non_bonded_inter', 1, 2] - sim_stress_nonbonded_intra = system.analysis.stress_tensor()[ - 'non_bonded_intra'] - sim_stress_nonbonded_intra00 = system.analysis.stress_tensor()[ - 'non_bonded_intra', 0, 0] - sim_stress_total = system.analysis.stress_tensor()['total'] + sim_stress_kinetic = np.copy( + system.analysis.stress_tensor()['kinetic']) + sim_stress_bonded = np.copy(system.analysis.stress_tensor()['bonded']) + sim_stress_bonded_harmonic = np.copy(system.analysis.stress_tensor()[ + 'bonded', len(system.bonded_inter) - 1]) + sim_stress_nonbonded = np.copy( + system.analysis.stress_tensor()['non_bonded']) + sim_stress_nonbonded_inter = np.copy(system.analysis.stress_tensor()[ + 'non_bonded_inter']) + sim_stress_nonbonded_inter12 = np.copy(system.analysis.stress_tensor()[ + 'non_bonded_inter', 1, 2]) + sim_stress_nonbonded_intra = np.copy(system.analysis.stress_tensor()[ + 'non_bonded_intra']) + sim_stress_nonbonded_intra00 = np.copy(system.analysis.stress_tensor()[ + 'non_bonded_intra', 0, 0]) + sim_stress_total = np.copy(system.analysis.stress_tensor()['total']) sim_pressure_kinetic = system.analysis.pressure()['kinetic'] sim_pressure_bonded = system.analysis.pressure()['bonded'] sim_pressure_bonded_harmonic = system.analysis.pressure()[ @@ -180,48 +179,66 @@ def test(self): system.part.clear() - self.assertLess(np.max(np.abs(sim_stress_kinetic - anal_stress_kinetic)), - tol, 'kinetic stress does not match analytical result') - self.assertLess(np.max(np.abs(sim_stress_bonded - anal_stress_bonded)), - tol, 'bonded stress does not match analytical result') - self.assertLess(np.max(np.abs(sim_stress_bonded_harmonic - anal_stress_bonded)), - tol, 'bonded stress harmonic bond does not match analytical result') - self.assertLess(np.max(np.abs(sim_stress_nonbonded - anal_stress_nonbonded)), - tol, 'non-bonded stress does not match analytical result') - self.assertLess(np.max(np.abs(sim_stress_nonbonded_inter - anal_stress_nonbonded_inter)), - tol, 'non-bonded intermolecular stress does not match analytical result') - self.assertLess(np.max(np.abs(sim_stress_nonbonded_inter12 - anal_stress_nonbonded_inter)), - tol, 'non-bonded intermolecular stress molecules 1 and 2 does not match analytical result') - self.assertLess(np.max(np.abs(sim_stress_nonbonded_intra - anal_stress_nonbonded_intra)), - tol, 'non-bonded intramolecular stress does not match analytical result') - self.assertLess(np.max(np.abs(sim_stress_nonbonded_intra00 - anal_stress_nonbonded_intra)), - tol, 'non-bonded intramolecular stress molecule 0 does not match analytical result') - self.assertLess(np.max(np.abs(sim_stress_total - anal_stress_total)), - tol, 'total stress does not match analytical result') - self.assertLess(np.max(np.abs(sim_stress_total - sim_stress_kinetic - sim_stress_bonded - sim_stress_nonbonded)), - tol, 'total stress is not given as the sum of all major stress components') - self.assertLess(np.abs(sim_pressure_kinetic - anal_pressure_kinetic), - tol, 'kinetic pressure does not match analytical result') - self.assertLess(np.abs(sim_pressure_bonded - anal_pressure_bonded), - tol, 'bonded pressure does not match analytical result') - self.assertLess(np.abs(sim_pressure_bonded_harmonic - anal_pressure_bonded), - tol, 'bonded pressure harmonic bond does not match analytical result') - self.assertLess(np.abs(sim_pressure_nonbonded - anal_pressure_nonbonded), - tol, 'non-bonded pressure does not match analytical result') - self.assertLess(np.abs(sim_pressure_nonbonded_inter - anal_pressure_nonbonded_inter), - tol, 'non-bonded intermolecular pressure does not match analytical result') - self.assertLess( - np.abs(sim_pressure_nonbonded_inter12 - - anal_pressure_nonbonded_inter), tol, - 'non-bonded intermolecular pressure molecule 1 and 2 does not match analytical result') - self.assertLess(np.abs(sim_pressure_nonbonded_intra - anal_pressure_nonbonded_intra), - tol, 'non-bonded intramolecular pressure does not match analytical result') - self.assertLess(np.abs(sim_pressure_nonbonded_intra00 - anal_pressure_nonbonded_intra), - tol, 'non-bonded intramolecular pressure molecule 0 does not match analytical result') - self.assertLess(np.abs(sim_pressure_total - anal_pressure_total), - tol, 'total pressure does not match analytical result') - self.assertLess(np.max(np.abs(sim_pressure_total - sim_pressure_kinetic - sim_pressure_bonded - sim_pressure_nonbonded)), - tol, 'total pressure is not given as the sum of all major pressure components') + np.testing.assert_allclose( + sim_stress_kinetic, anal_stress_kinetic, rtol=0, atol=tol, + err_msg='kinetic stress does not match analytical result') + np.testing.assert_allclose( + sim_stress_bonded, anal_stress_bonded, rtol=0, atol=tol, + err_msg='bonded stress does not match analytical result') + np.testing.assert_allclose( + sim_stress_bonded_harmonic, anal_stress_bonded, rtol=0, atol=tol, + err_msg='bonded stress harmonic bond does not match analytical result') + np.testing.assert_allclose( + sim_stress_nonbonded, anal_stress_nonbonded, rtol=0, atol=tol, + err_msg='non-bonded stress does not match analytical result') + np.testing.assert_allclose( + sim_stress_nonbonded_inter, anal_stress_nonbonded_inter, rtol=0, atol=tol, + err_msg='non-bonded intermolecular stress does not match analytical result') + np.testing.assert_allclose( + sim_stress_nonbonded_inter12, anal_stress_nonbonded_inter, rtol=0, atol=tol, + err_msg='non-bonded intermolecular stress molecules 1 and 2 does not match analytical result') + np.testing.assert_allclose( + sim_stress_nonbonded_intra, anal_stress_nonbonded_intra, rtol=0, atol=tol, + err_msg='non-bonded intramolecular stress does not match analytical result') + np.testing.assert_allclose( + sim_stress_nonbonded_intra00, anal_stress_nonbonded_intra, rtol=0, atol=tol, + err_msg='non-bonded intramolecular stress molecule 0 does not match analytical result') + np.testing.assert_allclose( + sim_stress_total, anal_stress_total, rtol=0, atol=tol, + err_msg='total stress does not match analytical result') + np.testing.assert_allclose( + sim_stress_total, sim_stress_kinetic + sim_stress_bonded + sim_stress_nonbonded, rtol=0, atol=tol, + err_msg='total stress is not given as the sum of all major stress components') + self.assertAlmostEqual( + sim_pressure_kinetic, anal_pressure_kinetic, delta=tol, + msg='kinetic pressure does not match analytical result') + self.assertAlmostEqual( + sim_pressure_bonded, anal_pressure_bonded, delta=tol, + msg='bonded pressure does not match analytical result') + self.assertAlmostEqual( + sim_pressure_bonded_harmonic, anal_pressure_bonded, delta=tol, + msg='bonded pressure harmonic bond does not match analytical result') + self.assertAlmostEqual( + sim_pressure_nonbonded, anal_pressure_nonbonded, delta=tol, + msg='non-bonded pressure does not match analytical result') + self.assertAlmostEqual( + sim_pressure_nonbonded_inter, anal_pressure_nonbonded_inter, delta=tol, + msg='non-bonded intermolecular pressure does not match analytical result') + self.assertAlmostEqual( + sim_pressure_nonbonded_inter12, anal_pressure_nonbonded_inter, delta=tol, + msg='non-bonded intermolecular pressure molecule 1 and 2 does not match analytical result') + self.assertAlmostEqual( + sim_pressure_nonbonded_intra, anal_pressure_nonbonded_intra, delta=tol, + msg='non-bonded intramolecular pressure does not match analytical result') + self.assertAlmostEqual( + sim_pressure_nonbonded_intra00, anal_pressure_nonbonded_intra, delta=tol, + msg='non-bonded intramolecular pressure molecule 0 does not match analytical result') + self.assertAlmostEqual( + sim_pressure_total, anal_pressure_total, delta=tol, + msg='total pressure does not match analytical result') + self.assertAlmostEqual( + sim_pressure_total, sim_pressure_kinetic + sim_pressure_bonded + sim_pressure_nonbonded, delta=tol, + msg='total pressure is not given as the sum of all major pressure components') # Compare stress tensor observable to stress tensor from analysis np.testing.assert_allclose( @@ -237,7 +254,7 @@ def get_anal_stress_fene(self, pos_1, pos_2, k, d_r_max, r_0): stress = np.zeros([3, 3]) vec_r = pos_1 - pos_2 f = -fene_force2(vec_r, k, d_r_max, r_0) - stress += np.einsum('i,j', f, vec_r) / np.prod(system.box_l) + stress += np.einsum('i,j', f, vec_r) / np.prod(np.copy(system.box_l)) return stress def test_fene(self): @@ -272,29 +289,33 @@ def test_fene(self): total_bonded_stresses = np.zeros([3, 3]) for i in range(len(system.bonded_inter)): - total_bonded_stresses = np.add( - total_bonded_stresses, system.analysis.stress_tensor()['bonded', i]) + total_bonded_stresses += system.analysis.stress_tensor()[ + 'bonded', i] anal_stress_fene = self.get_anal_stress_fene( system.part[0].pos, system.part[1].pos, k, d_r_max, r_0) - self.assertLess(np.max(np.abs(sim_stress_bonded - anal_stress_fene)), - tol, 'bonded stress does not match analytical result') - self.assertLess(np.max(np.abs(sim_stress_fene - anal_stress_fene)), - tol, 'bonded stress for fene does not match analytical result') - self.assertLess(np.max(np.abs(sim_stress_bonded - total_bonded_stresses)), - tol, 'bonded stresses do not sum up to the total value') + np.testing.assert_allclose( + sim_stress_bonded, anal_stress_fene, atol=tol, + err_msg='bonded stress does not match analytical result') + np.testing.assert_allclose( + sim_stress_fene, anal_stress_fene, atol=tol, + err_msg='bonded stress for fene does not match analytical result') + np.testing.assert_allclose( + sim_stress_bonded, total_bonded_stresses, atol=tol, + err_msg='bonded stresses do not sum up to the total value') sim_pressure_fene = system.analysis.pressure()[ 'bonded', len(system.bonded_inter) - 1] anal_pressure_fene = np.einsum("ii", anal_stress_fene) / 3.0 - self.assertLess(np.max(np.abs(sim_pressure_fene - anal_pressure_fene)), - tol, 'bonded pressure for fene does not match analytical result') + np.testing.assert_allclose( + sim_pressure_fene, anal_pressure_fene, atol=tol, + err_msg='bonded pressure for fene does not match analytical result') # Compare stress tensor observable to stress tensor from analysis np.testing.assert_allclose( - StressTensor().calculate(), + np.array(StressTensor().calculate()), system.analysis.stress_tensor()["total"].reshape(9), - atol=1E-10) + rtol=0, atol=1E-10) system.part.clear() diff --git a/testsuite/python/test_checkpoint.py b/testsuite/python/test_checkpoint.py index 647727909ef..7c4e623862d 100644 --- a/testsuite/python/test_checkpoint.py +++ b/testsuite/python/test_checkpoint.py @@ -25,7 +25,6 @@ import espressomd.virtual_sites import espressomd.integrate from espressomd.shapes import Sphere, Wall -import tests_common modes = {x for mode in set("@TEST_COMBINATION@".upper().split('-')) for x in [mode, mode.split('.')[0]]} @@ -74,7 +73,7 @@ def test_LB(self): state = lbf.get_params() reference = {'agrid': 0.5, 'visc': 1.3, 'dens': 1.5, 'tau': 0.01} for key in reference: - self.assertTrue(key in state) + self.assertIn(key, state) self.assertAlmostEqual(reference[key], state[key], delta=1E-7) @utx.skipIfMissingFeatures('ELECTROKINETICS') @@ -104,12 +103,12 @@ def test_EK(self): 'viscosity': 1.7, 'friction': 0.0, 'T': 1.1, 'prefactor': 0.88, 'stencil': "linkcentered"} for key in reference: - self.assertTrue(key in state) + self.assertIn(key, state) self.assertAlmostEqual(reference[key], state[key], delta=1E-5) state_species = ek_species.get_params() reference_species = {'density': 0.4, 'D': 0.02, 'valency': 0.3} for key in reference_species: - self.assertTrue(key in state_species) + self.assertIn(key, state_species) self.assertAlmostEqual( reference_species[key], state_species[key], @@ -241,11 +240,10 @@ def test_bonded_inter(self): @utx.skipIfMissingFeatures(['VIRTUAL_SITES', 'VIRTUAL_SITES_RELATIVE']) def test_virtual_sites(self): - self.assertEqual(system.part[1].virtual, True) - self.assertTrue( - isinstance( - system.virtual_sites, - espressomd.virtual_sites.VirtualSitesRelative)) + self.assertTrue(system.part[1].virtual) + self.assertIsInstance( + system.virtual_sites, + espressomd.virtual_sites.VirtualSitesRelative) def test_mean_variance_calculator(self): np.testing.assert_array_equal( @@ -268,16 +266,13 @@ def test_collision_detection(self): coldet = system.collision_detection self.assertEqual(coldet.mode, "bind_centers") self.assertAlmostEqual(coldet.distance, 0.11, delta=1E-9) - self.assertTrue(coldet.bond_centers, system.bonded_inter[0]) + self.assertEqual(coldet.bond_centers, system.bonded_inter[0]) @utx.skipIfMissingFeatures('EXCLUSIONS') def test_exclusions(self): - self.assertTrue(tests_common.lists_contain_same_elements( - system.part[0].exclusions, [2])) - self.assertTrue(tests_common.lists_contain_same_elements( - system.part[1].exclusions, [2])) - self.assertTrue(tests_common.lists_contain_same_elements( - system.part[2].exclusions, [0, 1])) + self.assertEqual(list(system.part[0].exclusions), [2]) + self.assertEqual(list(system.part[1].exclusions), [2]) + self.assertEqual(list(system.part[2].exclusions), [0, 1]) @ut.skipIf(not LB or EK or not (espressomd.has_features("LB_BOUNDARIES") or espressomd.has_features("LB_BOUNDARIES_GPU")), "Missing features") diff --git a/testsuite/python/tests_common.py b/testsuite/python/tests_common.py index 9eb601d318e..72782efcf22 100644 --- a/testsuite/python/tests_common.py +++ b/testsuite/python/tests_common.py @@ -18,34 +18,32 @@ import numpy as np -def params_match(inParams, outParams): +def assert_params_match(ut_obj, inParams, outParams, msg_long=None): """Check if the parameters set and gotten back match. - Only check keys present in inParams. + Only check keys present in ``inParams``. """ + if msg_long: + msg_long = "\n" + msg_long + else: + msg_long = "" - for k in list(inParams.keys()): - if k not in outParams: - print(k, "missing from returned parameters") - return False + for k in inParams.keys(): + ut_obj.assertIn(k, outParams) if isinstance(inParams[k], float): - if abs(outParams[k] - inParams[k]) >= 1E-14: - print("Mismatch in parameter ", k, inParams[k], outParams[k], type( - inParams[k]), type(outParams[k]), abs(inParams[k] - outParams[k])) - return False + ut_obj.assertAlmostEqual( + outParams[k], inParams[k], delta=1E-14, + msg="Mismatching parameter {!r}{}".format(k, msg_long)) else: - if outParams[k] != inParams[k]: - print("Mismatch in parameter ", k, inParams[k], - outParams[k], type(inParams[k]), type(outParams[k])) - return False - - return True + ut_obj.assertEqual( + outParams[k], inParams[k], + msg="Mismatching parameter {!r}{}".format(k, msg_long)) def generate_test_for_class(_system, _interClass, _params): """Generates test cases for checking interaction parameters set and gotten back from Es actually match. Only keys which are present in _params are checked - 1st: Interaction parameters as dictionary, i.e., {"k": 1.,"r_0": 0} - 2nd: Name of the interaction property to set (i.e. "P3M") + 1st: Interaction parameters as dictionary, i.e., ``{"k": 1., "r_0": 0}`` + 2nd: Name of the interaction property to set (i.e. ``"P3M"``) """ params = _params interClass = _interClass @@ -64,12 +62,8 @@ def func(self): outParams = Inter.get_params() del system.actors[0] - self.assertTrue( - params_match(params, outParams), - "Mismatch of parameters.\nParameters set " + - params.__str__() + - " vs. output parameters " + - outParams.__str__()) + assert_params_match(self, params, outParams, "Parameters set {} vs. {}" + .format(params, outParams)) return func @@ -612,10 +606,6 @@ def single_component_maxwell(x1, x2, kT): return np.trapz(np.exp(-x**2 / (2. * kT)), x) / np.sqrt(2. * np.pi * kT) -def lists_contain_same_elements(list1, list2): - return len(list1) == len(list2) and sorted(list1) == sorted(list2) - - def count_fluid_nodes(lbf): """Counts the non-boundary nodes in the passed lb fluid instance.""" diff --git a/testsuite/python/thermalized_bond.py b/testsuite/python/thermalized_bond.py index 42d67f88b11..88199361b67 100644 --- a/testsuite/python/thermalized_bond.py +++ b/testsuite/python/thermalized_bond.py @@ -56,7 +56,7 @@ def check_velocity_distribution(self, vel, minmax, n_bins, error_tol, kT): for j in range(n_bins): found = data[j] expected = single_component_maxwell(bins[j], bins[j + 1], kT) - self.assertLessEqual(abs(found - expected), error_tol) + self.assertAlmostEqual(found, expected, delta=error_tol) def test_com_langevin(self): """Test for COM thermalization.""" diff --git a/testsuite/python/virtual_sites_relative.py b/testsuite/python/virtual_sites_relative.py index 801e7848535..25a5d37078f 100644 --- a/testsuite/python/virtual_sites_relative.py +++ b/testsuite/python/virtual_sites_relative.py @@ -50,7 +50,7 @@ def director_from_quaternion(self, quat): def verify_vs(self, vs, verify_velocity=True): """Verify vs position and (if compiled in) velocity.""" - self.assertEqual(vs.virtual, True) + self.assertTrue(vs.virtual) vs_r = vs.vs_relative @@ -75,20 +75,19 @@ def verify_vs(self, vs, verify_velocity=True): def test_aa_method_switching(self): # Virtual sites should be disabled by default - self.assertTrue(isinstance(self.system.virtual_sites, VirtualSitesOff)) + self.assertIsInstance(self.system.virtual_sites, VirtualSitesOff) # Switch implementation self.system.virtual_sites = VirtualSitesRelative(have_velocity=False) - self.assertTrue(isinstance( - self.system.virtual_sites, VirtualSitesRelative)) - self.assertEqual(self.system.virtual_sites.have_velocity, False) + self.assertIsInstance(self.system.virtual_sites, VirtualSitesRelative) + self.assertFalse(self.system.virtual_sites.have_velocity) def test_vs_quat(self): self.system.part.clear() # First check that quaternion of virtual particle is unchanged if # have_quaterion is false. self.system.virtual_sites = VirtualSitesRelative(have_quaternion=False) - self.assertEqual(self.system.virtual_sites.have_quaternion, False) + self.assertFalse(self.system.virtual_sites.have_quaternion) self.system.part.add(id=0, pos=[1, 1, 1], rotation=[1, 1, 1], omega_lab=[1, 1, 1]) self.system.part.add(id=1, pos=[1, 1, 1], rotation=[1, 1, 1]) @@ -154,7 +153,7 @@ def test_pos_vel_forces(self): system.part.add(rotation=(1, 1, 1), pos=pos, id=cur_id) system.part[cur_id].vs_auto_relate_to(1) # Was the particle made virtual - self.assertEqual(system.part[cur_id].virtual, True) + self.assertTrue(system.part[cur_id].virtual) # Are vs relative to id and vs_r = system.part[cur_id].vs_relative # id @@ -164,9 +163,9 @@ def test_pos_vel_forces(self): system.part[1], system.part[cur_id]), places=6) cur_id += 1 - # Move central particle and Check vs placement + # Move central particle and check vs placement system.part[1].pos = (0.22, 0.22, 0.22) - # linear and rotation velocity on central particle + # Linear and rotational velocity on central particle system.part[1].v = (0.45, 0.14, 0.447) system.part[1].omega_lab = (0.45, 0.14, 0.447) system.integrator.run(0, recalc_forces=True) @@ -208,10 +207,11 @@ def test_pos_vel_forces(self): # Check virtual sites without velocity system.virtual_sites.have_velocity = False - v2 = system.part[2].v - system.part[1].v = 17, -13.5, 2 + # Velocity should not change + v2 = np.copy(system.part[2].v) + system.part[1].v = [17, -13.5, 2] system.integrator.run(0, recalc_forces=True) - self.assertLess(np.linalg.norm(v2 - system.part[2].v), 1E-6) + np.testing.assert_array_equal(v2, np.copy(system.part[2].v)) def run_test_lj(self): """This fills the system with vs-based dumbells, adds a lj potential, @@ -323,8 +323,8 @@ def test_zz_stress_tensor(self): system.min_global_cut = 0.2 # Should not have one if vs are turned off system.virtual_sites = VirtualSitesOff() - self.assertTrue("virtual_sites" not in system.analysis.pressure()) - self.assertTrue("virtual_sites" not in system.analysis.stress_tensor()) + self.assertNotIn("virtual_sites", system.analysis.pressure()) + self.assertNotIn("virtual_sites", system.analysis.stress_tensor()) # vs relative contrib system.virtual_sites = VirtualSitesRelative() diff --git a/testsuite/python/virtual_sites_tracers_common.py b/testsuite/python/virtual_sites_tracers_common.py index df12cfed449..4ebab12362a 100644 --- a/testsuite/python/virtual_sites_tracers_common.py +++ b/testsuite/python/virtual_sites_tracers_common.py @@ -58,13 +58,13 @@ def reset_lb(self, ext_force_density=(0, 0, 0)): def test_aa_method_switching(self): # Virtual sites should be disabled by default - self.assertTrue(isinstance(self.system.virtual_sites, VirtualSitesOff)) + self.assertIsInstance(self.system.virtual_sites, VirtualSitesOff) # Switch implementation self.system.virtual_sites = VirtualSitesInertialessTracers() - self.assertTrue( - isinstance(self.system.virtual_sites, VirtualSitesInertialessTracers)) - self.assertEqual(self.system.virtual_sites.have_velocity, True) + self.assertIsInstance( + self.system.virtual_sites, VirtualSitesInertialessTracers) + self.assertTrue(self.system.virtual_sites.have_velocity) def test_advection(self): self.reset_lb(ext_force_density=[0.1, 0, 0]) diff --git a/testsuite/python/writevtf.py b/testsuite/python/writevtf.py index 61b3dac85f8..998b0d48e49 100644 --- a/testsuite/python/writevtf.py +++ b/testsuite/python/writevtf.py @@ -69,9 +69,9 @@ def test_pos(self): simulation_pos = np.array( [((i * 2), float(i * 2), float(i * 2), float(i * 2)) for i in range(npart // 2)]) - self.assertTrue(np.allclose( - simulation_pos[:, 1:], self.written_pos[:, 1:]), - msg="Positions not written correctly by writevcf!") + np.testing.assert_allclose( + simulation_pos[:, 1:], self.written_pos[:, 1:], + err_msg="Positions not written correctly by writevcf!") def test_bonds(self): """Test if bonds have been written properly: just look at number of bonds""" @@ -80,9 +80,9 @@ def test_bonds(self): elif 2 in self.types_to_write: simulation_bonds = np.array(2) # only this one is type 2 - self.assertTrue(np.allclose( - np.shape(simulation_bonds), np.shape(self.written_bonds)), - msg="Bonds not written correctly by writevsf!") + np.testing.assert_allclose( + np.shape(simulation_bonds), np.shape(self.written_bonds), + err_msg="Bonds not written correctly by writevsf!") def test_atoms(self): """Test if atom declarations have been written properly.""" @@ -93,9 +93,9 @@ def test_atoms(self): simulation_atoms = np.array([((i * 2), 2) for i in range(npart // 2)]) - self.assertTrue(np.allclose( - simulation_atoms[:, 1], self.written_atoms[:, 1]), - msg="Atoms not written correctly by writevsf!") + np.testing.assert_allclose( + simulation_atoms[:, 1], self.written_atoms[:, 1], + err_msg="Atoms not written correctly by writevsf!") class VCFTestAll(CommonTests):