Exemple #1
0
def analyzeData(d_cum_data):

    l = []
    for key in d_cum_data:
        m, s = nu.meanstdv(d_cum_data[key])
        l.append([key, m])

    return l
def getSlipLength(bgf_file,
                  trj_file,
                  ff_file,
                  interval,
                  n_step,
                  n_avg_step,
                  silent=False):
    """
	This calculates the profile of averaged velocity according to r. 
	NOTE: This is different from averaged velocity profile according to r.
	"""

    # const
    PI = math.pi
    vdw_r_C = 1.7

    # init
    timestep = 0
    l_timestep = []
    line = []
    n_header = 0
    output = ""
    t1 = 0
    t2 = 0
    # clock

    myBGF = bgf.BgfFile(bgf_file)
    myTRJ = open(trj_file)
    myTRJ.seek(0)
    myPkl = open(
        trj_file + ".profile.r_ave_vel-s" + str(n_step) + "k" + str(n_skip) +
        ".pickle", 'w')
    #f_dump = open(trj_file + ".profile.r_ave_vel.dump", 'w')
    #dump = "";

    # how many steps to go?
    n_timestep = len(lt.getTrjInfo(trj_file, silent=False))
    if n_step == 0:
        n_step = n_timestep

    if not silent:
        print("The trajectory contains " + str(n_timestep) + " timesteps.")

    # extract aNos of CNT in the BGF file
    aNo_CNT = []
    aNo_WAT_O = []
    aNo_WAT_all = []

    for atom in myBGF.a:
        # Carbons in CNT
        if "CNT" in atom.rName:
            aNo_CNT.append(atom.aNo)

        # Oxygen in water
        if "WAT" in atom.rName and "O" in atom.aName:
            aNo_WAT_O.append(atom.aNo)

    N_CNT = len(aNo_CNT)  # the number of CNT atoms

    # check if there exists water properly
    if len(aNo_WAT_O) == 0:
        nu.die("No water molecules in the BGF file.")
    if len(aNo_CNT) == 0:
        nu.die("No CNT molecules in the BGF file.")

    # Find header of the trajectory file
    while 1:
        templine = myTRJ.readline()
        line.append(templine.strip('\n').strip('ITEM: '))
        n_header += 1
        if "ITEM: ATOMS" in templine:
            break

    # INITIAL trajectory information
    timestep = int(line[1])
    natoms = int(line[3])
    boxsize = [
        line[5].split(' ')[0], line[5].split(' ')[1], line[6].split(' ')[0],
        line[6].split(' ')[1], line[7].split(' ')[0], line[7].split(' ')[1]
    ]
    boxsize = [float(i) for i in boxsize]
    keywords = line[8].strip('ATOMS ')

    # for every shot in the trajectory file update BGF and manipulate
    dumpatom = get_line(trj_file)
    processed_step = 0

    t1 = t2 = 0
    elapsed_time = 0

    # calculate radius_CNT
    avg_radius_CNT = 0.0
    x_CNT = 0.0
    y_CNT = 0.0
    if not silent:
        print(
            "Calculating the average radius of CNT throughout the averaging steps"
        )
    while 1:

        ### Show progress
        t1 = time.time()
        remaining_time = elapsed_time * (n_step - processed_step)

        ### Read
        try:
            chunk = [next(dumpatom) for i in range(natoms + n_header)]
        except StopIteration:
            break

        # skip if necessary
        if processed_step <= n_skip:
            processed_step += 1
            continue

        timestep = int(chunk[1])
        l_timestep.append(timestep)
        natoms = int(chunk[3])
        boxsize = [
            chunk[5].split(' ')[0], chunk[5].split(' ')[1],
            chunk[6].split(' ')[0], chunk[6].split(' ')[1],
            chunk[7].split(' ')[0], chunk[7].split(' ')[1]
        ]
        boxsize = [float(i) for i in boxsize]
        boxsize = [(boxsize[1] - boxsize[0]), (boxsize[3] - boxsize[2]),
                   (boxsize[5] - boxsize[4])]
        keywords = chunk[8].split('ATOMS ')[1].strip('\n').split(' ')
        sys.stdout.write('\r' + "Fetched timestep: " + str(timestep) +
                         " (Remaining time: " +
                         "{0:4.1f}".format(remaining_time) + " seconds, " +
                         "{0:4.1f} minutes".format(remaining_time / 60) + ")")
        sys.stdout.flush()

        ### update myBGF with trajectory information ###
        natom_bgf = len(myBGF.a)  # number of atoms in BGF file

        mode = 'unwrapped'  # assume that "dump            1 all custom 100 ${sname}${rtemp}K.nvt.lammps id type xu yu zu vx vy vz" in lammps input

        # actual coordinate
        coordinfo = chunk[9:]

        # modified for fast treatment
        for atomline in coordinfo:
            atomcoord = atomline.split(' ')
            atom = myBGF.getAtom(int(atomcoord[0]))

            atom.x = float(atomcoord[2])
            atom.y = float(atomcoord[3])
            atom.z = float(atomcoord[4])

            try:
                for i in range(0, 3):
                    myBGF.CRYSTX[i] = boxsize[i]
            except:
                pass

        # apply periodic condition
        #myBGF = bgftools.periodicMoleculeSort(myBGF, 0, True)

        ### myBGF update complete! ###

        # for CNT atoms, calculate some properties
        min_x_CNT = 0.0
        max_x_CNT = 0.0
        radius_CNT = 0.0
        height_CNT = 0.0
        aNo_WAT_O_not_in_CNT = []
        temp = []
        min_y_CNT = 0.0
        max_y_CNT = 0.0
        min_z_CNT = 0.0
        max_z_CNT = 0.0
        CNT_orientation = ""

        l_radius_CNT = []
        l_x_CNT = []
        l_y_CNT = []

        for aNo in aNo_CNT:
            atom = myBGF.getAtom(aNo)

            # center of CNT
            l_x_CNT.append(atom.x)
            l_y_CNT.append(atom.y)

            # height
            if atom.z < min_z_CNT:
                min_z_CNT = atom.z
            if atom.z > max_z_CNT:
                max_z_CNT = atom.z

        x_CNT, a = nu.meanstdv(l_x_CNT)
        y_CNT, a = nu.meanstdv(l_y_CNT)
        z_diff = max_z_CNT - min_z_CNT

        # radius of CNT
        for aNo in aNo_CNT:
            atom = myBGF.getAtom(aNo)
            l_radius_CNT.append(
                math.sqrt((atom.x - x_CNT)**2 + (atom.y - y_CNT)**2))

        radius_CNT, a = nu.meanstdv(l_radius_CNT)
        l_avg_radius_CNT.append(radius_CNT)

        if processed_step > 3:
            break

    avg_radius_CNT, s = nu.meanstdv(l_avg_radius_CNT)
    bins = np.arange(0.0, math.ceil(radius_CNT), interval)
    l_radial_vz_profile = np.zeros(len(bins) - 1)

    if not silent:
        print("\nAveraged CNT radius: " + str(avg_radius_CNT) + " A")
    if not silent: print("CNT center: " + str([x_CNT, y_CNT]))

    # calculate properties
    myTRJ.close()
    myTRJ = open(trj_file)
    myTRJ.seek(0)
    dumpatom = get_line(trj_file)
    processed_step = 0
    r = []
    vz = []
    # data container
    while 1:
        data = dict()
        # stores [r vz] for a timestep

        ### Show progress
        t1 = time.time()
        remaining_time = elapsed_time * (n_step - processed_step)

        ### Read
        try:
            chunk = [next(dumpatom) for i in range(natoms + n_header)]
        except StopIteration:
            break

        if processed_step <= n_skip:
            processed_step += 1
            continue

        timestep = int(chunk[1])
        l_timestep.append(timestep)
        natoms = int(chunk[3])
        boxsize = [
            chunk[5].split(' ')[0], chunk[5].split(' ')[1],
            chunk[6].split(' ')[0], chunk[6].split(' ')[1],
            chunk[7].split(' ')[0], chunk[7].split(' ')[1]
        ]
        boxsize = [float(i) for i in boxsize]
        boxsize = [(boxsize[1] - boxsize[0]), (boxsize[3] - boxsize[2]),
                   (boxsize[5] - boxsize[4])]
        keywords = chunk[8].split('ATOMS ')[1].strip('\n').split(' ')
        sys.stdout.write('\r' + "Fetched timestep: " + str(timestep) +
                         " (Remaining time: " +
                         "{0:4.1f}".format(remaining_time) + " seconds, " +
                         "{0:4.1f} minutes".format(remaining_time / 60) + ")")
        sys.stdout.flush()

        ### update myBGF with trajectory information ###
        natom_bgf = len(myBGF.a)  # number of atoms in BGF file

        if not natom_bgf == natoms:
            nu.die(
                "Number of atoms in trajectory file does not match with BGF file."
            )

        mode = 'unwrapped'  # assume that "dump            1 all custom 100 ${sname}${rtemp}K.nvt.lammps id type xu yu zu vx vy vz" in lammps input

        # actual coordinate
        coordinfo = chunk[9:]

        # modified for fast treatment
        for atomline in coordinfo:
            atomcoord = atomline.split(' ')
            atom = myBGF.getAtom(int(atomcoord[0]))

            atom.x = float(atomcoord[2])
            atom.y = float(atomcoord[3])
            atom.z = float(atomcoord[4])
            atom.vx = float(atomcoord[5])
            atom.vy = float(atomcoord[6])
            atom.vz = float(atomcoord[7])

            try:
                for i in range(0, 3):
                    myBGF.CRYSTX[i] = boxsize[i]
            except:
                pass
                #nu.warn("Crystal information error: is this file not periodic?")

        # apply periodic condition
        myBGF = bgftools.periodicMoleculeSort(myBGF, 0, True)

        ### myBGF update complete! ###

        # calculate z-directional velocity of water molecules wrt r		vcm = sum vi mi / sum mi
        atom = myBGF.getAtom(aNo_WAT_O[0])
        mass_O = bgftools.getMass(myBGF, [aNo_WAT_O[0]], ff_file)
        atom = myBGF.getAtom(atom.CONECT[0])
        mass_H = bgftools.getMass(myBGF, [atom.aNo], ff_file)
        mass_H2O = mass_O + 2 * mass_H  # H2O mass

        for ano in aNo_WAT_O:
            atom = myBGF.getAtom(ano)  # oxygen

            # com & velocity calculation
            cmx = atom.x * mass_O
            cmy = atom.y * mass_O
            vcmz = atom.vz * mass_O

            for ano2 in atom.CONECT:
                atom2 = myBGF.getAtom(ano2)
                cmx += atom2.x * mass_H
                cmy += atom2.y * mass_H
                vcmz += atom2.vz * mass_H

            cmx /= mass_H2O
            cmy /= mass_H2O
            vcmz /= mass_H2O

            dist = math.sqrt((x_CNT - cmx)**2 + (y_CNT - cmy)**2)
            r.append(dist)
            vz.append(vcmz * 10**5)  # LAMMPS real unit conversion for velocity

        # timestep mark for starting average
        if l_avg_count == []:
            n_avg_count_step = timestep

        l_avg_count.append(timestep)

        # if the time has come.. average!
        if len(l_avg_count) == n_avg_step or processed_step == n_timestep - 1:
            if not silent:
                print(" Averaging invoked at timestep " + str(timestep) +
                      " (" + str(len(l_avg_count)) + " points)")

            # binning
            vz = np.array(vz)
            sum_vz = np.ma.array(np.histogram(r, bins, weights=vz)[0])
            sum_vz2 = np.ma.array(np.histogram(r, bins, weights=vz * vz)[0])
            n_vz = np.ma.array(np.histogram(r, bins)[0])
            #mask_n = ma.masked_values(n_vz, 0)

            mean = sum_vz / n_vz
            std = np.sqrt(sum_vz2 / n_vz - mean * mean)

            mean = np.ma.fix_invalid(mean, fill_value=0.0).data
            std = np.ma.fix_invalid(std, fill_value=0.0).data
            n_vz = np.ma.fix_invalid(n_vz, fill_value=0).data

            if len(mean) != len(bins) - 1 or len(std) != len(bins) - 1:
                nu.die("on numpy masked_array calculation!")

            l_result.append([l_avg_count, bins, n_vz, mean, std])

            # reset
            r = []
            vz = []
            l_radial_vz_profile = np.zeros(len(bins) - 1)
            l_avg_count = []

        t2 = time.time()  # time mark
        elapsed_time = t2 - t1
        processed_step += 1

    #f_dump.write(dump)
    pkl.dump(l_result, myPkl)

    print('')
    return 1
Exemple #3
0
def getVelocity(bgf_file, trj_file, n_step, silent=False):

    # const
    PI = math.pi
    vdw_r_C = 1.7

    # init
    timestep = 0
    l_timestep = []
    line = []
    n_header = 0
    t1 = 0
    t2 = 0
    # clock

    l_data = []
    # stores vz
    l_avg_radius_CNT = []

    myBGF = bgf.BgfFile(bgf_file)
    myTRJ = open(trj_file)
    myTRJ.seek(0)

    ftemp = open("countWater42.profile", 'w')
    ftemp.write(str(sys.argv) + "\n")

    curr_dir = os.path.abspath(".")
    temp_dir = curr_dir + "/CountWAT42/"
    if not os.path.isdir(temp_dir): os.makedirs(temp_dir)

    # how many steps to go?
    n_timestep = len(lt.getTrjInfo(trj_file))
    if n_step == 0:
        n_step = n_timestep

    print(" ..The trajectory contains " + str(n_timestep) + " timesteps.")
    print("The script will proceed for the last " + str(n_step) +
          " timesteps.")

    # extract aNos of CNT in the BGF file
    aNo_CNT = []
    aNo_WAT_O = []
    aNo_WAT_all = []

    for atom in myBGF.a:
        # Carbons in CNT or atoms in BNNT
        if "NT" in atom.rName:
            aNo_CNT.append(atom.aNo)

        # Oxygen in water
        if "WAT" in atom.rName and "O" in atom.aName:
            aNo_WAT_O.append(atom.aNo)

    N_CNT = len(aNo_CNT)  # the number of CNT atoms

    # check if there exists water properly
    if len(aNo_WAT_O) == 0:
        nu.die("No water molecules in the BGF file.")
    if len(aNo_CNT) == 0:
        nu.die("No CNT molecules in the BGF file.")

    # Find header of the trajectory file
    while 1:
        templine = myTRJ.readline()
        line.append(templine.strip('\n').strip('ITEM: '))
        n_header += 1
        if "ITEM: ATOMS" in templine:
            break

    # INITIAL trajectory information
    timestep = int(line[1])
    natoms = int(line[3])
    boxsize = [
        line[5].split(' ')[0], line[5].split(' ')[1], line[6].split(' ')[0],
        line[6].split(' ')[1], line[7].split(' ')[0], line[7].split(' ')[1]
    ]
    boxsize = [float(i) for i in boxsize]
    keywords = line[8].strip('ATOMS ')

    # for every shot in the trajectory file update BGF and manipulate
    dumpatom = get_line(trj_file)
    processed_step = 0

    t1 = t2 = 0
    elapsed_time = 0

    while 1:

        ### Show progress
        t1 = time.time()
        remaining_time = elapsed_time * (n_step - processed_step)
        sys.stdout.write('\r' + "Reading timestep.. " + str(timestep) +
                         " (Remaining time: " +
                         "{0:4.1f}".format(remaining_time) + " seconds, " +
                         "{0:4.1f} minutes".format(remaining_time / 60) + ")")
        sys.stdout.flush()

        if processed_step == n_step:
            break

        ### Read
        try:
            chunk = [next(dumpatom) for i in range(natoms + n_header)]
        except StopIteration:
            break

        timestep = int(chunk[1])
        natoms = int(chunk[3])
        boxsize = [
            chunk[5].split(' ')[0], chunk[5].split(' ')[1],
            chunk[6].split(' ')[0], chunk[6].split(' ')[1],
            chunk[7].split(' ')[0], chunk[7].split(' ')[1]
        ]
        boxsize = [float(i) for i in boxsize]
        boxsize = [(boxsize[1] - boxsize[0]), (boxsize[3] - boxsize[2]),
                   (boxsize[5] - boxsize[4])]
        keywords = chunk[8].split('ATOMS ')[1].strip('\n').split(' ')

        ### update myBGF with trajectory information ###
        natom_bgf = len(myBGF.a)  # number of atoms in BGF file

        if not natom_bgf == natoms:
            nu.die(
                "Number of atoms in trajectory file does not match with BGF file."
            )

        mode = 'unwrapped'  # assume that "dump            1 all custom 100 ${sname}${rtemp}K.nvt.lammps id type xu yu zu vx vy vz" in lammps input

        # actual coordinate
        coordinfo = chunk[9:]

        # modified for fast treatment
        for atomline in coordinfo:
            atomcoord = atomline.split(' ')
            atom = myBGF.getAtom(int(atomcoord[0]))

            atom.x = float(atomcoord[2])
            atom.y = float(atomcoord[3])
            atom.z = float(atomcoord[4])
            atom.vx = float(atomcoord[5])
            atom.vy = float(atomcoord[6])
            atom.vz = float(atomcoord[7])

        if myBGF.CRYSTX != []:
            for i in range(0, 3):
                myBGF.CRYSTX[i] = boxsize[i]
        else:
            nu.warn("Crystal information error: is this file not periodic?")
            for i in range(0, 3):
                myBGF.CRYSTX.append(boxsize[i])

        ### myBGF update complete! ###

        ### align CNT to z axis
        # initialize for the moment of inertia and the center of mass calculation
        U = 0
        Ut = 0
        Uv = 0
        Ixx = 0
        Ixy = 0
        Ixz = 0
        Iyx = 0
        Iyy = 0
        Iyz = 0
        Izx = 0
        Izy = 0
        Izz = 0
        Mx = 0
        My = 0
        Mz = 0

        # set COM of CNT as origin
        Mx = 0
        My = 0
        Mz = 0
        # Center of mass of CNT
        for atom in myBGF.a:
            if "NT" in atom.rName:
                Mx += atom.x / N_CNT
                My += atom.y / N_CNT
                Mz += atom.z / N_CNT

        for atom in myBGF.a:
            atom.x -= Mx  # move
            atom.y -= My
            atom.z -= Mz

        # calculate the moment of inertia (MI) and the center of mass (COM) of CNT from "myBGF"
        for aNo in aNo_CNT:
            atom = myBGF.getAtom(aNo)
            Ixx += (atom.y**2 + atom.z**2) / N_CNT
            Iyy += (atom.x**2 + atom.z**2) / N_CNT
            Izz += (atom.x**2 + atom.y**2) / N_CNT
            Ixy -= (atom.x * atom.y) / N_CNT
            Ixz -= (atom.x * atom.z) / N_CNT
            Iyz -= (atom.y * atom.z) / N_CNT

        # the moment of inertia tensor
        I = np.array([[Ixx, Ixy, Ixz], [Ixy, Iyy, Iyz], [Ixz, Iyz, Izz]])

        # eigenvalue & eigenvector calculation
        eigval, eigvec = np.linalg.eig(
            I)  # eigval[0] is the minimum among the values.

        # rearrange the U vector
        U = np.matrix(eigvec)
        Ut = U.T

        # "myBGF" rotation
        for atom in myBGF.a:
            v = np.matrix([atom.x, atom.y, atom.z]).T
            Uv = Ut * v
            atom.x = float(Uv[2])
            atom.y = float(Uv[1])
            atom.z = float(Uv[0])
        #dimension = np.matrix(boxsize).T
        #boxsize_prime = np.array(np.dot(Ut, dimension).T)
        boxsize_prime = np.transpose(
            np.dot(Ut,
                   np.transpose(np.array(boxsize))))  # new pbc from jackjack5
        print(boxsize)
        print(boxsize_prime)

        # move atoms to box center
        for atom in myBGF.a:
            atom.x -= boxsize_prime[0] / 2
            atom.y -= boxsize_prime[1] / 2
            atom.z -= boxsize_prime[2] / 2

        myBGF.saveBGF(temp_dir + bgf_file.split(".bgf")[0] + "." +
                      str(timestep) + ".beforepbc.bgf")
        myBGF = bgftools.periodicMoleculeSort(myBGF, 0, myBGF.CRYSTX)
        myBGF.saveBGF(temp_dir + bgf_file.split(".bgf")[0] + "." +
                      str(timestep) + ".bgf")

        # for CNT atoms, calculate some properties
        min_x_CNT = 1000.0
        max_x_CNT = -1000.0
        radius_CNT = 0.0
        height_CNT = 0.0
        min_y_CNT = 1000.0
        max_y_CNT = -1000.0
        min_z_CNT = 1000.0
        max_z_CNT = -1000.0

        l_radius_CNT = []
        l_x_CNT = []
        l_y_CNT = []
        for aNo in aNo_CNT:
            atom = myBGF.getAtom(aNo)

            # center of CNT
            l_x_CNT.append(atom.x)
            l_y_CNT.append(atom.y)

            # height
            if atom.z < min_z_CNT:
                min_z_CNT = atom.z
            if atom.z > max_z_CNT:
                max_z_CNT = atom.z

        x_CNT, a = nu.meanstdv(l_x_CNT)
        y_CNT, a = nu.meanstdv(l_y_CNT)
        z_diff = max_z_CNT - min_z_CNT
        height_CNT = z_diff

        # radius of CNT
        for aNo in aNo_CNT:
            atom = myBGF.getAtom(aNo)
            l_radius_CNT.append(
                math.sqrt((atom.x - x_CNT)**2 + (atom.y - y_CNT)**2))

        radius_CNT, a = nu.meanstdv(l_radius_CNT)
        l_avg_radius_CNT.append(radius_CNT)

        ### get water molecules in CNT

        # inside the CNT := min_z_CNT <= z <= max_z_CNT and (x - (x_diff/2))**2 + (y - (y_diff/2))**2 < radius_CNT**2
        # aNo_WAT_O_atoms: molecules which O atom is within CNT
        # we don't need to calculate H atoms. Let's consider only O atoms
        margin = 0.0
        # water molecules far from the margin will be only considered
        aNo_WAT_O_in_CNT = []
        for aNo in aNo_WAT_O:
            atom = myBGF.getAtom(aNo)
            dist_sq = (atom.x - x_CNT)**2 + (atom.y - y_CNT)**2
            if "WAT" in atom.rName and "O" in atom.ffType and min_z_CNT + margin <= atom.z and atom.z <= max_z_CNT - margin and dist_sq < radius_CNT**2:
                aNo_WAT_O_in_CNT.append(aNo)
            else:
                pass

        ### record number of water molecules in CNT
        #l_data.append([timestep, len(aNo_WAT_O_in_CNT), radius_CNT, z_diff])

        #output = str(timestep) + '\t' + str(len(aNo_WAT_O_in_CNT)) + '\t' + str(radius_CNT) + '\t' + str(z_diff) + '\n'
        output = str(timestep) + '\t' + str(
            len(aNo_WAT_O_in_CNT)) + '\t' + str(radius_CNT) + '\t' + str(
                min_z_CNT) + '\t' + str(max_z_CNT) + '\t' + str(
                    z_diff) + '\t' + str(height_CNT) + '\t' + str(
                        len(aNo_CNT)) + '\n'  # debug
        ftemp.write(output)

        #sys.stdout.write('Done                                                        ')
        sys.stdout.flush()

        t2 = time.time()  # time mark
        elapsed_time = t2 - t1
        processed_step += 1

    print('')
    ftemp.close()
    print(
        "numbers of water molecules are written in countWater.profile ..Done.")

    return 1
Exemple #4
0
def getVelocity(bgf_file, trj_file, n_step, silent=False):

    # const
    PI = math.pi
    vdw_r_C = 1.7

    # init
    timestep = 0
    l_timestep = []
    line = []
    n_header = 0
    t1 = 0
    t2 = 0
    # clock

    l_data = []
    # stores vz
    l_avg_radius_CNT = []

    myBGF = bgf.BgfFile(bgf_file)
    myTRJ = open(trj_file)
    myTRJ.seek(0)

    # how many steps to go?
    n_timestep = len(lt.getTrjInfo(trj_file))
    if n_step == 0:
        n_step = n_timestep

    print("The trajectory contains " + str(n_timestep) + " timesteps.")
    print("The script will proceed for the last " + str(n_step) +
          " timesteps.")

    # extract aNos of CNT in the BGF file
    aNo_CNT = []
    aNo_WAT_O = []
    aNo_WAT_all = []

    for atom in myBGF.a:
        # Carbons in CNT
        if "CNT" in atom.rName:
            aNo_CNT.append(atom.aNo)

        # Oxygen in water
        if "WAT" in atom.rName and "O" in atom.aName:
            aNo_WAT_O.append(atom.aNo)

    N_CNT = len(aNo_CNT)  # the number of CNT atoms

    # check if there exists water properly
    if len(aNo_WAT_O) == 0:
        nu.die("No water molecules in the BGF file.")
    if len(aNo_CNT) == 0:
        nu.die("No CNT molecules in the BGF file.")

    # Find header of the trajectory file
    while 1:
        templine = myTRJ.readline()
        line.append(templine.strip('\n').strip('ITEM: '))
        n_header += 1
        if "ITEM: ATOMS" in templine:
            break

    # INITIAL trajectory information
    timestep = int(line[1])
    natoms = int(line[3])
    boxsize = [
        line[5].split(' ')[0], line[5].split(' ')[1], line[6].split(' ')[0],
        line[6].split(' ')[1], line[7].split(' ')[0], line[7].split(' ')[1]
    ]
    boxsize = [float(i) for i in boxsize]
    keywords = line[8].strip('ATOMS ')

    # for every shot in the trajectory file update BGF and manipulate
    dumpatom = get_line(trj_file)
    processed_step = 0

    t1 = t2 = 0
    elapsed_time = 0

    while 1:
        ### Show progress
        t1 = time.time()
        remaining_time = elapsed_time * (n_step - processed_step)
        sys.stdout.write('\r' + "Reading timestep.. " + str(timestep) +
                         " (Remaining time: " +
                         "{0:4.1f}".format(remaining_time) + " seconds, " +
                         "{0:4.1f} minutes".format(remaining_time / 60) + ")")
        sys.stdout.flush()

        if processed_step == n_step:
            break

        ### Read
        try:
            chunk = [next(dumpatom) for i in range(natoms + n_header)]
        except StopIteration:
            break

        timestep = int(chunk[1])
        natoms = int(chunk[3])
        boxsize = [
            chunk[5].split(' ')[0], chunk[5].split(' ')[1],
            chunk[6].split(' ')[0], chunk[6].split(' ')[1],
            chunk[7].split(' ')[0], chunk[7].split(' ')[1]
        ]
        boxsize = [float(i) for i in boxsize]
        boxsize = [(boxsize[1] - boxsize[0]), (boxsize[3] - boxsize[2]),
                   (boxsize[5] - boxsize[4])]
        keywords = chunk[8].split('ATOMS ')[1].strip('\n').split(' ')

        ### update myBGF with trajectory information ###
        natom_bgf = len(myBGF.a)  # number of atoms in BGF file

        if not natom_bgf == natoms:
            nu.die(
                "Number of atoms in trajectory file does not match with BGF file."
            )

        mode = 'unwrapped'  # assume that "dump            1 all custom 100 ${sname}${rtemp}K.nvt.lammps id type xu yu zu vx vy vz" in lammps input

        # actual coordinate
        coordinfo = chunk[9:]

        del (chunk)

        # modified for fast treatment
        for atomline in coordinfo:
            atomcoord = atomline.split(' ')
            atom = myBGF.getAtom(int(atomcoord[0]))

            atom.x = float(atomcoord[2])
            atom.y = float(atomcoord[3])
            atom.z = float(atomcoord[4])
            atom.vx = float(atomcoord[5])
            atom.vy = float(atomcoord[6])
            atom.vz = float(atomcoord[7])

            try:
                for i in range(0, 3):
                    myBGF.CRYSTX[i] = boxsize[i]
            except:
                pass
                #nu.warn("Crystal information error: is this file not periodic?")

        # apply periodic condition
        myBGF = bgftools.periodicMoleculeSort(myBGF, 0, True)

        ### myBGF update complete! ###

        #aNo_WAT_O_in_CNT = copy.deepcopy(aNo_WAT_O)

        # for CNT atoms, calculate some properties
        min_x_CNT = 1000.0
        max_x_CNT = -1000.0
        radius_CNT = 0.0
        height_CNT = 0.0
        temp = []
        min_y_CNT = 1000.0
        max_y_CNT = -1000.0
        min_z_CNT = 1000.0
        max_z_CNT = -1000.0
        CNT_orientation = ""

        l_radius_CNT = []
        l_x_CNT = []
        l_y_CNT = []
        for aNo in aNo_CNT:
            atom = myBGF.getAtom(aNo)

            # center of CNT
            l_x_CNT.append(atom.x)
            l_y_CNT.append(atom.y)

            # height
            if atom.z < min_z_CNT:
                min_z_CNT = atom.z
            if atom.z > max_z_CNT:
                max_z_CNT = atom.z

        x_CNT, a = nu.meanstdv(l_x_CNT)
        y_CNT, a = nu.meanstdv(l_y_CNT)
        z_diff = max_z_CNT - min_z_CNT

        # radius of CNT
        for aNo in aNo_CNT:
            atom = myBGF.getAtom(aNo)
            l_radius_CNT.append(
                math.sqrt((atom.x - x_CNT)**2 + (atom.y - y_CNT)**2))

        radius_CNT, a = nu.meanstdv(l_radius_CNT)
        l_avg_radius_CNT.append(radius_CNT)

        ### get water molecules in CNT

        # inside the CNT := min_z_CNT <= z <= max_z_CNT and (x - (x_diff/2))**2 + (y - (y_diff/2))**2 < radius_CNT**2
        # aNo_WAT_O_atoms: molecules which O atom is within CNT
        # we don't need to calculate H atoms. Let's consider only O atoms
        margin = 0.0
        # water molecules far from the margin will be only considered
        aNo_WAT_O_in_CNT = []
        for aNo in aNo_WAT_O:
            atom = myBGF.getAtom(aNo)
            dist_sq = (atom.x - x_CNT)**2 + (atom.y - y_CNT)**2
            if "WAT" in atom.rName and "O" in atom.ffType and min_z_CNT + margin <= atom.z and atom.z <= max_z_CNT - margin and dist_sq < radius_CNT**2:
                aNo_WAT_O_in_CNT.append(aNo)
            else:
                pass

        ### record number of water molecules in CNT
        l_data.append([timestep, len(aNo_WAT_O_in_CNT), radius_CNT, z_diff])

        #sys.stdout.write('Done                                                        ')
        #sys.stdout.flush()

        t2 = time.time()  # time mark
        elapsed_time = t2 - t1
        processed_step += 1

    print('')

    ftemp = open("countWater.profile", 'w')
    ftemp.write(str(sys.argv))
    for i in l_data:
        output = str(i[0]) + '\t' + str(i[1]) + '\t' + str(i[2]) + '\t' + str(
            i[3]) + '\n'
        ftemp.write(output)
    ftemp.close()
    print(
        "numbers of water molecules are written in countWater.profile ..Done.")

    return 1
Exemple #5
0
def main():
    filename = forceFile
    v = read_value(filename)
    nv = len(v)
    t = numpy.arange(0, nv - 1, step)
    result = []
    result2 = []
    output = ""

    ### calculate constants
    reff = R - 0.5 * sOC
    A = 2 * pi * reff * L
    A *= 1e-20
    C = 1 / kb / T / A

    output += "Version " + str(version) + "\n"
    output += "Parameters\n"
    output += "R" + '\t' + str(R) + '\t' + \
     "r_eff" + '\t' + str(reff) + '\t' + \
     "area" + '\t' + str(A) + '\t' + \
     "coeff" + '\t' + str(C) + '\n'

    output += str("t") + '\t' + str("int fac") + '\t' + str("l") + '\t' + str(
        "b") + '\n'

    ### calculate AC
    print("Reading force file and calculating autocorrelation function..")
    print(str(t))
    for i in t:
        if i + averageStep <= nv:
            temp_v = v[i:i + averageStep]
            temp_acs = ac(temp_v)
            result.append(temp_acs)

    ### test for vac
    for index, i in enumerate(result):
        print "** timestep ", t[index]
        a = scipy.integrate.cumtrapz(i, dx=2e-15)  # integration
        a2, _ = nu.meanstdv(a[averageACStep:])
        a2 *= (6.95e-11)**2  # kcal/mol.m -> J/m

        print "\t- integrated force AC=", a2
        l = C * a2
        print "\t- lambda=", l
        b = u / l
        print "\t- slip length (m)=", b
        b *= 1e9
        print "\t- slip length (nm)=", b
        result2.append(b)

        output += str(
            t[index]) + '\t' + str(a2) + '\t' + str(l) + '\t' + str(b) + '\n'

    ### write output file
    fname = outFilePrefix + ".a." + str(averageStep) + ".s." + str(
        sampleStep) + ".n." + str(step) + ".t." + str(averageACStep)
    f_out = open(fname + ".out", 'w')
    f_out.write(str(sys.argv) + "\n")
    f_out.write(output)
    f_out.close()

    ### print averaged slip length
    m, _ = nu.meanstdv(result2)
    print "averaged slip length=", m, _

    ### write dump file
    f_dump = open(fname + ".dump", 'w')
    output = "\t"
    # timesteps
    for i in t:
        output += str(i) + "\t"
    output += "\n"
    # result
    for r, row in enumerate(result[0]):
        output += str(r) + "\t"
        for c, col in enumerate(result):
            output += str(result[c][r]) + "\t"
        output += "\n"
    f_dump.write(output)
    f_dump.close()

    return 1
Exemple #6
0
def getVelocity(bgf_file, trj_file, n_step, silent=False):

	# const
	PI = math.pi
	vdw_r_C = 1.7

	# init
	timestep = 0; l_timestep = []; line = []; n_header = 0;
	t1 = 0; t2 = 0; # clock
	interval = 0.1;

	l_data = [];	# stores vz
	l_avg_radius_CNT = [];

	myBGF = bgf.BgfFile(bgf_file)
	myTRJ = open(trj_file)
	myTRJ.seek(0)

	# how many steps to go?
	wc_trj_file = popen("grep TIMESTEP " + trj_file + " | wc -l ").read()
	n_timestep = int(wc_trj_file.split()[0]);

	print("The trajectory contains " + str(n_timestep) + " timesteps.")

	# extract aNos of CNT in the BGF file
	aNo_CNT = []
	aNo_WAT_O = []
	aNo_WAT_all = []

	for atom in myBGF.a:
		# Carbons in CNT
		if "CNT" in atom.rName:
			aNo_CNT.append(atom.aNo)

		# Oxygen in water
		if "WAT" in atom.rName and "O" in atom.aName:
			aNo_WAT_O.append(atom.aNo)

	N_CNT = len(aNo_CNT)	# the number of CNT atoms

	# check if there exists water properly
	if len(aNo_WAT_O) == 0:
		nu.die("No water molecules in the BGF file.")
	if len(aNo_CNT) == 0:
		nu.die("No CNT molecules in the BGF file.")

	# Find header of the trajectory file
	while 1:
		templine = myTRJ.readline()
		line.append(templine.strip('\n').strip('ITEM: '))
		n_header += 1
		if "ITEM: ATOMS" in templine:
			break;

	# INITIAL trajectory information
	timestep = int(line[1])
	natoms = int(line[3])
	boxsize = [line[5].split(' ')[0], line[5].split(' ')[1], line[6].split(' ')[0], line[6].split(' ')[1], line[7].split(' ')[0], line[7].split(' ')[1]]
	boxsize = [float(i) for i in boxsize]
	keywords = line[8].strip('ATOMS ')

	# for every shot in the trajectory file update BGF and manipulate
	dumpatom = get_line(trj_file)
	processed_step = 0;

	t1 = t2 = 0; elapsed_time = 0;

	while 1:
		### Show progress
		sys.stdout.write('\r' + "Reading timestep.. " + str(timestep) )
		sys.stdout.flush()

		### Read
		try:
			chunk = [next(dumpatom) for i in range(natoms+n_header)]
		except StopIteration:
			break;

		timestep = int(chunk[1])
		natoms = int(chunk[3])
		boxsize = [chunk[5].split(' ')[0], chunk[5].split(' ')[1], chunk[6].split(' ')[0], chunk[6].split(' ')[1], chunk[7].split(' ')[0], chunk[7].split(' ')[1]]; 
		boxsize = [float(i) for i in boxsize]; boxsize = [(boxsize[1] - boxsize[0]), (boxsize[3] - boxsize[2]), (boxsize[5] - boxsize[4])]
		keywords = chunk[8].split('ATOMS ')[1].strip('\n').split(' ')

		if timestep != n_step:
			continue;

		### update myBGF with trajectory information ###
		natom_bgf = len(myBGF.a)	# number of atoms in BGF file
	
		if not natom_bgf == natoms:
			nu.die("Number of atoms in trajectory file does not match with BGF file.")
	
		mode = 'unwrapped'	# assume that "dump            1 all custom 100 ${sname}${rtemp}K.nvt.lammps id type xu yu zu vx vy vz" in lammps input
	
		# actual coordinate
		coordinfo = chunk[9:]
	
		# modified for fast treatment
		for atomline in coordinfo:
			atomcoord = atomline.split(' ')
			atom = myBGF.getAtom(int(atomcoord[0]))
	
			atom.x = float(atomcoord[2])
			atom.y = float(atomcoord[3])
			atom.z = float(atomcoord[4])
			atom.vx = float(atomcoord[5])
			atom.vy = float(atomcoord[6])
			atom.vz = float(atomcoord[7])

			try:
				for i in range(0, 3):
					myBGF.CRYSTX[i] = boxsize[i]
			except:
				pass;
				#nu.warn("Crystal information error: is this file not periodic?")
				
		# apply periodic condition
		myBGF = bgftools.periodicMoleculeSort(myBGF, 0, True)

		### myBGF update complete! ###

		#aNo_WAT_O_in_CNT = copy.deepcopy(aNo_WAT_O)


		### align CNT to z axis
		# initialize for the moment of inertia and the center of mass calculation
		U = 0; Ut = 0; Uv = 0;
		Ixx = 0; Ixy = 0; Ixz = 0;
		Iyx = 0; Iyy = 0; Iyz = 0;
		Izx = 0; Izy = 0; Izz = 0;
		Mx = 0; My = 0; Mz = 0;

		# transpose for "all atoms in BGF": move COM of CNT as origin
		# com of CNT
		Mx = 0; My = 0; Mz = 0;
		for atom in myBGF.a:
			if "CNT" in atom.rName:
				Mx += atom.x / N_CNT
				My += atom.y / N_CNT
				Mz += atom.z / N_CNT

		# move
		for atom in myBGF.a:
			atom.x -= Mx
			atom.y -= My
			atom.z -= Mz

		# calculate the moment of inertia (MI) and the center of mass (COM) of CNT from "myBGF"
		for aNo in aNo_CNT:
			atom = myBGF.getAtom(aNo)
			Ixx += (atom.y**2 + atom.z**2) / N_CNT
			Iyy += (atom.x**2 + atom.z**2) / N_CNT
			Izz += (atom.x**2 + atom.y**2) / N_CNT
			Ixy -= (atom.x * atom.y) / N_CNT
			Ixz -= (atom.x * atom.z) / N_CNT
			Iyz -= (atom.y * atom.z) / N_CNT
			
		# the moment of inertia tensor
		I = np.array([[Ixx, Ixy, Ixz], [Ixy, Iyy, Iyz], [Ixz, Iyz, Izz]])

		# eigenvalue & eigenvector calculation
		eigval, eigvec = np.linalg.eig(I)	# eigval[0] is the minimum among the values.
	
		# rearrange the U vector
		U = np.matrix(eigvec)
		Ut = U.T

		# "myBGF" rotation
		for atom in myBGF.a:
			v = np.matrix([atom.x, atom.y, atom.z]).T
			Uv = Ut * v
			atom.x = float(Uv[1])
			atom.y = float(Uv[2])
			atom.z = float(Uv[0])


		# for CNT atoms, calculate some properties
		min_x_CNT = 1000.0; max_x_CNT = -1000.0; radius_CNT = 0.0; height_CNT = 0.0; temp = [];
		min_y_CNT = 1000.0; max_y_CNT = -1000.0;
		min_z_CNT = 1000.0; max_z_CNT = -1000.0;
		CNT_orientation = "";

		l_radius_CNT = [];
		l_x_CNT = [];
		l_y_CNT = [];
		for aNo in aNo_CNT:
			atom = myBGF.getAtom(aNo)

			# center of CNT
			l_x_CNT.append(atom.x)
			l_y_CNT.append(atom.y)

			# height
			if atom.z < min_z_CNT:
				min_z_CNT = atom.z
			if atom.z > max_z_CNT:
				max_z_CNT = atom.z
	
		x_CNT, a = nu.meanstdv(l_x_CNT)
		y_CNT, a = nu.meanstdv(l_y_CNT)
		z_diff = max_z_CNT - min_z_CNT

		# radius of CNT
		for aNo in aNo_CNT:
			atom = myBGF.getAtom(aNo)
			l_radius_CNT.append( math.sqrt( (atom.x - x_CNT)**2 + (atom.y - y_CNT)**2 ))

		radius_CNT, a = nu.meanstdv(l_radius_CNT)
		l_avg_radius_CNT.append(radius_CNT)


		### get water molecules in CNT

		# inside the CNT := min_z_CNT <= z <= max_z_CNT and (x - (x_diff/2))**2 + (y - (y_diff/2))**2 < radius_CNT**2
		# aNo_WAT_O_atoms: molecules which O atom is within CNT
		# we don't need to calculate H atoms. Let's consider only O atoms
		margin = 0.0;	# water molecules far from the margin will be only considered
		aNo_WAT_O_in_CNT = []
		aNo_WAT_O_not_in_CNT = []
		myBGF2 = copy.deepcopy(myBGF)

		# delete graphenes
		for atom in myBGF2.a:
			if "GRA" in atom.rName:
				aNo_WAT_O_not_in_CNT.append(myBGF.a2i[atom.aNo])

		# delete water molecules
		for aNo in aNo_WAT_O:
			atom = myBGF.getAtom(aNo)
			dist_sq = (atom.x - x_CNT)**2 + (atom.y - y_CNT)**2
			if "WAT" in atom.rName and "O" in atom.ffType and min_z_CNT + margin <= atom.z and atom.z <= max_z_CNT - margin and dist_sq < radius_CNT**2:
				aNo_WAT_O_in_CNT.append(aNo)
			else:
				delete_list = [];
				dummy = bgftools.getmolecule(myBGF, myBGF.getAtom(aNo), delete_list)
				for i in delete_list:
					aNo_WAT_O_not_in_CNT.append(myBGF.a2i[i])

		myBGF2.delAtoms(aNo_WAT_O_not_in_CNT)
		myBGF2.renumber()
		myBGF2.saveBGF(bgf_file[:-4] + "." + str(timestep) + "." + str(len(aNo_WAT_O_in_CNT)) + ".bgf")

		sys.stdout.write('Done                                                        ')
		sys.stdout.flush()

		print(len(aNo_WAT_O_in_CNT))

		processed_step += 1;


	print('')

	return 1
Exemple #7
0
def main():
    usage = """This script averages the data which has rows in 'step number', usually from LAMMPS profile.
	Usage: reduceText.py input output Nevery Nrepeat Nfreq
	With (Nevery, Nrepeat, Nfreq) == (2, 6, 100), the following will be averaged:
		[90, 92, 94, 96, 98, 100] --> 100
		[190, 192, 194, 196, 198, 200] --> 200
		...
	"""
    if len(sys.argv) < 2:
        print("Usage: " + str(sys.argv[0]) +
              " input output Nevery Nrepeat Nfreq")
        sys.exit(0)

    infile = sys.argv[1]
    outfile = sys.argv[2]
    n_every = int(sys.argv[3])
    n_repeat = int(sys.argv[4])
    n_freq = int(sys.argv[5])

    ifs = open(infile)
    ofs = open(outfile, 'w')

    n_count = 0
    # main counter
    output = ""
    temp = []

    while 1:

        line = ifs.readline()
        if not line:
            break

        if line[0] == "#":
            continue

        parse = line.split()
        step = int(parse[0])
        value = float(parse[1])

        n_count += 1

        if n_count <= n_freq:
            #temp.append(step);	#test
            temp.append(value)
        else:
            #temp.append(step);	#test
            #print(temp)		#test
            #print(temp[::n_every][-n_repeat:])	#test
            temp.append(value)
            m, _ = nu.meanstdv(temp[::n_every][-n_repeat:])  # average
            if _ != 0.0:
                output += str(parse[0]) + '\t' + str(m) + '\t' + str(_) + '\n'
            else:
                output += str(parse[0]) + '\t' + str(m) + '\n'

            # initialize
            temp = [0]
            n_count = 1

    ofs.write(output)
    print("File is written in " + outfile + " ...")
def countWaterCNT(bgf_file, trj_file, fixed, silent):

	# init
	timestep = 0; l_timestep = []; line = []; n_header = 0; output = ""; radius_CNTs = [];
	t1 = 0; t2 = 0; # clock
	radius_CNT = 0.0; 

	myBGF = bgf.BgfFile(bgf_file)
	myTRJ = open(trj_file)
	myTRJ.seek(0)

	# how many steps to go?
	#wc_trj_file = popen("grep TIMESTEP " + trj_file + " | wc -l ").read()
	#n_timestep = int(wc_trj_file.split()[0]);
	n_timestep = len(lt.getTrjInfo(trj_file))
	print("The trajectory contains " + str(n_timestep) + " timesteps.")

	# extract aNos of CNT in the BGF file
	aNo_CNT = []
	for atom in myBGF.a:
		# Carbons in CNT
		if "CNT" in atom.rName:
			aNo_CNT.append(atom.aNo)

	N_CNT = len(aNo_CNT)	# the number of CNT atoms

	# Find header of the trajectory file
	while 1:
		templine = myTRJ.readline()
		line.append(templine.strip('\n').strip('ITEM: '))
		n_header += 1
		if "ITEM: ATOMS" in templine:
			break;

	# INITIAL trajectory information
	timestep = int(line[1])
	natoms = int(line[3])
	boxsize = [line[5].split(' ')[0], line[5].split(' ')[1], line[6].split(' ')[0], line[6].split(' ')[1], line[7].split(' ')[0], line[7].split(' ')[1]]
	boxsize = [float(i) for i in boxsize]
	keywords = line[8].strip('ATOMS ')

	# for every shot in the trajectory file update BGF and manipulate
	dumpatom = get_line(trj_file)
	processed_step = 0;

	t1 = t2 = 0; elapsed_time = 0;

	while 1:
		try:
			chunk = [next(dumpatom) for i in range(natoms+n_header)]
		except StopIteration:
			break;
	
		timestep = int(chunk[1])
		natoms = int(chunk[3])
		boxsize = [chunk[5].split(' ')[0], chunk[5].split(' ')[1], chunk[6].split(' ')[0], chunk[6].split(' ')[1], chunk[7].split(' ')[0], chunk[7].split(' ')[1]]; 
		boxsize = [float(i) for i in boxsize]; boxsize = [(boxsize[1] - boxsize[0]), (boxsize[3] - boxsize[2]), (boxsize[5] - boxsize[4])]
		keywords = chunk[8].split('ATOMS ')[1].strip('\n').split(' ')

		### Show progress
		t1 = time.time();
		remaining_time = elapsed_time * (n_timestep - processed_step)
		sys.stdout.write('\r' + "Reading timestep.. " + str(timestep) + " (Elapsed time for the previous step: " + "{0:4.1f}".format(elapsed_time) + " seconds, Remaining time: " + "{0:4.1f}".format(remaining_time) + " seconds = " + "{0:4.1f} minutes".format(remaining_time/60) + ") " + str(radius_CNT))
		sys.stdout.flush()

		processed_step += 1;

		### if step is specified, then save only for that step.
		if step != 0:
			if timestep == step:
				pass;
			else:
				continue;
		else:
			pass;

		### update myBGF with trajectory information ###
		natom_bgf = len(myBGF.a)	# number of atoms in BGF file
	
		if not natom_bgf == natoms:
			nu.die("Number of atoms in trajectory file does not match with BGF file.")
	
		mode = ""
		if 'xs' in keywords or 'ys' in keywords or 'zs' in keywords:
			mode = 'scaled'
		elif 'x' in keywords or 'y' in keywords or 'z' in keywords:
			mode = 'normal'
		elif 'xu' in keywords or 'yu' in keywords or 'zu' in keywords:
			mode = 'unwrapped'
	
		# actual coordinate
		coordinfo = chunk[9:]
	
		# assume that coordinfo is similar to ['id', 'type', 'xs', 'ys', 'zs', 'ix', 'iy', 'iz']
		for atomline in coordinfo:
			atomcoord = atomline.split(' ')
			atom = myBGF.getAtom(int(atomcoord[0]))
	
			if mode == 'scaled':
				atom.x = float(atomcoord[2]) * boxsize[0]
				atom.y = float(atomcoord[3]) * boxsize[1]
				atom.z = float(atomcoord[4]) * boxsize[2]
	
			elif mode == 'unwrapped':
				atom.x = float(atomcoord[2])
				atom.y = float(atomcoord[3])
				atom.z = float(atomcoord[4])
	
			elif mode == 'normal':
				try:
					ix_index = keywords.index('ix')
					iy_index = keywords.index('iy')
					iz_index = keywords.index('iz')
				except ValueError:
					nu.warn("No image information no the trajectory file. Will be treated as unwrapped.")
					atom.x = float(atomcoord[2])
					atom.y = float(atomcoord[3])
					atom.z = float(atomcoord[4])
				else:
					atom.x = (int(atomcoord[ix_index]) * boxsize[0]) + float(atomcoord[2]) 
					atom.y = (int(atomcoord[iy_index]) * boxsize[1]) + float(atomcoord[3]) 
					atom.z = (int(atomcoord[iz_index]) * boxsize[2]) + float(atomcoord[4]) 
	
			try:
				for i in range(0, 3):
					myBGF.CRYSTX[i] = boxsize[i]
			except:
				pass;
				#nu.warn("Crystal information error: is this file not periodic?")
				
		# apply periodic condition
		myBGF = bgftools.periodicMoleculeSort(myBGF, 0)

		#myBGF.saveBGF(bgf_file[:-4] + "." + str(timestep) + ".trjupdated.bgf")
		### myBGF update complete! ###

		if not fixed:
			### rotate cnt to x axis
			# initialize for the moment of inertia and the center of mass calculation
			U = 0; Ut = 0; Uv = 0;
			Ixx = 0; Ixy = 0; Ixz = 0;
			Iyx = 0; Iyy = 0; Iyz = 0;
			Izx = 0; Izy = 0; Izz = 0;
			Mx = 0; My = 0; Mz = 0;

			# transpose for "all atoms in BGF": move COM of CNT as origin
			# com of CNT
			Mx = 0; My = 0; Mz = 0;
			for atom in myBGF.a:
				if "CNT" in atom.rName:
					Mx += atom.x / N_CNT
					My += atom.y / N_CNT
					Mz += atom.z / N_CNT

			# move
			for atom in myBGF.a:
				atom.x -= Mx
				atom.y -= My
				atom.z -= Mz

			# calculate the moment of inertia (MI) and the center of mass (COM) of CNT from "myBGF"
			for aNo in aNo_CNT:
				atom = myBGF.getAtom(aNo)
				Ixx += (atom.y**2 + atom.z**2) / N_CNT
				Iyy += (atom.x**2 + atom.z**2) / N_CNT
				Izz += (atom.x**2 + atom.y**2) / N_CNT
				Ixy -= (atom.x * atom.y) / N_CNT
				Ixz -= (atom.x * atom.z) / N_CNT
				Iyz -= (atom.y * atom.z) / N_CNT
				
			# the moment of inertia tensor
			I = numpy.array([[Ixx, Ixy, Ixz], [Ixy, Iyy, Iyz], [Ixz, Iyz, Izz]])

			# eigenvalue & eigenvector calculation
			eigval, eigvec = numpy.linalg.eig(I)	# eigval[0] is the minimum among the values.
		
			# rearrange the U vector
			U = numpy.matrix(eigvec)
			Ut = U.T

			# "myBGF" rotation
			for atom in myBGF.a:
				v = numpy.matrix([atom.x, atom.y, atom.z]).T
				Uv = Ut * v
				atom.x = float(Uv[0])
				atom.y = float(Uv[1])
				atom.z = float(Uv[2])


		# for CNT atoms, calculate some properties
		min_x_CNT = 0.0; max_x_CNT = 0.0; height_CNT = 0.0; aNo_MtOH_C_not_in_CNT = []; temp = [];
		min_y_CNT = 0.0; max_y_CNT = 0.0;
		min_z_CNT = 0.0; max_z_CNT = 0.0;
		CNT_orientation = "";

		# check the orientation of CNT
		for aNo in aNo_CNT:
			atom = myBGF.getAtom(aNo)
			# minimum and maximum x coord of CNT: this will be the height of CNT
			if atom.x < min_x_CNT:
				min_x_CNT = atom.x
			if atom.x > max_x_CNT:
				max_x_CNT = atom.x
			if atom.y < min_y_CNT:
				min_y_CNT = atom.y
			if atom.y > max_y_CNT:
				max_y_CNT = atom.y
			if atom.z < min_z_CNT:
				min_z_CNT = atom.z
			if atom.z > max_z_CNT:
				max_z_CNT = atom.z
	
		x_diff = max_x_CNT - min_x_CNT
		y_diff = max_y_CNT - min_y_CNT
		z_diff = max_z_CNT - min_z_CNT

		if x_diff > y_diff and x_diff > z_diff:
			# CNT is aligned along x axis
			height_CNT = x_diff
			CNT_orientation = "x"
		elif y_diff > x_diff and y_diff > z_diff:
			# CNT is aligned along y axis
			height_CNT = y_diff
			CNT_orientation = "y"
		elif z_diff > x_diff and z_diff > y_diff:
			# CNT is aligned along z axis
			height_CNT = z_diff
			CNT_orientation = "z"

		if CNT_orientation == "x":
			for aNo in aNo_CNT:
				atom = myBGF.getAtom(aNo)
				radius_CNT += math.sqrt(atom.y**2 + atom.z**2)	# average radius of CNT
		elif CNT_orientation == "y":
			for aNo in aNo_CNT:
				atom = myBGF.getAtom(aNo)
				radius_CNT += math.sqrt(atom.x**2 + atom.z**2)	# average radius of CNT
		elif CNT_orientation == "z":
			for aNo in aNo_CNT:
				atom = myBGF.getAtom(aNo)
				radius_CNT += math.sqrt(atom.x**2 + atom.y**2)	# average radius of CNT

		radius_CNT = radius_CNT / N_CNT
		radius_CNTs.append(radius_CNT)

		output += str(timestep) + '\t' + str(radius_CNT) + '\n'
		#if not silent: print(str(timestep) + '\t' + str(radius_CNT) + '\n')
		# write output
		#myBGF.saveBGF(bgf_file[:-4] + "." + str(timestep) + ".bgf")
		#myBGF2.saveBGF(bgf_file[:-4] + "." + str(timestep) + ".bgf")

		t2 = time.time()	# time mark
		elapsed_time = t2 - t1;

	#print(output)
	m, s = nu.meanstdv(radius_CNTs)
	output += "average: " + '\t' + str(m) + '\t' + str(s) + '\n'
	print('')
	print(output)
	return 1
def getSlipLength(bgf_file,
                  trj_file,
                  ff_file,
                  n_step,
                  n_avg_step,
                  silent=False):

    # const
    PI = math.pi
    vdw_r_C = 1.7

    # init
    timestep = 0
    l_timestep = []
    line = []
    n_header = 0
    t1 = 0
    t2 = 0
    # clock

    l_data = []
    # stores [r vz]
    l_F_N = []
    l_F_N_inner = []
    l_F_N_outer = []
    # stores sum of friction force
    l_result = []
    l_avg_radius_CNT = []

    n_avg_count = 0
    n_avg_count_step = 0

    myBGF = bgf.BgfFile(bgf_file)
    myTRJ = open(trj_file)
    myTRJ.seek(0)
    myPkl = open(trj_file + ".method2.pickle", 'w')
    myOut = open(trj_file + ".method2.avg_vz.out", 'w')
    myOut.write(str(n_avg_step) + " steps are averaged.\n")
    myOut.write("AVG_STARTING_STEP\tAVG_vz\tF_N\tF_N_outer\tF_N_inner\n")

    # how many steps to go?
    if not silent: print("== Step 1. Loading LAMMPS Trajectory")
    wc_trj_file = popen("grep TIMESTEP " + trj_file + " | wc -l ").read()
    n_timestep = int(wc_trj_file.split()[0])
    if n_step == 0:
        n_step = n_timestep

    print("The trajectory contains " + str(n_timestep) + " timesteps.")

    # extract aNos of CNT in the BGF file
    aNo_CNT = []
    aNo_WAT_O = []

    for atom in myBGF.a:
        # Carbons in CNT
        if "CNT" in atom.rName:
            aNo_CNT.append(atom.aNo)

        # Oxygen in water
        if "WAT" in atom.rName and "O" in atom.aName:
            aNo_WAT_O.append(atom.aNo)

    N_CNT = len(aNo_CNT)  # the number of CNT atoms

    # check if there exists water properly
    if len(aNo_WAT_O) == 0:
        nu.die("No water molecules in the BGF file.")
    if len(aNo_CNT) == 0:
        nu.die("No CNT molecules in the BGF file.")

    # Find header of the trajectory file
    while 1:
        templine = myTRJ.readline()
        line.append(templine.strip('\n').strip('ITEM: '))
        n_header += 1
        if "ITEM: ATOMS" in templine:
            break

    # INITIAL trajectory information
    timestep = int(line[1])
    natoms = int(line[3])
    boxsize = [
        line[5].split(' ')[0], line[5].split(' ')[1], line[6].split(' ')[0],
        line[6].split(' ')[1], line[7].split(' ')[0], line[7].split(' ')[1]
    ]
    boxsize = [float(i) for i in boxsize]
    keywords = line[8].strip(
        'ATOMS ')  # assume ATOMS id type xu yu zu vx vy vz fx fy fz

    # for every shot in the trajectory file update BGF and manipulate
    dumpatom = get_line(trj_file)
    processed_step = 0

    t1 = t2 = 0
    elapsed_time = 0

    while 1:
        ### Show progress
        t1 = time.time()
        remaining_time = elapsed_time * (n_step - processed_step)
        sys.stdout.write('\r' + "Reading timestep.. " + str(timestep) +
                         " (Remaining time: " +
                         "{0:4.1f}".format(remaining_time) + " seconds, " +
                         "{0:4.1f} minutes".format(remaining_time / 60) + ")")
        sys.stdout.flush()

        if processed_step == n_step:
            break

        ### Read
        try:
            chunk = [next(dumpatom) for i in range(natoms + n_header)]
        except StopIteration:
            break

        timestep = int(chunk[1])
        l_timestep.append(timestep)
        natoms = int(chunk[3])
        boxsize = [
            chunk[5].split(' ')[0], chunk[5].split(' ')[1],
            chunk[6].split(' ')[0], chunk[6].split(' ')[1],
            chunk[7].split(' ')[0], chunk[7].split(' ')[1]
        ]
        boxsize = [float(i) for i in boxsize]
        boxsize = [(boxsize[1] - boxsize[0]), (boxsize[3] - boxsize[2]),
                   (boxsize[5] - boxsize[4])]
        keywords = chunk[8].split('ATOMS ')[1].strip('\n').split(' ')

        ### update myBGF with trajectory information ###
        natom_bgf = len(myBGF.a)  # number of atoms in BGF file

        if not natom_bgf == natoms:
            nu.die(
                "Number of atoms in trajectory file does not match with BGF file."
            )

        mode = 'unwrapped'  # assume that "dump            1 all custom 100 ${sname}${rtemp}K.nvt.lammps id type xu yu zu vx vy vz fx fy fz" in lammps input

        # actual coordinate
        coordinfo = chunk[9:]

        # modified for fast treatment
        for atomline in coordinfo:
            atomcoord = atomline.split(' ')
            atom = myBGF.getAtom(int(atomcoord[0]))

            atom.x = float(atomcoord[2])  # coord
            atom.y = float(atomcoord[3])
            atom.z = float(atomcoord[4])
            atom.vx = float(atomcoord[5])  # vel
            atom.vy = float(atomcoord[6])
            atom.vz = float(atomcoord[7])
            if 'fx' in keywords:
                atom.fx = float(atomcoord[8])  # force
                atom.fy = float(atomcoord[9])
                atom.fz = float(atomcoord[10])

            try:
                for i in range(0, 3):
                    myBGF.CRYSTX[i] = boxsize[i]
            except:
                pass
                #nu.warn("Crystal information error: is this file not periodic?")

        # apply periodic condition
        myBGF = bgftools.periodicMoleculeSort(myBGF, 0, True)

        ### myBGF update complete! ###

        # for CNT atoms, calculate some properties on CNT
        min_x_CNT = 0.0
        max_x_CNT = 0.0
        radius_CNT = 0.0
        height_CNT = 0.0
        aNo_WAT_O_not_in_CNT = []
        temp = []
        min_y_CNT = 0.0
        max_y_CNT = 0.0
        min_z_CNT = 0.0
        max_z_CNT = 0.0
        CNT_orientation = ""

        l_radius_CNT = []
        l_x_CNT = []
        l_y_CNT = []
        for aNo in aNo_CNT:
            atom = myBGF.getAtom(aNo)

            # center of CNT
            l_x_CNT.append(atom.x)
            l_y_CNT.append(atom.y)

            # height
            if atom.z < min_z_CNT:
                min_z_CNT = atom.z
            if atom.z > max_z_CNT:
                max_z_CNT = atom.z

        # center of CNT
        x_CNT, a = nu.meanstdv(l_x_CNT)
        y_CNT, a = nu.meanstdv(l_y_CNT)
        z_diff = max_z_CNT - min_z_CNT

        # radius of CNT
        for aNo in aNo_CNT:
            atom = myBGF.getAtom(aNo)
            l_radius_CNT.append(
                math.sqrt((atom.x - x_CNT)**2 + (atom.y - y_CNT)**2))

        radius_CNT, a = nu.meanstdv(l_radius_CNT)
        l_avg_radius_CNT.append(radius_CNT)

        ### get water molecules in CNT

        # inside the CNT := min_z_CNT <= z <= max_z_CNT and (x - (x_diff/2))**2 + (y - (y_diff/2))**2 < radius_CNT**2
        margin = 0
        # water molecules far from the margin will be only considered
        aNo_WAT_O_in_CNT = []
        for aNo in aNo_WAT_O:
            atom = myBGF.getAtom(aNo)
            dist_sq = (atom.x - x_CNT)**2 + (atom.y - y_CNT)**2
            if "WAT" in atom.rName and min_z_CNT + margin <= atom.z and atom.z <= max_z_CNT - margin and dist_sq < radius_CNT**2:
                aNo_WAT_O_in_CNT.append(aNo)
            else:
                pass

        ### find outer water layer and collect data
        aNo_WAT_outer = []
        for aNo in aNo_WAT_O_in_CNT:
            atom = myBGF.getAtom(aNo)
            r = math.sqrt((atom.x - x_CNT)**2 + (atom.y - y_CNT)**2)

            # separate inner and outer water molecules	# for (12, 12) outer is r >= 3
            #if r >= 3: 	# 5 = 2 (depletion area) + 3 (outer shell)
            if radius_CNT - r <= 5:
                aNo_WAT_outer.append(aNo)
                #l_data.append(atom.vz*10**5)	# outer water velocity = v_slip, original velocity unit: A/fs = 10^5 m/s

        # calculate z-directional velocity of water molecules		vcm = sum vi mi / sum mi
        atom = myBGF.getAtom(aNo_WAT_outer[0])
        mass_O = bgftools.getMass(myBGF, [aNo_WAT_outer[0]], ff_file)
        atom = myBGF.getAtom(atom.CONECT[0])
        mass_H = bgftools.getMass(myBGF, [atom.aNo], ff_file)
        mass_H2O = mass_O + 2 * mass_H  # H2O mass

        for aNo in aNo_WAT_outer:
            atom = myBGF.getAtom(aNo)  # oxygen
            #vcmx = atom.vx * mass_O
            #vcmy = atom.vy * mass_O
            vcmz = atom.vz * mass_O

            for ano in atom.CONECT:
                atom2 = myBGF.getAtom(ano)
                #vcmx += atom.vx * mass_O
                #vcmy += atom.vy * mass_O
                vcmz += atom.vz * mass_H

            #vcmx /= mass_H2O
            #vcmy /= mass_H2O
            vcmz /= mass_H2O

            l_data.append(vcmz * 10**5)

        # calculate sum of forces on carbon atoms of CNT
        F_N = 0.0
        F_N_outer = 0.0
        F_N_inner = 0.0
        for aNo in aNo_CNT:
            atom = myBGF.getAtom(aNo)
            x, y = (atom.x - x_CNT, atom.y - y_CNT)
            theta = 0
            if y >= 0:
                theta = math.acos(x / (math.sqrt(x**2 + y**2)))
            else:
                theta = -math.acos(x / (math.sqrt(x**2 + y**2)))
            F_N += atom.fy * math.cos(theta) + atom.fx * math.sin(theta)
            #F_N += abs(atom.fx * math.cos(theta) + atom.fy * math.sin(theta))

        l_F_N.append(F_N)

        # timestep mark for starting average
        if n_avg_count == 0:
            n_avg_count_step = timestep

        n_avg_count += 1  # "Job's Done" counter

        # if the time comes.. average!
        if n_avg_count == n_avg_step:
            a = analyzeData(l_data)  # average vz
            l_result.append(
                [timestep, a]
            )  # note the the timestep here is not the timestep that the average started.

            t, s = nu.meanstdv(l_F_N)  # average force on CNT

            myOut.write(
                str(n_avg_count_step) + "\t" + str(a) + "\t" + str(t) + "\n")

            # reset
            l_data = []
            n_avg_count = 0
            l_F_N = []

        sys.stdout.write(
            'Done                                                        ')
        sys.stdout.flush()

        # ending for timestep treatment
        t2 = time.time()  # time mark
        elapsed_time = t2 - t1
        processed_step += 1

    # write output
    pkl.dump(l_result, myPkl)

    print('')
    return 1
def getSlipLength(bgf_file, trj_file, force_profile, silent=False):
    """
	This calculates the profile of averaged velocity according to r. 
	NOTE: This is different from averaged velocity profile according to r.
	"""

    # const
    PI = math.pi
    vdw_r_C = 1.7

    # init
    timestep = 0
    l_timestep = []
    line = []
    n_header = 0
    output = ""
    t1 = 0
    t2 = 0
    # clock
    output += "t\tforce\tarea\tvz\tvisc\tsliplen\n"

    l_radial_vz_profile = []
    l_avg_data = []
    l_result = []

    l_avg_count = []
    n_avg_count_step = 0

    myBGF = bgf.BgfFile(bgf_file)
    myTRJ = open(trj_file)
    myTRJ.seek(0)
    myOUT = open(trj_file + ".sliplength.profile", 'w')

    # how many steps to go?
    if not silent: print("Scanning trajectory file..")
    l_timestep = lt.getTrjInfo(trj_file, silent=False)
    n_timestep = len(l_timestep)

    if not silent:
        print("\nThe trajectory contains " + str(n_timestep) + " timesteps.")

    # read force data from force profile
    if not silent: print("Reading force profile..")
    f_fp = open(force_profile)
    force = dict()
    while 1:
        line = f_fp.readline()
        if not line:
            break
        if line[0] == "#":
            continue
        parse = line.split()
        step = int(parse[0])
        force[step] = float(parse[1])

    # extract aNos of CNT in the BGF file
    aNo_CNT = []
    aNo_WAT_O = []
    aNo_WAT_all = []

    for atom in myBGF.a:
        # Carbons in CNT
        if "CNT" in atom.rName:
            aNo_CNT.append(atom.aNo)

        # Oxygen in water
        if "WAT" in atom.rName and "O" in atom.aName:
            aNo_WAT_O.append(atom.aNo)

    N_CNT = len(aNo_CNT)  # the number of CNT atoms

    # check if there exists water properly
    if len(aNo_WAT_O) == 0:
        nu.die("No water molecules in the BGF file.")
    if len(aNo_CNT) == 0:
        nu.die("No CNT molecules in the BGF file.")

    t1 = t2 = 0
    elapsed_time = 0

    # Find header of the trajectory file
    line = []
    n_header = 0
    while 1:
        templine = myTRJ.readline()
        line.append(templine.strip('\n').strip('ITEM: '))
        n_header += 1
        if "ITEM: ATOMS" in templine:
            break

    # INITIAL trajectory information
    timestep = int(line[1])
    natoms = int(line[3])
    boxsize = [
        line[5].split(' ')[0], line[5].split(' ')[1], line[6].split(' ')[0],
        line[6].split(' ')[1], line[7].split(' ')[0], line[7].split(' ')[1]
    ]
    boxsize = [float(i) for i in boxsize]
    keywords = line[8].strip('ATOMS ')

    # calculate properties
    dumpatom = get_line(trj_file)
    processed_step = 0
    while 1:
        ### Show progress
        t1 = time.time()
        remaining_time = elapsed_time * (n_timestep - processed_step)

        ### Read
        try:
            chunk = [next(dumpatom) for i in range(natoms + n_header)]
        except StopIteration:
            break

        timestep = int(chunk[1])
        l_timestep.append(timestep)
        natoms = int(chunk[3])
        boxsize = [
            chunk[5].split(' ')[0], chunk[5].split(' ')[1],
            chunk[6].split(' ')[0], chunk[6].split(' ')[1],
            chunk[7].split(' ')[0], chunk[7].split(' ')[1]
        ]
        boxsize = [float(i) for i in boxsize]
        boxsize = [(boxsize[1] - boxsize[0]), (boxsize[3] - boxsize[2]),
                   (boxsize[5] - boxsize[4])]
        keywords = chunk[8].split('ATOMS ')[1].strip('\n').split(' ')
        sys.stdout.write('\r' + "Fetched timestep: " + str(timestep) +
                         " (Remaining time: " +
                         "{0:4.1f}".format(remaining_time) + " seconds, " +
                         "{0:4.1f} minutes".format(remaining_time / 60) + ")")
        sys.stdout.flush()

        if timestep == 0:
            continue

        ### update myBGF with trajectory information ###
        natom_bgf = len(myBGF.a)  # number of atoms in BGF file

        if not natom_bgf == natoms:
            nu.die(
                "Number of atoms in trajectory file does not match with BGF file."
            )

        mode = 'unwrapped'  # assume that "dump            1 all custom 100 ${sname}${rtemp}K.nvt.lammps id type xu yu zu vx vy vz" in lammps input

        # actual coordinate
        coordinfo = chunk[9:]

        # modified for fast treatment
        for atomline in coordinfo:
            atomcoord = atomline.split(' ')
            atom = myBGF.getAtom(int(atomcoord[0]))

            atom.vx = float(atomcoord[5])
            atom.vy = float(atomcoord[6])
            atom.vz = float(atomcoord[7])

        ### myBGF update complete! ###

        # calculate z-directional velocity of water molecules wrt r		vcm = sum vi mi / sum mi
        mass_O = 16.0000
        mass_H = 1.008
        mass_H2O = mass_O + 2 * mass_H  # H2O mass
        vz = []
        # data container

        # z velocity calculation
        for ano in aNo_WAT_O:
            atom = myBGF.getAtom(ano)  # oxygen
            vcmz = atom.vz * mass_O

            for ano2 in atom.CONECT:
                atom2 = myBGF.getAtom(ano2)  # hydrogens
                vcmz += atom2.vz * mass_H

            vcmz /= mass_H2O

            vz.append(vcmz * (10**5))  # velocity in A/fs -> m/s

        avg_vz, _ = nu.meanstdv(vz)

        f = force[timestep] * (6.95e9)
        l = f / A / avg_vz  # lambda
        b = v / l * 1e9  # slip length

        output += str(timestep) + "\t" + str(force[timestep]) + "\t" + str(
            A) + "\t" + str(avg_vz) + "\t" + str(v) + "\t" + str(b) + "\n"

        t2 = time.time()  # time mark
        elapsed_time = t2 - t1
        processed_step += 1

    myOUT.write(output)
    myOUT.close()

    print('')
    return 1
Exemple #11
0
def getVelocity(bgf_file, trj_file, n_step, silent=False):

	# const
	PI = math.pi
	vdw_r_C = 1.7

	# init
	timestep = 0; l_timestep = []; line = []; n_header = 0;
	t1 = 0; t2 = 0; # clock

	l_data = [];	# stores vz
	l_avg_radius_CNT = [];

	myBGF = bgf.BgfFile(bgf_file)
	myTRJ = open(trj_file)
	myTRJ.seek(0)

	ftemp = open("countWater4.profile.test", 'w')
	ftemp.write(str(sys.argv) + "\n")

	curr_dir = os.path.abspath(".")
	temp_dir = curr_dir + "/CountWAT5/"
	print(temp_dir)
	if not os.path.isdir(temp_dir): os.makedirs(temp_dir)

	# how many steps to go?
	n_timestep = len(lt.getTrjInfo(trj_file))
	if n_step == 0:
		n_step = n_timestep;

	print(" ..The trajectory contains " + str(n_timestep) + " timesteps.")
	print("The script will proceed for the last " + str(n_step) + " timesteps.")

	# extract aNos of CNT in the BGF file
	aNo_CNT = []
	aNo_WAT_O = []
	aNo_WAT_all = []

	for atom in myBGF.a:
		# Carbons in CNT or atoms in BNNT
		if "NT" in atom.rName:
			aNo_CNT.append(atom.aNo)

		# Oxygen in water
		if "WAT" in atom.rName and "O" in atom.aName:
			aNo_WAT_O.append(atom.aNo)

	N_CNT = len(aNo_CNT)	# the number of CNT atoms

	# check if there exists water properly
	if len(aNo_WAT_O) == 0:
		nu.die("No water molecules in the BGF file.")
	if len(aNo_CNT) == 0:
		nu.die("No CNT molecules in the BGF file.")

	# Find header of the trajectory file
	while 1:
		templine = myTRJ.readline()
		line.append(templine.strip('\n').strip('ITEM: '))
		n_header += 1
		if "ITEM: ATOMS" in templine:
			break;

	# INITIAL trajectory information
	timestep = int(line[1])
	natoms = int(line[3])
	boxsize = [line[5].split(' ')[0], line[5].split(' ')[1], line[6].split(' ')[0], line[6].split(' ')[1], line[7].split(' ')[0], line[7].split(' ')[1]]
	boxsize = [float(i) for i in boxsize]
	keywords = line[8].strip('ATOMS ')

	# for every shot in the trajectory file update BGF and manipulate
	dumpatom = get_line(trj_file)
	processed_step = 0;

	t1 = t2 = 0; elapsed_time = 0;

	while 1:

		### tester
		if processed_step == 50:
			break;

		### Show progress
		t1 = time.time();
		remaining_time = elapsed_time * (n_step - processed_step)
		sys.stdout.write('\r' + "Reading timestep.. " + str(timestep) + " (Remaining time: " + "{0:4.1f}".format(remaining_time) + " seconds, " + "{0:4.1f} minutes".format(remaining_time/60) + ")")
		sys.stdout.flush()

		if processed_step == n_step:
			break;

		### Read
		myBGF = bgf.BgfFile(bgf_file)
		try:
			chunk = [next(dumpatom) for i in range(natoms+n_header)]
		except StopIteration:
			break;

		timestep = int(chunk[1])
		natoms = int(chunk[3])
		boxsize = [chunk[5].split(' ')[0], chunk[5].split(' ')[1], chunk[6].split(' ')[0], chunk[6].split(' ')[1], chunk[7].split(' ')[0], chunk[7].split(' ')[1]]; 
		boxsize = [float(i) for i in boxsize]; boxsize = [(boxsize[1] - boxsize[0]), (boxsize[3] - boxsize[2]), (boxsize[5] - boxsize[4])]
		keywords = chunk[8].split('ATOMS ')[1].strip('\n').split(' ')

			
		### update myBGF with trajectory information ###
		natom_bgf = len(myBGF.a)	# number of atoms in BGF file
	
		if not natom_bgf == natoms:
			nu.die("Number of atoms in trajectory file does not match with BGF file.")
	
		mode = 'unwrapped'	# assume that "dump            1 all custom 100 ${sname}${rtemp}K.nvt.lammps id type xu yu zu vx vy vz" in lammps input
	
		# actual coordinate
		coordinfo = chunk[9:]
	
		# modified for fast treatment
		for atomline in coordinfo:
			atomcoord = atomline.split(' ')
			atom = myBGF.getAtom(int(atomcoord[0]))
	
			atom.x = float(atomcoord[2])
			atom.y = float(atomcoord[3])
			atom.z = float(atomcoord[4])
			atom.vx = float(atomcoord[5])
			atom.vy = float(atomcoord[6])
			atom.vz = float(atomcoord[7])

			
		### myBGF update complete! ###


		### align CNT to z axis
		# initialize for the moment of inertia and the center of mass calculation
		U = 0; Ut = 0; Uv = 0;
		Ixx = 0; Ixy = 0; Ixz = 0;
		Iyx = 0; Iyy = 0; Iyz = 0;
		Izx = 0; Izy = 0; Izz = 0;
		Mx = 0; My = 0; Mz = 0;

		# transpose "all atoms in BGF": move COM of CNT as origin
		# com of CNT (important: only one CNT!)
		Mx = 0; My = 0; Mz = 0;
		min_x_CNT = 0.0; max_x_CNT = 0.0; min_y_CNT = 0.0; max_y_CNT = 0.0; min_z_CNT = 0.0; max_z_CNT = 0.0;
		for atom in myBGF.a:
			if "NT" in atom.rName:
				Mx += atom.x / N_CNT
				My += atom.y / N_CNT
				Mz += atom.z / N_CNT

				### before we proceed to calculate MI first check how the CNT is lying across the periodic box
				if atom.x < min_x_CNT:
					min_x_CNT = atom.x
				if atom.x > max_x_CNT:
					max_x_CNT = atom.x
				if atom.y < min_y_CNT:
					min_y_CNT = atom.y
				if atom.y > max_y_CNT:
					max_y_CNT = atom.y
				if atom.z < min_z_CNT:
					min_z_CNT = atom.z
				if atom.z > max_z_CNT:
					max_z_CNT = atom.z
	
		max_x_axis = int(math.ceil(max_x_CNT/boxsize[0]))
		min_x_axis = int(math.floor(min_x_CNT/boxsize[0]))
		max_y_axis = int(math.ceil(max_y_CNT/boxsize[1]))
		min_y_axis = int(math.floor(min_y_CNT/boxsize[1]))
		max_z_axis = int(math.ceil(max_z_CNT/boxsize[2]))
		min_z_axis = int(math.floor(min_z_CNT/boxsize[2]))

		replNum = (min_x_axis, max_x_axis, min_y_axis, max_y_axis, min_z_axis, max_z_axis)
		copyNum = 0

		### copy water molecules
		for x in range(min_x_axis, max_x_axis):
			if x != 0: 
				myBGF2 = copy.deepcopy(myBGF)
				bgf.moveBGF(myBGF2, boxsize[0]*x, 0, 0)
				myBGF = myBGF.merge(myBGF2)
				copyNum += 1

		for y in range(min_y_axis, max_y_axis):
			if y != 0: 
				myBGF2 = copy.deepcopy(myBGF)
				bgf.moveBGF(myBGF2, 0, boxsize[1]*y, 0)
				myBGF = myBGF.merge(myBGF2)
				copyNum += 1

		for z in range(min_z_axis, max_z_axis):
			if z != 0: 
				myBGF2 = copy.deepcopy(myBGF)
				bgf.moveBGF(myBGF2, 0, 0, boxsize[2]*z)
				myBGF = myBGF.merge(myBGF2)
				copyNum += 1

		print(str(replNum) + " " + str(copyNum) + " natoms: " + str(len(myBGF.a)))


		### now continute to MI calculation
		# move atoms to box center
		COM = nu.array([[Mx, My, Mz]])
		CNT = CNT - COM
		'''
		for atom in myBGF.a:
			atom.x -= Mx 
			atom.y -= My 
			atom.z -= Mz 
		'''

		# calculate the moment of inertia (MI) and the center of mass (COM) of CNT from "myBGF"
		for aNo in aNo_CNT:
			atom = myBGF.getAtom(aNo)
			Ixx += (atom.y**2 + atom.z**2) / N_CNT
			Iyy += (atom.x**2 + atom.z**2) / N_CNT
			Izz += (atom.x**2 + atom.y**2) / N_CNT
			Ixy -= (atom.x * atom.y) / N_CNT
			Ixz -= (atom.x * atom.z) / N_CNT
			Iyz -= (atom.y * atom.z) / N_CNT
			
		# the moment of inertia tensor
		I = np.array([[Ixx, Ixy, Ixz], [Ixy, Iyy, Iyz], [Ixz, Iyz, Izz]])

		# eigenvalue & eigenvector calculation
		eigval, eigvec = np.linalg.eig(I)	# eigval[0] is the minimum among the values.
	
		# rearrange the U vector
		U = np.matrix(eigvec)
		Ut = U.T

		# "myBGF" rotation
		for atom in myBGF.a:
			v = np.matrix([atom.x, atom.y, atom.z]).T
			Uv = Ut * v
			atom.x = float(Uv[2])
			atom.y = float(Uv[1])
			atom.z = float(Uv[0])


		# for CNT atoms, calculate some properties
		min_x_CNT = 1000.0; max_x_CNT = -1000.0; radius_CNT = 0.0; height_CNT = 0.0; 
		min_y_CNT = 1000.0; max_y_CNT = -1000.0;
		min_z_CNT = 1000.0; max_z_CNT = -1000.0;
		CNT_orientation = "-"

		# move origin to box center
		for atom in myBGF.a:
			atom.x += boxsize[0]/2.0
			atom.y += boxsize[1]/2.0
			atom.z += boxsize[2]/2.0

		#myBGF = bgftools.periodicMoleculeSort(myBGF, 0, myBGF.CRYSTX)	##### testestestest

		### update PBC information
		myBGF.PERIOD = "111"
		myBGF.AXES = "ZYX"
		myBGF.SGNAME = "P 1                  1    1\n"
		myBGF.CELLS = [-1, 1, -1, 1, -1, 1]
		if myBGF.CRYSTX != []:
			for i in range(0, 3):
				myBGF.CRYSTX[i] = boxsize[i]
		else:
			for i in range(0, 3):
				myBGF.CRYSTX.append(boxsize[i])
			myBGF.CRYSTX += [90.0, 90.0, 90.0]

		myBGF.saveBGF(temp_dir + bgf_file.split(".bgf")[0] + "." + str(timestep) + ".bgf")

		l_radius_CNT = [];
		l_x_CNT = [];
		l_y_CNT = [];
		for aNo in aNo_CNT:
			atom = myBGF.getAtom(aNo)

			# center of CNT
			l_x_CNT.append(atom.x)
			l_y_CNT.append(atom.y)

			# height
			if atom.z < min_z_CNT:
				min_z_CNT = atom.z
			if atom.z > max_z_CNT:
				max_z_CNT = atom.z
	
		x_CNT, a = nu.meanstdv(l_x_CNT)
		y_CNT, a = nu.meanstdv(l_y_CNT)
		z_diff = max_z_CNT - min_z_CNT
		height_CNT = z_diff

		# radius of CNT
		for aNo in aNo_CNT:
			atom = myBGF.getAtom(aNo)
			l_radius_CNT.append( math.sqrt( (atom.x - x_CNT)**2 + (atom.y - y_CNT)**2 ))

		radius_CNT, a = nu.meanstdv(l_radius_CNT)
		l_avg_radius_CNT.append(radius_CNT)


		### get water molecules in CNT

		# inside the CNT := min_z_CNT <= z <= max_z_CNT and (x - (x_diff/2))**2 + (y - (y_diff/2))**2 < radius_CNT**2
		# aNo_WAT_O_atoms: molecules which O atom is within CNT
		# we don't need to calculate H atoms. Let's consider only O atoms
		margin = 0.0;	# water molecules far from the margin will be only considered
		aNo_WAT_O_in_CNT = []
		for aNo in aNo_WAT_O:
			atom = myBGF.getAtom(aNo)
			dist_sq = (atom.x - x_CNT)**2 + (atom.y - y_CNT)**2
			if "WAT" in atom.rName and "O" in atom.ffType and min_z_CNT + margin <= atom.z and atom.z <= max_z_CNT - margin and dist_sq < radius_CNT**2:
				aNo_WAT_O_in_CNT.append(aNo)
			else:
				pass;

		#output = str(timestep) + '\t' + str(len(aNo_WAT_O_in_CNT)) + '\t' + str(radius_CNT) + '\t' + str(z_diff) + '\n'
		output = str(timestep) + '\t' + str(len(aNo_WAT_O_in_CNT)) + '\t' + str(radius_CNT) + '\t' + str(boxsize[0]/2) + '\t' + str(boxsize[1]/2) + '\t' + str(min_z_CNT) + '\t' + str(max_z_CNT) + '\t' + str(z_diff) + '\t' + str(height_CNT) + '\t' + str(len(aNo_CNT)) + '\t' + str(replNum) + '\t' + str(copyNum) + '\n'	# debug
		ftemp.write(output)


		#sys.stdout.write('Done                                                        ')
		sys.stdout.flush()

		t2 = time.time()	# time mark
		elapsed_time = t2 - t1;
		processed_step += 1;


	print('')
	ftemp.close()
	print("numbers of water molecules are written in countWater.profile ..Done.")


	return 1