Tutorial 2: Charged Systems: Counterion Condensation

Table of contents

Introduction

In this tutorial, we simulate a charged system consisting of a fixed charged rod with ions around it. This setup represents a simplified model for polyelectrolyte gels. We will investigate the condensation of ions onto the oppositely charged rod and compare the results to a meanfield analytical solution obtained from Poisson−Boltzmann (PB) theory. Finally we will go beyond the expected applicability of PB and add concentrated additional salt ions to observe an overcharging effect.

The tutorial follows "Deserno, Markus, Christian Holm, and Sylvio May. "Fraction of condensed counterions around a charged rod: Comparison of Poisson−Boltzmann theory and computer simulations. Macromolecules 33.1 (2000): 199-206, 10.1021/ma990897o". We refer to that publication for further reading.

In [1]:
import espressomd
espressomd.assert_features(['WCA', 'ELECTROSTATICS'])

from espressomd import System, interactions, electrostatics, observables, accumulators

import numpy as np
from scipy import optimize
%matplotlib inline
import matplotlib.pyplot as plt
In [2]:
np.random.seed(41)
plt.rcParams.update({'font.size': 22})

System setup

After importing the necessary ESPResSo features and external modules, we define a cubic system geometry and some physical parameters (which define our unit system).

In [3]:
# system parameters
ROD_LENGTH = 50
BJERRUM_LENGTH = 1.0

# we assume a unit system where the elementary charge and the thermal energy are both 1
system = System(box_l=3 * [ROD_LENGTH])
KT = 1.
Q_E = 1.

system.time_step = 0.01
system.cell_system.skin = 0.4

We will build the charged rod from individual particles that are fixed in space. With this, we can use the particle-based electrostatics methods of ESPResSo. For analysis, we give the rod particles a different type than the counterions.

In [4]:
# interaction parameters
WCA_EPSILON = 1.0
ION_DIAMETER = 1.0
ROD_RADIUS = 1.0
# particle types
ROD_TYPE = 1
COUNTERION_TYPE = 2

Exercise:

  • Setup the purely repulsive Weeks-Chandler-Anderson (WCA) interaction (Non-bonded Interactions) between the ions and between the ions and the rod particles. Use the parameters introduced in the cell above.

Hints:

  • The WCA potential uses the same parameters as the Lennard-Jones potential, but the cutoff and shift are calculated automatically
  • Use the Lorentz combining rule (arithmetic mean) to determine the sigma parameter of the interaction between the rod particles and the ions
In [5]:
# ion-ion interaction
system.non_bonded_inter[COUNTERION_TYPE, COUNTERION_TYPE].wca.set_params(
    epsilon=WCA_EPSILON, sigma=ION_DIAMETER)

# ion-rod interaction
system.non_bonded_inter[COUNTERION_TYPE, ROD_TYPE].wca.set_params(
    epsilon=WCA_EPSILON, sigma=ION_DIAMETER / 2. + ROD_RADIUS)

Now we need to place the particles in the box

Exercise:

  • Implement a function to place the rod particles along the $x_3$ axis in the middle of the simulation box and the ions randomly distributed
  • Use the signature setup_rod_and_counterions(system, ion_valency, counterion_type, rod_charge_dens, N_rod_beads, rod_type)
  • Determine the number of counterions from the condition of neutrality for the whole system (the rod should be positive, the counterions negative)
  • Assign the rod particles and counterions their correct type
  • Give the counterions a charge q according to their ion_valency
  • Give the rod particles a charge such that the rod_charge_dens is uniformly distributed along the N_rod_beads individual particles
  • Fix the rod particles in space so they do not get moved if forces act upon them
  • Return the newly created counterion particles

Hints:

  • Look into espresso particle properties to find the keywords to set charges and to fix particles
  • use np.random.random() to generate the counterion positions
In [6]:
def setup_rod_and_counterions(system, ion_valency, counterion_type,
                              rod_charge_dens, N_rod_beads, rod_type):

    # calculate charge of the single rod beads
    rod_length = system.box_l[2]
    total_rod_charge = rod_charge_dens * rod_length
    rod_charge_per_bead = total_rod_charge / N_rod_beads

    # number of counterions
    N_ions = int(total_rod_charge / ion_valency)

    rod_zs = np.linspace(0, rod_length, num=N_rod_beads, endpoint=False)
    rod_positions = np.column_stack(([system.box_l[0] / 2.] * N_rod_beads,
                                     [system.box_l[1] / 2.] * N_rod_beads,
                                     rod_zs))

    system.part.add(pos=rod_positions, type=[rod_type] * N_rod_beads,
                    q=[rod_charge_per_bead] * N_rod_beads,
                    fix=[3 * [True]] * N_rod_beads)

    ion_positions = np.random.random((N_ions, 3)) * system.box_l

    counter_ions = system.part.add(pos=ion_positions, type=[
                                   counterion_type] * N_ions, q=[-ion_valency] * N_ions)

    return counter_ions
In [7]:
COUNTERION_VALENCY = 1
ROD_CHARGE_DENS = 2

# number of beads that make up the rod
N_rod_beads = int(ROD_LENGTH / ROD_RADIUS)

setup_rod_and_counterions(system, COUNTERION_VALENCY, COUNTERION_TYPE,
                          ROD_CHARGE_DENS, N_rod_beads, ROD_TYPE)

# check that the particle setup was done correctly
assert abs(sum(system.part[:].q)) < 1e-10
assert np.all(system.part.select(type=ROD_TYPE).fix)

Now we set up the electrostatics method to calculate the forces and energies from the longrange coulomb interaction. ESPResSo uses so-called actors for electrostatics, magnetostatics and hydrodynamics. This ensures that unphysical combinations of algorithms are avoided, for example simultaneous usage of two electrostatic interactions. Adding an actor to the system also activates the method and calls necessary initialization routines. Here, we define a P$^3$M object using the Bjerrum length and rms force error. This automatically starts a tuning function which tries to find optimal parameters for P$^3$M and prints them to the screen. For more details, see the Espresso documentation.

In [8]:
p3m_params = {'prefactor': KT * BJERRUM_LENGTH * Q_E**2,
              'accuracy': 1e-3}

For the accuracy, ESPResSo estimates the relative error in the force calculation introduced by the approximations of $P^3M$. We choose a relatively poor accuracy (large value) for this tutorial to make it run faster. For your own production simulations you should reduce that number.

Exercise:

  • Set up a p3m instance and add it to the actors of the system
In [9]:
p3m = electrostatics.P3M(**p3m_params)
system.actors.add(p3m)
P3M tune parameters: Accuracy goal = 1.00000e-03 prefactor = 1.00000e+00
System: box_l = 5.00000e+01 # charged part = 150 Sum[q_i^2] = 3.00000e+02
mesh cao r_cut_iL     alpha_L      err          rs_err     ks_err     time [ms]
6    7   cao too large for this mesh
10   7   2.37352e-01 8.46940e+00 9.88093e-04 7.071e-04 6.902e-04 0.38    
10   6   2.42156e-01 8.29105e+00 9.86440e-04 7.071e-04 6.878e-04 0.34    
10   5   2.50805e-01 7.98771e+00 9.94789e-04 7.071e-04 6.997e-04 0.32    
10   4   2.68102e-01 7.44127e+00 9.99962e-04 7.071e-04 7.071e-04 0.31    
10   3   3.10383e-01 6.36820e+00 9.99603e-04 7.071e-04 7.065e-04 0.35    
10   2   4.92000e-01 3.89721e+00 1.02867e-03 7.071e-04 7.471e-04 accuracy not achieved
16   4   1.79607e-01 1.13837e+01 9.91862e-04 7.071e-04 6.955e-04 0.48    
16   3   2.09978e-01 9.64580e+00 9.96796e-04 7.071e-04 7.026e-04 0.47    
16   5   1.67563e-01 1.22525e+01 9.94288e-04 7.071e-04 6.990e-04 0.50    
16   2   2.68102e-01 7.44127e+00 1.58833e-03 7.071e-04 1.422e-03 accuracy not achieved
20   4   1.48461e-01 1.39279e+01 9.84531e-04 7.071e-04 6.851e-04 0.83    
20   3   1.74708e-01 1.17223e+01 9.91380e-04 7.071e-04 6.949e-04 0.82    
20   5   1.37798e-01 1.50709e+01 9.99296e-04 7.071e-04 7.061e-04 0.90    
20   2   2.09978e-01 9.64580e+00 1.88705e-03 7.071e-04 1.750e-03 accuracy not achieved
26   4   1.18065e-01 1.77468e+01 9.89784e-04 7.071e-04 6.926e-04 2.14    
26   3   1.39903e-01 1.48311e+01 9.98276e-04 7.071e-04 7.047e-04 2.11    
26   5   1.09875e-01 1.91475e+01 9.88159e-04 7.071e-04 6.903e-04 2.19    
26   2   1.74708e-01 1.17223e+01 1.80827e-03 7.071e-04 1.664e-03 accuracy not achieved
30   4   1.04381e-01 2.02136e+01 9.86481e-04 7.071e-04 6.879e-04 3.03    
30   3   1.24055e-01 1.68422e+01 9.99827e-04 7.071e-04 7.069e-04 3.00    
30   5   9.67299e-02 2.19055e+01 9.94581e-04 7.071e-04 6.994e-04 3.15    
30   2   1.39903e-01 1.48311e+01 2.39580e-03 7.071e-04 2.289e-03 accuracy not achieved

resulting parameters: mesh: (10 10 10), cao: 4, r_cut_iL: 2.6810e-01,
                      alpha_L: 7.4413e+00, accuracy: 9.9996e-04, time: 0.31

Before we can start the simulation, we need to remove the overlap between particles to avoid large forces which would crash the simulation. For this, we use the steepest descent integrator with a relative convergence criterion for forces and energies.

In [10]:
def remove_overlap(system, sd_params):
    # Removes overlap by steepest descent until forces or energies converge
    # Set up steepest descent integration
    system.integrator.set_steepest_descent(f_max=0,
                                           gamma=sd_params['damping'],
                                           max_displacement=sd_params['max_displacement'])

    # Initialize integrator to obtain initial forces
    system.integrator.run(0)
    maxforce = np.max(np.linalg.norm(system.part[:].f, axis=1))
    energy = system.analysis.energy()['total']

    i = 0
    while i < sd_params['max_steps'] // sd_params['emstep']:
        prev_maxforce = maxforce
        prev_energy = energy
        system.integrator.run(sd_params['emstep'])
        maxforce = np.max(np.linalg.norm(system.part[:].f, axis=1))
        relforce = np.abs((maxforce - prev_maxforce) / prev_maxforce)
        energy = system.analysis.energy()['total']
        relener = np.abs((energy - prev_energy) / prev_energy)
        if i > 1 and (i + 1) % 4 == 0:
            print(f"minimization step: {(i+1)*sd_params['emstep']:4.0f}"
                  f"    max. rel. force change:{relforce:+3.3e}"
                  f"    rel. energy change:{relener:+3.3e}")
        if relforce < sd_params['f_tol'] or relener < sd_params['e_tol']:
            break
        i += 1

    system.integrator.set_vv()
In [11]:
STEEPEST_DESCENT_PARAMS = {'f_tol': 1e-2,
                           'e_tol': 1e-5,
                           'damping': 30,
                           'max_steps': 10000,
                           'max_displacement': 0.01,
                           'emstep': 10}

remove_overlap(system, STEEPEST_DESCENT_PARAMS)
minimization step:   40    max. rel. force change:+4.117e-02    rel. energy change:+5.690e-03
minimization step:   80    max. rel. force change:+4.860e-02    rel. energy change:+5.895e-03
minimization step:  120    max. rel. force change:+1.574e-01    rel. energy change:+6.268e-03
minimization step:  160    max. rel. force change:+1.294e-01    rel. energy change:+6.106e-03
minimization step:  200    max. rel. force change:+3.497e-02    rel. energy change:+5.924e-03
minimization step:  240    max. rel. force change:+4.085e-02    rel. energy change:+6.396e-03
minimization step:  280    max. rel. force change:+4.912e-02    rel. energy change:+6.965e-03
minimization step:  320    max. rel. force change:+6.108e-02    rel. energy change:+7.678e-03
minimization step:  360    max. rel. force change:+6.878e-02    rel. energy change:+7.350e-03
minimization step:  400    max. rel. force change:+6.456e-02    rel. energy change:+7.315e-03
minimization step:  440    max. rel. force change:+8.429e-02    rel. energy change:+8.290e-03
minimization step:  480    max. rel. force change:+4.138e-02    rel. energy change:+7.379e-03
minimization step:  520    max. rel. force change:+4.895e-02    rel. energy change:+8.187e-03
minimization step:  560    max. rel. force change:+6.022e-02    rel. energy change:+9.254e-03
minimization step:  600    max. rel. force change:+5.612e-02    rel. energy change:+9.820e-03

After the overlap is removed, we activate a thermostat to simulate the system at a given temperature.

In [12]:
LANGEVIN_PARAMS = {'kT': KT,
                   'gamma': 0.5,
                   'seed': 42}
system.thermostat.set_langevin(**LANGEVIN_PARAMS)

First run and observable setup

Before running the simulations to obtain the histograms, we need to decide how long we need to equilibrate the system. For this we plot the total energy vs the time steps.

In [13]:
energies = []
STEPS_PER_SAMPLE_FIRST_RUN = 10
N_SAMPLES_FIRST_RUN = 1000
for i in range(N_SAMPLES_FIRST_RUN):
    system.integrator.run(STEPS_PER_SAMPLE_FIRST_RUN)
    energies.append(system.analysis.energy()['total'])
In [14]:
# plot time in time_steps so we can judge the number of warmup steps
ts = np.arange(0, N_SAMPLES_FIRST_RUN) * STEPS_PER_SAMPLE_FIRST_RUN
plt.figure(figsize=(10, 7))
plt.plot(ts, energies)
plt.xlabel('time steps')
plt.ylabel('system total energy')
plt.show()
In [15]:
WARMUP_STEPS = 5000
STEPS_PER_SAMPLE = 100

Now we are ready to implement the observable calculation. As we are interested in the condensation of counterions on the rod, the physical quantity of interest is the density of charges $\rho(r)$ around the rod, where $r$ is the distance from the rod. We need many samples to calculate the density from histograms.

From the last tutorial you should already be familiar with the concepts of observables and accumulators in ESPResSo. We will use the CylindricalDensityProfile observable and the MeanVarianceCalculator accumulator

Exercise:

  • Write a function setup_profile_calculation(system, delta_N, ion_types, r_min, n_radial_bins) to create observables for $\rho(r)$
  • delta_N is the number of integration steps between observable calculation
  • ion_types is a list of types for which the radial distances should be calculated. For the moment we only have counterions, but later we will also add additional salt ions for which we would also like to calculate the density
  • return a a dictionary of the accumulators radial_distances[counterion_type] = <accumulator> and the edges of the bins

Hints:

  • Use system.part.select(type=...) to get only the particles of a specific type
  • The azimuthal angle and the $x_3$ position are irrelevant, so you need only one big bin for these coordinates
In [16]:
def setup_profile_calculation(system, delta_N, ion_types, r_min, n_radial_bins):
    radial_profile_accumulators = {}
    for ion_type in ion_types:
        ion_ids = system.part.select(type=ion_type).id
        radial_profile_obs = observables.CylindricalDensityProfile(
            ids=ion_ids,
            center=np.array(system.box_l) / 2.,
            axis=[0, 0, 1, ],
            n_r_bins=n_radial_bins,
            n_phi_bins=1,
            n_z_bins=1,
            min_r=r_min,
            min_phi=-np.pi,
            min_z=-system.box_l[2] / 2.,
            max_r=system.box_l[0] / 2.,
            max_phi=np.pi,
            max_z=system.box_l[2] / 2.)

        bin_edges = radial_profile_obs.bin_edges()

        radial_profile_acc = accumulators.MeanVarianceCalculator(
            obs=radial_profile_obs, delta_N=delta_N)
        system.auto_update_accumulators.add(radial_profile_acc)

        radial_profile_accumulators[ion_type] = radial_profile_acc

    return radial_profile_accumulators, bin_edges
In [17]:
r_min = ROD_RADIUS + ION_DIAMETER / 2.
r_max = system.box_l[0] / 2.
N_RADIAL_BINS = 200
radial_profile_accs, bin_edges = setup_profile_calculation(
    system, STEPS_PER_SAMPLE, [COUNTERION_TYPE], r_min, N_RADIAL_BINS)
assert isinstance(
    radial_profile_accs[COUNTERION_TYPE], accumulators.MeanVarianceCalculator)
assert len(bin_edges) == N_RADIAL_BINS + 1

To run the simulation with different parameters, we need a way to reset the system and return it to an empty state before setting it up again.

Exercise:

  • Write a function clear_system(system) that
    • turns off the thermostat
    • removes all particles
    • removes all accumulators added to the auto-update-list
    • resets the system clock

Hints:

In [18]:
def clear_system(system):
    system.thermostat.turn_off()
    system.part.clear()
    system.auto_update_accumulators.clear()
    system.time = 0.
In [19]:
clear_system(system)

Production run and analysis

Now we are finally ready to run the simulations and produce the data we can compare to the Poisson-Boltzmann predictions. First we define the parameters and then loop over them.

In [20]:
runs = [{'params': {'counterion_valency': 2, 'rod_charge_dens': 1},
         'histogram': None},
        {'params': {'counterion_valency': 1, 'rod_charge_dens': 2},
         'histogram': None}
        ]
N_SAMPLES = 1500

For longer simulation runs it will be convenient to have a progress bar

In [21]:
def integrate_system(system, n_steps):
    for i in range(100):
        system.integrator.run(int(n_steps / 100))
        print(f'progress={i}%', end='\r')
    print('progress=100%')

Exercise:

  • Run the simulation for the parameters given above and save the histograms in the corresponding dictionary for analysis

Hints:

  • Don't forget to clear the system before setting up the system with a new set of parameters
  • Don't forget to tune() the p3m instance after each change of parameters. If we reuse the p3m that was tuned before, likely the desired accuracy will not be achieved.
  • Extract the radial density profile from the accumulator via .mean()
In [22]:
for run in runs:
    clear_system(system)
    setup_rod_and_counterions(
        system, run['params']['counterion_valency'], COUNTERION_TYPE,
        run['params']['rod_charge_dens'], N_rod_beads, ROD_TYPE)
    p3m.tune()
    remove_overlap(system, STEEPEST_DESCENT_PARAMS)
    system.thermostat.set_langevin(**LANGEVIN_PARAMS)
    print('starting warmup')
    integrate_system(system, WARMUP_STEPS)
    radial_profile_accs, bin_edges = setup_profile_calculation(
        system, STEPS_PER_SAMPLE, [COUNTERION_TYPE], r_min, N_RADIAL_BINS)
    print('starting simulation')
    integrate_system(system, N_SAMPLES * STEPS_PER_SAMPLE)

    run['histogram'] = radial_profile_accs[COUNTERION_TYPE].mean()
    print('simulation for parameters {} done\n'.format(run['params']))
P3M tune parameters: Accuracy goal = 9.99962e-04 prefactor = 1.00000e+00
System: box_l = 5.00000e+01 # charged part = 75 Sum[q_i^2] = 1.50000e+02
mesh cao r_cut_iL     alpha_L      err          rs_err     ks_err     time [ms]
4    7   cao too large for this mesh
10   7   2.17172e-01 8.90365e+00 9.86982e-04 7.071e-04 6.886e-04 0.26    
10   6   2.21016e-01 8.73853e+00 9.86628e-04 7.071e-04 6.881e-04 0.22    
10   5   2.28703e-01 8.42543e+00 9.86784e-04 7.071e-04 6.883e-04 0.20    
10   4   2.43117e-01 7.89321e+00 9.92862e-04 7.071e-04 6.970e-04 0.19    
10   3   2.76750e-01 6.87270e+00 9.95489e-04 7.071e-04 7.007e-04 0.20    
10   2   4.20891e-01 4.38615e+00 9.97980e-04 7.071e-04 7.043e-04 0.28    
10   1   4.92000e-01 3.70900e+00 5.27388e-03 7.071e-04 5.226e-03 accuracy not achieved
14   4   1.83288e-01 1.06686e+01 9.85313e-04 7.071e-04 6.862e-04 0.33    
14   3   2.08929e-01 9.27884e+00 9.99111e-04 7.071e-04 7.059e-04 0.32    
14   5   1.71891e-01 1.14236e+01 9.88809e-04 7.071e-04 6.912e-04 0.35    
14   2   2.43117e-01 7.89321e+00 1.73585e-03 7.071e-04 1.585e-03 accuracy not achieved
20   4   1.34661e-01 1.48109e+01 9.93816e-04 7.071e-04 6.984e-04 0.81    
20   3   1.55880e-01 1.26766e+01 9.89522e-04 7.071e-04 6.922e-04 0.79    
20   5   1.26500e-01 1.58283e+01 9.88863e-04 7.071e-04 6.913e-04 0.82    
20   2   2.08929e-01 9.27884e+00 1.32024e-03 7.071e-04 1.115e-03 accuracy not achieved
24   4   1.15084e-01 1.75008e+01 9.94522e-04 7.071e-04 6.994e-04 1.41    
24   3   1.33351e-01 1.49656e+01 9.98953e-04 7.071e-04 7.057e-04 1.45    
24   5   1.07777e-01 1.87627e+01 9.96304e-04 7.071e-04 7.019e-04 1.50    
24   2   1.55880e-01 1.26766e+01 1.87146e-03 7.071e-04 1.733e-03 accuracy not achieved
30   4   9.53036e-02 2.13772e+01 9.82523e-04 7.071e-04 6.822e-04 3.11    
30   3   1.11487e-01 1.81006e+01 9.82901e-04 7.071e-04 6.827e-04 2.92    
30   5   8.90100e-02 2.29827e+01 9.86530e-04 7.071e-04 6.880e-04 3.01    
30   2   1.15084e-01 1.75008e+01 2.64142e-03 7.071e-04 2.545e-03 accuracy not achieved

resulting parameters: mesh: (10 10 10), cao: 4, r_cut_iL: 2.4312e-01,
                      alpha_L: 7.8932e+00, accuracy: 9.9286e-04, time: 0.19

minimization step:   40    max. rel. force change:+2.955e-02    rel. energy change:+6.903e-03
minimization step:   80    max. rel. force change:+3.465e-02    rel. energy change:+6.025e-03
minimization step:  120    max. rel. force change:+4.101e-02    rel. energy change:+5.899e-03
minimization step:  160    max. rel. force change:+4.912e-02    rel. energy change:+6.142e-03
minimization step:  200    max. rel. force change:+6.052e-02    rel. energy change:+6.782e-03
starting warmup
progress=100%
starting simulation
progress=100%
simulation for parameters {'counterion_valency': 2, 'rod_charge_dens': 1} done

P3M tune parameters: Accuracy goal = 9.92862e-04 prefactor = 1.00000e+00
System: box_l = 5.00000e+01 # charged part = 150 Sum[q_i^2] = 3.00000e+02
mesh cao r_cut_iL     alpha_L      err          rs_err     ks_err     time [ms]
6    7   cao too large for this mesh
10   7   2.37352e-01 8.47690e+00 9.87559e-04 7.021e-04 6.945e-04 0.38    
10   6   2.42156e-01 8.29842e+00 9.85753e-04 7.021e-04 6.920e-04 0.34    
10   5   2.51766e-01 7.96243e+00 9.81393e-04 7.021e-04 6.857e-04 0.32    
10   4   2.69063e-01 7.41970e+00 9.88130e-04 7.021e-04 6.954e-04 0.31    
10   3   3.11344e-01 6.35311e+00 9.90830e-04 7.021e-04 6.992e-04 0.34    
10   2   4.92000e-01 3.90101e+00 1.02648e-03 7.021e-04 7.488e-04 accuracy not achieved
16   4   1.79725e-01 1.13855e+01 9.88733e-04 7.021e-04 6.962e-04 0.48    
16   3   2.10205e-01 9.64316e+00 9.92627e-04 7.021e-04 7.017e-04 0.48    
16   5   1.67639e-01 1.22571e+01 9.91940e-04 7.021e-04 7.008e-04 0.52    
16   2   2.69063e-01 7.41970e+00 1.57627e-03 7.021e-04 1.411e-03 accuracy not achieved
20   4   1.48133e-01 1.39723e+01 9.90203e-04 7.021e-04 6.983e-04 0.86    
20   3   1.74811e-01 1.17250e+01 9.88275e-04 7.021e-04 6.956e-04 0.86    
20   5   1.38304e-01 1.50251e+01 9.85482e-04 7.021e-04 6.916e-04 0.88    
20   2   1.79725e-01 1.13855e+01 2.83584e-03 7.021e-04 2.748e-03 accuracy not achieved
26   4   1.18134e-01 1.77503e+01 9.86757e-04 7.021e-04 6.934e-04 2.14    
26   3   1.40668e-01 1.47581e+01 9.84272e-04 7.021e-04 6.899e-04 2.07    
26   5   1.09940e-01 1.91511e+01 9.85187e-04 7.021e-04 6.912e-04 2.19    
26   2   1.74811e-01 1.17250e+01 1.80724e-03 7.021e-04 1.665e-03 accuracy not achieved
30   4   1.04402e-01 2.02255e+01 9.84597e-04 7.021e-04 6.903e-04 2.99    
30   3   1.24733e-01 1.67591e+01 9.85812e-04 7.021e-04 6.921e-04 3.06    
30   5   9.72589e-02 2.17971e+01 9.74183e-04 7.021e-04 6.754e-04 3.14    
30   2   1.40668e-01 1.47581e+01 2.36534e-03 7.021e-04 2.259e-03 accuracy not achieved

resulting parameters: mesh: (10 10 10), cao: 4, r_cut_iL: 2.6906e-01,
                      alpha_L: 7.4197e+00, accuracy: 9.8813e-04, time: 0.31

minimization step:   40    max. rel. force change:+7.683e-01    rel. energy change:+4.829e-01
minimization step:   80    max. rel. force change:+9.299e-01    rel. energy change:+7.919e-03
minimization step:  120    max. rel. force change:+5.162e-02    rel. energy change:+5.518e-03
minimization step:  160    max. rel. force change:+7.904e-02    rel. energy change:+5.603e-03
minimization step:  200    max. rel. force change:+5.228e-01    rel. energy change:+5.219e-03
minimization step:  240    max. rel. force change:+5.482e-02    rel. energy change:+5.424e-03
minimization step:  280    max. rel. force change:+1.176e-01    rel. energy change:+5.357e-03
minimization step:  320    max. rel. force change:+3.329e-02    rel. energy change:+5.599e-03
minimization step:  360    max. rel. force change:+3.781e-02    rel. energy change:+6.033e-03
minimization step:  400    max. rel. force change:+4.445e-02    rel. energy change:+6.597e-03
minimization step:  440    max. rel. force change:+5.373e-02    rel. energy change:+7.311e-03
minimization step:  480    max. rel. force change:+1.656e-02    rel. energy change:+7.973e-03
minimization step:  520    max. rel. force change:+8.291e-02    rel. energy change:+7.883e-03
minimization step:  560    max. rel. force change:+1.550e-01    rel. energy change:+7.820e-03
minimization step:  600    max. rel. force change:+5.476e-02    rel. energy change:+8.169e-03
minimization step:  640    max. rel. force change:+4.649e-02    rel. energy change:+8.428e-03
minimization step:  680    max. rel. force change:+5.574e-02    rel. energy change:+9.531e-03
minimization step:  720    max. rel. force change:+8.332e-03    rel. energy change:+9.451e-03
starting warmup
progress=100%
starting simulation
progress=100%
simulation for parameters {'counterion_valency': 1, 'rod_charge_dens': 2} done

Question

  • Why does the second simulation take much longer than the first one?

The rod charge density is doubled, so the total charge of the counterions needs to be doubled, too. Since their valency is only half of the one in the first run, there will be four times more counterions in the second run.

We plot the density of counterions around the rod as the normalized integrated radial counterion charge distribution function $P(r)$, meaning the integrated probability to find an amount of charge within the radius $r$. We express the rod charge density $\lambda$ in terms of the dimensionless Manning parameter $\xi = \lambda l_B / e$ where $l_B$ is the Bjerrum length and $e$ the elementary charge

In [23]:
# With the notion of P(r) the probability to find the charge up to r,
# we only use the right side of the bin edges for plotting
rs = bin_edges[1:, 0, 0, 0]

fig, ax = plt.subplots(figsize=(10, 7))
for run in runs:
    hist = np.array(run['histogram'][:, 0, 0])
    # The CylindricalDensityProfile normalizes the bin values by the bin size.
    # We want the 'raw' distribution (number of ions within a radius)
    # so we need to multiply by the radii
    hist = hist * rs
    cum_hist = np.cumsum(hist)
    cum_hist /= cum_hist[-1]
    manning_xi = run['params']['rod_charge_dens'] * BJERRUM_LENGTH / Q_E
    ax.plot(rs, cum_hist, label=r'$\xi ={}, \nu = {}$'.format(manning_xi,
                                                              run['params']['counterion_valency']))
ax.set_xscale('log')
ax.legend()
plt.xlabel('r')
plt.ylabel('P(r)')
plt.show()

In the semilogarithmic plot we see an inflection point of the cumulative charge distribution which is the indicator for ion condensation. To compare to the meanfield approach of PB, we calculate the solution of the analytical expressions given in 10.1021/ma990897o

In [24]:
def eq_to_solve_for_gamma(gamma, manning_parameter, rod_radius, max_radius):
    # eq 7 - eq 6 from 10.1021/ma990897o
    return gamma * np.log(max_radius / rod_radius) - np.arctan(1 / gamma) + np.arctan((1 - manning_parameter) / gamma)


def calc_manning_radius(gamma, max_radius):
    # eq 7 from 10.1021/ma990897o
    return max_radius * np.exp(-np.arctan(1. / gamma) / gamma)


def calc_PB_probability(r, manning_parameter, gamma, manning_radius):
    # eq 8 and 9 from 10.1021/ma990897o
    return 1. / manning_parameter + gamma / manning_parameter * np.tan(gamma * np.log(r / manning_radius))

For multivalent counterions, the manning parameter $\xi$ has to be multiplied by the valency $\nu$. The result depends only on the product of rod_charge_dens and ion_valency, so we only need one curve

In [25]:
rod_charge_density = runs[0]['params']['rod_charge_dens']
ion_valency = runs[0]['params']['counterion_valency']
manning_parameter_times_valency = BJERRUM_LENGTH * rod_charge_density * ion_valency

gamma = optimize.fsolve(eq_to_solve_for_gamma, 1, args=(
    manning_parameter_times_valency, r_min, r_max))
manning_radius = calc_manning_radius(gamma, r_max)

PB_probability = calc_PB_probability(
    rs, manning_parameter_times_valency, gamma, manning_radius)

ax.plot(rs, PB_probability, label=r'PB $\xi \cdot \nu$ = {}'.format(
    manning_parameter_times_valency))
ax.legend()
ax.set_xscale('log')
fig
Out[25]:

We see that overall agreement is quite good, but the deviations from the PB solution get stronger the more charged the ions are. Poisson Boltzmann makes two simplifying assumptions: Particles are points and there are no correlations between the particles. Both is not given in the simulation. Excluded volume effects can only lower the density, but we see in the figure that the simulated density is always larger that the calculated one. This means that correlation effects cause the discrepancy.

Overcharging by added salt

Above simulations were performed for a system where all ions come from dissociation off the polyelectrolyte. We can also investigate systems where there are additional salt ions present.

In [26]:
def add_salt(system, anion_params, cation_params):

    N_anions = anion_params['number']
    N_cations = cation_params['number']

    anion_positions = np.random.random((N_anions, 3)) * system.box_l
    cation_positions = np.random.random((N_cations, 3)) * system.box_l

    anions = system.part.add(pos=anion_positions, type=[anion_params['type']] * N_anions,
                             q=[-anion_params['valency']] * N_anions)
    cations = system.part.add(pos=cation_positions, type=[cation_params['type']] * N_cations,
                              q=[cation_params['valency']] * N_cations)

    return anions, cations
In [27]:
ANION_PARAMS = {'type': 3,
                'valency': 2,
                'number': 150}
CATION_PARAMS = {'type': 4,
                 'valency': 2,
                 'number': 150}
ROD_LENGTH = 10
N_rod_beads = int(ROD_LENGTH / ROD_RADIUS)
ROD_CHARGE_DENS = 1
COUNTERION_VALENCY = 1

STEPS_PER_SAMPLE_SALT = 20
N_SAMPLES_SALT = 1500
N_RADIAL_BINS = 100

all_ion_types = [COUNTERION_TYPE, ANION_PARAMS['type'], CATION_PARAMS['type']]
In [28]:
# set interactions of salt with the rod and all ions
for salt_type in [ANION_PARAMS['type'], CATION_PARAMS['type']]:
    system.non_bonded_inter[salt_type, ROD_TYPE].wca.set_params(
        epsilon=WCA_EPSILON, sigma=ION_DIAMETER / 2. + ROD_RADIUS)
    for ion_type in all_ion_types:
        system.non_bonded_inter[salt_type, ion_type].wca.set_params(
            epsilon=WCA_EPSILON, sigma=ION_DIAMETER)
In [29]:
clear_system(system)
system.box_l = 3 * [ROD_LENGTH]
counterions = setup_rod_and_counterions(
    system, COUNTERION_VALENCY, COUNTERION_TYPE,
    ROD_CHARGE_DENS, N_rod_beads, ROD_TYPE)
anions, cations = add_salt(system, ANION_PARAMS, CATION_PARAMS)
assert abs(sum(anions.q) + sum(cations.q)) < 1e-10

p3m.tune()
remove_overlap(system, STEEPEST_DESCENT_PARAMS)
system.thermostat.set_langevin(**LANGEVIN_PARAMS)
print('starting warmup')
integrate_system(system, WARMUP_STEPS)
radial_profile_accs, bin_edges = setup_profile_calculation(
    system, STEPS_PER_SAMPLE_SALT, all_ion_types, r_min, N_RADIAL_BINS)
print('starting simulation')
integrate_system(system, N_SAMPLES_SALT * STEPS_PER_SAMPLE_SALT)
print('simulation done')
P3M tune parameters: Accuracy goal = 9.88130e-04 prefactor = 1.00000e+00
System: box_l = 1.00000e+01 # charged part = 320 Sum[q_i^2] = 1.22000e+03
mesh cao r_cut_iL     alpha_L      err          rs_err     ks_err     time [ms]
8    7   4.60000e-01 6.13527e+00 2.02443e-02 6.987e-04 2.023e-02 accuracy not achieved
8    7   4.60000e-01 6.13527e+00 2.02443e-02 6.987e-04 2.023e-02 accuracy not achieved
10   7   4.60000e-01 6.13527e+00 3.00351e-03 6.987e-04 2.921e-03 accuracy not achieved
10   7   4.60000e-01 6.13527e+00 3.00351e-03 6.987e-04 2.921e-03 accuracy not achieved
12   7   4.44727e-01 6.35270e+00 9.82967e-04 6.987e-04 6.914e-04 2.66    
12   6   4.60000e-01 6.13527e+00 1.14367e-03 6.987e-04 9.054e-04 accuracy not achieved
12   7   4.44727e-01 6.35270e+00 9.82967e-04 6.987e-04 6.914e-04 2.66    
12   6   4.44727e-01 6.35270e+00 1.43478e-03 6.987e-04 1.253e-03 accuracy not achieved
14   7   3.85661e-01 7.35826e+00 9.84289e-04 6.987e-04 6.933e-04 2.09    
14   6   4.10851e-01 6.89354e+00 9.82353e-04 6.987e-04 6.905e-04 2.28    
14   5   4.44727e-01 6.35270e+00 1.15920e-03 6.987e-04 9.250e-04 accuracy not achieved
14   7   3.85661e-01 7.35826e+00 9.84289e-04 6.987e-04 6.933e-04 2.08    
14   6   3.85661e-01 7.35826e+00 1.44662e-03 6.987e-04 1.267e-03 accuracy not achieved
16   7   3.41220e-01 8.34817e+00 9.78731e-04 6.987e-04 6.854e-04 1.78    
16   6   3.63064e-01 7.83088e+00 9.87887e-04 6.987e-04 6.984e-04 1.91    
16   5   3.85661e-01 7.35826e+00 1.29389e-03 6.987e-04 1.089e-03 accuracy not achieved
16   7   3.41220e-01 8.34817e+00 9.78731e-04 6.987e-04 6.854e-04 1.78    
16   6   3.41220e-01 8.34817e+00 1.44532e-03 6.987e-04 1.265e-03 accuracy not achieved
18   7   3.05898e-01 9.34342e+00 9.80277e-04 6.987e-04 6.876e-04 1.83    
18   6   3.25892e-01 8.75320e+00 9.87810e-04 6.987e-04 6.983e-04 1.91    
18   5   3.41220e-01 8.34817e+00 1.41260e-03 6.987e-04 1.228e-03 accuracy not achieved
18   7   3.05898e-01 9.34342e+00 9.80277e-04 6.987e-04 6.876e-04 1.84    
18   6   3.05898e-01 9.34342e+00 1.45753e-03 6.987e-04 1.279e-03 accuracy not achieved
20   7   2.77220e-01 1.03410e+01 9.85162e-04 6.987e-04 6.945e-04 1.70    
20   6   2.96339e-01 9.65419e+00 9.80498e-04 6.987e-04 6.879e-04 1.79    
20   5   3.05898e-01 9.34342e+00 1.53266e-03 6.987e-04 1.364e-03 accuracy not achieved
20   7   2.77220e-01 1.03410e+01 9.85162e-04 6.987e-04 6.945e-04 1.70    
20   6   2.77220e-01 1.03410e+01 1.47589e-03 6.987e-04 1.300e-03 accuracy not achieved
22   7   2.53938e-01 1.13192e+01 9.81958e-04 6.987e-04 6.900e-04 2.06    
22   6   2.71264e-01 1.05750e+01 9.85007e-04 6.987e-04 6.943e-04 2.07    
22   5   2.77220e-01 1.03410e+01 1.65109e-03 6.987e-04 1.496e-03 accuracy not achieved
22   7   2.53938e-01 1.13192e+01 9.81958e-04 6.987e-04 6.900e-04 2.05    
22   6   2.53938e-01 1.13192e+01 1.47784e-03 6.987e-04 1.302e-03 accuracy not achieved
24   7   2.34099e-01 1.23086e+01 9.85941e-04 6.987e-04 6.956e-04 2.14    
24   6   2.50962e-01 1.14575e+01 9.75834e-04 6.987e-04 6.812e-04 2.14    
24   5   2.53938e-01 1.13192e+01 1.74714e-03 6.987e-04 1.601e-03 accuracy not achieved
24   7   2.34297e-01 1.22979e+01 9.81223e-04 6.987e-04 6.889e-04 2.12    
24   6   2.50962e-01 1.14575e+01 9.75834e-04 6.987e-04 6.812e-04 2.11    
24   5   2.50962e-01 1.14575e+01 1.88427e-03 6.987e-04 1.750e-03 accuracy not achieved
26   7   2.17631e-01 1.32691e+01 9.78961e-04 6.987e-04 6.857e-04 2.74    
26   6   2.33317e-01 1.23512e+01 9.73540e-04 6.987e-04 6.779e-04 2.67    
26   5   2.50962e-01 1.14575e+01 1.23870e-03 6.987e-04 1.023e-03 accuracy not achieved
26   7   2.17823e-01 1.32570e+01 9.74151e-04 6.987e-04 6.788e-04 2.74    
26   6   2.33317e-01 1.23512e+01 9.73540e-04 6.987e-04 6.779e-04 2.67    
26   5   2.33317e-01 1.23512e+01 1.89063e-03 6.987e-04 1.757e-03 accuracy not achieved
28   7   2.03241e-01 1.42377e+01 9.77339e-04 6.987e-04 6.834e-04 2.91    
28   6   2.17823e-01 1.32570e+01 9.76787e-04 6.987e-04 6.826e-04 2.83    
28   5   2.33317e-01 1.23512e+01 1.27708e-03 6.987e-04 1.069e-03 accuracy not achieved
28   7   2.03358e-01 1.42292e+01 9.74187e-04 6.987e-04 6.789e-04 2.93    
28   6   2.17823e-01 1.32570e+01 9.76787e-04 6.987e-04 6.826e-04 2.89    
28   5   2.17823e-01 1.32570e+01 1.91156e-03 6.987e-04 1.779e-03 accuracy not achieved
30   7   1.90595e-01 1.52114e+01 9.78785e-04 6.987e-04 6.854e-04 3.67    
30   6   2.04209e-01 1.41682e+01 9.82357e-04 6.987e-04 6.905e-04 3.47    
30   5   2.17823e-01 1.32570e+01 1.32059e-03 6.987e-04 1.121e-03 accuracy not achieved
30   7   1.90648e-01 1.52071e+01 9.77253e-04 6.987e-04 6.832e-04 3.57    
30   6   2.04209e-01 1.41682e+01 9.82357e-04 6.987e-04 6.905e-04 3.46    
30   5   2.04209e-01 1.41682e+01 1.93844e-03 6.987e-04 1.808e-03 accuracy not achieved
32   7   1.79480e-01 1.61823e+01 9.80061e-04 6.987e-04 6.873e-04 4.27    
32   6   1.92244e-01 1.50771e+01 9.87712e-04 6.987e-04 6.981e-04 4.49    
32   5   2.04209e-01 1.41682e+01 1.36564e-03 6.987e-04 1.173e-03 accuracy not achieved

resulting parameters: mesh: (20 20 20), cao: 7, r_cut_iL: 2.7722e-01,
                      alpha_L: 1.0341e+01, accuracy: 9.8516e-04, time: 1.70

minimization step:   40    max. rel. force change:+9.562e-01    rel. energy change:+9.299e-01
minimization step:   80    max. rel. force change:+7.655e-01    rel. energy change:+1.981e-01
minimization step:  120    max. rel. force change:+8.291e-04    rel. energy change:+4.839e-03
starting warmup
progress=100%
starting simulation
progress=100%
simulation done
In [30]:
rs = bin_edges[1:, 0, 0, 0]
cum_hists = {}
for ion_type in all_ion_types:
    hist = radial_profile_accs[ion_type].mean()
    hist = hist[:, 0, 0] * rs
    cum_hist = np.cumsum(hist)
    cum_hist /= cum_hist[-1]
    cum_hists[ion_type] = cum_hist

Exercise:

  • Use the cumulative histograms from the cell above to create the cumulative charge histogram of the total ion charge

Hints

  • You need to account for the fact that the cumulative histograms are all normalized, but the total charge of each ion type is different
In [31]:
counterion_charge = sum(counterions.q)
anion_charge = sum(anions.q)
cation_charge = sum(cations.q)
charge_hist = counterion_charge * cum_hists[COUNTERION_TYPE] + \
    anion_charge * cum_hists[ANION_PARAMS['type']] + \
    cation_charge * cum_hists[CATION_PARAMS['type']]
In [32]:
charge_hist /= charge_hist[-1]
fig2, ax2 = plt.subplots(figsize=(10, 7))
ax2.plot(rs, charge_hist)
ax2.set_xscale('linear')
plt.xlabel('r')
plt.ylabel('P(r)')
plt.show()

You should observe a strong overcharging effect, where ions accumulate close to the rod.