Пример #1
0
def do_work(bgf_file, out_file, simple, silent=True):

    #initialize
    myPEI = bgf.BgfFile()
    n_H = []

    # open BGF
    myBGF = bgf.BgfFile(bgf_file)

    # remove hydrogens
    pei = bgftools.getBackbone(myBGF, 0)

    # convert connection into dictionary
    d_graph = bgftools.getConnectionDict(pei)

    # convert dictionary into Graph
    G = nx.Graph(d_graph)

    # calculate the all shortest length path
    #d_dist = nx.floyd_warshall(G)	# seems a problem
    d_dist = nx.all_pairs_shortest_path_length(G)

    # get Wiener Index
    index = 0
    for key in d_dist.iterkeys():
        for key2 in d_dist[key].iterkeys():
            index += d_dist[key][key2]
    index = index / 2.0

    return index
Пример #2
0
def copy_bgf_info(bgf_file, out_file=""):
    """
    Generates an empty BGF file with same information.
    copy_bgf_info(bgf_file): return new bgf file, DON'T SAVE
    copy_bgf_info(bgf_file, out_file="filename"): return new bgf file, DO SAVE
    """

    if isinstance(bgf_file, bgf.BgfFile):
        orig = bgf_file
    else:
        orig = bgf.BgfFile(bgf_file)
    new = bgf.BgfFile()

    new.BIOGRF = orig.BIOGRF
    new.DESCRP = orig.DESCRP
    new.REMARK = orig.REMARK
    new.FF = orig.FF
    new.FORMAT = orig.FORMAT
    new.PERIOD = orig.PERIOD
    new.AXES = orig.AXES
    new.SGNAME = orig.SGNAME
    new.CRYSTX = orig.CRYSTX
    new.OTHER = orig.OTHER
    new.CELLS = orig.CELLS

    if out_file:
        new.saveBGF(out_file)

    return new
Пример #3
0
def check_isomorphism(l):

    if simple:
        # open BGF
        myBGF1 = bgf.BgfFile(bgf_file1)
        myBGF2 = bgf.BgfFile(bgf_file2)

        # remove hydrogens only in carbon atoms
        remove_aNo1 = []
        remove_aNo2 = []
        for atom in myBGF1.a:
            if "C_" in atom.ffType:
                n_H = []
                for aNo in atom.CONECT:
                    if myBGF1.getAtom(aNo).is_hydrogen():
                        n_H.append(myBGF1.a2i[aNo])
                if len(n_H) != 3:
                    n_H.sort()
                    n_H.reverse()
                    myBGF1.delAtoms(n_H)
                    myBGF1.renumber()

        for atom in myBGF2.a:
            if "C_" in atom.ffType:
                n_H = []
                for aNo in atom.CONECT:
                    if myBGF2.getAtom(aNo).is_hydrogen():
                        n_H.append(myBGF2.a2i[aNo])
                if len(n_H) != 3:
                    n_H.sort()
                    n_H.reverse()
                    myBGF2.delAtoms(n_H)
                    myBGF2.renumber()

        # toss reduced BGFs to networkx
        pei1 = myBGF1
        pei2 = myBGF2

    else:
        # toss whole structures
        pei1 = bgf_file1
        pei2 = bgf_file2

    # convert connection into dictionary
    d_graph1 = bgftools.getConnectionDict(pei1)
    d_graph2 = bgftools.getConnectionDict(pei2)

    # convert dictionary into Graph
    G1 = nx.Graph(d_graph1)
    G2 = nx.Graph(d_graph2)

    # check isomorphism
    GM = isomorphism.GraphMatcher(G1, G2)
    result = GM.is_isomorphic()

    return bgf_file1, bgf_file2, result
Пример #4
0
def randomDisperse(bgf_file, size, number, out_file, silent=False):
	"""
def randomDisperse():
	Create a randomly distributed cubic with full of the monomers

Function Parameters:
	bgf_file	A string which contains a monomer information in a BGF format. 
	size
	number
	out_file
	"""

	# initialize

	# open bgf
	if not silent: print("reading monomer..")
	cubicBGF = bgf.BgfFile()
	#for atom in cubicBGF.a:
	#	cubicBGF.delAtom(cubicBGF.a2i[atom.aNo])

	# repeat up to number:
	if not silent: print("generating cubic box..")
	for i in xrange(number):

        # create three random numbers
		x1 = random.uniform(0, size)
		y1 = random.uniform(0, size)
		z1 = random.uniform(0, size)
		
        # move the monomer
		addBGF = bgf.BgfFile(bgf_file)
		headAtom = addBGF.a[0]
		#delta = (headAtom.x - x1, headAtom.y - y1, headAtom.z - z1)
		delta = (x1 - headAtom.x, y1 - headAtom.y, z1 - headAtom.z)
		bgf.moveBGF(addBGF, delta[0], delta[1], delta[2])

        # merge
		cubicBGF = cubicBGF.merge(addBGF, True)

	# make it periodic
	cubicBGF.BIOGRF = "200"
	cubicBGF.DESCRP = bgf_file[:-4]
	cubicBGF.REMARK.insert(0, "Cubic generated by " + os.path.basename(sys.argv[0]) + " by " + os.environ["USER"] + " on " + time.asctime(time.gmtime()))
	cubicBGF.FF = "FORCEFIELD DREIDING"
	cubicBGF.PERIOD = "111"
	cubicBGF.CRYSTX = [ size, size, size, 90.0, 90.0, 90.0 ]
	cubicBGF.AXES = "ZYX"
	cubicBGF.SGNAME = "P 1                  1    1\n"
	cubicBGF.CELLS = [-1, 1, -1, 1, -1, 1]

	# save
	if not silent: print("saving.. " + out_file)
	cubicBGF.saveBGF(out_file)
Пример #5
0
def test_isomorphism(bgf_file1, bgf_file2, simple, silent=True):
    """
def test_isomorphism():

Function Parameters:
	bgf_file	A string of filename or BgfFile class.

	"""
    # initialize
    pei1 = 0
    pei2 = 0

    # open BGF
    if isinstance(bgf_file1, bgf.BgfFile):
        myBGF = bgf_file1
    else:
        if not silent: print("opening bgf file 1.. " + str(bgf_file1))
        myBGF = bgf.BgfFile(bgf_file1)

    if isinstance(bgf_file2, bgf.BgfFile):
        myBGF = bgf_file2
    else:
        if not silent: print("opening bgf file 2.. " + str(bgf_file2))
        myBGF = bgf.BgfFile(bgf_file2)

    if simple:
        # reduce hydrogens
        pei1 = bgftools.getBackbone(bgf_file1)
        pei2 = bgftools.getBackbone(bgf_file2)
    else:
        pei1 = bgf_file1
        pei2 = bgf_file2

    # convert connection into dictionary
    d_graph1 = bgftools.getConnectionDict(pei1)
    d_graph2 = bgftools.getConnectionDict(pei2)
    if not silent: print("structures are converted to graph.")

    G1 = nx.Graph(d_graph1)
    G2 = nx.Graph(d_graph2)
    if not silent: print("graphs are loaded.")

    # check isomorphism
    if not silent: print("now comparing two graphs..")
    GM = isomorphism.GraphMatcher(G1, G2)
    result = GM.is_isomorphic()

    if not silent:
        print(result)
    else:
        return result
Пример #6
0
def selectResName(bgf_file, resName, out_file, silent=False):
    """
selectResName(bgf_file, resName, out_file, silent=False):
	return a BgfFile class which contains the same residue name as designated.
	"""

    # open bgf
    if isinstance(bgf_file, bgf.BgfFile):
        myBGF = copy.deepcopy(bgf_file)
    else:
        if not silent: print("Reading " + bgf_file + " ..")
        myBGF = bgf.BgfFile(bgf_file)

    l_notSelected_aNo = []

    # delete unwanted atoms
    for atom in myBGF.a:
        if not resName in atom.rName:
            l_notSelected_aNo.append(atom.aNo)

    l_notSelected_aNo.sort()
    l_notSelected_aNo.reverse()
    myBGF.delAtoms(l_notSelected_aNo)
    if not silent: print(str(len(myBGF.a)) + " atoms are selected.")

    # save
    if isinstance(out_file, str):
        if not silent: print("Saving information to " + out_file + " ..")
        myBGF.saveBGF(out_file)
        return 1
    else:
        return myBGF
Пример #7
0
def getShortestPath(bgf_file, ano1, ano2, silent=True):
    """
def getShortestPath(bgf_file, ano1, ano2):
    Get a list of the shortest path between two atoms of the given BGF structure using findShortestPath()

Function Parameters:
    bgf_file:    a filename or BgfFile class
    ano1:        atom number of the starting atom
    ano2:        atom number of the ending atom
    """

    # open bgf
    if isinstance(bgf_file, bgf.BgfFile):
        myBGF = bgf_file
    else:
        if not silent: print("reading " + bgf_file + " ..")
        myBGF = bgf.BgfFile(bgf_file)

    ### REMARK: be sure that the hydrogen branches of bgf_file are taken off.
    ## cut off all hydrogen branches
    #myBGF = getBackbone(myBGF)

    # prepare the connection information
    graph = getConnectionDict(myBGF)

    # run and return
    return findShortestPath(graph, ano1, ano2)
Пример #8
0
def template(bgf_file, out_file, silent=False):
    """
def template():
	Write what this function does.

Function Parameters:
	bgf_file	A string of filename or BgfFile class.
	out_file	A string of filename or BgfFile class.
	"""
    # open BGF
    if isinstance(bgf_file, bgf.BgfFile):
        myBGF = bgf_file
    else:
        if not silent: print("opening bgf file.. " + str(bgf_file))
        myBGF = bgf.BgfFile(bgf_file)

    # Write down the Template function here

    # save BGF
    if isinstance(out_file, str):
        if not silent: print("Saving information to " + out_file + " ..")
        myBGF.saveBGF(out_file)
        return 1
    else:
        return myBGF
Пример #9
0
def getMoleculeList(bgf_file, recursion_limit=10000, silent=True):
    """
def getMoleculeList(bgf_file, silent=True):
    Get a list of atom numbers (aNo) of the molecules of the given BGF file.
    """

    sys.setrecursionlimit(recursion_limit)

    # open bgf
    if isinstance(bgf_file, bgf.BgfFile):
        myBGF = bgf_file
    else:
        if not silent: print("reading " + bgf_file + " ..")
        myBGF = bgf.BgfFile(bgf_file)

    # build all ano list
    l_all_atom = []
    for atom in myBGF.a:
        l_all_atom.append(atom.aNo)

    # for every atoms, get connected atoms
    l_all_molecules = []
    l_molecule = []
    while len(l_all_atom) > 0:
        l_temp = []
        l_molecule = getmolecule(
            myBGF, myBGF.getAtom(l_all_atom[0]), l_temp, recursion_limit
        )  # l_molecule is kind of dummy.. no items in there.
        l_all_molecules.append(l_temp)
        for i in l_temp:
            l_all_atom.remove(i)

    return l_all_molecules
Пример #10
0
def rotate(bgf_file, v, out_file, silent=True):
    """
	rotate BGF to v2 to z axis.
	"""
    # Initialization

    # Open BGF
    if isinstance(bgf_file, bgf.BgfFile):
        myBGF = bgf_file
    else:
        if not silent: print("opening bgf file.. " + str(bgf_file))
        myBGF = bgf.BgfFile(bgf_file)

    # rotation 1 to x axis
    v1_dot_v2 = v[0]
    mag_v1 = 1.0
    mag_v2 = math.sqrt(v[0]**2 + v[1]**2)
    theta = math.acos(v1_dot_v2 / (mag_v1 * mag_v2))
    theta = -theta
    print(theta)
    rot1 = np.array([[math.cos(theta), -math.sin(theta), 0],
                     [math.sin(theta), math.cos(theta), 0], [0, 0, 1]])

    # rotation 2 to y axis
    v1_dot_v2 = v[1]
    mag_v1 = 1.0
    mag_v2 = math.sqrt(v[1]**2 + v[2]**2)
    rho = math.acos(v1_dot_v2 / (mag_v1 * mag_v2))
    rho = -rho
    print(rho)
    rot2 = np.array([[1, 0, 0], [0, math.cos(rho),
                                 math.sin(rho)],
                     [0, -math.sin(rho), math.cos(rho)]])

    # rotation 3 to z axis
    v1_dot_v2 = v[2]
    mag_v1 = 1.0
    mag_v2 = math.sqrt(v[0]**2 + v[2]**2)
    phi = math.acos(v1_dot_v2 / (mag_v1 * mag_v2))
    phi = -phi
    print(phi)
    rot3 = np.array([[math.cos(phi), 0, math.sin(phi)], [0, 1, 0],
                     [-math.sin(phi), 0, math.cos(phi)]])

    for atom in myBGF.a:
        coord = [atom.x, atom.y, atom.z]
        newcoord = np.dot(rot1, coord)
        newcoord = np.dot(rot2, newcoord)
        newcoord = np.dot(rot3, newcoord)
        atom.x = newcoord[0]
        atom.y = newcoord[1]
        atom.z = newcoord[2]

    # save
    if isinstance(out_file, str):
        if not silent: print("Saving information to " + out_file + " ..")
        myBGF.saveBGF(out_file)
        return 1
    else:
        return myBGF
Пример #11
0
def check_monomer(monomer, ff_file):
    """
Check whether monomer has proper number of branching points

    :str monomer:
    :str ff_file:
    :bool : object
    """
    try:
        f = bgf.BgfFile(monomer)
    except IOError:
        return False

    branch = 0
    head = 0

    for atom in f.a:
        atom.rNo = 0  # this residue number will be the key to distinguish body and the new block
        if atom.chain == "B":
            branch += 1
        if atom.chain == "H":
            head += 1
    if branch != 1:
        raise ValueError('More than two branch atoms inside ' + str(monomer))
        return False
    if head != 1:
        raise ValueError('More than two head atoms inside ' + str(monomer))
        return False

    mass = bgftools.getMass(f, ff_file)
    f.saveBGF(monomer)
    return mass
Пример #12
0
def analyze(bgf_file, trj_file, ff_file='', out_file=''):
    '''analyze something within a timestep in a series of lammps trajectory.
    '''

    # variables

    # inner functions
    def get_line(file):
        with open(file, 'r') as f:
            for line in f:
                yield line

    # 1. Load BGF
    mybgf = bgf.BgfFile(bgf_file)
    N_BGF_ATOMS = len(mybgf.a)

    # 2. Read LAMMPS Trajectory
    #timesteps, N_HEADER, N_ATOMS = lt.getTrjInfo(trj_file)
    mytrj = lt.lammpstrj(trj_file)
    timesteps = mytrj.load()
    N_HEADER = mytrj.nheader
    N_ATOMS = mytrj.natoms[0]
    N_BUFFER = N_HEADER + N_ATOMS
    if N_BGF_ATOMS != N_ATOMS:
        nu.die(
            "Number of atoms in trajectory file does not match with BGF file.")

    # 3. Determine dump style
    dump_keywords = mytrj.dumpstyle
    yes_scale = False
    if 'xs' in dump_keywords:
        yes_scale = True

    # 4. Update coordinates from the snapshot
    dump = get_line(trj_file)
    for t in tqdm.tqdm(timesteps, ncols=120, desc="Analyzing"):
        chunk = [next(dump) for i in range(N_BUFFER)]

        t = int(chunk[1])
        mybgf.CRYSTX = mytrj.pbc[t] + [90.0, 90.0, 90.0]

        coords = chunk[9:]
        for c in coords:
            c = c.split(' ')
            atom = mybgf.getAtom(int(c[0]))

            if yes_scale:
                atom.x = float(c[2]) * pbc[0]
                atom.y = float(c[3]) * pbc[1]
                atom.z = float(c[4]) * pbc[2]
            else:
                atom.x = float(c[2])
                atom.y = float(c[3])
                atom.z = float(c[4])

        mybgf = bt.periodicMoleculeSort(mybgf,
                                        mybgf.CRYSTX,
                                        ff_file=ff_file,
                                        silent=True)
Пример #13
0
def dat2bgf(bgf_file, dat_file, out_file):

    # init
    mybgf = bgf.BgfFile(bgf_file)
    
    f_dat_file = open(dat_file)
    temp = f_dat_file.read().split('\n')
    f_dat_file.close()

    temp = [i.partition('#')[0].rstrip() for i in temp if i != ""]

    # PBC
    for i in temp:
        if 'xlo' in i:
            line = i.split()
            mybgf.CRYSTX[0] = float(line[1]) - float(line[0])
        if 'ylo' in i:
            line = i.split()
            mybgf.CRYSTX[1] = float(line[1]) - float(line[0])
        if 'zlo' in i:
            line = i.split()
            mybgf.CRYSTX[2] = float(line[1]) - float(line[0])

    # Coordinates
    dat_atom_start = temp.index('Atoms')
    dat_atom_end = temp.index('Bonds')
    if 'Velocities' in temp:
        dat_atom_end = temp.index('Velocities') # if data file is from write_restart command, Velocities are also written in the file.:w

    temp = temp[dat_atom_start + 1:dat_atom_end]

    n_dat_atoms = len(temp)
    n_bgf_atoms = len(mybgf.a)

    if n_dat_atoms != n_bgf_atoms:
        nu.die("Number of atoms mismatch between bgf and LAMMPS data file.")

    coords = [] # coords = id type molid charge x y z ix iy iz
    for i in temp:
        line = i.split()
        coords.append(line)

    for i in coords:
        id = int(i[0])
        atom = mybgf.a[mybgf.a2i[id]]   # getAtom
        atom.x = float(i[4])
        atom.y = float(i[5])
        atom.z = float(i[6])

    if out_file == "": out_file = bgf_file.split(".bgf")[0] + "_mod.bgf"
    mybgf.REMARK.append("Coordinates updated on %s" % time.asctime(time.gmtime()))
    mybgf.REMARK.append("Coordinates updated with data file %s" % os.path.abspath(dat_file))
    mybgf.saveBGF(out_file)


    print('Done. Check %s ' % out_file)
    return 1
Пример #14
0
def assignWaterResidue(bgf_file, out_file, silent=True):

    mybgf = bgf.BgfFile(bgf_file)

    for atom in mybgf.a:
        for i in bgftools.is_water(mybgf, atom.aNo):
            mybgf.getAtom(i).rName = "WAT"

    mybgf.saveBGF(out_file)
Пример #15
0
def removebadcontacts(bgf_file, out_file, thresh, silent=True):

    if isinstance(bgf_file, bgf.BgfFile):
        myBGF = bgf_file
    else:
        if not silent:
            print(sys.argv[0] + ": Removing bad contacts from " + bgf_file +
                  " with distance threshold " + str(thresh) +
                  " A and saving to " + out_file + ".")
        myBGF = bgf.BgfFile(bgf_file)

    delete_list = []

    if not silent:
        print("removeBadContacts will remove water molecules within " +
              str(thresh) + " Angstrom from the solute.")
    for solute_aNo in bgftools.listSoluteAtoms(myBGF):
        solute = myBGF.getAtom(solute_aNo)
        for oxygen_aNo in bgftools.listOxygenAtoms(myBGF):
            water = bgftools.is_water(myBGF, oxygen_aNo)
            if water != [] or type(water) != NoneType:
                if len(water) == 3:  # if water is a water molecule,
                    # calculate the distance between solute atoms and the molecule
                    O = myBGF.getAtom(water[0])
                    H1 = myBGF.getAtom(water[1])
                    H2 = myBGF.getAtom(water[2])
                    dist_O_sol = bgf.distance(solute, O)
                    dist_H1_sol = bgf.distance(solute, H1)
                    dist_H2_sol = bgf.distance(solute, H2)
                    if dist_O_sol < thresh or dist_H1_sol < thresh or dist_H2_sol < thresh:
                        if oxygen_aNo not in delete_list:
                            delete_list.append(oxygen_aNo)
                            delete_list.sort()
                        ##if water not in delete_list:
                        ##delete_list.append(water)

    if delete_list != []:
        delete_list.reverse()  # reverse sort for delAtoms
        for oxygen_index in delete_list:
            bgftools.deleteWaterAtoms(myBGF, oxygen_index)
        myBGF.renumber()

        if not silent:
            print("removeBadContacts: " + str(len(delete_list)) +
                  " water molecules are removed.")
    else:
        if not silent:
            print(
                "There are no water molecules that corresponds to the criteria."
            )

    if isinstance(out_file, bgf.BgfFile):
        return myBGF
    else:
        myBGF.saveBGF(out_file)
        return 1
Пример #16
0
def setAmineGroupInfo(bgf_file, out_file, silent=True):
    """
setAmineGroupInfo(bgf_file, silent=True):
    get a BGF file or BgfFile class object
    returns a BgfFile or 1 with  primary, secondary, and tertiary amines information corrected.

    Note that corrections WILL BE applied to the original BGF file.
    """
    n_pri = 0
    n_sec = 0
    n_ter = 0
    n_garbage = 0

    # open bgf
    if isinstance(bgf_file, bgf.BgfFile):
        myBGF = bgf_file
    else:
        if not silent: print("Reading " + bgf_file + " ..")
        myBGF = bgf.BgfFile(bgf_file)

    # get nitrogen ano lists
    l_nitrogen_ano = []
    for atom in myBGF.a:
        if "N_" in atom.ffType: l_nitrogen_ano.append(atom.aNo)

    # for every nitrogen
    for aNo in l_nitrogen_ano:
        n_carbon = 0
        connected_ano = myBGF.getAtom(aNo).CONECT
        ## for every connection
        for aNo2 in connected_ano:
            if "C_" in myBGF.getAtom(aNo2).ffType:
                n_carbon += 1

        ### no carbon: primary, 1 carbons: secondary, 2 carbons: tertiary
        if n_carbon == 1:
            myBGF.getAtom(aNo).rName = "PRI"
        elif n_carbon == 2:
            myBGF.getAtom(aNo).rName = "SEC"
        elif n_carbon == 3:
            myBGF.getAtom(aNo).rName = "TER"
        else:
            n_garbage += 1
            # what are you??

    if n_garbage != 0:
        nu.warn("Suspicious amine groups are found!")
        return 0

    # save
    if isinstance(out_file, str):
        if not silent: print("Saving information to " + out_file + " ..")
        myBGF.saveBGF(out_file)
        return getAmineGroupInfo(myBGF)
    else:
        return getAmineGroupInfo(myBGF)
Пример #17
0
def get_head_ano_of_monomer(monomer):
    """
    """
    ano = 0
    f = bgf.BgfFile(monomer)
    for atom in f.a:
        if atom.chain == "B":
            ano = atom.aNo

    return ano
Пример #18
0
def removeFragments(bgf_file, resname, n_frag, out_file, silent=True):
    """
    """

    # variables
    l_delatoms = []
    n_molecules = 0
    n_atoms = 0

    # open bgf
    if isinstance(bgf_file, bgf.BgfFile):
        myBGF = bgf_file
    else:
        if not silent: print("Reading " + bgf_file + " ..")
        myBGF = bgf.BgfFile(bgf_file)

    # get lists of molecules
    l_molecule = getMoleculeList(bgf_file)

    if not silent:
        print("Molecules which is less atoms than " + str(n_frag) +
              " among the residue name " + str(resname) + " will be removed.")

    # for every molecule
    for molecule in l_molecule:
        if len(molecule) < n_frag:
            for ano in molecule:
                # check rName
                atom = myBGF.getAtom(ano)
                if resname in atom.rName:
                    l_delatoms.append(myBGF.a2i[ano])  # remove index, not ano!
                    #l_delatoms.append(ano)    # remove index, not ano!
                    n_molecules += 1

    # delete and compute stats
    n_atoms = len(l_delatoms)
    l_delatoms.sort()
    l_delatoms.reverse()
    myBGF.renumber()
    myBGF.delAtoms(l_delatoms)
    myBGF.renumber()

    if not silent:
        print(
            str(n_molecules) + " molecules (" + str(n_atoms) +
            " atoms) are deleted.")

    # save
    if isinstance(out_file, str):
        if not silent: print("Saving information to " + out_file + " ..")
        myBGF.saveBGF(out_file)
        return 1
    else:
        return myBGF
Пример #19
0
 def __init__(self, max_branch=2):
     super(RandomPolymer, self).__init__()
     self.monomers = {}
     self.num_monomer = 0
     self.max_num_branch = max_branch  # number of allowed branchs per a node
     self.target_mw = 0  # target molecular weight
     self.num_target_node = 0  # number of nodes required to build a random polymer
     self.Terminal = ""
     self.Linear = ""
     self.Dendron = ""
     self.bgfmodel = bgf.BgfFile()
     self.ff = ""
Пример #20
0
def evaporate(bgf_file, out_file=False, safemode=False, silent=True):
    """
evaporate(bgf_file, out_file):

	bgf_file	A string for input file.
	out_file	A string for output file.
	safemode	A boolean for safe mode determination.

	To-do:
		None
	"""
    # Initialization
    temp = []

    # Open BGF
    if isinstance(bgf_file, bgf.BgfFile):
        myBGF = bgf_file
    else:
        if not silent: print("opening bgf file.. " + str(bgf_file))
        myBGF = bgf.BgfFile(bgf_file)

    # Delete water molecules
    if safemode:
        for atom in myBGF.a:
            temp.append(atom.aNo)
        for aNo in temp:
            bgftools.deleteWaterAtoms(myBGF, aNo)
    else:
        if not silent: print("listing water molecules..")
        for atom in myBGF.a:
            if "WAT" in atom.rName:
                temp.append(myBGF.a2i[atom.aNo])
        n_delatoms = len(temp)
        if not silent:
            print("found " + str(n_delatoms) + " atoms for water molecules..")
        if n_delatoms % 3 != 0:
            nu.die(
                "ERROR: the number of atoms to be deleted is not divided in 3. Check the structure."
            )
        if not silent: print("deleting water molecules..")
        myBGF.delAtoms(temp, silent)
        myBGF.renumber()

    # Save BGF
    if isinstance(out_file, str):
        if not silent: print("\nsaving information to " + out_file + " ..")
        myBGF.REMARK.insert(
            0, "Evaporated by " + os.path.basename(sys.argv[0]) + " by " +
            os.environ["USER"] + " on " + time.asctime(time.gmtime()))
        myBGF.saveBGF(out_file)
        return 1
    else:
        return myBGF
Пример #21
0
    def __init__(self, fname, *args, **kwargs):

        bgf_file = ""
        if fname:
            bgf_file = fname

            if isinstance(bgf_file, bgf.BgfFile):
                self.bgfmodel = bgf_file
                self.model_filename = ""  # if the model is directly from bgf object, no filename will be assigned.
            else:
                self.bgfmodel = bgf.BgfFile(bgf_file)
                self.model_filename = bgf_file

            #
            # Determine nanotube type and atom types
            #
            self.NTatoms = self.find_NT_atoms()
            self.WATatoms = self.find_WAT_atoms()
            self.otheratoms = self.find_other_atoms()
            self.find_type()
            self.set_ff()

            #
            # Set number of atoms
            #
            self.n_allatoms = len(self.bgfmodel.a)
            self.n_nanotube = len(self.NTatoms)
            self.n_water = len(self.WATatoms)

            #
            # Properties of CNT: requires special treatment so not automatically calculated.
            #
            self.isAligned = False
            self.isRadiusCalc = False
            self.isPBCadjusted = False
            self.orientation = None
            self.radius = None
            self.height = None
            self.zhi = None
            self.zlo = None
            self.water_position_determined = False

            # model check-up: total charge
            chg = bgftools.charge(self.bgfmodel)
            if chg != 0 and abs(chg) > 1e-10:
                nu.warn("Charge is not neutral: " + str(chg))

            if self.bgfmodel.CRYSTX != []:
                self.pbc = self.bgfmodel.CRYSTX[:3]
        else:
            nu.warn("Nanotube class: An empty object created.")
Пример #22
0
def selectAtoms(bgf_file, selection, out_file, silent=True):
    """
selectAtoms(bgf_file, selection, out_file):
    Extract some atoms from bgf_file. 
    IMPORTANT NOTE: Connection information are not returned.
            If you want to select atoms because of direct manipulation (i.e. adding 10 to xcoord)
            then you'd better use another function.
    """

    # variables
    myBGF = 0
    myBGF2 = 0

    # open bgf
    if isinstance(bgf_file, bgf.BgfFile):
        myBGF = bgf_file
    else:
        if not silent: print("Reading " + bgf_file + " ..")
        myBGF = bgf.BgfFile(bgf_file)

    # find
    myBGF2 = bgf.BgfFile()
    executable = "if " + selection + ": " + "myBGF2.addAtom(atom)"
    for atom in myBGF.a:
        exec(executable)

    # if more than one atom is selected:
    # save
    if len(myBGF2) > 0:
        if isinstance(out_file, str):
            if not silent: print("Saving information to " + out_file + " ..")
            myBGF2.saveBGF(out_file)
            return 1
        else:
            return myBGF2
    else:
        print("No atoms are selected. Quit.")
        return 0
Пример #23
0
def centerbgf(bgf_file, out_file, ff_file, method="com_origin", silent=False):
    if silent == 1:
        nu.shutup()

    boxcenter = []

    # open bgf
    if isinstance(bgf_file, bgf.BgfFile):
        myBGF = bgf_file
    else:
        if not silent: print("Reading " + bgf_file + " ..")
        myBGF = bgf.BgfFile(bgf_file)
        if not silent:
            print("Moving the origin of the coordinate in " + bgf_file +
                  " and saving to " + out_file + ".")

    if method != "box_origin":
        new_x, new_y, new_z = bgftools.getCom(myBGF, ff_file)

    if len(myBGF.CRYSTX) > 2:
        boxcenter = [(i / 2.0) for i in myBGF.CRYSTX[0:3]]
    else:
        boxsize = bgf.getBGFSize(myBGF, 0)  # [xlo, xhi, ylo, yhi, zlo, zhi]
        boxcenter = [(boxsize[1] - boxsize[0]) / 2,
                     (boxsize[3] - boxsize[2]) / 2,
                     (boxsize[5] - boxsize[4]) / 2]

    if method == "com_origin":
        bgf.moveBGF(myBGF, (-new_x), (-new_y), (-new_z))
    elif method == "com_center":
        dx = boxcenter[0] - new_x
        dy = boxcenter[1] - new_y
        dz = boxcenter[2] - new_z
        bgf.moveBGF(myBGF, dx, dy, dz)
    elif method == "box_origin":
        dx = boxcenter[0]
        dy = boxcenter[1]
        dz = boxcenter[2]
        bgf.moveBGF(myBGF, dx, dy, dz)
    else:
        bgf.moveBGF(myBGF, (-new_x), (-new_y), (-new_z))

    # save
    if isinstance(out_file, str):
        if not silent: print("Saving information to " + out_file + " ..")
        myBGF.saveBGF(out_file)
        return 1
    else:
        return myBGF
Пример #24
0
def xyz2bgf(xyz_file, bgf_file, silent=False):
    """
	Converts xyz to bgf
	"""

    ### open xyz
    f_xyz = open(xyz_file, 'r')

    ### create bgf
    myBGF = bgf.BgfFile()
    myBGF.BIOGRF = '200'
    myBGF.DESCRP = xyz_file

    ### read and create atoms for bgf file
    while 1:
        line = f_xyz.readline()

        if not line: break

        words = string.split(line)

        if not words: break

        natoms = int(words[0])
        myBGF.REMARK = [cleansym(f_xyz.readline())]

        for i in range(natoms):
            line = f_xyz.readline()
            words = string.split(line)
            sym = words[0]
            sym = cleansym(sym)
            x, y, z = float(words[1]), float(words[2]), float(words[3])

            ### add atoms
            atom = bgf.BgfAtom()
            atom.x = x
            atom.y = y
            atom.z = z
            atom.ffType = sym
            atom.aNo = i
            atom.aName = sym + str(i)
            atom.rNo = 1
            atom.chain = "A"
            atom.rName = "RES"
            myBGF.addAtom(atom)

    ### save bgf
    myBGF.OTHER = []
    myBGF.saveBGF(bgf_file)
Пример #25
0
def getAmineGroupInfo(bgf_file, silent=True):
    """
getAmineGroupInfo(bgf_file, silent=True):
    get a BGF file or BgfFile class object
    returns a triplet list of numbers of primary, secondary, and tertiary amines.

    Note that any corrections are not applied to the original BGF file.
    """
    n_pri = 0
    n_sec = 0
    n_ter = 0
    n_garbage = 0

    # open bgf
    if isinstance(bgf_file, bgf.BgfFile):
        myBGF = bgf_file
    else:
        if not silent: print("Reading " + bgf_file + " ..")
        myBGF = bgf.BgfFile(bgf_file)

    # get nitrogen ano lists
    l_nitrogen_ano = []
    for atom in myBGF.a:
        if "N_" in atom.ffType: l_nitrogen_ano.append(atom.aNo)

    # for every nitrogen
    for aNo in l_nitrogen_ano:
        n_carbon = 0
        connected_ano = myBGF.getAtom(aNo).CONECT
        ## for every connection
        for aNo2 in connected_ano:
            if "C_" in myBGF.getAtom(aNo2).ffType:
                n_carbon += 1

        ### no carbon: primary, 1 carbons: secondary, 2 carbons: tertiary
        if n_carbon == 1:
            n_pri += 1
            #myBGF.getAtom(aNo).rName = "PRI"
        elif n_carbon == 2:
            n_sec += 1
            #myBGF.getAtom(aNo).rName = "SEC"
        elif n_carbon == 3:
            n_ter += 1
            #myBGF.getAtom(aNo).rName = "TER"
        else:
            n_garbage += 1

    # return the number of pri, sec, and ter
    return [n_pri, n_sec, n_ter]
Пример #26
0
def alignBGF(bgf_file, atom1, atom2, out_file, silent=False):

    # open
    if isinstance(bgf_file, bgf.BgfFile):
        myBGF = bgf_file
    else:
        if not silent: print("reading " + bgf_file + " ..")
        myBGF = bgf.BgfFile(bgf_file)

    a1 = myBGF.a[myBGF.a2i[atom1]];
    a2 = myBGF.a[myBGF.a2i[atom2]];

    v1 = (a1.x, a1.y, a1.z)

    # move atom1 to origin
    for atom in myBGF.a:
        atom.x -= v1[0]
        atom.y -= v1[1]
        atom.z -= v1[2]

    v21 = [ (a2.x - a1.x), (a2.y - a1.y), (a2.z - a1.z) ]

    # rotate v21 to x axis
    u1 = v21 / np.linalg.norm(v21)    ##

    v2 = [u1[1], -u1[0], 0]
    u2 = v2 / np.linalg.norm(v2)    ##

    v3 = np.cross(u1, u2)
    u3 = v3 / np.linalg.norm(v3)    ##

    U = np.array([[u1[0], u1[1], u1[2]], [u2[0], u2[1], u2[2]], [u3[0], u3[1], u3[2]]])

    # rotate all atoms
    for atom in myBGF.a:
        a = np.matrix([atom.x, atom.y, atom.z]).T
        b = U*a
        atom.x = float(b[0])
        atom.y = float(b[1])
        atom.z = float(b[2])

    ## save
    if isinstance(out_file, str):
        if not silent: print("saving information to " + out_file + " ..")
        myBGF.saveBGF(out_file)
        return 1;
    else:
        return myBGF;
Пример #27
0
def get_residue_names(bgf_file):
    """
    returns all residue names in the BGF file.
    """

    # bgf open
    if isinstance(bgf_file, bgf.BgfFile):
        mybgf = bgf_file
    else:
        mybgf = bgf.BgfFile(bgf_file)

    result = set()
    for atom in mybgf.a:
        result.add(atom.rName)

    return list(result)
Пример #28
0
def fixbgf(bgf_file, out_file, silent=False):
	"""
fixbgf(bgf_file, out_file):

	bgf_file	A string for input file.
	out_file	A string for output file.

	To-do:
		None
	"""
	# Open BGF
	myBGF = bgf.BgfFile(bgf_file)

	# Save BGF
	myBGF.REMARK.insert(0, "Renumbered by " + os.path.basename(sys.argv[0]) + " by " + os.environ["USER"] + " on " + time.asctime(time.gmtime()))
	myBGF.renumber()
	myBGF.saveBGF(out_file)
Пример #29
0
def count_layer(bgf_file, trj_file, ff_file='', out_file=''):
    '''counts number of O atoms in each layer.
    '''
    # variables
    result = dict()

    # 1. Load BGF
    mybgf = bgf.BgfFile(bgf_file)
    N_BGF_ATOMS = len(mybgf.a)
    r_vdw_C = 3.38383824 / 2

    # 2. Read LAMMPS Trajectory
    mytrj = lt.lammpstrj(trj_file)
    timesteps = mytrj.load()
    N_ATOMS = mytrj.natoms[0]
    if N_BGF_ATOMS != N_ATOMS:
        nu.die(
            "Number of atoms in trajectory file does not match with BGF file.")

    # 4. Update coordinates from the snapshot
    for t in tqdm.tqdm(timesteps,
                       ncols=120,
                       desc="Calculating graphene z positions"):
        mybgf = get_timestep(mybgf, trj_file, t)
        avg_gra_z1 = bt.atoms_average(
            mybgf,
            'atom.z',
            selection="'C_2G' in atom.ffType and atom.rNo == 1")
        avg_gra_z2 = bt.atoms_average(
            mybgf,
            'atom.z',
            selection="'C_2G' in atom.ffType and atom.rNo == 2")
        dist = avg_gra_z2 - avg_gra_z1
        eff_dist = avg_gra_z2 - avg_gra_z1 - 2 * r_vdw_C
        result[t] = [avg_gra_z1, avg_gra_z2, dist, eff_dist]

    # 5. Analyze
    timesteps = sorted(result.keys())
    with open('z_position.test.dat', 'w') as f:
        output = ''
        for t in timesteps:
            output += "%d " % t
            output += "%8.3f %8.3f %8.3f %8.3f\n" % result[t]

        f.write(output)
Пример #30
0
def bgf2qcin(bgf_file, qchem_in_file, rem_file):

    # bgf open
    print("Reading " + bgf_file + " ..")
    myBGF = bgf.BgfFile(bgf_file)

    # output
    output = [
        "$comment\n",
        "from " + bgf_file + " at " + time.asctime(time.gmtime()) + " on " +
        os.environ["HOSTNAME"] + " by " + os.environ["USER"] + "\n", "$end\n"
    ]

    # charge and multiplicity
    output += ["\n$molecule\n"]
    chg = myBGF.charge()
    if abs(chg) < 0.000001:
        output += ["0" + "\t" + "1" + "\n"]
    else:
        nu.warn("Charge is not neutral. Charge will be written as " +
                "{0:<4.1f}".format(chg))
        output += ["{0:<4.1f}".format(chg) + "\t" + "1" + "\n"]

    # coordinates
    for atom in myBGF.a:
        output += [
            atom.ffType.split("_")[0] + "\t" +
            "{0:10.6f} {1:10.6f} {2:10.6f}".format(atom.x, atom.y, atom.z) +
            "\n"
        ]

    output += ["$end\n\n"]

    # rem
    remf = open(rem_file)
    remline = remf.readlines()
    output += remline

    # target file
    qcinf = open(qchem_in_file, 'w')
    qcinf.writelines(output)
    qcinf.close()

    print("Generated " + qchem_in_file + " . Done.")