Esempio n. 1
0
def test_length_one_msd_nd():
    N = 1
    ND = 4
    data = np.ones((N, ND))
    reference_msd = np.zeros_like(data[:, 0])
    computed_msd = tidynamics.msd(data)
    assert np.allclose(reference_msd, computed_msd)
def MSD(df, conversion="x"):
    """
    Computes the Mean Square Displacement (MSD)
    which is the mean squared difference between the x or y coordinates of the fronts

    --------------------------
    Parameters:
    --------------------------
    df : pandas dataframe which contains x or y coordinates for different frames
    conversion : string variable to convert pixels in micrometers, because the conversion is different for
    the x and y axes
    ----------------------------
    Returns a dataframe with the MSD

    References:
    -----------------
    [1]http://lab.pdebuyl.be/tidynamics/
    """
    #conversion from pixels to micrometers
    if conversion == "y":
        df = df / 1200 * 633
    else:
        df = df / 1600 * 844
    msd = []
    for i in range(len(df)):
        #computes the msd for the x or y coordinates between the different frames
        msd.append(tidynamics.msd(df.T[i]))

    msd = pd.DataFrame(msd)

    return msd
Esempio n. 3
0
def test_random_walk_msd():
    def brute_force_msd(pos):
        """
        Compute the mean-square displacement with an explicit loop over all
        time intervals.
        """
        pos = np.asarray(pos)
        if pos.ndim == 1:
            pos = pos.reshape((-1, 1))
        trajectory_length = len(pos)
        msd = np.zeros(trajectory_length)
        msd_count = np.zeros(trajectory_length)
        for i in range(trajectory_length):
            for j in range(i, trajectory_length):
                msd[j - i] += np.sum((pos[i] - pos[j])**2)
                msd_count[j - i] += 1
        msd = msd / msd_count
        return msd

    N = 200
    N_dim = 2
    time = np.arange(N)
    # Generate steps of value +/- 1
    steps = -1 + 2 * np.random.randint(0, 2, size=(N, N_dim))
    # Compute random walk position
    walk = np.cumsum(steps, axis=0)

    tidynamics_msd = tidynamics.msd(walk)
    comparison_msd = brute_force_msd(walk)

    assert np.allclose(tidynamics_msd, comparison_msd)
Esempio n. 4
0
def test_cross_disp_1():
    N = 100
    D = 4
    data = np.random.random(size=(N, D))
    cross_disp = tidynamics.cross_displacement(data)
    for i in range(D):
        assert np.allclose(cross_disp[i][i], tidynamics.msd(data[:,i]))
Esempio n. 5
0
    def _conclude(self):
        
        self.lagtimes = self.frames * self.dt
        
        for lipid_index in range(self.membrane.n_residues):
            
            self.msd[lipid_index] = tidynamics.msd(self.lipid_com_pos[lipid_index])

        # MSD must start at 0
        self.msd[:, 0] = 0.0

        # Convert A^2 to nm^2
        self.msd /= 100
        
        return None
    def _conclude_fft(self):  # with FFT, np.float64 bit prescision required.
        r""" Calculates the MSD via the FCA fast correlation algorithm.
        """
        try:
            import tidynamics
        except ImportError:
            raise ImportError("""ERROR --- tidynamics was not found!
                tidynamics is required to compute an FFT based MSD (default)
                try installing it using pip eg:
                    pip install tidynamics
                or set fft=False""")

        positions = self._position_array.astype(np.float64)
        for n in range(self.n_particles):
            self.msds_by_particle[:, n] = tidynamics.msd(positions[:, n, :])
        self.timeseries = self.msds_by_particle.mean(axis=1)
Esempio n. 7
0
def diffusion(u, t, block):
    '''Computes mean squared displacement of water molecules within specified
    layers parallel to a surface.

    Args:
        u: MDAnalysis Universe object containing trajectory.
        t: Thresholds specifying layer boundaries.
        block: Range of frames composing block.

    Returns:
        Parallel (xy) mean squared displacement.
    '''

    # Select oxygen atoms
    oxygen = u.select_atoms('name O')
    msd = []

    # Initialize 3D position array (frame, atom, dimension)
    position_array = np.zeros((len(block), oxygen.n_atoms, 3))

    for i, ts in enumerate(u.trajectory[block.start:block.stop]):
        print('Processing blocks %.1f%%' % (100*i/len(block)), end='\r')

        # Store positions of all oxygens at current frame
        position_array[i, :, :] = oxygen.positions

    # Loop over oxygen atoms
    for k in range(oxygen.n_atoms):

        # Get atoms in region
        z = position_array[:, k, 2]
        z_bool = (z > t[0])*(z < t[1])+(z > t[2])*(z < t[3])

        # Get intervals in which atom remains continuously in region
        contiguous_region = find_objects(label(z_bool)[0])

        # Compute mean squared displacement of atom for each interval
        for reg in contiguous_region:
            msd.append(tidynamics.msd(
                position_array[reg[0].start:reg[0].stop, k, :2]))

    # Return average of all MSDs
    return tolerant.mean(msd)
Esempio n. 8
0
    def _conclude(self):

        self.lagtimes = self.frames * self.dt

        # lagtimes must start from zero, and should be in ns
        self.lagtimes -= self.lagtimes[0]
        self.lagtimes /= 1000

        for lipid_index in range(self.membrane.n_residues):

            self.msd[lipid_index] = tidynamics.msd(
                self.lipid_com_pos[lipid_index])

        # MSD must start at 0
        self.msd[:, 0] = 0.0

        # Convert A^2 to nm^2
        self.msd /= 100

        return None
def MSD_Sham(dir, side="dx", delimiter="\t"):
    """
    Computes the Mean Square Displacement (MSD)
    which is the mean squared difference between the y coordinates of the fronts

    --------------------------
    Parameters:
    --------------------------
    dir : the directory which contains the txt files with the coordinates
    side : the side of the front which is left or right, this distinguish the txt files
    delimiter : the space between the x and y coordinates in the txt file

    ----------------------------
    Returns a numpy array with the MSD
    """

    x = pd.DataFrame()
    y = pd.DataFrame()
    for fname in os.listdir(dir):
        if side in fname:
            k = fname.split('_')[-2]
            k = int(k)
            #df = grid(dir + fname + str(i+1) + side + ".txt", delimiter = delimiter)
            dfx, dfy = necklace_points(dir + fname, N=80, sep=delimiter)
            x[k] = dfx
            y[k] = dfy
    col = np.arange(1, len(x.T))
    x = x[col]
    count = 0
    mean = np.zeros(len(x.T))
    for i in range(len(mean)):
        mean = mean + tidynamics.msd(x.T[i])
        count += 1

    mean /= count
    return mean, x, y
Esempio n. 10
0
def test_length_one_msd():
    N = 1
    pos = np.zeros(N)
    reference_msd = np.zeros(N)
    computed_msd = tidynamics.msd(pos)
    assert np.allclose(reference_msd, computed_msd)
Esempio n. 11
0
plt.rcParams['figure.figsize'] = 5.12, 3.84
plt.rcParams['figure.subplot.bottom'] = 0.18
plt.rcParams['figure.subplot.left'] = 0.16

# Generate 32 random walks and compute their mean-square
# displacements

N = 1000
mean = np.zeros(N)
count = 0
for i in range(32):
    # Generate steps of value +/- 1
    steps = -1 + 2 * np.random.randint(0, 2, size=(N, 2))
    # Compute random walk position
    data = np.cumsum(steps, axis=0)
    mean += tidynamics.msd(data)
    count += 1

mean /= count
mean = mean[1:N // 2]

time = np.arange(N)[1:N // 2]

plt.plot(time, mean, label='Random walk (num.)')

plt.plot(time, 2 * time, label='Random walk (theo.)')

time = np.arange(N // 2)

# Display the mean-square displacement for a trajectory with
# constant velocity. Here the trajectory is taken equal to the
Esempio n. 12
0
        r_dt = group['position/time'][()]
        im = group['image/value'][:, slicer, :]
        v = group['velocity/value'][:, slicer, :]
        v_dt = group['velocity/time'][()]
        edges = group['box/edges'][:].reshape((1, -1))
        r += im * edges
        assert abs(r_dt - v_dt) < 1e-12
        if args.dimer:
            assert r.shape[1] == 2
            assert r.shape[2] == 3
            r = r.mean(axis=1)
            v_com = v.mean(axis=1)

        if r.ndim == 3:
            for i in range(r.shape[1]):
                msd_data.append(tidynamics.msd(r[:, i, :]))
        else:
            msd_data.append(tidynamics.msd(r))

msd_data = np.array(msd_data)
m = msd_data.mean(axis=0)
s = msd_data.std(axis=0)
time = np.arange(r.shape[0]) * r_dt

plt.plot(time, m, 'k-')
plt.plot(time, m + s, 'k--')
plt.plot(time, m - s, 'k--')

fit = np.polyfit(time[:r.shape[0] // 4], m[:r.shape[0] // 4], 1)
D = fit[0] / 6
plt.plot(time, 6 * D * time, 'k:')
Esempio n. 13
0
np.savetxt from NumPy.

For more information, consult the documentation of tidynamics at
http://lab.pdebuyl.be/tidynamics/

"""
from __future__ import print_function, division

import argparse
import numpy as np
import tidynamics

parser = argparse.ArgumentParser(
    description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('action',
                    help='Choice of computation to perform on input file',
                    choices=['acf', 'msd'])
parser.add_argument('input_file', help='Filename for input data')
parser.add_argument('output_file',
                    help='Filename for the result of the computation')
args = parser.parse_args()

input_data = np.loadtxt(args.input_file)

if args.action == 'acf':
    result = tidynamics.acf(input_data)
elif args.action == 'msd':
    result = tidynamics.msd(input_data)

np.savetxt(args.output_file, result)
Esempio n. 14
0
def test_linear_msd():
    N = 100
    time = np.arange(N)
    reference_msd = time**2
    computed_msd = tidynamics.msd(time)
    assert np.allclose(reference_msd, computed_msd)
Esempio n. 15
0
def test_cst_msd():
    N = 100
    data = np.ones(N)
    reference_msd = np.zeros_like(data)
    computed_msd = tidynamics.msd(data)
    assert np.allclose(reference_msd, computed_msd)