def test(self): if "CUDA" in espressomd.features(): system = espressomd.System(box_l=[1, 1, 1]) self.assertEqual(system.cuda_init_handle.device_list != {}, espressomd.gpu_available()) else: self.assertFalse(espressomd.gpu_available())
def test(self): if espressomd.has_features("CUDA"): self.assertEqual(self.system.cuda_init_handle.list_devices() != {}, espressomd.gpu_available()) self.assertEqual( self.system.cuda_init_handle.list_devices_properties() != {}, espressomd.gpu_available()) else: self.assertFalse(espressomd.gpu_available())
def skipIfMissingFeatureStokesianDynamics(): """Specialized unittest skipIf decorator for missing Stokesian Dynamics.""" if not espressomd.has_features(["STOKESIAN_DYNAMICS"]) and ( not espressomd.has_features(["STOKESIAN_DYNAMICS_GPU"]) or not espressomd.gpu_available()): return ut.skip("Skipping test: feature STOKESIAN_DYNAMICS unavailable") return utx._id
def skipIfMissingGPU(): """Unittest skipIf decorator for missing GPU.""" if not espressomd.gpu_available(): return unittest.skip("Skipping test: no GPU available") devices = espressomd.cuda_init.CudaInitHandle().device_list current_device_id = espressomd.cuda_init.CudaInitHandle().device return _id
def test_thermostat_LB(self): thmst = system.thermostat.get_state()[0] if 'LB.GPU' in modes and not espressomd.gpu_available(): self.assertEqual(thmst['type'], 'OFF') else: self.assertEqual(thmst['type'], 'LB') # rng_counter_fluid = seed, seed is 0 because kT=0 self.assertEqual(thmst['rng_counter_fluid'], 0) self.assertEqual(thmst['gamma'], 2.0)
def skipIfMissingGPU(skip_ci_amd=False): """Unittest skipIf decorator for missing GPU.""" if not espressomd.gpu_available(): return unittest.skip("Skipping test: no GPU available") # special case for our CI infrastructure: disable specific GPU tests # for AMD GPUs, see https://github.com/espressomd/espresso/pull/2653 if skip_ci_amd and str(espressomd.cuda_init.CudaInitHandle().device_list[0] ) == "Device 687f": return unittest.skip("Skipping test: AMD GPU") return _id
def test_exceptions(self): error_msg = 'CUDA error: ' if espressomd.gpu_available(): n_gpus = len(self.system.cuda_init_handle.list_devices()) with self.assertRaisesRegex(RuntimeError, error_msg): self.system.cuda_init_handle.device = n_gpus + 1 else: with self.assertRaisesRegex(RuntimeError, error_msg): self.system.cuda_init_handle.device with self.assertRaisesRegex(RuntimeError, error_msg): self.system.cuda_init_handle.device = 0
def skipIfMissingGPU(): """Unittest skipIf decorator for missing GPU.""" if not espressomd.gpu_available(): return unittest.skip("Skipping test: no GPU available") return _id
import unittest_decorators as utx import numpy as np import espressomd import espressomd.checkpointing import espressomd.virtual_sites 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]] } LB = ('LB.CPU' in modes or 'LB.GPU' in modes and espressomd.gpu_available()) EK = ('EK.GPU' in modes and espressomd.gpu_available() and espressomd.has_features('ELECTROKINETICS')) class CheckpointTest(ut.TestCase): @classmethod def setUpClass(cls): cls.checkpoint = espressomd.checkpointing.Checkpoint( checkpoint_id="mycheckpoint_@TEST_COMBINATION@_@TEST_BINARY@". replace('.', '__'), checkpoint_path="@CMAKE_CURRENT_BINARY_DIR@") cls.checkpoint.load(0) @ut.skipIf(not LB, "Skipping test due to missing mode.")
class CoulombCloudWall(ut.TestCase): """This compares p3m, p3m_gpu, scafacos_p3m and scafacos_p2nfft 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] forces = {} tolerance = 1E-3 # Reference energy from p3m in the tcl test case reference_energy = 148.94229549 def setUp(self): self.S.box_l = (10, 10, 10) self.S.time_step = 0.01 self.S.cell_system.skin = 0.4 # Clear actors that might be left from prev tests if self.S.actors: del self.S.actors[0] self.S.part.clear() data = np.genfromtxt( tests_common.abspath("data/coulomb_cloud_wall_system.data")) # Add particles to system and store reference forces in hash # Input format: id pos q f for particle in data: id = particle[0] pos = particle[1:4] q = particle[4] f = particle[5:] self.S.part.add(id=int(id), pos=pos, q=q) self.forces[id] = f def compare(self, method_name, energy=True, prefactor=None): # Compare forces and energy now in the system to stored ones # Force force_abs_diff = 0. for p in self.S.part: force_abs_diff += abs( np.sqrt(sum((p.f / prefactor - self.forces[p.id])**2))) 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.assertLessEqual( force_abs_diff, self.tolerance, "Absolute force difference " + str(force_abs_diff) + " too large for method " + method_name) # Tests for individual methods if espressomd.has_features(["P3M"]): def test_p3m_direct_caf(self): """ This checks P3M with using the charge assignment function (window function) directly by setting the `inter` parameter to zero. """ self.S.actors.add( espressomd.electrostatics.P3M(prefactor=3, r_cut=1.001, accuracy=1e-3, mesh=64, cao=7, alpha=2.70746, tune=False, inter=0)) self.S.integrator.run(0) self.compare("p3m", energy=True, prefactor=3) def test_p3m_interpolated_caf(self): """ This checks P3M with using an interpolated charge assignment function (window function), which is the default. """ self.S.actors.add( espressomd.electrostatics.P3M(prefactor=3, r_cut=1.001, accuracy=1e-3, mesh=64, cao=7, alpha=2.70746, tune=False)) self.S.integrator.run(0) self.compare("p3m", energy=True, prefactor=3) @ut.skipIf(not espressomd.gpu_available(), "no gpu") def test_p3m_gpu(self): if str(espressomd.cuda_init.CudaInitHandle().device_list[0] ) == "Device 687f": print("skipping test on amd gpu") return self.S.actors.add( espressomd.electrostatics.P3MGPU(prefactor=2.2, r_cut=1.001, accuracy=1e-3, mesh=64, cao=7, alpha=2.70746, tune=False)) self.S.integrator.run(0) self.compare("p3m_gpu", energy=False, prefactor=2.2) if espressomd.has_features(["SCAFACOS"]): if "p3m" in scafacos.available_methods(): def test_scafacos_p3m(self): self.S.actors.add( espressomd.electrostatics.Scafacos(prefactor=0.5, method_name="p3m", method_params={ "p3m_r_cut": 1.001, "p3m_grid": 64, "p3m_cao": 7, "p3m_alpha": 2.70746 })) self.S.integrator.run(0) self.compare("scafacos_p3m", energy=True, prefactor=0.5) if "p2nfft" in scafacos.available_methods(): def test_scafacos_p2nfft(self): self.S.actors.add( espressomd.electrostatics.Scafacos(prefactor=2.8, method_name="p2nfft", method_params={ "p2nfft_r_cut": 1.001, "tolerance_field": 1E-4 })) self.S.integrator.run(0) self.compare("scafacos_p2nfft", energy=True, prefactor=2.8) def test_zz_deactivation(self): # Is the energy and force 0, if no methods active self.assertEqual(self.S.analysis.energy()["total"], 0.0) self.S.integrator.run(0, recalc_forces=True) for p in self.S.part: self.assertAlmostEqual(np.linalg.norm(p.f), 0, places=11)
# create checkpoint folder idx = "mycheckpoint_@TEST_COMBINATION@_@TEST_BINARY@".replace(".", "__") checkpoint = espressomd.checkpointing.Checkpoint( checkpoint_id=idx, checkpoint_path="@CMAKE_CURRENT_BINARY_DIR@") # cleanup old checkpoint files if checkpoint.has_checkpoints(): for filepath in os.listdir(checkpoint.checkpoint_dir): if filepath.endswith((".checkpoint", ".cpt")): os.remove(os.path.join(checkpoint.checkpoint_dir, filepath)) LB_implementation = None if 'LB.CPU' in modes: LB_implementation = espressomd.lb.LBFluid elif 'LB.GPU' in modes and espressomd.gpu_available(): LB_implementation = espressomd.lb.LBFluidGPU if LB_implementation: lbf = LB_implementation(agrid=0.5, visc=1.3, dens=1.5, tau=0.01) system.actors.add(lbf) if 'THERM.LB' in modes: system.thermostat.set_lb(LB_fluid=lbf, seed=23, gamma=2.0) if any(has_features(i) for i in ["LB_BOUNDARIES", "LB_BOUNDARIES_GPU"]): if 'EK.GPU' not in modes: system.lbboundaries.add( LBBoundary(shape=Wall(normal=(0, 0, 1), dist=0.5), velocity=(1e-4, 1e-4, 0))) EK_implementation = None if 'EK.GPU' in modes and espressomd.gpu_available( ) and espressomd.has_features('ELECTROKINETICS'):
class LBSwitchActor(ut.TestCase): system = espressomd.System(box_l=[10.0, 10.0, 10.0]) system.time_step = 0.01 system.cell_system.skin = 0.1 def switch_test(self, GPU=False): system = self.system system.actors.clear() system.part.add(pos=[1., 1., 1.], v=[1., 0, 0], fix=[1, 1, 1]) ext_force_density = [0.2, 0.3, 0.15] lb_fluid_params = {'agrid': 2.0, 'dens': 1.0, 'visc': 1.0, 'tau': 0.03} friction_1 = 1.5 friction_2 = 4.0 if GPU: lb_fluid_1 = espressomd.lb.LBFluidGPU(**lb_fluid_params) lb_fluid_2 = espressomd.lb.LBFluidGPU(**lb_fluid_params) else: lb_fluid_1 = espressomd.lb.LBFluid(**lb_fluid_params) lb_fluid_2 = espressomd.lb.LBFluid(**lb_fluid_params) system.actors.add(lb_fluid_1) system.thermostat.set_lb(LB_fluid=lb_fluid_1, gamma=friction_1) system.integrator.run(1) force_on_part = -friction_1 * np.copy(system.part[0].v) np.testing.assert_allclose(np.copy(system.part[0].f), force_on_part) system.integrator.run(100) self.assertNotAlmostEqual(lb_fluid_1[3, 3, 3].velocity[0], 0.0) system.actors.remove(lb_fluid_1) system.part[0].v = [1, 0, 0] system.integrator.run(0) np.testing.assert_allclose(np.copy(system.part[0].f), 0.0) system.actors.add(lb_fluid_2) system.thermostat.set_lb(LB_fluid=lb_fluid_2, gamma=friction_2) for p in product(range(5), range(5), range(5)): np.testing.assert_allclose(np.copy(lb_fluid_2[p].velocity), np.zeros((3, ))) system.part[0].v = [1, 0, 0] system.integrator.run(1) np.testing.assert_allclose(np.copy(system.part[0].f), [-friction_2, 0.0, 0.0]) @ut.skipIf(not espressomd.has_features(["LB"]), "LB_GPU not available, skipping test.") def test_CPU_LB(self): self.switch_test() @ut.skipIf((not espressomd.gpu_available() or not espressomd.has_features(["LB_GPU"])), "LB_GPU not available or no gpu present, skipping test.") def test_GPU_LB(self): self.switch_test(GPU=True)
# use a box with 3 different dimensions system = espressomd.System(box_l=[12.0, 14.0, 16.0]) system.cell_system.skin = 0.1 system.seed = system.cell_system.get_state()["n_nodes"] * [1234] system.time_step = 0.01 system.min_global_cut = 2.0 # create checkpoint folder idx = "mycheckpoint_@TEST_COMBINATION@_@TEST_BINARY@".replace(".", "__") checkpoint = espressomd.checkpointing.Checkpoint( checkpoint_id=idx, checkpoint_path="@CMAKE_CURRENT_BINARY_DIR@") LB_implementation = None if 'LB.CPU' in modes: LB_implementation = espressomd.lb.LBFluid elif 'LB.GPU' in modes and espressomd.gpu_available(): LB_implementation = espressomd.lb.LBFluidGPU if LB_implementation: lbf = LB_implementation(agrid=0.5, visc=1.3, dens=1.5, tau=0.01) system.actors.add(lbf) if 'LBTHERM' in modes: system.thermostat.set_lb(LB_fluid=lbf, seed=23, gamma=2.0) if espressomd.has_features("LB_BOUNDARIES") or espressomd.has_features("LB_BOUNDARIES_GPU"): if not 'EK.GPU' in modes: system.lbboundaries.add( LBBoundary(shape=Wall(normal=(0, 0, 1), dist=0.5), velocity=(1e-4, 1e-4, 0))) EK_implementation = None if 'EK.GPU' in modes and espressomd.gpu_available() and espressomd.has_features('ELECTROKINETICS'): EK_implementation = espressomd.electrokinetics ek = EK_implementation.Electrokinetics(
# along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function import time as tm import unittest as ut import math import numpy as np from numpy import linalg as la from numpy.random import random, seed import espressomd import espressomd.magnetostatics @ut.skipIf( not espressomd.gpu_available() or not espressomd.has_features( ["DIPOLAR_BARNES_HUT"]), "Features or gpu not available, skipping test!") class BHGPUPerfTest(ut.TestCase): # Handle for espresso system system = espressomd.System(box_l=[10.0, 10.0, 10.0]) def vectorsTheSame(self, a, b): tol = 15E-2 vec_len = la.norm(a - b) rel = 2 * vec_len / (la.norm(a) + la.norm(b)) return rel <= tol def stopAll(self): for i in range(len(self.system.part)): self.system.part[i].v = np.array([0.0, 0.0, 0.0])
class CoulombCloudWallTune(ut.TestCase): """This compares p3m, p3m_gpu electrostatic forces against stored data.""" system = espressomd.System(box_l=[1.0, 1.0, 1.0]) system.seed = system.cell_system.get_state()['n_nodes'] * [1234] tolerance = 1E-3 def setUp(self): self.system.box_l = (10, 10, 10) self.system.time_step = 0.01 self.system.cell_system.skin = 0.4 # Clear actors that might be left from prev tests self.system.actors.clear() self.system.part.clear() data = np.load(tests_common.abspath("data/coulomb_tuning_system.npz")) self.forces = [] # Add particles to system and store reference forces in hash # Input format: id pos q f for id in range(len(data['pos'])): pos = data['pos'][id] q = data['charges'][id] self.forces.append(data['forces'][id]) self.system.part.add(id=id, pos=pos, q=q) def compare(self, method_name): # Compare forces now in the system to stored ones force_abs_diff = 0. for p in self.system.part: force_abs_diff += abs(np.sqrt(sum((p.f - self.forces[p.id])**2))) 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) # Tests for individual methods if espressomd.has_features(["P3M"]): def test_p3m(self): # We have to add some tolerance here, because the reference # system is not homogeneous self.system.actors.add( espressomd.electrostatics.P3M(prefactor=1., accuracy=5e-4, tune=True)) self.system.integrator.run(0) self.compare("p3m") @ut.skipIf(not espressomd.gpu_available(), "no gpu") def test_p3m_gpu(self): if str(espressomd.cuda_init.CudaInitHandle().device_list[0]) == "Device 687f": print("Test skipped on amd gpu") return # We have to add some tolerance here, because the reference # system is not homogeneous self.system.actors.add( espressomd.electrostatics.P3MGPU(prefactor=1., accuracy=5e-4, tune=True)) self.system.integrator.run(0) self.compare("p3m_gpu")
import unittest as ut import unittest_decorators as utx import numpy as np import espressomd import espressomd.checkpointing import espressomd.virtual_sites import tests_common modes = { x for mode in set("@TEST_COMBINATION@".upper().split('-')) for x in [mode, mode.split('.')[0]] } LB = ('LB.CPU' in modes or espressomd.gpu_available() and espressomd.has_features('CUDA') and 'LB.GPU' in modes) EK = (espressomd.gpu_available() and espressomd.has_features('ELECTROKINETICS') and 'EK.GPU' in modes) class CheckpointTest(ut.TestCase): @classmethod def setUpClass(cls): cls.checkpoint = espressomd.checkpointing.Checkpoint( checkpoint_id="mycheckpoint_@TEST_COMBINATION@_@TEST_BINARY@". replace('.', '__'), checkpoint_path="@CMAKE_CURRENT_BINARY_DIR@") cls.checkpoint.load(0)
force = np.linalg.norm(sphere.get_force()) if np.abs(last_force - force) < 0.01 * stokes_force: break last_force = force force = np.copy(sphere.get_force()) np.testing.assert_allclose( force, [0, 0, stokes_force], rtol=0.03, atol=stokes_force * 0.03) @ut.skipIf(not espressomd.gpu_available() or not espressomd.has_features( ['LB_GPU', 'LB_BOUNDARIES_GPU', 'EXTERNAL_FORCES']), "Skipping test due to missing features.") class LBGPUStokes(ut.TestCase, Stokes): def setUp(self): self.lbf = espressomd.lb.LBFluidGPU(**LB_PARAMS) @ut.skipIf(not espressomd.has_features( ['LB', 'LB_BOUNDARIES', 'EXTERNAL_FORCES']), "Skipping test due to missing features.") class LBCPUStokes(ut.TestCase, Stokes): def setUp(self): self.lbf = espressomd.lb.LBFluid(**LB_PARAMS)
pnt1 = pntm size = size / 2.0 pntm = pnt1 - size else: pnt0 = pntm size = size / 2.0 pntm = pnt0 + size else: sys.exit( "Bisection method fails:\nTuning of domain boundaries may be required." ) return pntm @ut.skipIf( not espressomd.gpu_available() or not espressomd.has_features(["ELECTROKINETICS", "EK_BOUNDARIES"]), "Features or gpu not available, skipping test!") class ek_eof_one_species(ut.TestCase): system = espressomd.System(box_l=[1.0, 1.0, 1.0]) system.seed = system.cell_system.get_state()['n_nodes'] * [1234] xi = bisection(params_base) def run_test(self, params): system = self.system system.box_l = [params['box_x'], params['box_y'], params['box_z']] system.time_step = params_base['dt'] system.thermostat.turn_off() system.cell_system.skin = 0.1 system.thermostat.turn_off()
class TestCylindricalLBObservable(ut.TestCase): """ Testcase for the CylindricalFluxDensityObservable. """ system = espressomd.System(box_l=(10, 10, 10)) system.time_step = 0.01 system.cell_system.skin = 0.4 positions = [] params = { 'ids': range(10), 'center': [5.0, 5.0, 5.0], # center of the histogram 'axis': 'y', 'n_r_bins': 10, # number of bins in r 'n_phi_bins': 2, # -*- in phi 'n_z_bins': 2, # -*- in z 'min_r': 0.0, 'min_phi': -np.pi, 'min_z': -5.0, 'max_r': 5.0, 'max_phi': np.pi, 'max_z': 5.0, } @classmethod def setUpClass(self): if espressomd.has_features('LB_GPU'): self.lbf_gpu = espressomd.lb.LBFluidGPU( agrid=1.0, dens=1.0, visc=1.0, tau=0.01) if espressomd.has_features('LB'): self.lbf_cpu = espressomd.lb.LBFluid( agrid=1.0, dens=1.0, visc=1.0, tau=0.01) def tearDown(self): del self.positions[:] def swap_axis(self, arr, axis): if axis == 'x': arr = np.dot(tests_common.rotation_matrix( [0, 1, 0], np.pi / 2.0), arr) elif axis == 'y': arr = np.dot(tests_common.rotation_matrix( [1, 0, 0], -np.pi / 2.0), arr) return arr def swap_axis_inverse(self, arr, axis): if axis == 'x': arr = np.dot(tests_common.rotation_matrix( [0, 1, 0], -np.pi / 2.0), arr) elif axis == 'y': arr = np.dot(tests_common.rotation_matrix( [1, 0, 0], np.pi / 2.0), arr) return arr def pol_coords(self): positions = np.zeros((len(self.positions), 3)) for i, p in enumerate(self.positions): tmp = p - np.array(self.params['center']) tmp = self.swap_axis_inverse(tmp, self.params['axis']) positions[i, :] = tests_common.transform_pos_from_cartesian_to_polar_coordinates( tmp) return positions def set_particles(self): self.system.part.clear() self.system.part.add(pos=self.positions) def set_fluid_velocity(self): del self.positions[:] # Choose the cartesian velocities such that each particle gets the same # v_r, v_phi and v_z, respectively. self.v_r = .75 self.v_phi = 2.5 self.v_z = 1.5 node_positions = np.arange(-4.5, 5.0, 1.0) for i, value in enumerate(node_positions): position = np.array( [node_positions[i], node_positions[i], node_positions[i]]) v_y = (position[0] * np.sqrt(position[0]**2.0 + position[1]**2.0) * self.v_phi + position[1] * self.v_r) / np.sqrt(position[0]**2.0 + position[1]**2.0) v_x = ( self.v_r * np.sqrt(position[0]**2.0 + position[1]**2.0) - position[1] * v_y) / position[0] velocity = np.array([v_x, v_y, self.v_z]) velocity = self.swap_axis(velocity, self.params['axis']) position = self.swap_axis(position, self.params['axis']) position += np.array(self.params['center']) self.positions.append(position) self.lbf[np.array(position, dtype=int)].velocity = velocity def set_fluid_velocity_on_all_nodes(self): self.system.part.clear() self.v_r = .75 self.v_phi = 2.5 self.v_z = 1.5 node_positions = np.arange(-4.5, 5.0, 1.0) for x in node_positions: for y in node_positions: for z in node_positions: position = np.array([x, y, z]) v_y = (position[0] * np.sqrt(position[0]**2.0 + position[1]**2.0) * self.v_phi + position[1] * self.v_r) / np.sqrt(position[0]**2.0 + position[1]**2.0) v_x = ( self.v_r * np.sqrt(position[0]**2.0 + position[1]**2.0) - position[1] * v_y) / position[0] velocity = np.array([v_x, v_y, self.v_z]) velocity = self.swap_axis(velocity, self.params['axis']) position = self.swap_axis(position, self.params['axis']) position += np.array(self.params['center']) self.positions.append(position) self.lbf[np.array(position, dtype=int)].velocity = velocity def normalize_with_bin_volume(self, histogram): bin_volume = tests_common.get_cylindrical_bin_volume( self.params['n_r_bins'], self.params['n_phi_bins'], self.params['n_z_bins'], self.params['min_r'], self.params['max_r'], self.params['min_phi'], self.params['max_phi'], self.params['min_z'], self.params['max_z']) # Normalization for i in range(self.params['n_r_bins']): histogram[i, :, :] /= bin_volume[i] return histogram def LB_fluxdensity_profile_test(self): self.set_fluid_velocity() self.set_particles() # Set up the Observable. p = espressomd.observables.CylindricalLBFluxDensityProfileAtParticlePositions( **self.params) core_hist = np.array( p.calculate()).reshape( self.params['n_r_bins'], self.params['n_phi_bins'], self.params['n_z_bins'], 3) core_hist_v_r = core_hist[:, :, :, 0] core_hist_v_phi = core_hist[:, :, :, 1] core_hist_v_z = core_hist[:, :, :, 2] self.pol_positions = self.pol_coords() np_hist, _ = np.histogramdd( self.pol_positions, bins=(self.params['n_r_bins'], self.params[ 'n_phi_bins'], self.params[ 'n_z_bins']), range=[(self.params['min_r'], self.params['max_r']), (self.params['min_phi'], self.params['max_phi']), (self.params['min_z'], self.params['max_z'])]) np_hist = self.normalize_with_bin_volume(np_hist) np.testing.assert_array_almost_equal(np_hist * self.v_r, core_hist_v_r) np.testing.assert_array_almost_equal( np_hist * self.v_phi, core_hist_v_phi) np.testing.assert_array_almost_equal(np_hist * self.v_z, core_hist_v_z) self.assertEqual(p.n_values(), len(np_hist.flatten()) * 3) def LB_velocity_profile_at_particle_positions_test(self): self.set_fluid_velocity() self.set_particles() # Set up the Observable. p = espressomd.observables.CylindricalLBVelocityProfileAtParticlePositions( **self.params) core_hist = np.array( p.calculate()).reshape( self.params['n_r_bins'], self.params['n_phi_bins'], self.params['n_z_bins'], 3) core_hist_v_r = core_hist[:, :, :, 0] core_hist_v_phi = core_hist[:, :, :, 1] core_hist_v_z = core_hist[:, :, :, 2] self.pol_positions = self.pol_coords() np_hist, _ = np.histogramdd( self.pol_positions, bins=(self.params['n_r_bins'], self.params[ 'n_phi_bins'], self.params[ 'n_z_bins']), range=[(self.params['min_r'], self.params['max_r']), (self.params['min_phi'], self.params['max_phi']), (self.params['min_z'], self.params['max_z'])]) for x in np.nditer(np_hist, op_flags=['readwrite']): if x[...] > 0.0: x[...] /= x[...] np.testing.assert_array_almost_equal(np_hist * self.v_r, core_hist_v_r) np.testing.assert_array_almost_equal( np_hist * self.v_phi, core_hist_v_phi) np.testing.assert_array_almost_equal(np_hist * self.v_z, core_hist_v_z) self.assertEqual(p.n_values(), len(np_hist.flatten()) * 3) def LB_velocity_profile_test(self): self.set_fluid_velocity_on_all_nodes() # Set up the Observable. local_params = self.params.copy() del local_params['ids'] local_params['sampling_delta_x'] = 1 local_params['sampling_delta_y'] = 1 local_params['sampling_delta_z'] = 1 local_params['sampling_offset_x'] = 0.5 local_params['sampling_offset_y'] = 0.5 local_params['sampling_offset_z'] = 0.5 local_params['allow_empty_bins'] = True p = espressomd.observables.CylindricalLBVelocityProfile( **local_params) core_hist = np.array( p.calculate()).reshape( self.params['n_r_bins'], self.params['n_phi_bins'], self.params['n_z_bins'], 3) core_hist_v_r = core_hist[:, :, :, 0] core_hist_v_phi = core_hist[:, :, :, 1] core_hist_v_z = core_hist[:, :, :, 2] self.pol_positions = self.pol_coords() np_hist, _ = np.histogramdd( self.pol_positions, bins=(self.params['n_r_bins'], self.params[ 'n_phi_bins'], self.params[ 'n_z_bins']), range=[(self.params['min_r'], self.params['max_r']), (self.params['min_phi'], self.params['max_phi']), (self.params['min_z'], self.params['max_z'])]) for x in np.nditer(np_hist, op_flags=['readwrite']): if x[...] > 0.0: x[...] /= x[...] np.testing.assert_array_almost_equal(np_hist * self.v_r, core_hist_v_r) np.testing.assert_array_almost_equal( np_hist * self.v_phi, core_hist_v_phi) np.testing.assert_array_almost_equal(np_hist * self.v_z, core_hist_v_z) self.assertEqual(p.n_values(), len(np_hist.flatten()) * 3) @ut.skipIf(not espressomd.has_features('LB'), "LB not compiled in, skipping test.") def test_x_axis_cpu(self): self.params['axis'] = 'x' self.lbf = self.lbf_cpu self.system.actors.add(self.lbf) self.LB_fluxdensity_profile_test() self.LB_velocity_profile_test() self.LB_velocity_profile_at_particle_positions_test() self.system.actors.remove(self.lbf) @ut.skipIf(not espressomd.has_features('LB'), "LB not compiled in, skipping test.") def test_y_axis_cpu(self): self.params['axis'] = 'y' self.lbf = self.lbf_cpu self.system.actors.add(self.lbf) self.LB_fluxdensity_profile_test() self.LB_velocity_profile_test() self.LB_velocity_profile_at_particle_positions_test() self.system.actors.remove(self.lbf) @ut.skipIf(not espressomd.has_features('LB'), "LB not compiled in, skipping test.") def test_z_axis_cpu(self): self.params['axis'] = 'z' self.lbf = self.lbf_cpu self.system.actors.add(self.lbf) self.LB_fluxdensity_profile_test() self.LB_velocity_profile_test() self.LB_velocity_profile_at_particle_positions_test() self.system.actors.remove(self.lbf) @ut.skipIf(not espressomd.gpu_available() or not espressomd.has_features('LB_GPU'), "LB_GPU not compiled in, skipping test.") def test_x_axis_gpu(self): self.params['axis'] = 'x' self.lbf = self.lbf_gpu self.system.actors.add(self.lbf) self.LB_fluxdensity_profile_test() self.LB_velocity_profile_at_particle_positions_test() self.LB_velocity_profile_test() self.system.actors.remove(self.lbf) @ut.skipIf(not espressomd.gpu_available() or not espressomd.has_features('LB_GPU'), "LB_GPU not compiled in or no gpu present, skipping test.") def test_y_axis_gpu(self): self.params['axis'] = 'y' self.lbf = self.lbf_gpu self.system.actors.add(self.lbf) self.LB_fluxdensity_profile_test() self.LB_velocity_profile_at_particle_positions_test() self.LB_velocity_profile_test() self.system.actors.remove(self.lbf) @ut.skipIf(not espressomd.gpu_available() or not espressomd.has_features('LB_GPU'), "LB_GPU not compiled in, skipping test.") def test_z_axis_gpu(self): self.params['axis'] = 'z' self.lbf = self.lbf_gpu self.system.actors.add(self.lbf) self.LB_fluxdensity_profile_test() self.LB_velocity_profile_at_particle_positions_test() self.LB_velocity_profile_test() self.system.actors.remove(self.lbf)
def configure_and_import(filepath, gpu=False, substitutions=lambda x: x, cmd_arguments=None, script_suffix="", move_to_script_dir=True, mock_visualizer=True, **parameters): """ Copy a Python script to a new location and alter some lines of code: - change global variables and local variables (up to 1 indentation level) - pass command line arguments during import to emulate shell execution - disable the OpenGL module if dependencies are missing - disable the matplotlib GUI using a text-based backend - temporarily move to the directory where the script is located Parameters ---------- filepath : :obj:`str` python script to import gpu : :obj:`bool` whether GPU is necessary or not substitutions : :obj:`function` custom text replacement operation (useful to edit out calls to the OpenGL visualizer's ``run()`` method) cmd_arguments : :obj:`list` command line arguments, i.e. sys.argv without the script path script_suffix : :obj:`str` suffix to append to the configured script (useful when a single module is being tested by multiple tests in parallel) mock_visualizer : :obj:`bool` if ``True``, substitute the visualizer with a ``Mock`` class in case of ``ImportError`` (use ``False`` if an ``ImportError`` is relevant to your test) move_to_script_dir : :obj:`bool` if ``True``, move to the script's directory (useful when the script needs to load files hardcoded as relative paths, or when files are generated and need cleanup); this is enabled by default \*\*parameters : global variables to replace """ filepath = pathlib.Path(filepath).resolve() if skip_future_imports: module = unittest.mock.MagicMock() skipIfMissingImport = skip_future_imports_dependency(filepath) return module, skipIfMissingImport if gpu and not espressomd.gpu_available(): skip_future_imports_dependency(filepath) skipIfMissingGPU = unittest.skip("gpu not available, skipping test!") module = unittest.mock.MagicMock() return module, skipIfMissingGPU # load original script code = filepath.read_text() # custom substitutions code = substitutions(code) assert code.strip() # substitute global variables code = substitute_variable_values(code, **parameters) # substitute command line arguments if cmd_arguments is not None: code, old_sys_argv = set_cmd(code, filepath, cmd_arguments) # disable matplotlib GUI using the Agg backend code = disable_matplotlib_gui(code) # disable OpenGL GUI in case of ImportError using MagicMock() if mock_visualizer: code = mock_es_visualization(code) # save changes to a new file output_filepath = filepath.parent / \ f"{filepath.stem}_{script_suffix}_processed.py" assert not output_filepath.exists(), \ f"File {output_filepath} already processed, cannot overwrite" output_filepath.write_bytes(code.encode(encoding="utf-8")) # import dirname = output_filepath.parent if move_to_script_dir: os.chdir(dirname) sys.path.insert(0, str(dirname)) module_name = output_filepath.stem try: module = importlib.import_module(module_name) except espressomd.FeaturesError as err: skip_future_imports_dependency(filepath) skipIfMissingFeatures = unittest.skip(f"{err}, skipping test!") module = unittest.mock.MagicMock() else: def skipIfMissingFeatures(x): return x if cmd_arguments is not None: # restore original command line arguments sys.argv = old_sys_argv return module, skipIfMissingFeatures
n_nodes = system.cell_system.get_state()["n_nodes"] # Lees-Edwards boundary conditions if 'INT.NPT' not in modes: protocol = espressomd.lees_edwards.LinearShear(initial_pos_offset=0.1, time_0=0.2, shear_velocity=1.2) system.lees_edwards.set_boundary_conditions(shear_direction="x", shear_plane_normal="y", protocol=protocol) lbf_actor = None if 'LB.CPU' in modes: lbf_actor = espressomd.lb.LBFluid elif 'LB.GPU' in modes and espressomd.gpu_available(): lbf_actor = espressomd.lb.LBFluidGPU if lbf_actor: lbf_cpt_mode = 0 if 'LB.ASCII' in modes else 1 lbf = lbf_actor(agrid=0.5, visc=1.3, dens=1.5, tau=0.01, gamma_odd=0.2, gamma_even=0.3) system.actors.add(lbf) if 'THERM.LB' in modes: system.thermostat.set_lb(LB_fluid=lbf, seed=23, gamma=2.0) if (espressomd.has_features("LB_BOUNDARIES") or espressomd.has_features("LB_BOUNDARIES_GPU")): system.lbboundaries.add(
idx = "mycheckpoint_@TEST_COMBINATION@_@TEST_BINARY@".replace(".", "__") checkpoint = espressomd.checkpointing.Checkpoint( checkpoint_id=idx, checkpoint_path="@CMAKE_CURRENT_BINARY_DIR@") # cleanup old checkpoint files if checkpoint.has_checkpoints(): for filepath in os.listdir(checkpoint.checkpoint_dir): if filepath.endswith((".checkpoint", ".cpt")): os.remove(os.path.join(checkpoint.checkpoint_dir, filepath)) n_nodes = system.cell_system.get_state()["n_nodes"] LB_implementation = None if 'LB.CPU' in modes: LB_implementation = espressomd.lb.LBFluid elif 'LB.GPU' in modes and espressomd.gpu_available(): LB_implementation = espressomd.lb.LBFluidGPU if LB_implementation: lbf = LB_implementation(agrid=0.5, visc=1.3, dens=1.5, tau=0.01, gamma_odd=0.2, gamma_even=0.3) system.actors.add(lbf) if 'THERM.LB' in modes: system.thermostat.set_lb(LB_fluid=lbf, seed=23, gamma=2.0) if n_nodes == 1 and (espressomd.has_features("LB_BOUNDARIES") or espressomd.has_features("LB_BOUNDARIES_GPU")): system.lbboundaries.add( espressomd.lbboundaries.LBBoundary(shape=espressomd.shapes.Wall(
import espressomd import espressomd.checkpointing import espressomd.electrostatics import espressomd.magnetostatics import espressomd.io.writer # pylint: disable=unused-import import espressomd.lees_edwards import espressomd.virtual_sites import espressomd.integrate import espressomd.shapes import espressomd.constraints with contextlib.suppress(ImportError): import h5py # h5py has to be imported *after* espressomd (MPI) config = utg.TestGenerator() is_gpu_available = espressomd.gpu_available() modes = config.get_modes() has_lb_mode = 'LB.CPU' in modes or 'LB.GPU' in modes and is_gpu_available has_p3m_mode = 'P3M.CPU' in modes or 'P3M.GPU' in modes and is_gpu_available class CheckpointTest(ut.TestCase): checkpoint = espressomd.checkpointing.Checkpoint( **config.get_checkpoint_params()) checkpoint.load(0) path_cpt_root = pathlib.Path(checkpoint.checkpoint_dir) n_nodes = system.cell_system.get_state()["n_nodes"] @classmethod def setUpClass(cls):
# use a box with 3 different dimensions system = espressomd.System(box_l=[12.0, 14.0, 16.0]) system.cell_system.skin = 0.1 system.seed = system.cell_system.get_state()["n_nodes"] * [1234] system.time_step = 0.01 system.min_global_cut = 2.0 # create checkpoint folder idx = "mycheckpoint_@TEST_COMBINATION@_@TEST_BINARY@".replace(".", "__") checkpoint = espressomd.checkpointing.Checkpoint( checkpoint_id=idx, checkpoint_path="@CMAKE_CURRENT_BINARY_DIR@") LB_implementation = None if 'LB.CPU' in modes: LB_implementation = espressomd.lb.LBFluid elif espressomd.gpu_available() and espressomd.has_features( 'CUDA') and 'LB.GPU' in modes: LB_implementation = espressomd.lb.LBFluidGPU if LB_implementation: lbf = LB_implementation(agrid=0.5, visc=1.3, dens=1.5, tau=0.01) system.actors.add(lbf) EK_implementation = None if espressomd.gpu_available() and espressomd.has_features( 'ELECTROKINETICS') and 'EK.GPU' in modes: EK_implementation = espressomd.electrokinetics ek = EK_implementation.Electrokinetics(agrid=0.5, lb_density=26.15, viscosity=1.7, friction=0.0, T=1.1,
class CoulombCloudWall(ut.TestCase): if "ELECTROSTATICS" in espressomd.features(): """This compares p3m, p3m_gpu, scafacos_p3m and scafacos_p2nfft 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) forces = {} tolerance = 1E-3 # Reference energy from p3m in the tcl test case reference_energy = 2. * 148.94229549 def setUp(self): self.S.box_l = (10, 10, 20) self.S.time_step = 0.01 self.S.cell_system.skin = 0.4 # Clear actors that might be left from prev tests if self.S.actors: del self.S.actors[0] self.S.part.clear() data = np.genfromtxt( abspath("data/coulomb_cloud_wall_duplicated_system.data")) # Add particles to system and store reference forces in hash # Input format: id pos q f for particle in data: id = particle[0] pos = particle[1:4] q = particle[4] f = particle[5:] self.S.part.add(id=int(id), pos=pos, q=q) self.forces[id] = f 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: force_abs_diff += abs( np.sqrt(sum((p.f - self.forces[p.id])**2))) force_abs_diff /= len(self.S.part) # 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) # Tests for individual methods if "P3M" in espressomd.features(): def test_p3m(self): self.S.actors.add( espressomd.electrostatics.P3M(prefactor=1, r_cut=1.001, accuracy=1e-3, mesh=[64, 64, 128], cao=7, alpha=2.70746, tune=False)) self.S.integrator.run(0) self.compare("p3m", energy=True) @ut.skipIf(not espressomd.gpu_available(), "No gpu") def test_p3m_gpu(self): if str(espressomd.cuda_init.CudaInitHandle().device_list[0] ) == "Device 687f": print("Test skipped on AMD GPU") return self.S.actors.add( espressomd.electrostatics.P3MGPU(prefactor=1, r_cut=1.001, accuracy=1e-3, mesh=[64, 64, 128], cao=7, alpha=2.70746, tune=False)) self.S.integrator.run(0) 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)
def configure_and_import(filepath, gpu=False, substitutions=lambda x: x, cmd_arguments=None, script_suffix=None, move_to_script_dir=True, random_seeds=True, mock_visualizers=True, **parameters): """ Copy a Python script to a new location and alter some lines of code: - change global variables and local variables (up to 1 indentation level) - pass command line arguments during import to emulate shell execution - disable the OpenGL/Mayavi modules if they are not compiled - disable the matplotlib GUI using a text-based backend - use random seeds for the RNG in NumPy and ESPResSo - temporarily move to the directory where the script is located Parameters ---------- filepath : str python script to import gpu : bool whether GPU is necessary or not substitutions function custom text replacement operation (useful to edit out calls to the OpenGL or Mayavi visualizers' ``run()`` method) cmd_arguments : list command line arguments, i.e. sys.argv without the script path script_suffix : str suffix to append to the configured script (useful when a single module is being tested by multiple tests in parallel) random_seeds : bool if ``True``, use random seeds in RNGs mock_visualizers : bool if ``True``, substitute ES visualizers with `Mock()` classes in case of `ImportError()` (use ``False`` if an `ImportError()` is relevant to your test) move_to_script_dir : bool if ``True``, move to the script's directory (useful when the script needs to load files hardcoded as relative paths, or when files are generated and need cleanup); this is enabled by default \*\*parameters : global variables to replace """ if skip_future_imports: module = MagicMock() skipIfMissingImport = skip_future_imports_dependency(filepath) return module, skipIfMissingImport if gpu and not espressomd.gpu_available(): skip_future_imports_dependency(filepath) skipIfMissingGPU = unittest.skip("gpu not available, skipping test!") module = MagicMock() return module, skipIfMissingGPU filepath = os.path.abspath(filepath) # load original script # read in binary mode, then decode as UTF-8 to avoid this python3.5 error: # UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 915: # ordinal not in range(128) with open(filepath, "rb") as f: code = f.read().decode(encoding="utf-8") # custom substitutions code = substitutions(code) assert code.strip() # substitute global variables code = substitute_variable_values(code, **parameters) # substitute command line arguments if cmd_arguments is not None: code, old_sys_argv = set_cmd(code, filepath, cmd_arguments) # disable matplotlib GUI using the Agg backend code = disable_matplotlib_gui(code) # disable OpenGL/Mayavi GUI using MagicMock() if mock_visualizers: code = mock_es_visualization(code) # use random seeds for ES and NumPy RNGs if random_seeds: code = set_random_seeds(code) # save changes to a new file if script_suffix: if script_suffix[0] != "_": script_suffix = "_" + script_suffix else: script_suffix = "" script_suffix += "_processed.py" output_filepath = os.path.splitext(filepath)[0] + script_suffix assert os.path.isfile(output_filepath) is False, \ "File {} already processed, cannot overwrite".format(output_filepath) with open(output_filepath, "wb") as f: f.write(code.encode(encoding="utf-8")) # import dirname, basename = os.path.split(output_filepath) if move_to_script_dir: os.chdir(dirname) sys.path.insert(0, dirname) module_name = os.path.splitext(basename)[0] try: module = importlib.import_module(module_name) except espressomd.FeaturesError as err: skip_future_imports_dependency(filepath) skipIfMissingFeatures = unittest.skip(str(err) + ", skipping test!") module = MagicMock() else: skipIfMissingFeatures = _id if cmd_arguments is not None: # restore original command line arguments sys.argv = old_sys_argv return module, skipIfMissingFeatures
import unittest as ut import numpy as np import espressomd import espressomd.checkpointing import espressomd.virtual_sites import tests_common modes = { x for mode in set("@TEST_COMBINATION@".upper().split('-')) for x in [mode, mode.split('.')[0]] } LB = (espressomd.has_features('LB') and 'LB.CPU' in modes or espressomd.gpu_available() and espressomd.has_features('LB_GPU') and 'LB.GPU' in modes) EK = (espressomd.gpu_available() and espressomd.has_features('ELECTROKINETICS') and 'EK.GPU' in modes) class CheckpointTest(ut.TestCase): @classmethod def setUpClass(self): self.checkpoint = espressomd.checkpointing.Checkpoint( checkpoint_id="mycheckpoint_@TEST_COMBINATION@_@TEST_BINARY@". replace('.', '__'), checkpoint_path="@CMAKE_CURRENT_BINARY_DIR@") self.checkpoint.load(0)
def setUp(self): if not self.lbf: self.lbf = espressomd.lb.LBFluid(visc=1.0, dens=1.0, agrid=0.5, tau=1.0) self.system.actors.add(self.lbf) def tearDown(self): self.system.lbboundaries.clear() self.system.actors.remove(self.lbf) @ut.skipIf(not espressomd.gpu_available() or not espressomd.has_features(["LB_BOUNDARIES_GPU"]), "Features or not available, skipping test!") class LBBoundariesGPU(ut.TestCase, LBBoundariesBase): lbf = None def setUp(self): if not self.lbf: self.lbf = espressomd.lb.LBFluidGPU(visc=1.0, dens=1.0, agrid=0.5, tau=1.0) self.system.actors.add(self.lbf) def tearDown(self):
from numpy import linalg as la from numpy.random import random, seed import espressomd import espressomd.magnetostatics import espressomd.analyze import espressomd.cuda_init import tests_common def stopAll(system): system.part[:].v = np.zeros(3) system.part[:].omega_body = np.zeros(3) @ut.skipIf(not espressomd.gpu_available() or not espressomd.has_features(["DIPOLAR_BARNES_HUT"]), "Features or gpu not available, skipping test!") class BHGPUTest(ut.TestCase): system = espressomd.System(box_l=[1, 1, 1]) system.seed = system.cell_system.get_state()['n_nodes'] * [1234] np.random.seed(system.seed) def vectorsTheSame(self, a, b): tol = 5E-2 vec_len = la.norm(a - b) rel = 2 * vec_len / (la.norm(a) + la.norm(b)) return rel <= tol def run_test_case(self): seed(1) pf_bh_gpu = 2.34 pf_dawaanr = 3.524