Ferrofluid - Part II

Remark: The equilibration and sampling times used in this tutorial would be not sufficient for scientific purposes, but they are long enough to get at least a qualitative insight of the behaviour of ferrofluids. They have been shortened so we achieve reasonable computation times for the purpose of a tutorial.

Applying an external magnetic field

In this part we want to investigate the influence of a homogeneous external magnetic field exposed to a ferrofluid system.

We import all necessary packages and check for the required ESPResSo features

In [1]:
import espressomd
espressomd.assert_features('DIPOLES', 'LENNARD_JONES')

from espressomd.magnetostatics import DipolarP3M
from espressomd.magnetostatic_extensions import DLC

import numpy as np

and set up the simulation parameters where we introduce a new dimensionless parameter

\begin{equation} \alpha = \frac{\mu B}{k_{\text{B}}T} = \frac{\mu \mu_0 H}{k_{\text{B}}T} \end{equation}

which is called Langevin parameter. We intentionally choose a relatively high volume fraction $\phi$ and dipolar interaction parameter $\lambda$ to clearly see the influence of the dipole-dipole interaction

In [2]:
# Lennard-Jones parameters
LJ_CUT = 2**(1. / 6.) * LJ_SIGMA

# Particles
N_PART = 700

# Area fraction of the mono-layer
PHI = 0.06

# Dipolar interaction parameter lambda = MU_0 m^2 /(4 pi sigma^3 kT)

# Temperature
KT = 1.0

# Friction coefficient
GAMMA = 1.0

# Time step
TIME_STEP = 0.01

# Langevin parameter ALPHA = MU_0 m H / kT
ALPHA = 10.

# vacuum permeability
MU_0 = 1.

Now we set up the system. As in part I, the orientation of the dipole moments is set directly on the particles, whereas the magnitude of the moments is taken into account when determining the prefactor of the dipolar P3M (for more details see part I).

Hint: It should be noted that we seed both the Langevin thermostat and the random number generator of numpy. The latter means that the initial configuration of our system is the same every time this script will be executed. As the time evolution of the system depends not solely on the Langevin thermostat but also on the numeric accuracy and DP3M as well as DLC (the tuned parameters are slightly different every time) it is only partly predefined. You can change the seeds to simulate with a different initial configuration and a guaranteed different time evolution.

In [3]:
# System setup
box_size = (N_PART * np.pi * (LJ_SIGMA / 2.)**2. / PHI)**0.5

print("Box size", box_size)
# Note that the dipolar P3M and dipolar layer correction need a cubic
# simulation box for technical reasons.
system = espressomd.System(box_l=(box_size, box_size, box_size))
system.time_step = TIME_STEP

# Lennard-Jones interaction
system.non_bonded_inter[0, 0].lennard_jones.set_params(epsilon=LJ_EPSILON, sigma=LJ_SIGMA, cutoff=LJ_CUT, shift="auto")

# Random dipole moments
dip_phi = 2. * np.pi * np.random.random((N_PART, 1))
dip_cos_theta = 2 * np.random.random((N_PART, 1)) - 1
dip_sin_theta = np.sin(np.arccos(dip_cos_theta))
dip = np.hstack((
    dip_sin_theta * np.sin(dip_phi),
    dip_sin_theta * np.cos(dip_phi),

# Random positions in the monolayer
pos = box_size * np.hstack((np.random.random((N_PART, 2)), np.zeros((N_PART, 1))))

# Add particles
system.part.add(pos=pos, rotation=N_PART * [(1, 1, 1)], dip=dip, fix=N_PART * [(0, 0, 1)])

# Remove overlap between particles by means of the steepest descent method
    f_max=0, gamma=0.1, max_displacement=0.05)

while system.analysis.energy()["total"] > 5 * KT * N_PART:

# Switch to velocity Verlet integrator
system.thermostat.set_langevin(kT=KT, gamma=GAMMA, seed=1)

# tune verlet list skin
system.cell_system.tune_skin(min_skin=0.4, max_skin=2., tol=0.2, int_steps=100)

# Setup dipolar P3M and dipolar layer correction (DLC)
dp3m = DipolarP3M(accuracy=5E-4, prefactor=DIP_LAMBDA * LJ_SIGMA**3 * KT)
dlc = DLC(maxPWerror=1E-4, gap_size=box_size - LJ_SIGMA)

# tune verlet list skin again
system.cell_system.tune_skin(min_skin=0.4, max_skin=2., tol=0.2, int_steps=100)

# print skin value
print('tuned skin = {}'.format(system.cell_system.skin))
Box size 95.72344839677595
Dipolar P3M tune parameters: Accuracy goal = 5.00000e-04 prefactor = 4.00000e+00
System: box_l = 9.57234e+01 # charged part = 700 Sum[q_i^2] = 7.00000e+02
Dmesh cao Dr_cut_iL   Dalpha_L     Derr         Drs_err    Dks_err    time [ms]
8    3   7.31480e-02 2.54050e+01 4.96625e-04 3.536e-04 3.488e-04 1       
8    2   7.97126e-02 2.19599e+01 4.95928e-04 3.536e-04 3.478e-04 1       
8    4   6.93968e-02 2.76533e+01 4.99061e-04 3.536e-04 3.522e-04 2       
8    1   9.19039e-02 1.67627e+01 4.94683e-04 3.536e-04 3.460e-04 2       
10   3   7.31480e-02 2.54050e+01 5.95205e-04 3.536e-04 4.788e-04 accuracy not achieved
10   4   7.31480e-02 2.54050e+01 5.64548e-04 3.536e-04 4.401e-04 accuracy not achieved
10   5   7.31480e-02 2.54050e+01 5.49719e-04 3.536e-04 4.209e-04 accuracy not achieved
10   6   7.31480e-02 2.54050e+01 5.42787e-04 3.536e-04 4.118e-04 accuracy not achieved
10   7   7.31480e-02 2.54050e+01 5.39628e-04 3.536e-04 4.077e-04 accuracy not achieved
12   3   7.31480e-02 2.54050e+01 6.83186e-04 3.536e-04 5.846e-04 accuracy not achieved
12   4   7.31480e-02 2.54050e+01 6.32075e-04 3.536e-04 5.239e-04 accuracy not achieved
12   5   7.31480e-02 2.54050e+01 6.03758e-04 3.536e-04 4.894e-04 accuracy not achieved
12   6   7.31480e-02 2.54050e+01 5.88343e-04 3.536e-04 4.703e-04 accuracy not achieved
12   7   7.31480e-02 2.54050e+01 5.80158e-04 3.536e-04 4.600e-04 accuracy not achieved
14   3   7.31480e-02 2.54050e+01 7.40816e-04 3.536e-04 6.510e-04 accuracy not achieved
14   4   7.31480e-02 2.54050e+01 6.72368e-04 3.536e-04 5.719e-04 accuracy not achieved
14   5   7.31480e-02 2.54050e+01 6.31811e-04 3.536e-04 5.236e-04 accuracy not achieved
14   6   7.31480e-02 2.54050e+01 6.07529e-04 3.536e-04 4.941e-04 accuracy not achieved
14   7   7.31480e-02 2.54050e+01 5.93209e-04 3.536e-04 4.763e-04 accuracy not achieved
16   3   7.31480e-02 2.54050e+01 7.60937e-04 3.536e-04 6.738e-04 accuracy not achieved
16   4   7.31480e-02 2.54050e+01 6.80545e-04 3.536e-04 5.815e-04 accuracy not achieved
16   5   7.31480e-02 2.54050e+01 6.31806e-04 3.536e-04 5.236e-04 accuracy not achieved
16   6   7.31480e-02 2.54050e+01 6.01057e-04 3.536e-04 4.861e-04 accuracy not achieved
16   7   7.31480e-02 2.54050e+01 5.81626e-04 3.536e-04 4.618e-04 accuracy not achieved
18   3   7.31480e-02 2.54050e+01 7.46691e-04 3.536e-04 6.577e-04 accuracy not achieved
18   4   7.31480e-02 2.54050e+01 6.60242e-04 3.536e-04 5.576e-04 accuracy not achieved
18   5   7.31480e-02 2.54050e+01 6.08103e-04 3.536e-04 4.948e-04 accuracy not achieved
18   6   7.31480e-02 2.54050e+01 5.74521e-04 3.536e-04 4.529e-04 accuracy not achieved
18   7   7.31480e-02 2.54050e+01 5.52432e-04 3.536e-04 4.245e-04 accuracy not achieved
20   3   7.31480e-02 2.54050e+01 7.07030e-04 3.536e-04 6.123e-04 accuracy not achieved
20   4   7.31480e-02 2.54050e+01 6.20001e-04 3.536e-04 5.093e-04 accuracy not achieved
20   5   7.31480e-02 2.54050e+01 5.68765e-04 3.536e-04 4.455e-04 accuracy not achieved
20   6   7.31480e-02 2.54050e+01 5.35853e-04 3.536e-04 4.027e-04 accuracy not achieved
20   7   7.31480e-02 2.54050e+01 5.13848e-04 3.536e-04 3.729e-04 accuracy not achieved
22   3   7.31480e-02 2.54050e+01 6.52670e-04 3.536e-04 5.486e-04 accuracy not achieved
22   4   7.31480e-02 2.54050e+01 5.69679e-04 3.536e-04 4.467e-04 accuracy not achieved
22   5   7.31480e-02 2.54050e+01 5.22691e-04 3.536e-04 3.850e-04 accuracy not achieved
22   6   7.31480e-02 2.54050e+01 4.93120e-04 3.536e-04 3.438e-04 7       
22   7   7.20051e-02 2.60659e+01 4.99408e-04 3.536e-04 3.527e-04 7       

resulting parameters: mesh: 8, cao: 3, r_cut_iL: 7.3148e-02,
                      alpha_L: 2.5405e+01, accuracy: 4.9662e-04, time: 1

tuned skin = 0.55

We now apply the external magnetic field which is

\begin{equation} B = \mu_0 H = \frac{\alpha~k_{\text{B}}T}{\mu} \end{equation}

As only the current orientation of the dipole moments, i.e. the unit vector of the dipole moments, is saved in the particle list but not their magnitude, we have to use $B\cdot \mu$ as the strength of the external magnetic field. We will apply the field in x-direction using the class constraints of ESPResSo

In [4]:
# magnetic field times dipole moment
H_dipm = ALPHA * KT
H_field = [H_dipm, 0, 0]


Define a homogenous magnetic field constraint using H_field and add it to system's contraints.

In [5]:
H_constraint = espressomd.constraints.HomogeneousMagneticField(H=H_field)
<espressomd.constraints.HomogeneousMagneticField at 0x7fbc2edf70e0>

Equilibrate the system.

In [6]:
# Equilibrate
equil_rounds = 10
equil_steps = 100
for i in range(equil_rounds):
    print("progress: {:3.0f}%, dipolar energy: {:9.2f}".format(
        (i + 1) * 100. / equil_rounds, system.analysis.energy()["dipolar"]), end="\r")
print("\nEquilibration done")
progress: 100%, dipolar energy:  -9602.78
Equilibration done

Now we can visualize the current state and see that the particles mostly create chains oriented in the direction of the external magnetic field. Also some monomers should be present.

In [7]:
import matplotlib.pyplot as plt
In [8]:
plt.figure(figsize=(10, 10))
plt.xlim(0, box_size)
plt.ylim(0, box_size)
plt.xlabel('x-position', fontsize=20)
plt.ylabel('y-position', fontsize=20)
plt.plot(system.part[:].pos_folded[:, 0], system.part[:].pos_folded[:, 1], 'o')

Video of the development of the system

You may want to get an insight of how the system develops in time. Thus we now create a function which will save a video and embed it in an html string to create a video of the systems development

In [9]:
import matplotlib.pyplot as plt
In [10]:
import matplotlib.animation as animation
In [ ]:
from tempfile import NamedTemporaryFile
import base64

VIDEO_TAG = """<video controls>
 <source src="data:video/x-m4v;base64,{0}" type="video/mp4">
 Your browser does not support the video tag.

def anim_to_html(anim):
    if not hasattr(anim, '_encoded_video'):
        with NamedTemporaryFile(suffix='.mp4') as f:
            anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264'])
            with open(f.name, "rb") as g:
                video = g.read()
        anim._encoded_video = base64.b64encode(video).decode('ascii')
    return VIDEO_TAG.format(anim._encoded_video)

animation.Animation._repr_html_ = anim_to_html

def init():
    # Set x and y range
    ax.set_ylim(0, box_size)
    ax.set_xlim(0, box_size)
    xdata, ydata = [], []
    part.set_data(xdata, ydata)
    return part,

def run(i):

    # Save current system state as a plot
    xdata, ydata = system.part[:].pos_folded[:, 0], system.part[:].pos_folded[:, 1]
    part.set_data(xdata, ydata)
    print("progress: {:3.0f}%".format(i + 1), end="\r")
    return part,

We now can start the sampling over the animation class of matplotlib

In [11]:
fig, ax = plt.subplots(figsize=(10, 10))
part, = ax.plot([], [], 'o')

animation.FuncAnimation(fig, run, frames=100, blit=True, interval=0, repeat=False, init_func=init)
progress: 100%