示例#1
0
    def test_00_interface(self):
        self.assertEqual(len(self.system.bond_breakage), 0)

        spec2 = BreakageSpec(breakage_length=1.2, action_type="delete_bond")
        spec4 = BreakageSpec(breakage_length=0.2,
                             action_type="revert_bind_at_point_of_collision")
        self.system.bond_breakage[2] = spec2
        self.system.bond_breakage[4] = spec4
        self.assertEqual(self.system.bond_breakage[2], spec2)
        self.assertEqual(self.system.bond_breakage[4], spec4)
        self.assertEqual(len(self.system.bond_breakage), 2)
        self.assertEqual(sorted(self.system.bond_breakage.keys()), [2, 4])
        self.assertEqual(sorted(self.system.bond_breakage.items()),
                         [(2, spec2), (4, spec4)])

        self.system.bond_breakage.clear()
        self.assertEqual(len(self.system.bond_breakage), 0)
        self.assertEqual(self.system.bond_breakage.keys(), [])
        with self.assertRaisesRegex(TypeError, "Key has to be of type int"):
            self.system.bond_breakage[None]
        with self.assertRaisesRegex(TypeError, "Key has to be of type int"):
            self.system.bond_breakage[None] = None
        with self.assertRaisesRegex(TypeError, "Key has to be of type int"):
            self.system.bond_breakage.remove(None)
        with self.assertRaisesRegex(
                ValueError, "Bond needs to be added to the system first"):
            self.system.bond_breakage[HarmonicBond(k=1, r_0=0)]
        with self.assertRaisesRegex(
                RuntimeError,
                "Inserting breakage spec without a bond type is not permitted"
        ):
            self.system.bond_breakage.call_method("insert", object=spec2)
    def setup_system(self):
        """Setup the Espresso system parameters."""

        # Shorthand for Espresso system handle
        s = self.s

        # Positions and number of nodes of the gel network
        self.node_pos = self.node_positions()
        self.n_nodes = len(self.node_pos)

        # Box size is highest coordinate of any node +1/2 node_spacing
        l = np.amax(self.node_pos) + self.node_spacing / 2
        s.box_l = l, l, l

        # Open boundary conditions
        s.periodicity = 0, 0, 0

        # Thermostat
        s.thermostat.set_langevin(kT=self.kT, gamma=self.gamma)

        # Integrator
        s.time_step = self.dt
        s.cell_system.skin = self.skin

        # Lennard Jones interaction
        s.non_bonded_inter[0, 0].lennard_jones.set_params(sigma=self.lj_sigma,
                                                          epsilon=self.lj_eps,
                                                          cutoff=self.lj_cut,
                                                          shift="auto")

        # Harmonic bond
        self.bond = HarmonicBond(r_0=self.lj_cut, k=self.bond_strength)
        s.bonded_inter.add(self.bond)
示例#3
0
    def setUpClass(cls):
        pos1 = cls.system.box_l / 2 - 0.5
        pos2 = cls.system.box_l / 2 + 0.5
        cls.p1 = cls.system.part.add(pos=pos1)
        cls.p2 = cls.system.part.add(pos=pos2)

        cls.p1v = cls.system.part.add(pos=pos1)
        cls.p1v.vs_auto_relate_to(cls.p1)

        cls.p2v = cls.system.part.add(pos=pos2)
        cls.p2v.vs_auto_relate_to(cls.p2)

        cls.h1 = HarmonicBond(k=1, r_0=0)
        cls.h2 = HarmonicBond(k=1, r_0=0)
        cls.system.bonded_inter.add(cls.h1)
        cls.system.bonded_inter.add(cls.h2)
 def test_aa_bondedInterSetterGetter(self):
     self.system.bondedInter[0] = HarmonicBond(k=0, r_0=0)
     bond = self.system.bondedInter[0]
     self.assertTrue(
         isinstance(bond, HarmonicBond),
         "The bond was created as harmonic bond but the instance gotten back is of different type."
     )
args = parser.parse_args()

box_l = 50
n_part = 200

system = espressomd.System(box_l=[box_l] * 3)
system.set_random_state_PRNG()
np.random.seed(seed=system.seed)

system.time_step = 0.01
system.cell_system.skin = 0.4
system.thermostat.set_langevin(kT=0.1, gamma=20.0, seed=42)

system.non_bonded_inter[0, 0].lennard_jones.set_params(
    epsilon=0, sigma=1, cutoff=2, shift="auto")
system.bonded_inter[0] = HarmonicBond(k=0.5, r_0=1.0)

for i in range(n_part):
    system.part.add(id=i, pos=np.random.random(3) * system.box_l)

for i in range(n_part - 1):
    system.part[i].add_bond((system.bonded_inter[0], system.part[i + 1].id))

# Select visualizer
if args.visualizer == "mayavi":
    visualizer = visualization.mayaviLive(system)
else:
    visualizer = visualization.openGLLive(system, bond_type_radius=[0.3])

system.minimize_energy.init(
    f_max=10, gamma=50.0, max_steps=1000, max_displacement=0.2)
示例#6
0
class AnalyzeEnergy(ut.TestCase):
    system = espressomd.System(box_l=[1.0, 1.0, 1.0])

    harmonic = HarmonicBond(r_0=0.0, k=3)

    @classmethod
    def setUpClass(cls):
        box_l = 20
        cls.system.box_l = [box_l, box_l, box_l]
        cls.system.cell_system.skin = 0.4
        cls.system.time_step = 0.01
        cls.system.non_bonded_inter[0, 0].lennard_jones.set_params(
            epsilon=1.0, sigma=1.0,
            cutoff=2**(1. / 6.), shift="auto")
        cls.system.non_bonded_inter[0, 1].lennard_jones.set_params(
            epsilon=1.0, sigma=1.0,
            cutoff=2**(1. / 6.), shift="auto")
        cls.system.non_bonded_inter[1, 1].lennard_jones.set_params(
            epsilon=1.0, sigma=1.0,
            cutoff=2**(1. / 6.), shift="auto")
        cls.system.thermostat.set_langevin(kT=0., gamma=1., seed=42)
        cls.system.bonded_inter.add(cls.harmonic)

    def setUp(self):
        self.system.part.clear()
        self.system.part.add(id=0, pos=[1, 2, 2], type=0)
        self.system.part.add(id=1, pos=[5, 2, 2], type=0)

    def test_kinetic(self):
        self.system.part[0].pos = [1, 2, 2]
        self.system.part[1].pos = [5, 2, 2]
        self.system.part[0].v = [3, 4, 5]
        self.system.part[1].v = [0, 0, 0]
        # single moving particle
        energy = self.system.analysis.energy()
        self.assertAlmostEqual(energy["total"], 25., delta=1e-7)
        self.assertAlmostEqual(energy["kinetic"], 25., delta=1e-7)
        self.assertAlmostEqual(energy["bonded"], 0., delta=1e-7)
        self.assertAlmostEqual(energy["non_bonded"], 0., delta=1e-7)
        # two moving particles
        self.system.part[1].v = [3, 4, 5]
        energy = self.system.analysis.energy()
        self.assertAlmostEqual(energy["total"], 50., delta=1e-7)
        self.assertAlmostEqual(energy["kinetic"], 50., delta=1e-7)
        self.assertAlmostEqual(energy["bonded"], 0., delta=1e-7)
        self.assertAlmostEqual(energy["non_bonded"], 0., delta=1e-7)
        self.system.part[0].v = [0, 0, 0]
        self.system.part[1].v = [0, 0, 0]

    def test_non_bonded(self):
        self.system.part[0].pos = [1, 2, 2]
        self.system.part[1].pos = [2, 2, 2]
        energy = self.system.analysis.energy()
        self.assertAlmostEqual(energy["total"], 1., delta=1e-5)
        self.assertAlmostEqual(energy["kinetic"], 0., delta=1e-7)
        self.assertAlmostEqual(energy["bonded"], 0., delta=1e-7)
        self.assertAlmostEqual(energy["non_bonded"], 1., delta=1e-7)
        # add another pair of particles
        self.system.part.add(id=2, pos=[3, 2, 2], type=1)
        self.system.part.add(id=3, pos=[4, 2, 2], type=1)
        energy = self.system.analysis.energy()
        self.assertAlmostEqual(energy["total"], 3., delta=1e-7)
        self.assertAlmostEqual(energy["kinetic"], 0., delta=1e-7)
        self.assertAlmostEqual(energy["bonded"], 0., delta=1e-7)
        self.assertAlmostEqual(energy["non_bonded"], 3., delta=1e-7)
        self.assertAlmostEqual(
            energy["non_bonded", 0, 1], energy["non_bonded", 1, 0], delta=1e-7)
        self.assertAlmostEqual(energy["non_bonded", 0, 0]
                               + energy["non_bonded", 0, 1]
                               + energy["non_bonded", 1, 1], energy["total"], delta=1e-7)
        self.system.part[2].remove()
        self.system.part[3].remove()

    def test_bonded(self):
        self.system.part[0].pos = [1, 2, 2]
        self.system.part[1].pos = [3, 2, 2]
        self.system.part[0].v = [0, 0, 0]
        self.system.part[1].v = [0, 0, 0]
        # single bond
        self.system.part[0].add_bond((self.harmonic, 1))
        energy = self.system.analysis.energy()
        self.assertAlmostEqual(energy["total"], 6, delta=1e-7)
        self.assertAlmostEqual(energy["kinetic"], 0., delta=1e-7)
        self.assertAlmostEqual(energy["bonded"], 6, delta=1e-7)
        self.assertAlmostEqual(energy["non_bonded"], 0., delta=1e-7)
        # two bonds
        self.system.part[1].add_bond((self.harmonic, 0))
        energy = self.system.analysis.energy()
        self.assertAlmostEqual(energy["total"], 12, delta=1e-7)
        self.assertAlmostEqual(energy["kinetic"], 0., delta=1e-7)
        self.assertAlmostEqual(energy["bonded"], 12, delta=1e-7)
        self.assertAlmostEqual(energy["non_bonded"], 0., delta=1e-7)
        # bonds deleted
        self.system.part[0].delete_all_bonds()
        self.system.part[1].delete_all_bonds()
        energy = self.system.analysis.energy()
        self.assertAlmostEqual(energy["total"], 0., delta=1e-7)
        self.assertAlmostEqual(energy["kinetic"], 0., delta=1e-7)
        self.assertAlmostEqual(energy["bonded"], 0, delta=1e-7)
        self.assertAlmostEqual(energy["non_bonded"], 0., delta=1e-7)

    def test_all(self):
        self.system.part[0].pos = [1, 2, 2]
        self.system.part[1].pos = [2, 2, 2]
        self.system.part[0].v = [3, 4, 5]
        self.system.part[1].v = [3, 4, 5]
        # single bond
        self.system.part[0].add_bond((self.harmonic, 1))
        energy = self.system.analysis.energy()
        self.assertAlmostEqual(energy["total"], 50. + 3. / 2. + 1., delta=1e-7)
        self.assertAlmostEqual(energy["kinetic"], 50., delta=1e-7)
        self.assertAlmostEqual(energy["bonded"], 3. / 2., delta=1e-7)
        self.assertAlmostEqual(energy["non_bonded"], 1., delta=1e-7)
        # two bonds
        self.system.part[1].add_bond((self.harmonic, 0))
        energy = self.system.analysis.energy()
        self.assertAlmostEqual(energy["total"], 50. + 3 + 1., delta=1e-7)
        self.assertAlmostEqual(energy["kinetic"], 50., delta=1e-7)
        self.assertAlmostEqual(energy["bonded"], 3., delta=1e-7)
        self.assertAlmostEqual(energy["non_bonded"], 1., delta=1e-7)
        # add another pair of particles
        self.system.part.add(id=2, pos=[1, 5, 5], type=1)
        self.system.part.add(id=3, pos=[2, 5, 5], type=1)
        energy = self.system.analysis.energy()
        self.assertAlmostEqual(
            energy["total"], 50. + 3 + (1. + 1.), delta=1e-7)
        self.assertAlmostEqual(energy["kinetic"], 50., delta=1e-7)
        self.assertAlmostEqual(energy["bonded"], 3., delta=1e-7)
        self.assertAlmostEqual(energy["non_bonded"], 1. + 1., delta=1e-7)
        self.system.part[2].remove()
        self.system.part[3].remove()
        self.system.part[0].delete_all_bonds()

    @utx.skipIfMissingFeatures(["ELECTROSTATICS", "P3M"])
    def test_electrostatics(self):

        from espressomd import electrostatics

        self.system.part[0].pos = [1, 2, 2]
        self.system.part[1].pos = [3, 2, 2]
        self.system.part[0].q = 1
        self.system.part[1].q = -1
        p3m = electrostatics.P3M(prefactor=1.0,
                                 accuracy=9.910945054074526e-08,
                                 mesh=[22, 22, 22],
                                 cao=7,
                                 r_cut=8.906249999999998,
                                 alpha=0.387611049779351,
                                 tune=False)
        self.system.actors.add(p3m)

        # did not verify if this is correct, but looks pretty good (close to
        # 1/2)
        u_p3m = -0.501062398379
        energy = self.system.analysis.energy()
        self.assertAlmostEqual(energy["total"], u_p3m, delta=1e-5)
        self.assertAlmostEqual(energy["kinetic"], 0., delta=1e-7)
        self.assertAlmostEqual(energy["bonded"], 0., delta=1e-7)
        self.assertAlmostEqual(energy["non_bonded"], 0, delta=1e-7)
        self.assertAlmostEqual(energy["coulomb"], u_p3m, delta=1e-7)
        self.system.part[0].q = 0
        self.system.part[1].q = 0
        self.system.part[0].pos = [1, 2, 2]
        self.system.part[1].pos = [5, 2, 2]
示例#7
0
else:
    print("\n-->Tune P3M CPU")
    p3m = P3M(prefactor=coulomb_prefactor, accuracy=1e-3)

system.actors.add(p3m)

if args.drude:
    print("-->Adding Drude related bonds")
    thermalized_dist_bond = ThermalizedBond(temp_com=temperature_com,
                                            gamma_com=gamma_com,
                                            temp_distance=temperature_drude,
                                            gamma_distance=gamma_drude,
                                            r_cut=min(lj_sigmas.values()) *
                                            0.5,
                                            seed=123)
    harmonic_bond = HarmonicBond(k=k_drude, r_0=0.0, r_cut=1.0)
    system.bonded_inter.add(thermalized_dist_bond)
    system.bonded_inter.add(harmonic_bond)

    for i in anion_ids:
        drude_helpers.add_drude_particle_to_core(
            system, harmonic_bond, thermalized_dist_bond, system.part[i],
            i + 1, types["PF6_D"], polarizations["PF6"], args.mass_drude,
            coulomb_prefactor)
    for i in cation_c1_ids:
        drude_helpers.add_drude_particle_to_core(
            system, harmonic_bond, thermalized_dist_bond, system.part[i],
            i + 1, types["BMIM_C1_D"], polarizations["BMIM_C1"],
            args.mass_drude, coulomb_prefactor)
    for i in cation_c2_ids:
        drude_helpers.add_drude_particle_to_core(
class ReactionEnsembleTest(ut.TestCase):
    """Test the core implementation of the wang_landau reaction ensemble.

    Create a harmonic bond between the two reacting particles. Therefore the
    potential energy is quadratic in the elongation of the bond and
    therefore the density of states is known as the one of the harmonic
    oscillator
    """

    # System parameters
    #
    box_l = 6 * np.sqrt(2)
    temperature = 1.0

    # Integration parameters
    #
    system = espressomd.System(box_l=[box_l, box_l, box_l])
    system.seed = system.cell_system.get_state()['n_nodes'] * [1234]
    np.random.seed(seed=system.seed)
    system.time_step = 0.01
    system.cell_system.skin = 0
    system.cell_system.set_n_square(use_verlet_lists=False)

    #
    # Setup System
    #

    N0 = 1  # number of titratable units
    K_diss = 0.0088

    system.part.add(id=0, pos=[0, 0, 0] * system.box_l, type=3)
    system.part.add(id=1, pos=[1.0, 1.0, 1.0] * system.box_l / 2.0, type=1)
    system.part.add(id=2, pos=np.random.random() * system.box_l, type=2)
    system.part.add(id=3, pos=np.random.random() * system.box_l, type=2)

    h = HarmonicBond(r_0=0, k=1)
    system.bonded_inter[0] = h
    system.part[0].add_bond((h, 1))
    WLRE = reaction_ensemble.WangLandauReactionEnsemble(
        temperature=temperature, exclusion_radius=0, seed=69)
    WLRE.add_reaction(gamma=K_diss,
                      reactant_types=[0],
                      reactant_coefficients=[1],
                      product_types=[1, 2],
                      product_coefficients=[1, 1],
                      default_charges={
                          0: 0,
                          1: -1,
                          2: +1
                      })
    system.setup_type_map([0, 1, 2, 3])
    # initialize wang_landau
    # generate preliminary_energy_run_results here, this should be done in a
    # separate simulation without energy reweighting using the update energy
    # functions
    np.savetxt("energy_boundaries.dat",
               np.c_[[0, 1], [0, 0], [9, 9]],
               delimiter='\t',
               header="nbar   E_potmin   E_potmax")

    WLRE.add_collective_variable_degree_of_association(
        associated_type=0, min=0, max=1, corresponding_acid_types=[0, 1])
    WLRE.set_wang_landau_parameters(
        final_wang_landau_parameter=1e-2,
        do_not_sample_reaction_partition_function=True,
        full_path_to_output_filename="WL_potential_out.dat")

    def test_wang_landau_energy_recording(self):
        self.WLRE.update_maximum_and_minimum_energies_at_current_state()
        self.WLRE.write_out_preliminary_energy_run_results()
        nbars, E_mins, E_maxs = np.loadtxt("preliminary_energy_run_results",
                                           unpack=True)
        npt.assert_almost_equal(nbars, [0, 1])
        npt.assert_almost_equal(E_mins, [27.0, -10])
        npt.assert_almost_equal(E_maxs, [27.0, -10])

    def test_wang_landau_output(self):
        self.WLRE.add_collective_variable_potential_energy(
            filename="energy_boundaries.dat", delta=0.05)
        while True:
            try:
                self.WLRE.reaction()
                for i in range(2):
                    self.WLRE.displacement_mc_move_for_particles_of_type(3)
            except reaction_ensemble.WangLandauHasConverged:  # only catch my exception
                break
        # test as soon as wang_landau has converged (throws exception then)
        nbars, Epots, WL_potentials = np.loadtxt("WL_potential_out.dat",
                                                 unpack=True)
        mask_nbar_0 = np.where(np.abs(nbars - 1.0) < 0.0001)
        Epots = Epots[mask_nbar_0]
        Epots = Epots[1:]
        WL_potentials = WL_potentials[mask_nbar_0]
        WL_potentials = WL_potentials[1:]

        expected_canonical_potential_energy = np.sum(
            np.exp(WL_potentials) * Epots *
            np.exp(-Epots / self.temperature)) / np.sum(
                np.exp(WL_potentials) * np.exp(-Epots / self.temperature))

        expected_canonical_squared_potential_energy = np.sum(
            np.exp(WL_potentials) * Epots**2 *
            np.exp(-Epots / self.temperature)) / np.sum(
                np.exp(WL_potentials) * np.exp(-Epots / self.temperature))

        expected_canonical_configurational_heat_capacity = expected_canonical_squared_potential_energy - \
            expected_canonical_potential_energy**2

        # for the calculation regarding the analytical results which are
        # compared here, see Master Thesis Jonas Landsgesell p. 72
        self.assertAlmostEqual(
            expected_canonical_potential_energy - 1.5,
            0.00,
            places=1,
            msg=
            "difference to analytical expected canonical potential energy too big"
        )
        self.assertAlmostEqual(
            expected_canonical_configurational_heat_capacity - 1.5,
            0.00,
            places=1,
            msg=
            "difference to analytical expected canonical configurational heat capacity too big"
        )

    def _wang_landau_output_checkpoint(self, filename):
        # write first checkpoint
        self.WLRE.write_wang_landau_checkpoint()
        old_checkpoint = np.loadtxt(filename)

        # modify old_checkpoint in memory and in file (this destroys the
        # information contained in the checkpoint, but allows for testing of
        # the functions)
        modified_checkpoint = old_checkpoint
        modified_checkpoint[0] = 1
        np.savetxt(filename, modified_checkpoint)

        # check whether changes are carried out correctly
        self.WLRE.load_wang_landau_checkpoint()
        self.WLRE.write_wang_landau_checkpoint()
        new_checkpoint = np.loadtxt(filename)
        npt.assert_almost_equal(new_checkpoint, modified_checkpoint)

    def test_wang_landau_output_checkpoint(self):
        filenames = [
            "checkpoint_wang_landau_potential_checkpoint",
            "checkpoint_wang_landau_histogram_checkpoint"
        ]
        for filename in filenames:
            self._wang_landau_output_checkpoint(filename)
示例#9
0
    def test(self):
        # system parameters
        system.box_l = 3 * [10.0]
        skin = 0.4
        time_step = 0.01
        system.time_step = time_step

        # thermostat and cell system
        system.thermostat.set_langevin(kT=0.0, gamma=1.0, seed=41)
        system.cell_system.skin = skin
        system.periodicity = [1, 1, 1]

        # particles and bond
        system.part.add(id=0, pos=[9.9, 9.75, 9.9], type=0, mol_id=0)
        system.part.add(id=1, pos=[9.9, 10.25, 9.9], type=0, mol_id=0)
        system.part.add(id=2, pos=[0.1, 9.7, 0.1], type=1, mol_id=1)
        system.part.add(id=3, pos=[0.1, 10.3, 0.1], type=2, mol_id=2)

        harmonic = HarmonicBond(k=1e4, r_0=0)
        system.bonded_inter.add(harmonic)
        system.part[0].add_bond((harmonic, 1))
        system.part[2].add_bond((harmonic, 3))

        system.non_bonded_inter[0, 0].lennard_jones.set_params(epsilon=1.0,
                                                               sigma=1.0,
                                                               cutoff=2.0,
                                                               shift=0)
        system.non_bonded_inter[1, 2].lennard_jones.set_params(epsilon=1.0,
                                                               sigma=1.0,
                                                               cutoff=2.0,
                                                               shift=0)

        system.integrator.run(steps=0)

        system.part[0].v = [10.0, 20.0, 30.0]
        system.part[1].v = [-15, -25, -35]
        system.part[2].v = [27.0, 23.0, 17.0]
        system.part[3].v = [13.0, 11.0, 19.0]

        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_pressure_kinetic = system.analysis.pressure()['kinetic']
        sim_pressure_bonded = system.analysis.pressure()['bonded']
        sim_pressure_bonded_harmonic = system.analysis.pressure()[
            'bonded', len(system.bonded_inter) - 1]
        sim_pressure_nonbonded = system.analysis.pressure()['non_bonded']
        sim_pressure_nonbonded_inter = system.analysis.pressure(
        )['non_bonded_inter']
        sim_pressure_nonbonded_inter12 = system.analysis.pressure()[
            'non_bonded_inter', 1, 2]
        sim_pressure_nonbonded_intra = system.analysis.pressure(
        )['non_bonded_intra']
        sim_pressure_nonbonded_intra00 = system.analysis.pressure()[
            'non_bonded_intra', 0, 0]
        sim_pressure_total = system.analysis.pressure()['total']

        anal_stress_kinetic = stress_kinetic(vel)
        anal_stress_bonded = stress_bonded(pos)
        anal_stress_nonbonded = stress_nonbonded(system.part.pairs())
        anal_stress_nonbonded_inter = stress_nonbonded_inter(
            system.part.pairs())
        anal_stress_nonbonded_intra = stress_nonbonded_intra(
            system.part.pairs())
        anal_stress_total = anal_stress_kinetic + \
            anal_stress_bonded + anal_stress_nonbonded
        anal_pressure_kinetic = np.einsum('ii', anal_stress_kinetic) / 3.0
        anal_pressure_bonded = np.einsum('ii', anal_stress_bonded) / 3.0
        anal_pressure_nonbonded = np.einsum('ii', anal_stress_nonbonded) / 3.0
        anal_pressure_nonbonded_inter = np.einsum(
            'ii', anal_stress_nonbonded_inter) / 3.0
        anal_pressure_nonbonded_intra = np.einsum(
            'ii', anal_stress_nonbonded_intra) / 3.0
        anal_pressure_total = anal_pressure_kinetic + \
            anal_pressure_bonded + anal_pressure_nonbonded

        system.part.clear()

        self.assertTrue(
            np.max(np.abs(sim_stress_kinetic - anal_stress_kinetic)) < tol,
            'kinetic stress does not match analytical result')
        self.assertTrue(
            np.max(np.abs(sim_stress_bonded - anal_stress_bonded)) < tol,
            'bonded stress does not match analytical result')
        self.assertTrue(
            np.max(
                np.abs(sim_stress_bonded_harmonic - anal_stress_bonded)) < tol,
            'bonded stress harmonic bond does not match analytical result')
        self.assertTrue(
            np.max(np.abs(sim_stress_nonbonded - anal_stress_nonbonded)) < tol,
            'non-bonded stress does not match analytical result')
        self.assertTrue(
            np.max(
                np.abs(sim_stress_nonbonded_inter -
                       anal_stress_nonbonded_inter)) < tol,
            'non-bonded intermolecular stress does not match analytical result'
        )
        self.assertTrue(
            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.assertTrue(
            np.max(
                np.abs(sim_stress_nonbonded_intra -
                       anal_stress_nonbonded_intra)) < tol,
            'non-bonded intramolecular stress does not match analytical result'
        )
        self.assertTrue(
            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.assertTrue(
            np.max(np.abs(sim_stress_total - anal_stress_total)) < tol,
            'total stress does not match analytical result')
        self.assertTrue(
            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.assertTrue(
            np.abs(sim_pressure_kinetic - anal_pressure_kinetic) < tol,
            'kinetic pressure does not match analytical result')
        self.assertTrue(
            np.abs(sim_pressure_bonded - anal_pressure_bonded) < tol,
            'bonded pressure does not match analytical result')
        self.assertTrue(
            np.abs(sim_pressure_bonded_harmonic - anal_pressure_bonded) < tol,
            'bonded pressure harmonic bond does not match analytical result')
        self.assertTrue(
            np.abs(sim_pressure_nonbonded - anal_pressure_nonbonded) < tol,
            'non-bonded pressure does not match analytical result')
        self.assertTrue(
            np.abs(sim_pressure_nonbonded_inter -
                   anal_pressure_nonbonded_inter) < tol,
            'non-bonded intermolecular pressure does not match analytical result'
        )
        self.assertTrue(
            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.assertTrue(
            np.abs(sim_pressure_nonbonded_intra -
                   anal_pressure_nonbonded_intra) < tol,
            'non-bonded intramolecular pressure does not match analytical result'
        )
        self.assertTrue(
            np.abs(sim_pressure_nonbonded_intra00 -
                   anal_pressure_nonbonded_intra) < tol,
            'non-bonded intramolecular pressure molecule 0 does not match analytical result'
        )
        self.assertTrue(
            np.abs(sim_pressure_total - anal_pressure_total) < tol,
            'total pressure does not match analytical result')
        self.assertTrue(
            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'
        )

        # Compare stress tensor observable to stress tensor from analysis
        np.testing.assert_allclose(
            StressTensor().calculate(),
            system.analysis.stress_tensor()["total"].reshape(9),
            atol=1E-10)
示例#10
0
    def test(self):
        # system parameters
        box_l = 10.0
        system.box_l = [box_l, box_l, box_l]
        skin = 0.4
        time_step = 0.01
        system.time_step = time_step

        # thermostat and cell system
        system.thermostat.set_langevin(kT=0.0, gamma=1.0)
        system.cell_system.skin = skin
        system.periodicity = [1, 1, 1]

        # particles and bond
        system.part.add(id=0, pos=[9.9, 9.75, 9.9], type=0, mol_id=0)
        system.part.add(id=1, pos=[9.9, 10.25, 9.9], type=0, mol_id=0)
        system.part.add(id=2, pos=[0.1, 9.7, 0.1], type=1, mol_id=1)
        system.part.add(id=3, pos=[0.1, 10.3, 0.1], type=2, mol_id=2)

        harmonic = HarmonicBond(k=1e4, r_0=0)
        system.bonded_inter.add(harmonic)
        system.part[0].add_bond((harmonic, 1))
        system.part[2].add_bond((harmonic, 3))

        system.non_bonded_inter[0, 0].lennard_jones.set_params(epsilon=1.0,
                                                               sigma=1.0,
                                                               cutoff=2.0,
                                                               shift=0)
        system.non_bonded_inter[1, 2].lennard_jones.set_params(epsilon=1.0,
                                                               sigma=1.0,
                                                               cutoff=2.0,
                                                               shift=0)

        # calculate forces and stress with Lees-Edwards offset
        le_offset = 0.3
        system.lees_edwards_offset = le_offset
        system.integrator.run(steps=0)

        system.part[0].v = [10.0, 20.0, 30.0]
        system.part[1].v = [-15, -25, -35]
        system.part[2].v = [27.0, 23.0, 17.0]
        system.part[3].v = [13.0, 11.0, 19.0]

        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_pressure_kinetic = system.analysis.pressure()['kinetic']
        sim_pressure_bonded = system.analysis.pressure()['bonded']
        sim_pressure_bonded_harmonic = system.analysis.pressure()[
            'bonded', len(system.bonded_inter) - 1]
        sim_pressure_nonbonded = system.analysis.pressure()['non_bonded']
        sim_pressure_nonbonded_inter = system.analysis.pressure(
        )['non_bonded_inter']
        sim_pressure_nonbonded_inter12 = system.analysis.pressure()[
            'non_bonded_inter', 1, 2]
        sim_pressure_nonbonded_intra = system.analysis.pressure(
        )['non_bonded_intra']
        sim_pressure_nonbonded_intra00 = system.analysis.pressure()[
            'non_bonded_intra', 0, 0]
        sim_pressure_total = system.analysis.pressure()['total']

        anal_stress_kinetic = stress_kinetic(vel, box_l)
        anal_stress_bonded = stress_bonded(pos, box_l)
        anal_stress_nonbonded = stress_nonbonded(system.part.pairs(), box_l)
        anal_stress_nonbonded_inter = stress_nonbonded_inter(
            system.part.pairs(), box_l)
        anal_stress_nonbonded_intra = stress_nonbonded_intra(
            system.part.pairs(), box_l)
        anal_stress_total = anal_stress_kinetic + anal_stress_bonded + anal_stress_nonbonded
        anal_pressure_kinetic = np.einsum('ii', anal_stress_kinetic) / 3.0
        anal_pressure_bonded = np.einsum('ii', anal_stress_bonded) / 3.0
        anal_pressure_nonbonded = np.einsum('ii', anal_stress_nonbonded) / 3.0
        anal_pressure_nonbonded_inter = np.einsum(
            'ii', anal_stress_nonbonded_inter) / 3.0
        anal_pressure_nonbonded_intra = np.einsum(
            'ii', anal_stress_nonbonded_intra) / 3.0
        anal_pressure_total = anal_pressure_kinetic + anal_pressure_bonded + anal_pressure_nonbonded

        print('le_offset = {}'.format(system.lees_edwards_offset))

        print('particle positions')
        print(pos)
        print('particle velocities')
        print(vel)

        print('\nsimulated kinetic pressure=')
        print(sim_pressure_kinetic)
        print('analytical kinetic pressure=')
        print(anal_pressure_kinetic)

        print('\nsimulated bonded pressure=')
        print(sim_pressure_bonded)
        print('analytical bonded pressure=')
        print(anal_pressure_bonded)

        print('\nsimulated bonded pressure harmonic bond=')
        print(sim_pressure_bonded_harmonic)
        print('analytical bonded pressure harmonic bond=')
        print(anal_pressure_bonded)

        print('\nsimulated non-bonded pressure=')
        print(sim_pressure_nonbonded)
        print('analytic non-bonded pressure=')
        print(anal_pressure_nonbonded)

        print('\nsimulated non-bonded intermolecular pressure=')
        print(sim_pressure_nonbonded_inter)
        print('analytic non-bonded intermolecular pressure=')
        print(anal_pressure_nonbonded_inter)

        print(
            '\nsimulated non-bonded intermolecular pressure molecule 1 and 2=')
        print(sim_pressure_nonbonded_inter12)
        print('analytic non-bonded intermolecular pressure molecule 1 and 2=')
        print(anal_pressure_nonbonded_inter)

        print('\nsimulated non-bonded intramolecular pressure=')
        print(sim_pressure_nonbonded_intra)
        print('analytic non-bonded intramolecular pressure=')
        print(anal_pressure_nonbonded_intra)

        print('\nsimulated non-bonded intramolecular pressure molecule 0=')
        print(sim_pressure_nonbonded_intra00)
        print('analytic non-bonded intramolecular pressure molecule 0=')
        print(anal_pressure_nonbonded_intra)

        print('\nsimulated total pressure=')
        print(sim_pressure_total)
        print('analytic total pressure=')
        print(anal_pressure_total)

        print('\nsimulated kinetic stress=')
        print(sim_stress_kinetic)
        print('analytic kinetic stress=')
        print(anal_stress_kinetic)

        print('\nsimulated bonded stress=')
        print(sim_stress_bonded)
        print('analytic bonded stress=')
        print(anal_stress_bonded)

        print('\nsimulated bonded stress harmonic bond=')
        print(sim_stress_bonded_harmonic)
        print('analytic bonded stress harmonic bond=')
        print(anal_stress_bonded)

        print('\nsimulated non-bonded stress=')
        print(sim_stress_nonbonded)
        print('analytic non-bonded stress=')
        print(anal_stress_nonbonded)

        print('\nsimulated non-bonded intermolecular stress=')
        print(sim_stress_nonbonded_inter)
        print('analytic non-bonded intermolecular stress=')
        print(anal_stress_nonbonded_inter)

        print(
            '\nsimulated non-bonded intermolecular stress between molecule 1 and 2='
        )
        print(sim_stress_nonbonded_inter12)
        print(
            'analytic non-bonded intermolecular stress between molecule 1 and 2='
        )
        print(anal_stress_nonbonded_inter)

        print('\nsimulated total non-bonded intramolecular stress=')
        print(sim_stress_nonbonded_intra)
        print('analytic total non-bonded intramolecular stress=')
        print(anal_stress_nonbonded_intra)

        print('\nsimulated non-bonded intramolecular stress molecule 0=')
        print(sim_stress_nonbonded_intra00)
        print('analytic non-bonded intramolecular stress molecule 0=')
        print(anal_stress_nonbonded_intra)

        print('\nsimulated total stress=')
        print(sim_stress_total)
        print('analytic total stress=')
        print(anal_stress_total)

        system.part.clear()

        self.assertTrue(
            np.max(np.abs(sim_stress_kinetic - anal_stress_kinetic)) < tol,
            'kinetic stress does not match analytical result')
        self.assertTrue(
            np.max(np.abs(sim_stress_bonded - anal_stress_bonded)) < tol,
            'bonded stress does not match analytical result')
        self.assertTrue(
            np.max(
                np.abs(sim_stress_bonded_harmonic - anal_stress_bonded)) < tol,
            'bonded stress harmonic bond does not match analytical result')
        self.assertTrue(
            np.max(np.abs(sim_stress_nonbonded - anal_stress_nonbonded)) < tol,
            'non-bonded stress does not match analytical result')
        self.assertTrue(
            np.max(
                np.abs(sim_stress_nonbonded_inter -
                       anal_stress_nonbonded_inter)) < tol,
            'non-bonded intermolecular stress does not match analytical result'
        )
        self.assertTrue(
            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.assertTrue(
            np.max(
                np.abs(sim_stress_nonbonded_intra -
                       anal_stress_nonbonded_intra)) < tol,
            'non-bonded intramolecular stress does not match analytical result'
        )
        self.assertTrue(
            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.assertTrue(
            np.max(np.abs(sim_stress_total - anal_stress_total)) < tol,
            'total stress does not match analytical result')
        self.assertTrue(
            np.abs(sim_pressure_kinetic - anal_pressure_kinetic) < tol,
            'kinetic pressure does not match analytical result')
        self.assertTrue(
            np.abs(sim_pressure_bonded - anal_pressure_bonded) < tol,
            'bonded pressure does not match analytical result')
        self.assertTrue(
            np.abs(sim_pressure_bonded_harmonic - anal_pressure_bonded) < tol,
            'bonded pressure harmonic bond does not match analytical result')
        self.assertTrue(
            np.abs(sim_pressure_nonbonded - anal_pressure_nonbonded) < tol,
            'non-bonded pressure does not match analytical result')
        self.assertTrue(
            np.abs(sim_pressure_nonbonded_inter -
                   anal_pressure_nonbonded_inter) < tol,
            'non-bonded intermolecular pressure does not match analytical result'
        )
        self.assertTrue(
            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.assertTrue(
            np.abs(sim_pressure_nonbonded_intra -
                   anal_pressure_nonbonded_intra) < tol,
            'non-bonded intramolecular pressure does not match analytical result'
        )
        self.assertTrue(
            np.abs(sim_pressure_nonbonded_intra00 -
                   anal_pressure_nonbonded_intra) < tol,
            'non-bonded intramolecular pressure molecule 0 does not match analytical result'
        )
        self.assertTrue(
            np.abs(sim_pressure_total - anal_pressure_total) < tol,
            'total pressure does not match analytical result')
        # Compare stress tensor observable to stress tensor from analysis
        np.testing.assert_allclose(
            StressTensor().calculate(),
            system.analysis.stress_tensor()["total"].reshape(9),
            atol=1E-10)
示例#11
0
class CollisionDetection(ut.TestCase):
    """Tests interface and functionality of the collision detection / dynamic binding"""

    s = espressomd.System(box_l=[1.0, 1.0, 1.0])
    s.seed = s.cell_system.get_state()['n_nodes'] * [1234]
    np.random.seed(seed=s.seed)
    if espressomd.has_features("VIRTUAL_SITES"):
        from espressomd.virtual_sites import VirtualSitesRelative
        s.virtual_sites = VirtualSitesRelative()

    H = HarmonicBond(k=5000, r_0=0.1)
    H2 = HarmonicBond(k=25000, r_0=0.02)
    s.bonded_inter.add(H)
    s.bonded_inter.add(H2)
    s.time_step = 0.001
    s.cell_system.skin = 0.05
    s.min_global_cut = 0.112

    part_type_to_attach_vs_to = 0
    part_type_vs = 1
    part_type_to_be_glued = 2
    part_type_after_glueing = 3
    other_type = 5

    def test_00_interface_and_defaults(self):
        # Is it off by default
        self.assertEqual(self.s.collision_detection.mode, "off")
        # Make sure params cannot be set individually
        with self.assertRaises(Exception):
            self.s.collision_detection.mode = "bind_centers"

        # Verify exception throwing for unknown collision modes
        with self.assertRaises(Exception):
            self.s.collision_detection.set_params(mode=0)
            self.s.collision_detection.set_params(mode="blahblah")

        # That should work
        self.s.collision_detection.set_params(mode="off")
        self.assertEqual(self.s.collision_detection.mode, "off")

    def test_bind_centers(self):
        # Check that it leaves particles alone, wehn off
        self.s.collision_detection.set_params(mode="off")

        self.s.part.clear()
        self.s.part.add(pos=(0, 0, 0), id=0)
        self.s.part.add(pos=(0.1, 0, 0), id=1)
        self.s.part.add(pos=(0.1, 0.3, 0), id=2)
        self.s.integrator.run(0)
        self.assertEqual(self.s.part[0].bonds, ())
        self.assertEqual(self.s.part[1].bonds, ())
        self.assertEqual(self.s.part[2].bonds, ())

        # Check that it cannot be activated
        self.s.collision_detection.set_params(mode="bind_centers",
                                              distance=0.11,
                                              bond_centers=self.H)
        self.s.integrator.run(1, recalc_forces=True)
        bond0 = ((self.s.bonded_inter[0], 1), )
        bond1 = ((self.s.bonded_inter[0], 0), )
        self.assertTrue(self.s.part[0].bonds == bond0
                        or self.s.part[1].bonds == bond1)
        self.assertEqual(self.s.part[2].bonds, ())

        # Check that no additional bonds appear
        self.s.integrator.run(1)
        self.assertTrue(self.s.part[0].bonds == bond0
                        or self.s.part[1].bonds == bond1)
        self.assertEqual(self.s.part[2].bonds, ())

        # Check turning it off
        self.s.collision_detection.set_params(mode="off")
        self.assertEqual(self.s.collision_detection.mode, "off")

    def run_test_bind_at_point_of_collision_for_pos(self, *positions):
        positions = list(positions)
        shuffle(positions)
        self.s.part.clear()
        # Place particle which should not take part in collisions
        p = self.s.part.add(pos=(0.1, 0.3, 0))
        for pos in positions:
            p1 = self.s.part.add(pos=pos + (0, 0, 0))
            p2 = self.s.part.add(pos=pos + (0.1, 0, 0))
            if self.s.distance(p1, p) < 0.12 or self.s.distance(p2, p) < 0.12:
                raise Exception(
                    "Test particle too close to particle, which should not take part in collision"
                )

        # 2 non-virtual + 2 virtual + one that doesn't tkae part
        expected_np = 4 * len(positions) + 1

        self.s.collision_detection.set_params(
            mode="bind_at_point_of_collision",
            distance=0.11,
            bond_centers=self.H,
            bond_vs=self.H2,
            part_type_vs=1,
            vs_placement=0.4)
        self.s.integrator.run(0, recalc_forces=True)
        self.verify_state_after_bind_at_poc(expected_np)

        # Integrate again and check that nothing has changed
        self.s.integrator.run(0, recalc_forces=True)
        self.verify_state_after_bind_at_poc(expected_np)

        # Check that nothing explodes, when the particles are moved.
        # In particular for parallel simulations
        self.s.thermostat.set_langevin(kT=0, gamma=0.01)
        self.s.part[:].v = 0.05, 0.01, 0.15
        self.s.integrator.run(3000)
        self.verify_state_after_bind_at_poc(expected_np)

    def verify_state_after_bind_at_poc(self, expected_np):
        self.assertEqual(len(self.s.part), expected_np)

        # At the end of test, this list should be empty
        parts_not_accounted_for = list(range(expected_np))

        # Collect pairs of non-virtual-particles found
        non_virtual_pairs = []

        # We traverse particles. We look for a vs with a bond to find the other vs.
        # From the two vs we find the two non-virtual particles
        for p in self.s.part:
            # Skip non-virtual
            if p.virtual == 0:
                continue
            # Skip vs that doesn't have a bond
            if p.bonds == ():
                continue
            # Parse the bond
            self.assertEqual(len(p.bonds), 1)
            # Bond type
            self.assertEqual(p.bonds[0][0], self.H2)
            # get partner
            p2 = self.s.part[p.bonds[0][1]]
            # Is that really a vs
            self.assertEqual(p2.virtual, 1)
            # Get base particles
            base_p1 = self.s.part[p.vs_relative[0]]
            base_p2 = self.s.part[p2.vs_relative[0]]
            # Take note of accounted-for particles
            for _p in p, p2, base_p1, base_p2:
                parts_not_accounted_for.remove(_p.id)
            self.verify_bind_at_poc_pair(base_p1, base_p2, p, p2)
        # 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, 0)
        self.assertEqual(p.bonds, ())
        parts_not_accounted_for.remove(p.id)
        self.assertEqual(parts_not_accounted_for, [])

    def verify_bind_at_poc_pair(self, p1, p2, vs1, vs2):
        bond_p1 = ((self.s.bonded_inter[0], p2.id), )
        bond_p2 = ((self.s.bonded_inter[0], p1.id), )
        self.assertTrue(p1.bonds == bond_p1 or p2.bonds == bond_p2)

        # Check for presence of vs
        # Check for bond betwen vs
        bond_vs1 = ((self.s.bonded_inter[1], vs2.id), )
        bond_vs2 = ((self.s.bonded_inter[1], vs1.id), )
        self.assertTrue(vs1.bonds == bond_vs1 or vs2.bonds == bond_vs2)

        # Vs properties
        self.assertEqual(vs1.virtual, 1)
        self.assertEqual(vs2.virtual, 1)

        # vs_relative properties
        seen = []
        for p in vs1, vs2:
            r = p.vs_relative
            rel_to = r[0]
            dist = r[1]
            # Vs is related to one of the particles
            self.assertTrue(rel_to == p1.id or rel_to == p2.id)
            # The two vs relate to two different particles
            self.assertNotIn(rel_to, seen)
            seen.append(rel_to)

            # Check placement
            if rel_to == p1.id:
                dist_centers = np.copy(p2.pos - p1.pos)
            else:
                dist_centers = p1.pos - p2.pos
            expected_pos = self.s.part[rel_to].pos_folded + \
                self.s.collision_detection.vs_placement * dist_centers
            np.testing.assert_allclose(np.copy(p.pos_folded),
                                       expected_pos,
                                       atol=1E-4)

    @ut.skipIf(not espressomd.has_features("VIRTUAL_SITES_RELATIVE"),
               "VIRTUAL_SITES not compiled in")
    def test_bind_at_point_of_collision(self):
        # Single collision head node
        self.run_test_bind_at_point_of_collision_for_pos(np.array((0, 0, 0)))
        # Single collision, mixed
        self.run_test_bind_at_point_of_collision_for_pos(np.array(
            (0.45, 0, 0)))
        # Single collision, non-head-node
        self.run_test_bind_at_point_of_collision_for_pos(np.array((0.7, 0, 0)))

        # head-node + mixed
        self.run_test_bind_at_point_of_collision_for_pos(
            np.array((0, 0, 0)), np.array((0.45, 0, 0)))
        # Mixed + other node
        self.run_test_bind_at_point_of_collision_for_pos(
            np.array((0.45, 0, 0)), np.array((0.7, 0, 0)))
        # Head + other
        self.run_test_bind_at_point_of_collision_for_pos(
            np.array((0.0, 0, 0)), np.array((0.7, 0, 0)))
        # Head + mixed + other
        self.run_test_bind_at_point_of_collision_for_pos(
            np.array((0.2, 0, 0)), np.array((0.95, 0, 0)), np.array(
                (0.7, 0, 0)))

    @ut.skipIf(not espressomd.has_features("LENNARD_JONES", "VIRTUAL_SITES"),
               "Skipping for lack of LJ potential")
    def test_bind_at_point_of_collision_random(self):
        """Integrate lj liquid and check that no double bonds are formed
           and the number of bonds fits the number of virtual sites

        """
        self.s.part.clear()

        # Add randomly placed particles
        self.s.part.add(pos=np.random.random((200, 3)))

        # Setup Lennard-Jones
        self.s.non_bonded_inter[0, 0].lennard_jones.set_params(
            epsilon=1, sigma=0.1, cutoff=2**(1. / 6) * 0.1, shift="auto")

        # Remove overalp between particles
        self.s.integrator.set_steepest_descent(f_max=0,
                                               gamma=1,
                                               max_displacement=0.001)
        while self.s.analysis.energy()["total"] > len(self.s.part):
            self.s.integrator.run(10)

        # Collision detection
        self.s.collision_detection.set_params(
            mode="bind_at_point_of_collision",
            distance=0.11,
            bond_centers=self.H,
            bond_vs=self.H2,
            part_type_vs=1,
            vs_placement=0.4)

        # Integrate lj liquid
        self.s.integrator.set_vv()
        self.s.integrator.run(5000)

        # Analysis
        virtual_sites = self.s.part.select(virtual=1)
        non_virtual = self.s.part.select(virtual=0)

        # Check bonds on non-virtual particles
        bonds = []
        for p in non_virtual:
            for bond in p.bonds:
                # Sort bond partners to make them unique independently of
                # which particle got the bond
                bonds.append(tuple(sorted([p.id, bond[1]])))

        # No duplicate bonds?
        self.assertEqual(len(bonds), len(set(bonds)))

        # 2 virtual sites per bond?
        self.assertEqual(2 * len(bonds), len(virtual_sites))

        # Find pairs of bonded virtual sites
        vs_pairs = []
        for p in virtual_sites:
            # 0 or 1 bond on vs?
            self.assertTrue(len(p.bonds) in [0, 1])

            if len(p.bonds) == 1:
                vs_pairs.append((p.id, p.bonds[0][1]))

        # Number of vs pairs = number of bonds?
        self.assertEqual(len(vs_pairs), len(bonds))

        # Che3ck that vs pairs and bonds agree
        for vs_pair in vs_pairs:
            # Get corresponding non-virtual particles
            base_particles = tuple(
                sorted([
                    self.s.part[vs_pair[0]].vs_relative[0],
                    self.s.part[vs_pair[1]].vs_relative[0]
                ]))

            # Is there a corresponding bond?
            self.assertTrue(base_particles in bonds)

        # Tidy
        self.s.non_bonded_inter[0, 0].lennard_jones.set_params(epsilon=0,
                                                               sigma=0,
                                                               cutoff=0)

    def run_test_glue_to_surface_for_pos(self, *positions):
        positions = list(positions)
        shuffle(positions)
        self.s.part.clear()
        # Place particle which should not take part in collisions
        # In this case, it is skipped, because it is of the wrong type,
        # even if it is within range for a collision
        p = self.s.part.add(pos=positions[0], type=self.other_type)
        for pos in positions:
            # Since this is non-symmetric, we randomize order
            if np.random.random() > .5:
                p1 = self.s.part.add(pos=pos + (0, 0, 0),
                                     type=self.part_type_to_attach_vs_to)
                p2 = self.s.part.add(pos=pos + (0.1, 0, 0),
                                     type=self.part_type_to_be_glued)
            else:
                p2 = self.s.part.add(pos=pos + (0.1, 0, 0),
                                     type=self.part_type_to_be_glued)
                p1 = self.s.part.add(pos=pos + (0, 0, 0),
                                     type=self.part_type_to_attach_vs_to)

        # 2 non-virtual + 1 virtual + one that doesn't takekae part
        expected_np = 3 * len(positions) + 1

        self.s.collision_detection.set_params(
            mode="glue_to_surface",
            distance=0.11,
            distance_glued_particle_to_vs=0.02,
            bond_centers=self.H,
            bond_vs=self.H2,
            part_type_vs=self.part_type_vs,
            part_type_to_attach_vs_to=self.part_type_to_attach_vs_to,
            part_type_to_be_glued=self.part_type_to_be_glued,
            part_type_after_glueing=self.part_type_after_glueing)
        self.s.integrator.run(0, recalc_forces=True)
        self.verify_state_after_glue_to_surface(expected_np)

        # Integrate again and check that nothing has changed
        self.s.integrator.run(0, recalc_forces=True)
        self.verify_state_after_glue_to_surface(expected_np)

        # Check that nothing explodes, when the particles are moved.
        # In particular for parallel simulations
        self.s.thermostat.set_langevin(kT=0, gamma=0.01)
        self.s.part[:].v = 0.05, 0.01, 0.15
        self.s.integrator.run(3000)
        self.verify_state_after_glue_to_surface(expected_np)

    def verify_state_after_glue_to_surface(self, expected_np):
        self.assertEqual(len(self.s.part), expected_np)

        # At the end of test, this list should be empty
        parts_not_accounted_for = list(range(expected_np))

        # We traverse particles. We look for a vs, get base particle from there
        # and prtner particle via bonds
        for p in self.s.part:
            # Skip non-virtual
            if p.virtual == 0:
                continue
            # The vs shouldn't have bonds
            self.assertEqual(p.bonds, ())

            # Get base particles
            base_p = self.s.part[p.vs_relative[0]]

            # Get bound particle
            # There is a bond between the base particle and the bound particle
            # but we have no guarantee, on where its stored
            # 1. On the base particle of the vs
            p2 = None
            if len(base_p.bonds) == 1:
                self.assertEqual(base_p.bonds[0][0], self.H)
                p2 = self.s.part[base_p.bonds[0][1]]
            else:
                # We need to go through all particles to find it
                for candidate in self.s.part:
                    if candidate.id not in parts_not_accounted_for:
                        continue
                    if len(candidate.bonds) >= 1:
                        for b in candidate.bonds:
                            if b[0] == self.H and b[1] == base_p.id:
                                p2 = candidate
                if p2 is None:
                    raise Exception("Bound particle not found")
            # Take note of accounted-for particles
            parts_not_accounted_for.remove(base_p.id)
            parts_not_accounted_for.remove(p.id)
            parts_not_accounted_for.remove(p2.id)
            self.verify_glue_to_surface_pair(base_p, p, p2)
        # 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, 0)
        self.assertEqual(p.type, self.other_type)
        self.assertEqual(p.bonds, ())
        parts_not_accounted_for.remove(p.id)
        self.assertEqual(parts_not_accounted_for, [])

    def verify_glue_to_surface_pair(self, base_p, vs, bound_p):
        # Check all types
        self.assertEqual(base_p.type, self.part_type_to_attach_vs_to)
        self.assertEqual(vs.type, self.part_type_vs)
        self.assertEqual(bound_p.type, self.part_type_after_glueing)

        # Bound particle should have a bond to vs. It can additionally have a bond
        # to the base particle
        bond_to_vs_found = 0
        for b in bound_p.bonds:
            if b[0] == self.H2:
                # bond to vs
                self.assertEqual(b, (self.H2, vs.id))
                bond_to_vs_found += 1
        self.assertEqual(bond_to_vs_found, 1)
        # Vs should not have a bond
        self.assertEqual(vs.bonds, ())

        # Vs properties
        self.assertEqual(vs.virtual, 1)
        self.assertEqual(vs.vs_relative[0], base_p.id)

        # Distance vs,bound_p
        self.assertAlmostEqual(self.s.distance(vs, bound_p), 0.02, places=3)
        self.assertAlmostEqual(self.s.distance(base_p, bound_p), 0.1, places=3)
        self.assertAlmostEqual(self.s.distance(base_p, vs), 0.08, places=3)

        # base_p,vs,bound_p on a line
        self.assertGreater(
            np.dot(self.s.distance_vec(base_p, vs),
                   self.s.distance_vec(base_p, bound_p)) /
            self.s.distance(base_p, vs) / self.s.distance(base_p, bound_p),
            0.99)

    @ut.skipIf(not espressomd.has_features("VIRTUAL_SITES_RELATIVE"),
               "Skipped due to missing VIRTUAL_SITES_RELATIVE")
    def test_glue_to_surface(self):
        # Single collision head node
        self.run_test_glue_to_surface_for_pos(np.array((0, 0, 0)))
        # Single collision, mixed
        self.run_test_glue_to_surface_for_pos(np.array((0.45, 0, 0)))
        # Single collision, non-head-node
        self.run_test_glue_to_surface_for_pos(np.array((0.7, 0, 0)))

        # head-node + mixed
        self.run_test_glue_to_surface_for_pos(np.array((0, 0, 0)),
                                              np.array((0.45, 0, 0)))
        # Mixed + other node
        self.run_test_glue_to_surface_for_pos(np.array((0.45, 0, 0)),
                                              np.array((0.7, 0, 0)))
        # Head + other
        self.run_test_glue_to_surface_for_pos(np.array((0.0, 0, 0)),
                                              np.array((0.7, 0, 0)))
        # Head + mixed + other
        self.run_test_glue_to_surface_for_pos(np.array((0.2, 0, 0)),
                                              np.array((0.95, 0, 0)),
                                              np.array((0.7, 0, 0)))

    @ut.skipIf(not espressomd.has_features("VIRTUAL_SITES_RELATIVE"),
               "VIRTUAL_SITES not compiled in")
    def test_glue_to_surface_random(self):
        """Integrate lj liquid and check that no double bonds are formed
           and the number of bonds fits the number of virtual sites

        """
        self.s.part.clear()

        # Add randomly placed particles
        self.s.part.add(pos=np.random.random((100, 3)),
                        type=100 * [self.part_type_to_attach_vs_to])
        self.s.part.add(pos=np.random.random((100, 3)),
                        type=100 * [self.part_type_to_be_glued])
        self.s.part.add(pos=np.random.random((100, 3)),
                        type=100 * [self.other_type])

        # Setup Lennard-Jones
        self.s.non_bonded_inter[0, 0].lennard_jones.set_params(
            epsilon=1, sigma=0.1, cutoff=2**(1. / 6) * 0.1, shift="auto")

        # Remove overalp between particles
        self.s.integrator.set_steepest_descent(f_max=0,
                                               gamma=1,
                                               max_displacement=0.001)
        while self.s.analysis.energy()["total"] > len(self.s.part):
            self.s.integrator.run(10)

        # Collision detection
        self.s.collision_detection.set_params(
            mode="glue_to_surface",
            distance=0.11,
            distance_glued_particle_to_vs=0.02,
            bond_centers=self.H,
            bond_vs=self.H2,
            part_type_vs=self.part_type_vs,
            part_type_to_attach_vs_to=self.part_type_to_attach_vs_to,
            part_type_to_be_glued=self.part_type_to_be_glued,
            part_type_after_glueing=self.part_type_after_glueing)

        # Integrate lj liquid
        self.s.integrator.set_vv()
        self.s.integrator.run(500)

        # Analysis
        virtual_sites = self.s.part.select(virtual=1)
        non_virtual = self.s.part.select(virtual=0)
        to_be_glued = self.s.part.select(type=self.part_type_to_be_glued)
        after_glueing = self.s.part.select(type=self.part_type_after_glueing)

        # One virtual site per glued particle?
        self.assertEqual(len(after_glueing), len(virtual_sites))

        # Check bonds on non-virtual particles
        bonds_centers = []
        bonds_virtual = []
        for p in non_virtual:
            # Inert particles should not have bonds
            if p.type == self.other_type:
                self.assertEqual(len(p.bonds), 0)

            # Particles that have not yet collided should not have a bond
            if p.type == self.part_type_to_be_glued:
                self.assertEqual(len(p.bonds), 0)

            for bond in p.bonds:
                # Bond type and partner type
                # 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))
                    # Bonds to virtual sites:
                    if bond[0] == self.H2:
                        self.assertEqual(self.s.part[bond[1]].type,
                                         self.part_type_vs)
                    else:
                        self.assertEqual(self.s.part[bond[1]].type,
                                         self.part_type_to_attach_vs_to)
                elif p.type == self.part_type_to_attach_vs_to:
                    self.assertEqual(bond[0], self.H)
                    self.assertEqual(self.s.part[bond[1]].type,
                                     self.part_type_after_glueing)
                else:
                    print(p.id, p.type, p.bonds)
                    raise Exception("Particle should not have bonds. ")

                # Collect bonds
                # Sort bond partners to make them unique independently of
                # which particle got the bond
                if bond[0] == self.H:
                    bonds_centers.append(tuple(sorted([p.id, bond[1]])))
                else:
                    bonds_virtual.append(tuple(sorted([p.id, bond[1]])))

        # No duplicate bonds?
        self.assertEqual(len(bonds_centers), len(set(bonds_centers)))
        self.assertEqual(len(bonds_virtual), len(set(bonds_virtual)))

        # 1 bond between centers and one between vs and glued particle
        # per collision
        self.assertEqual(len(bonds_virtual), len(bonds_centers))

        # 1 virtual sites per bond?
        self.assertEqual(len(bonds_centers), len(virtual_sites))

        # no bonds on vs and vs particle type
        for p in virtual_sites:
            self.assertEqual(len(p.bonds), 0)
            self.assertEqual(p.type, self.part_type_vs)

        # Tidy
        self.s.non_bonded_inter[0, 0].lennard_jones.set_params(epsilon=0,
                                                               sigma=0,
                                                               cutoff=0)

    #@ut.skipIf(not espressomd.has_features("AngleHarmonic"),"Tests skipped because AngleHarmonic not compiled in")
    def test_AngleHarmonic(self):
        # Setup particles
        self.s.part.clear()
        dx = np.array((1, 0, 0))
        dy = np.array((0, 1, 0))
        dz = np.array((0, 0, 1))
        a = np.array((0.499, 0.499, 0.499))
        b = a + 0.1 * dx
        c = a + 0.03 * dx + 0.03 * dy
        d = a + 0.03 * dx - 0.03 * dy
        e = a - 0.1 * dx

        self.s.part.add(id=0, pos=a)
        self.s.part.add(id=1, pos=b)
        self.s.part.add(id=2, pos=c)
        self.s.part.add(id=3, pos=d)
        self.s.part.add(id=4, pos=e)

        # Setup bonds
        res = 181
        for i in range(0, res, 1):
            self.s.bonded_inter[i + 2] = AngleHarmonic(bend=1,
                                                       phi0=float(i) /
                                                       (res - 1) * np.pi)
        cutoff = 0.11
        self.s.collision_detection.set_params(
            mode="bind_three_particles",
            bond_centers=self.H,
            bond_three_particles=2,
            three_particle_binding_angle_resolution=res,
            distance=cutoff)
        self.s.integrator.run(0, recalc_forces=True)
        self.verify_triangle_binding(cutoff, self.s.bonded_inter[2], res)

        # Make sure no extra bonds appear
        self.s.integrator.run(0, recalc_forces=True)
        self.verify_triangle_binding(cutoff, self.s.bonded_inter[2], res)

        # Place the particles in two steps and make sure, the bonds are the
        # same
        self.s.part.clear()
        self.s.part.add(id=0, pos=a)
        self.s.part.add(id=2, pos=c)
        self.s.part.add(id=3, pos=d)
        self.s.integrator.run(0, recalc_forces=True)

        self.s.part.add(id=4, pos=e)
        self.s.part.add(id=1, pos=b)
        self.s.cell_system.set_domain_decomposition()
        self.s.integrator.run(0, recalc_forces=True)
        self.verify_triangle_binding(cutoff, self.s.bonded_inter[2], res)
        self.s.cell_system.set_n_square()
        self.s.part[:].bonds = ()
        self.s.integrator.run(0, recalc_forces=True)
        self.verify_triangle_binding(cutoff, self.s.bonded_inter[2], res)

    def verify_triangle_binding(self, distance, first_bond, angle_res):
        # Gather pairs
        n = len(self.s.part)
        angle_res = angle_res - 1

        expected_pairs = []
        for i in range(n):
            for j in range(i + 1, n, 1):
                if self.s.distance(self.s.part[i], self.s.part[j]) <= distance:
                    expected_pairs.append((i, j))

        # Find triangles
        # Each elemtn is a particle id, a bond id and two bond partners in
        # ascending order
        expected_angle_bonds = []
        for i in range(n):
            for j in range(i + 1, n, 1):
                for k in range(j + 1, n, 1):
                    # Ref to particles
                    p_i = self.s.part[i]
                    p_j = self.s.part[j]
                    p_k = self.s.part[k]

                    # Normalized distnace vectors
                    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))

                    if self.s.distance(p_i,
                                       p_j) <= distance and self.s.distance(
                                           p_i, p_k) <= distance:
                        id_i = first_bond._bond_id + \
                            int(np.round(
                                np.arccos(np.dot(d_ij, d_ik)) * angle_res / np.pi))
                        expected_angle_bonds.append((i, id_i, j, k))

                    if self.s.distance(p_i,
                                       p_j) <= distance and self.s.distance(
                                           p_j, p_k) <= distance:
                        id_j = first_bond._bond_id + \
                            int(np.round(
                                np.arccos(np.dot(-d_ij, d_jk)) * angle_res / np.pi))
                        expected_angle_bonds.append((j, id_j, i, k))
                    if self.s.distance(p_i,
                                       p_k) <= distance and self.s.distance(
                                           p_j, p_k) <= distance:
                        id_k = first_bond._bond_id + \
                            int(np.round(
                                np.arccos(np.dot(-d_ik, -d_jk)) * angle_res / np.pi))
                        expected_angle_bonds.append((k, id_k, i, j))

        # Gather actual pairs and actual triangles
        found_pairs = []
        found_angle_bonds = []
        for i in range(n):
            for b in self.s.part[i].bonds:
                if len(b) == 2:
                    self.assertEqual(b[0]._bond_id, self.H._bond_id)
                    found_pairs.append(tuple(sorted((i, b[1]))))
                elif len(b) == 3:
                    partners = sorted(b[1:])
                    found_angle_bonds.append(
                        (i, b[0]._bond_id, partners[0], partners[1]))
                else:
                    raise Exception(
                        "There should be only 2 and three particle bonds")

        # The order between expected and found bonds does not malways match
        # because collisions occur in random order. Sort stuff
        found_pairs = sorted(found_pairs)
        found_angle_bonds = sorted(found_angle_bonds)
        expected_angle_bonds = sorted(expected_angle_bonds)
        self.assertEqual(expected_pairs, found_pairs)

        if not expected_angle_bonds == found_angle_bonds:
            # Verbose info
            print("expected:", expected_angle_bonds)
            missing = []
            for b in expected_angle_bonds:
                if b in found_angle_bonds:
                    found_angle_bonds.remove(b)
                else:
                    missing.append(b)
            print("missing", missing)
            print("extra:", found_angle_bonds)
            print()

        self.assertEqual(expected_angle_bonds, found_angle_bonds)
# type 1 = A-
# type 2 = H+

N0 = 1  # number of titratable units
K_diss = 0.0088

system.part.add(id=0, pos=[0, 0, 0] * system.box_l, type=3)
system.part.add(id=1, pos=[1.0, 1.0, 1.0] * system.box_l / 2.0, type=1)
system.part.add(id=2, pos=np.random.random() * system.box_l, type=2)
system.part.add(id=3, pos=np.random.random() * system.box_l, type=2)

# create a harmonic bond between the two reacting particles => the
# potential energy is quadratic in the elongation of the bond and
# therefore the density of states is known as the one of the harmonic
# oscillator
h = HarmonicBond(r_0=0, k=1)
system.bonded_inter[0] = h
system.part[0].add_bond((h, 1))


RE = reaction_ensemble.WangLandauReactionEnsemble(
    temperature=1, exclusion_radius=0, seed=77)
RE.add_reaction(gamma=K_diss, reactant_types=[0], reactant_coefficients=[1],
                product_types=[1, 2], product_coefficients=[1, 1],
                default_charges={0: 0, 1: -1, 2: +1})
print(RE.get_status())
system.setup_type_map([0, 1, 2, 3])


# initialize wang_landau
# generate preliminary_energy_run_results here, this should be done in a
示例#13
0
    def test(self):
        # system parameters
        system.box_l = 3 * [10.0]
        skin = 0.4
        time_step = 0.01
        system.time_step = time_step

        # thermostat and cell system
        system.thermostat.set_langevin(kT=0.0, gamma=1.0, seed=41)
        system.cell_system.skin = skin
        system.periodicity = [1, 1, 1]

        # particles and bond
        p0 = system.part.add(pos=[9.9, 9.75, 9.9], type=0, mol_id=0)
        p1 = system.part.add(pos=[9.9, 10.25, 9.9], type=0, mol_id=0)
        p2 = system.part.add(pos=[0.1, 9.7, 0.1], type=1, mol_id=1)
        p3 = system.part.add(pos=[0.1, 10.3, 0.1], type=2, mol_id=2)

        harmonic = HarmonicBond(k=1e4, r_0=0)
        system.bonded_inter.add(harmonic)
        p0.add_bond((harmonic, p1))
        p2.add_bond((harmonic, p3))

        system.non_bonded_inter[0, 0].lennard_jones.set_params(epsilon=1.0,
                                                               sigma=1.0,
                                                               cutoff=2.0,
                                                               shift=0)
        system.non_bonded_inter[1, 2].lennard_jones.set_params(epsilon=1.0,
                                                               sigma=1.0,
                                                               cutoff=2.0,
                                                               shift=0)

        system.integrator.run(steps=0)

        p0.v = [10.0, 20.0, 30.0]
        p1.v = [-15., -25., -35.]
        p2.v = [27.0, 23.0, 17.0]
        p3.v = [13.0, 11.0, 19.0]

        pos = system.part[:].pos
        vel = system.part[:].v

        sim_pressure_tensor = system.analysis.pressure_tensor()
        sim_pressure_tensor_kinetic = np.copy(sim_pressure_tensor['kinetic'])
        sim_pressure_tensor_bonded = np.copy(sim_pressure_tensor['bonded'])
        sim_pressure_tensor_bonded_harmonic = np.copy(
            sim_pressure_tensor['bonded',
                                len(system.bonded_inter) - 1])
        sim_pressure_tensor_nonbonded = np.copy(
            sim_pressure_tensor['non_bonded'])
        sim_pressure_tensor_nonbonded_inter = np.copy(
            sim_pressure_tensor['non_bonded_inter'])
        sim_pressure_tensor_nonbonded_inter12 = np.copy(
            sim_pressure_tensor['non_bonded_inter', 1, 2])
        sim_pressure_tensor_nonbonded_intra = np.copy(
            sim_pressure_tensor['non_bonded_intra'])
        sim_pressure_tensor_nonbonded_intra00 = np.copy(
            sim_pressure_tensor['non_bonded_intra', 0, 0])
        sim_pressure_tensor_total = np.copy(sim_pressure_tensor['total'])

        sim_pressure = system.analysis.pressure()
        sim_pressure_kinetic = sim_pressure['kinetic']
        sim_pressure_bonded = sim_pressure['bonded']
        sim_pressure_bonded_harmonic = sim_pressure['bonded',
                                                    len(system.bonded_inter) -
                                                    1]
        sim_pressure_nonbonded = sim_pressure['non_bonded']
        sim_pressure_nonbonded_inter = sim_pressure['non_bonded_inter']
        sim_pressure_nonbonded_inter12 = sim_pressure['non_bonded_inter', 1, 2]
        sim_pressure_nonbonded_intra = sim_pressure['non_bonded_intra']
        sim_pressure_nonbonded_intra00 = sim_pressure['non_bonded_intra', 0, 0]
        sim_pressure_total = sim_pressure['total']

        anal_pressure_tensor_kinetic = pressure_tensor_kinetic(vel)
        anal_pressure_tensor_bonded = pressure_tensor_bonded(pos)
        anal_pressure_tensor_nonbonded = pressure_tensor_nonbonded(
            system.part.pairs())
        anal_pressure_tensor_nonbonded_inter = pressure_tensor_nonbonded_inter(
            system.part.pairs())
        anal_pressure_tensor_nonbonded_intra = pressure_tensor_nonbonded_intra(
            system.part.pairs())
        anal_pressure_tensor_total = anal_pressure_tensor_kinetic + \
            anal_pressure_tensor_bonded + anal_pressure_tensor_nonbonded
        anal_pressure_kinetic = np.einsum('ii',
                                          anal_pressure_tensor_kinetic) / 3.0
        anal_pressure_bonded = np.einsum('ii',
                                         anal_pressure_tensor_bonded) / 3.0
        anal_pressure_nonbonded = np.einsum(
            'ii', anal_pressure_tensor_nonbonded) / 3.0
        anal_pressure_nonbonded_inter = np.einsum(
            'ii', anal_pressure_tensor_nonbonded_inter) / 3.0
        anal_pressure_nonbonded_intra = np.einsum(
            'ii', anal_pressure_tensor_nonbonded_intra) / 3.0
        anal_pressure_total = anal_pressure_kinetic + \
            anal_pressure_bonded + anal_pressure_nonbonded

        np.testing.assert_allclose(
            sim_pressure_tensor_kinetic,
            anal_pressure_tensor_kinetic,
            rtol=0,
            atol=tol,
            err_msg='kinetic pressure tensor does not match analytical result')
        np.testing.assert_allclose(
            sim_pressure_tensor_bonded,
            anal_pressure_tensor_bonded,
            rtol=0,
            atol=tol,
            err_msg='bonded pressure tensor does not match analytical result')
        np.testing.assert_allclose(
            sim_pressure_tensor_bonded_harmonic,
            anal_pressure_tensor_bonded,
            rtol=0,
            atol=tol,
            err_msg=
            'bonded pressure tensor harmonic bond does not match analytical result'
        )
        np.testing.assert_allclose(
            sim_pressure_tensor_nonbonded,
            anal_pressure_tensor_nonbonded,
            rtol=0,
            atol=tol,
            err_msg=
            'non-bonded pressure tensor does not match analytical result')
        np.testing.assert_allclose(
            sim_pressure_tensor_nonbonded_inter,
            anal_pressure_tensor_nonbonded_inter,
            rtol=0,
            atol=tol,
            err_msg=
            'non-bonded intermolecular pressure tensor does not match analytical result'
        )
        np.testing.assert_allclose(
            sim_pressure_tensor_nonbonded_inter12,
            anal_pressure_tensor_nonbonded_inter,
            rtol=0,
            atol=tol,
            err_msg=
            'non-bonded intermolecular pressure tensor molecules 1 and 2 does not match analytical result'
        )
        np.testing.assert_allclose(
            sim_pressure_tensor_nonbonded_intra,
            anal_pressure_tensor_nonbonded_intra,
            rtol=0,
            atol=tol,
            err_msg=
            'non-bonded intramolecular pressure tensor does not match analytical result'
        )
        np.testing.assert_allclose(
            sim_pressure_tensor_nonbonded_intra00,
            anal_pressure_tensor_nonbonded_intra,
            rtol=0,
            atol=tol,
            err_msg=
            'non-bonded intramolecular pressure tensor molecule 0 does not match analytical result'
        )
        np.testing.assert_allclose(
            sim_pressure_tensor_total,
            anal_pressure_tensor_total,
            rtol=0,
            atol=tol,
            err_msg='total pressure tensor does not match analytical result')
        np.testing.assert_allclose(
            sim_pressure_tensor_total,
            sim_pressure_tensor_kinetic + sim_pressure_tensor_bonded +
            sim_pressure_tensor_nonbonded,
            rtol=0,
            atol=tol,
            err_msg=
            'total pressure tensor is not given as the sum of all major pressure 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 pressure observables to pressure from analysis
        np.testing.assert_allclose(PressureTensor().calculate(),
                                   sim_pressure_tensor["total"],
                                   rtol=0,
                                   atol=1E-10)
        self.assertAlmostEqual(Pressure().calculate(),
                               sim_pressure["total"],
                               delta=tol)
示例#14
0
frac_range = [x / 100 for x in range(0, 100, 25)
              if x != 0]  # # # #    frac' range

n_polymers = 1000  # # # #    total polymers
i_box_l = ((((bpc_range[0] * n_polymers) / dens_range[0])**(1. / 3.)) -
           1) * np.ones(3)  # # # #    initial box length
system = espressomd.System(box_l=i_box_l, periodicity=[True, True, True])

################################
#####     Interactions     #####
################################

eps = 1.0
sig = 1.0
cut = 2.5  # # # #    non_bonded interaction's variables
hb = HarmonicBond(k=30., r_0=1.)
system.bonded_inter.add(hb)
system.non_bonded_inter[0, 0].lennard_jones.set_params(epsilon=.9 * eps,
                                                       sigma=.9 * sig,
                                                       cutoff=cut,
                                                       shift=0)
system.non_bonded_inter[0, 1].wca.set_params(epsilon=1.2 * eps,
                                             sigma=1.2 * sig)
system.non_bonded_inter[1, 1].wca.set_params(epsilon=1.2 * eps,
                                             sigma=1.2 * sig)

for a in bpc_range:

    configs = open('configurations_of_' + str(a) + '_beads.txt', 'a+')
    configs.write(
        " Total Particles | Monomers per Polymer | Real Frac Phobic | Density | Average Radius of Gyration | Mean End-To-End Distance of Chains\n"
示例#15
0
system = espressomd.System()
system.time_step = 0.01
system.skin      = 0.4
system.thermostat.set_langevin(kT=1.0,gamma=1.0)

# integration
int_steps   = 250000
int_n_times = 500

system.box_l = [box_l,box_l,box_l]

system.non_bonded_inter[0,0].lennard_jones.set_params(
    epsilon=0, sigma=1,
    cutoff=2, shift="auto")
system.bonded_inter[0] = HarmonicBond(k=1.0,r_0=1.0)
system.bonded_inter[1] = HarmonicBond(k=1.0,r_0=1.0)

for i in range(n_part):
  system.part.add(id=i, pos=numpy.random.random(3) * system.box_l)

for i in range(n_part/2):
  system.part[i].add_bond((system.bonded_inter[0], system.part[i+1].id))
for i in range(n_part/2,n_part-1):
  system.part[i].add_bond((system.bonded_inter[1], system.part[i+1].id))

mayavi = visualization.mayavi_live(system)

j = 0
for i in range(0,int_n_times):
  print(i)