Esempio n. 1
0
"""
This sample sets up an electrokinetics (LB) fluid confined between charged walls.
"""

import espressomd

required_features = ["ELECTROKINETICS", "EK_BOUNDARIES", "EXTERNAL_FORCES"]
espressomd.assert_features(required_features)

from espressomd import System, shapes, electrokinetics
import sys

system = System(box_l=[10, 10, 10])
system.set_random_state_PRNG()
#system.seed = system.cell_system.get_state()['n_nodes'] * [1234]

system.cell_system.skin = 0.4
system.time_step = 0.1

ek = electrokinetics.Electrokinetics(lb_density=1,
                                     friction=1,
                                     agrid=1,
                                     viscosity=1,
                                     T=1,
                                     prefactor=1)

pos = electrokinetics.Species(density=0.05,
                              D=0.1,
                              valency=1,
                              ext_force_density=[0, 0, 1.])
neg = electrokinetics.Species(density=0.05,
Esempio n. 2
0
print("""
Start warmup integration:
At maximum {} times {} steps
Stop if minimal distance is larger than {}
""".strip().format(warm_n_times, warm_steps, min_dist))

# set LJ cap
lj_cap = 20
es.nonBondedInter.setForceCap(lj_cap)
print(es.nonBondedInter[0,0].lennardJones)

# Warmup Integration Loop
i = 0
while (i < warm_n_times and act_min_dist < min_dist):
  es.integrate(warm_steps)
  # Warmup criterion
#  act_min_dist = float(es._espressoHandle.Tcl_Eval('analyze mindist'))
  act_min_dist = es.analyze.mindist() 
#  print("\rrun %d at time=%f (LJ cap=%f) min dist = %f\r" % (i,es.glob.time,lj_cap,act_min_dist), end=' ')
  i += 1

#   write observables
#    puts $obs_file "{ time [setmd time] } [analyze energy]"

#   Increase LJ cap
  lj_cap = lj_cap + 10
  es.nonBondedInter.setForceCap(lj_cap)

# Just to see what else we may get from the c code
print("""
Esempio n. 3
0
def calc(var):

    # AVB: Create an output directory for this to store the output files
    outdir = "./Noelle/r01.5kBT4Ads/1000=3.2"
    if not os.path.exists(outdir):
        os.makedirs(outdir)

    # Setup constant
    time_step = 0.01
    loops = 30
    step_per_loop = 100

    # AVB: the parameters (that I usually use)
    a = 0.05
    r0 = 2.0 * a
    kBT = 4.0e-6
    vwf_type = 0
    collagen_type = 1
    monomer_mass = 0.01

    box_l = 32.0
    #print("Shear velocity:")
    #shear_velocity = float(input())
    #vy = box_l*shear_velocity
    vy = var
    print(vy)
    v = [0, vy, 0]

    # System setup

    system = 0

    system = System(box_l=[box_l, box_l, box_l])
    system.set_random_state_PRNG()
    np.random.seed(seed=system.seed)
    system.cell_system.skin = 0.4

    mpc = 20  # The number of monomers has been set to be 20 as default
    # Change this value for further simulations

    # Fene interaction
    fene = interactions.FeneBond(k=0.04, d_r_max=0.3)
    system.bonded_inter.add(fene)

    # Setup polymer of part_id 0 with fene bond
    # AVB: Notice the mode, max_tries and shield parameters for pruned self-avoiding random walk algorithm
    polymer.create_polymer(N_P=1,
                           MPC=mpc,
                           bond=fene,
                           bond_length=r0,
                           start_pos=[29.8, 16.0, 16.0],
                           mode=2,
                           max_tries=100,
                           shield=0.6 * r0)

    # AVB: setting the type of particles and changing mass of each monomer to 0.01
    system.part[:].type = vwf_type
    system.part[:].mass = monomer_mass

    # AVB: I suggest to add Lennard-Jones interaction between the monomers
    # AVB: to reproduce hydrophobicity
    # AVB: parameters for the potential (amplitude and cut-off redius)
    amplVwfVwf = 4.0 * kBT  # sometimes we change this to 2.0*kBT
    rcutVwfVwf = 1.5 * r0
    # AVB: the potential
    system.non_bonded_inter[vwf_type, vwf_type].lennard_jones.set_params(
        epsilon=amplVwfVwf,
        sigma=r0 / 1.122,
        shift="auto",
        cutoff=rcutVwfVwf,
        min=r0 * 0.6)

    print("Warming up the polymer chain.")
    ## For longer chains (>100) an extensive
    ## warmup is neccessary ...
    system.time_step = 0.002
    system.thermostat.set_langevin(kT=4.0e-6, gamma=1.0)
    # AVB: Here the Langevin thermostat is needed, because we have not yet initialized the LB-fluid.
    # AVB: And somehow it is necessary so that the polymer adopts the equilibrium conformation of the globule.
    # AVB: you may skip this step

    for i in range(100):
        system.force_cap = float(i) + 1
        system.integrator.run(100)

    print("Warmup finished.")
    system.force_cap = 0
    system.integrator.run(100)
    system.time_step = time_step
    system.integrator.run(500)

    # AVB: the following command turns the Langevin thermostat on in line 49
    system.thermostat.turn_off()

    # AVB: This command sets the velocities of all particles to zero
    system.part[:].v = [0, 0, 0]

    # AVB: The density was too small here. I have set 1.0 for now.
    # AVB: It would be necessary to recalculate, but the density of the liquid should not affect the movements of the polymer (this is how our physical model works).
    lbf = espressomd.lb.LBFluid(agrid=1,
                                dens=1.0,
                                visc=1.0e2,
                                tau=time_step,
                                fric=0.01)
    system.actors.add(lbf)
    system.thermostat.set_lb(kT=4.0e-6)

    # Setup boundaries
    walls = [lbboundaries.LBBoundary() for k in range(2)]
    walls[0].set_params(shape=shapes.Wall(normal=[1, 0, 0], dist=1.5),
                        velocity=v)
    walls[1].set_params(shape=shapes.Wall(normal=[-1, 0, 0], dist=-30.5))

    for wall in walls:
        system.lbboundaries.add(wall)

    print("Warming up the system with LB fluid.")
    system.integrator.run(5000)
    print("LB fluid warming finished.")
    # AVB: after this you should have a completely collapsed polymer globule
    # AVB: If you want to watch the process of globule formation in Paraview, just change 5000 to 0 in line 100

    N = 25
    x_coord = np.array([30] * N)
    y_coord = np.arange(14, 24, 5 / N)
    z_coord = np.arange(14, 24, 5 / N)
    for i in range(N):
        for j in range(N):
            system.part.add(id=i * N + j + 100,
                            pos=np.array([x_coord[i], y_coord[j], z_coord[i]]),
                            v=np.array([0, 0, 0]),
                            type=i * N + j + 100)

    all_collagen = range(100, (N - 1) * N + (N - 1) + 100)
    system.comfixed.types = all_collagen

    for i in range(100, (N - 1) * N + (N - 1) + 100):
        system.non_bonded_inter[vwf_type,
                                i].lennard_jones.set_params(epsilon=amplVwfVwf,
                                                            sigma=r0 / 1.122,
                                                            shift="auto",
                                                            cutoff=rcutVwfVwf,
                                                            min=r0 * 0.6)

    # configure correlators
    com_pos = ComPosition(ids=(0, ))
    c = Correlator(obs1=com_pos,
                   tau_lin=16,
                   tau_max=loops * step_per_loop,
                   delta_N=1,
                   corr_operation="square_distance_componentwise",
                   compress1="discard1")
    system.auto_update_accumulators.add(c)

    print("Sampling started.")
    print("lenth after warmup")
    print(
        system.analysis.calc_re(chain_start=0,
                                number_of_chains=1,
                                chain_length=mpc - 1)[0])

    lengths = []

    ylengths = []

    for i in range(loops):
        system.integrator.run(step_per_loop)
        system.analysis.append()
        lengths.append(
            system.analysis.calc_re(chain_start=0,
                                    number_of_chains=1,
                                    chain_length=mpc - 1)[0])
        lbf.print_vtk_velocity(outdir + "/" + str(vy) + "%04i.vtk" % i)
        system.part.writevtk(outdir + "/" + str(vy) + "vwf_all%04i.vtk" % i,
                             types=all_collagen)
        system.part.writevtk(outdir + "/" + str(vy) + "vwf_poly%04i.vtk" % i,
                             types=[0])
        cor = list(system.part[:].pos)
        y = []
        for l in cor:
            y.append(l[1])
        ylengths.append(max(y) - min(y))

        sys.stdout.write("\rSampling: %05i" % i)
        sys.stdout.flush()

    walls[0].set_params(shape=shapes.Wall(normal=[1, 0, 0], dist=1.5))
    walls[1].set_params(shape=shapes.Wall(normal=[-1, 0, 0], dist=-30.5))

    for i in range(100):
        system.integrator.run(step_per_loop)
        lengths.append(
            system.analysis.calc_re(chain_start=0,
                                    number_of_chains=1,
                                    chain_length=mpc - 1)[0])

    system.part.writevtk(outdir + "/" + str(vy) +
                         "vwf_all[r0=2,kBT=4]intheEND.vtk")

    with open(outdir + "/lengths" + str(vy) + ".dat", "a") as datafile:
        datafile.write("\n".join(map(str, lengths)))

    with open(outdir + "/lengthsY" + str(vy) + ".dat", "a") as datafile:
        datafile.write("\n".join(map(str, ylengths)))

    mean_vy = [(vy * 10000) / 32, sum(ylengths) / len(ylengths)]

    print("mean_vy")
    print(mean_vy)

    with open(outdir + "/mean_vy" + "2kBT_2r0" + ".dat", "a") as datafile:
        datafile.write(" ".join(map(str, mean_vy)))

    c.finalize()
    corrdata = c.result()
    corr = zeros((corrdata.shape[0], 2))
    corr[:, 0] = corrdata[:, 0]
    corr[:, 1] = (corrdata[:, 2] + corrdata[:, 3] + corrdata[:, 4]) / 3

    savetxt(outdir + "/msd_nom" + str(mpc) + ".dat", corr)

    with open(outdir + "/rh_out.dat", "a") as datafile:
        rh = system.analysis.calc_rh(chain_start=0,
                                     number_of_chains=1,
                                     chain_length=mpc - 1)
        datafile.write(str(mpc) + "    " + str(rh[0]) + "\n")
Esempio n. 4
0
class SwimmerTest():
    system = System(box_l=3 * [6])
    system.cell_system.skin = 1
    system.time_step = 1e-2
    LB_params = {'agrid': 1,
                 'dens': 1.1,
                 'visc': 1.2,
                 'kT': 0,
                 'tau': system.time_step}    
    gamma = 0.3
    lbf = None
    
    def add_all_types_of_swimmers(
        self,
        fix=False,
     rotation=False,
     put_in_corners=True):
        """Places all combinations of pusher/puller and f_swim/v_swim
        in a box, either in the corners or around the center
        """
        system = self.system      
        plus_x = np.sqrt([.5, 0, .5, 0])
        plus_y = np.sqrt([0, 0, .5, .5])
        plus_z = np.sqrt([.5, 0, 0, .5])
        minus_y = np.sqrt([.5, .5, 0, 0])
        
        pos0 = [2, 0.01, 3] if put_in_corners else [2, 3, 2.5]
        pos1 = [5.99, 2, 3] if put_in_corners else [3.1, 2.1, 2.2]
        pos2 = [2, 3, 5.99] if put_in_corners else [2.9, 2.5, 3]
        pos3 = [1.5, 5.99, 1] if put_in_corners else [2, 2, 2.5]
        
        system.part.add(pos=pos0, quat=minus_y, fix=3 * [fix],
                        mass=0.9, rinertia=3 * [7], rotation=3 * [rotation],
                        swimming={"mode": "pusher", "f_swim": 0.10,
                                  "dipole_length": 0.5, "rotational_friction": 0.3})
        system.part.add(pos=pos1, quat=plus_x, fix=3 * [fix],
                        mass=1.9, rinertia=3 * [8], rotation=3 * [rotation],
                        swimming={"mode": "pusher", "v_swim": 0.02,
                                  "dipole_length": 0.6, "rotational_friction": 0.4})
        system.part.add(pos=pos2, quat=plus_z, fix=3 * [fix],
                        mass=2.9, rinertia=3 * [9], rotation=3 * [rotation],
                        swimming={"mode": "puller", "f_swim": 0.08,
                                  "dipole_length": 0.7, "rotational_friction": 0.8})
        system.part.add(pos=pos3, quat=plus_y, fix=3 * [fix],
                        mass=3.9, rinertia=3 * [10], rotation=3 * [rotation],
                        swimming={"mode": "puller", "v_swim": 0.05,
                                  "dipole_length": 0.8, "rotational_friction": 0.3})

    def tearDown(self):
        self.system.part.clear()
        self.system.actors.clear()
        self.system.lbboundaries.clear()
        self.system.thermostat.turn_off()
        self.lbf = None
    
    def test_conflicting_parameters(self):
        """v_swim and f_swim can't be set at the same time
        """
        swimmer = self.system.part.add(pos=[3] * 3)
        with self.assertRaises(Exception):
            swimmer.swimming = {"v_swim": 0.3, "f_swim": 0.6}      
    
    def test_momentum_conservation(self):
        """friction as well as 'active' forces apply to particles
        and to the fluid, so total momentum is conserved
        """
        self.add_all_types_of_swimmers(rotation=False)
        self.system.integrator.run(20, reuse_forces=True)
        tot_mom = self.system.analysis.linear_momentum(include_particles=True,
                                                       include_lbfluid=True)
        np.testing.assert_allclose(tot_mom, 3 * [0.], atol=self.tol) 

    def test_particle_forces(self):
        """run through all swimmers to check expected forces
        """
        self.add_all_types_of_swimmers(rotation=False)
        self.system.integrator.run(10)
        for swimmer in self.system.part:
            
            f_swim = swimmer.swimming['f_swim']
            v_swim = swimmer.swimming['v_swim']
            director = swimmer.director
            
            #due to dt/2 time-shift between force calculation and LB-update,
            #v_swimmer has to be calculated at the half step
            v_swimmer = swimmer.v + \
                0.5 * self.system.time_step * swimmer.f / swimmer.mass 
            #for friction coupling, the old fluid at the new position is used
            v_fluid = self.lbf.get_interpolated_velocity(
                swimmer.pos + self.system.time_step * v_swimmer)
            force = -self.gamma * (v_swimmer - v_fluid) + \
                f_swim * director + self.gamma * v_swim * director
                
            self.system.integrator.run(1, reuse_forces=True)
            np.testing.assert_allclose(swimmer.f, force, atol=self.tol)
    
    def check_fluid_force(self, swimmer):
        pass
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
Visualization sample for Poiseuille flow with Lattice Boltzmann.
"""

from espressomd import System, lb, shapes, lbboundaries
import numpy as np
from threading import Thread
import espressomd.visualization_opengl

required_features = ["LB_BOUNDARIES", "EXTERNAL_FORCES"]
espressomd.assert_features(required_features)

# System setup
box_l = 16
system = 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.2

visualizer = espressomd.visualization_opengl.openGLLive(
    system,
    LB_draw_boundaries=True,
    LB_draw_velocity_plane=True,
    LB_plane_dist=8,
    LB_plane_axis=1,
    LB_vel_scale=1e2,
    LB_plane_ngrid=15,
    camera_position=[8, 16, 50],
Esempio n. 6
0
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
Set up an electrokinetics (LB) fluid confined between charged walls.
"""

import espressomd

required_features = ["ELECTROKINETICS", "EK_BOUNDARIES", "EXTERNAL_FORCES"]
espressomd.assert_features(required_features)

from espressomd import System, shapes, electrokinetics, ekboundaries
import os

system = System(box_l=[10, 10, 10])

system.cell_system.skin = 0.4
system.time_step = 0.1


ek = electrokinetics.Electrokinetics(
    lb_density=1, friction=1, agrid=1, viscosity=1, T=1, prefactor=1)

pos = electrokinetics.Species(
    density=0.05, D=0.1, valency=1, ext_force_density=[0, 0, 1.])
neg = electrokinetics.Species(
    density=0.05, D=0.1, valency=-1, ext_force_density=[0, 0, -1.])
ek.add_species(pos)
ek.add_species(neg)
system.actors.add(ek)
Esempio n. 7
0
class DiamondPolymer(ut.TestCase):
    """
    Test the functionality of espressomd.polymer.setup_diamond_polymer()
    in terms of
    * properties of particles created
    * connections via bonds
    * the geometry of the polymer network
    """

    system = System(box_l=3 * [16])
    diamond_params = {
        'MPC': 15,
        'dist_cM': 3,
        'val_cM': -1.3,
        'val_nodes': 0.6,
        'start_id': 3,
        'no_bonds': False,
        'type_nodes': 2,
        'type_nM': 5,
        'type_cM': 7
    }
    bond_length = system.box_l[0] * \
        (0.25 * np.sqrt(3)) / (diamond_params['MPC'] + 1)

    def setUp(self):
        bond = interactions.HarmonicBond(k=1.5, r_0=self.bond_length, r_cut=3)
        self.system.bonded_inter.add(bond)
        polymer.setup_diamond_polymer(system=self.system,
                                      bond=bond,
                                      **self.diamond_params)
        self.system.time_step = 0.1
        self.node_parts = self.system.part.select(
            type=self.diamond_params['type_nodes'])
        self.charged_mono = self.system.part.select(
            type=self.diamond_params['type_cM'])
        self.noncharged_mono = self.system.part.select(
            type=self.diamond_params['type_nM'])

    def tearDown(self):
        self.system.part.clear()

    @utx.skipIfMissingFeatures(["ELECTROSTATICS"])
    def test_particle_properties(self):
        """
        checks if the particles created have the right type and charge

        """
        # number of particles created
        number_non_node = 16 * self.diamond_params['MPC']
        self.assertEqual(len(self.system.part), number_non_node + 8)
        # number of each type
        self.assertEqual(len(self.node_parts), 8)
        self.assertEqual(
            len(self.charged_mono),
            np.rint(number_non_node / self.diamond_params['dist_cM']))
        self.assertEqual(
            len(self.noncharged_mono),
            np.rint(number_non_node *
                    (1 - 1 / self.diamond_params['dist_cM'])))
        # charge
        np.testing.assert_allclose(
            self.node_parts.q,
            len(self.node_parts) * [self.diamond_params['val_nodes']])
        np.testing.assert_allclose(self.noncharged_mono.q,
                                   len(self.noncharged_mono) * [0])
        np.testing.assert_allclose(
            self.charged_mono.q,
            len(self.charged_mono) * [self.diamond_params['val_cM']])
        # particle id
        self.assertGreaterEqual(min(self.system.part[:].id),
                                self.diamond_params['start_id'])

    def test_bonds(self):
        """
        test that the right number of bonds is formed on each particle
        """
        # 4 bonds on nodes
        for part in self.node_parts:
            self.assertEqual(len(part.bonds), 4)
        # 1 or 0 bonds on chain monomers
        n_bonds = [
            len(bonds)
            for bonds in self.noncharged_mono.bonds + self.charged_mono.bonds
        ]
        self.assertLessEqual(np.max(n_bonds), 1)
        # total number of bonds
        number_non_node = 16 * self.diamond_params['MPC']
        self.assertEqual(np.sum(n_bonds), number_non_node - 16)

    @utx.skipIfMissingFeatures(["EXTERNAL_FORCES"])
    def test_connected(self):
        """
        test that all particles in the polymer are connected by pushing one particle
        """

        self.system.part[self.diamond_params['start_id']].ext_force = 3 * [2]
        self.system.integrator.run(200)
        vels = np.linalg.norm(self.system.part[:].v, axis=1)
        self.assertGreater(np.min(vels), 1e-6)

    def test_geometry(self):
        """
        check if the distance between all monomers is correct,
        only nearest neighbouring nodes are connected
        and that the nodes have the right position

        """
        # Energy calculation checks distance indirectly through
        # position of minimum of HarmonicBond
        # With formula for self.bond_length this also ensures
        # that only nearest neighbours can be reached
        E = self.system.analysis.energy()['total']
        self.assertAlmostEqual(E, 0., delta=1e-13)

        node_pos_scaled = np.array(self.node_parts.pos) / self.system.box_l[0]
        node_pos_shouldbe = 0.25 * np.array([[0, 0, 0], [1, 1, 1], [2, 2, 0],
                                             [0, 2, 2], [2, 0, 2], [3, 3, 1],
                                             [1, 3, 3], [3, 1, 3]])
        for pos1, pos2 in zip(node_pos_scaled, node_pos_shouldbe):
            np.testing.assert_allclose(pos1, pos2)
"""
This sample simulates planar Poiseuille flow in Espresso. A spherical RBC-like
particle is added and advected with and without volume conservation.
"""
import espressomd

required_features = ["LB_BOUNDARIES", "VIRTUAL_SITES_INERTIALESS_TRACERS"]
espressomd.assert_features(required_features)

from espressomd import System, lb, shapes, lbboundaries
import numpy as np
from espressomd.virtual_sites import VirtualSitesInertialessTracers

# System setup
boxZ = 20
system = System(box_l=(20, 20, boxZ))
system.time_step = 1 / 6.
system.cell_system.skin = 0.1
system.virtual_sites = VirtualSitesInertialessTracers()
print("Parallelization: " + str(system.cell_system.node_grid))

force = 0.001
from addSoft import AddSoft
k1 = 0.1
k2 = 1
AddSoft(system, 10, 10, 10, k1, k2)

## case without bending and volCons
#outputDir = "outputPure"

## case with bending
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
Visualize the Poiseuille flow in a lattice-Boltzmann fluid with an
external force applied.
"""

from espressomd import System, lb, shapes, lbboundaries
import numpy as np
import espressomd.visualization_opengl

required_features = ["LB_BOUNDARIES", "EXTERNAL_FORCES"]
espressomd.assert_features(required_features)

# System setup
box_l = 16
system = System(box_l=[box_l] * 3)
np.random.seed(seed=42)

system.time_step = 0.01
system.cell_system.skin = 0.2

visualizer = espressomd.visualization_opengl.openGLLive(
    system,
    LB_draw_boundaries=True,
    LB_draw_velocity_plane=True,
    LB_plane_dist=8,
    LB_plane_axis=1,
    LB_vel_scale=1e2,
    LB_plane_ngrid=15,
    camera_position=[8, 16, 50],
    velocity_arrows=True,
Esempio n. 10
0
# Setup constant
time_step = 0.01
loops = 20
step_per_loop = 100

# AVB: the parameters (that I usually use)
a = 0.05
r0 = 2.0 * a
kBT = 4.0e-6
vwf_type = 0
monomer_mass = 0.01

# System setup
box_l = 32.0
system = System(box_l=[box_l, box_l, box_l])
system.set_random_state_PRNG()
np.random.seed(seed=system.seed)
system.cell_system.skin = 0.4

print("The number of monomers")
mpc = float(input())  # The number of monomers has been set to be 20 as default
# Change this value for further simulations

# Lennard-Jones interaction
#system.non_bonded_inter[0,0].lennard_jones.set_params(
#    epsilon=0.01, sigma=1.0,
#    shift="auto", cutoff=2.0**(1.0/6.0))

# Fene interaction
fene = interactions.FeneBond(k=0.4, d_r_max=0.3)
Esempio n. 11
0
    os.makedirs(outdir)

# Setup constant
time_step = 0.01
loops = 50
step_per_loop = 100

# AVB: the parameters (that I usually use)
a = 0.05
r0 = 2.0 * a
kBT = 4.0e-6
vwf_type = 0
monomer_mass = 0.01

# System setup
system = System(box_l=[32.0, 32.0, 32.0])
system.set_random_state_PRNG()
np.random.seed(seed=system.seed)
system.cell_system.skin = 0.4

mpc = 20  # The number of monomers has been set to be 20 as default
# Change this value for further simulations

# Fene interaction
fene = interactions.FeneBond(k=0.04, d_r_max=0.3)
system.bonded_inter.add(fene)

# Setup polymer of part_id 0 with fene bond
# AVB: Notice the mode, max_tries and shield parameters for pruned self-avoiding random walk algorithm
polymer.create_polymer(N_P=1,
                       MPC=mpc,