Ejemplo n.º 1
0
def dpth(u):
	L = LeafletFinder(u, 'name P')
	L0 = L.group(0)
	L1 = L.group(1)
	"""bi_cntr = (np.mean(L0.positions,axis=0)[-1]+np.mean(L1.positions,axis=0)[-1])/2"""
	int_cntr=L0.centroid()[-1]
	return int_cntr
Ejemplo n.º 2
0
def density(u, lipid_sel, lipid_heads, lipids, nbins):

    sel = "resname " + str(lipids[str(lipid_sel)]) + " and (name " + str(lipid_heads[str(lipid_sel)] + ")")

    print "Lipid selection = " + str(lipids[str(lipid_sel)])

    # xu, xl, yu, yl, zu, zl = [], [], [], [], [], []

    lip_coord_store = []

    for frame in range(len(u.trajectory)):

        u.trajectory[frame]

        if frame % 10 == 0:

            print frame

        L = LeafletFinder(universe=u, selectionstring=sel)

        leaflet_upper = L.groups(0)
        leaflet_lower = L.groups(1)

        for particle in range(len(leaflet_upper)):

            lip_coord_store.append((leaflet_upper[particle].position[0], leaflet_upper[particle].position[1], leaflet_upper[particle].position[2]))
def determine_leaflets(universe,phosphateSelection):
    '''
    From a selection of phosphates, determine which belong to the upper and lower leaflets.
    
    Keyword arguments:
    universe -- an MDAnalysis Universe object
    phosphateSelection -- a string specifying how to select the phosphate atoms (e.g. "name P1")         
    '''
    leaflets = {}

    # calculate the z value of the phosphates defining the bilayer (assumes bilayer is in x and y..)
    po4=universe.selectAtoms(phosphateSelection)
    bilayerCentre = po4.centerOfGeometry()[2]
    
    # apply the MDAnalysis LeafletFinder graph-based method to determine the two largest groups which
    #  should correspond to the upper and lower leaflets
    phosphates = LeafletFinder(universe,phosphateSelection)

    
    # find the two largest groups - required as the first two returned by LeafletFinder, whilst usually are the largest, this is not always so
    (a,b) = largest_groups(phosphates.sizes())
    
    # check to see where the first leaflet lies
    if phosphates.group(a).centroid()[2] > bilayerCentre:
        leaflets[1] = phosphates.group(a)
        leaflets[2] = phosphates.group(b)
    else:
        leaflets[2] = phosphates.group(a)
        leaflets[1] = phosphates.group(b)

    return leaflets
Ejemplo n.º 4
0
    def estimate_bilayerDist_hack(self, dmin=5.0, dmax=30.0, step=0.5, max_imbalance=0.2):
        """
        DEPRECATED
        """
        for cutoff in np.arange(dmin, dmax, step):
            LF = LeafletFinder(self.universe, self.phosphates, cutoff=cutoff)
            sizes = LF.sizes()
            if len(sizes) < 2:
                continue

            size_values = sizes.values()
            max_val = max(size_values)
            max_index = size_values.index(max_val)
            size_values[max_index] = 0
            second_max_val = max(size_values)
            second_max_index = size_values.index(second_max_val)
          
            imbalance = np.abs(max_val - second_max_val) / (max_val + second_max_val)
            
            print cutoff, len(sizes), imbalance
            if imbalance > max_imbalance:
                break
            else:
                sizes = (cutoff, len(LF.sizes()))
        self.bilayerDist = sizes
Ejemplo n.º 5
0
def test_write_selection(universe, lipid_heads, tmpdir):
    lfls_ag = LeafletFinder(universe, lipid_heads, cutoff=15.0, pbc=True)
    with tmpdir.as_cwd():
        filename = lfls_ag.write_selection('leaflet.vmd')
        expected_output = lines2one([
            """# leaflets based on select=<AtomGroup with 360 atoms> cutoff=15.000000
        # MDAnalysis VMD selection
        atomselect macro leaflet_1 {index 1 13 25 37 49 61 73 85 \\
        97 109 121 133 145 157 169 181 \\
        193 205 217 229 241 253 265 277 \\
        289 301 313 325 337 349 361 373 \\
        385 397 409 421 433 445 457 469 \\
        481 493 505 517 529 541 553 565 \\
        577 589 601 613 625 637 649 661 \\
        673 685 697 709 721 733 745 757 \\
        769 781 793 805 817 829 841 853 \\
        865 877 889 901 913 925 937 949 \\
        961 973 985 997 1009 1021 1033 1045 \\
        1057 1069 1081 1093 1105 1117 1129 1141 \\
        1153 1165 1177 1189 1201 1213 1225 1237 \\
        1249 1261 1273 1285 1297 1309 1321 1333 \\
        1345 1357 1369 1381 1393 1405 1417 1429 \\
        1441 1453 1465 1477 1489 1501 1513 1525 \\
        1537 1549 1561 1573 1585 1597 1609 1621 \\
        1633 1645 1657 1669 1681 1693 1705 1717 \\
        1729 1741 1753 1765 1777 1789 1801 1813 \\
        1825 1837 1849 1861 1873 1885 1897 1909 \\
        1921 1933 1945 1957 1969 1981 1993 2005 \\
        2017 2029 2041 2053 2065 2077 2089 2101 \\
        2113 2125 2137 2149 }
        # MDAnalysis VMD selection
        atomselect macro leaflet_2 {index 2521 2533 2545 2557 2569 2581 2593 2605 \\
        2617 2629 2641 2653 2665 2677 2689 2701 \\
        2713 2725 2737 2749 2761 2773 2785 2797 \\
        2809 2821 2833 2845 2857 2869 2881 2893 \\
        2905 2917 2929 2941 2953 2965 2977 2989 \\
        3001 3013 3025 3037 3049 3061 3073 3085 \\
        3097 3109 3121 3133 3145 3157 3169 3181 \\
        3193 3205 3217 3229 3241 3253 3265 3277 \\
        3289 3301 3313 3325 3337 3349 3361 3373 \\
        3385 3397 3409 3421 3433 3445 3457 3469 \\
        3481 3493 3505 3517 3529 3541 3553 3565 \\
        3577 3589 3601 3613 3625 3637 3649 3661 \\
        3673 3685 3697 3709 3721 3733 3745 3757 \\
        3769 3781 3793 3805 3817 3829 3841 3853 \\
        3865 3877 3889 3901 3913 3925 3937 3949 \\
        3961 3973 3985 3997 4009 4021 4033 4045 \\
        4057 4069 4081 4093 4105 4117 4129 4141 \\
        4153 4165 4177 4189 4201 4213 4225 4237 \\
        4249 4261 4273 4285 4297 4309 4321 4333 \\
        4345 4357 4369 4381 4393 4405 4417 4429 \\
        4441 4453 4465 4477 4489 4501 4513 4525 \\
        4537 4549 4561 4573 4585 4597 4609 4621 \\
        4633 4645 4657 4669 }

"""
        ])

        assert lines2one(open('leaflet.vmd').readlines()) == expected_output
Ejemplo n.º 6
0
def test_pbc_on_off_difference(universe, lipid_heads):
    lfls_pbc_on = LeafletFinder(universe, lipid_heads, cutoff=7, pbc=True)
    lfls_pbc_off = LeafletFinder(universe, lipid_heads, cutoff=7, pbc=False)
    pbc_on_graph = lfls_pbc_on.graph
    pbc_off_graph = lfls_pbc_off.graph
    diff_graph = NX.difference(pbc_on_graph, pbc_off_graph)
    assert_equal(set(diff_graph.edges), {(69, 153), (73, 79), (206, 317),
                                         (313, 319)})
Ejemplo n.º 7
0
def dpth(u, pro_z):
    L = LeafletFinder(u, 'name P')
    L0 = L.group(0)
    L1 = L.group(1)
    """bi_cntr = (np.mean(L0.positions,axis=0)[-1]+np.mean(L1.positions,axis=0)[-1])/2"""
    int_cntr = L1.centroid()[-1]
    bi_cntr_dpth = (pro_z - int_cntr)
    return bi_cntr_dpth
Ejemplo n.º 8
0
def density(u, lipid_sel, lipid_heads, lipids, nbins):

    sel = "resname " + str(lipids[str(lipid_sel)]) + " and (name " + str(
        lipid_heads[str(lipid_sel)] + ")")

    print "Lipid selection = " + str(lipids[str(lipid_sel)])

    xu, yu, xl, yl = [], [], [], []

    for frame in range(len(u.trajectory)):

        u.trajectory[frame]

        # if u.trajectory.frame == 100:
        #     break

        if frame % 10 == 0:

            print frame

        L = LeafletFinder(universe=u, selectionstring=sel)

        leaflet_upper = L.groups(0)
        leaflet_lower = L.groups(1)

        for particle in range(len(leaflet_upper)):

            xu.append(leaflet_upper[particle].position[0])
            yu.append(leaflet_upper[particle].position[1])

        for particle in range(len(leaflet_lower)):

            xl.append(leaflet_lower[particle].position[0])
            yl.append(leaflet_lower[particle].position[1])

    xuedges = np.linspace(np.min(xu), np.max(xu), nbins)
    yuedges = np.linspace(np.min(yu), np.max(yu), nbins)

    xledges = np.linspace(np.min(xl), np.max(xl), nbins)
    yledges = np.linspace(np.min(yl), np.max(yl), nbins)

    H_upper, plot_xu, plot_yu = np.histogram2d(x=xu,
                                               y=yu,
                                               bins=(xuedges, yuedges))
    H_lower, plot_xl, plot_yl = np.histogram2d(x=xl,
                                               y=yl,
                                               bins=(xledges, yledges))

    # compress data for return
    H = [H_upper, H_lower]
    edges = {
        'ul_xedge': xuedges,
        'ul_yedge': yuedges,
        'll_xedge': xledges,
        'll_yedge': yledges
    }

    return lipid_sel, H, edges
Ejemplo n.º 9
0
 def test_leaflet_finder(self):
     from MDAnalysis.analysis.leaflet import LeafletFinder
     lfls = LeafletFinder(self.universe, self.lipid_heads, pbc=True)
     top_heads, bottom_heads = lfls.groups()
     # Make top be... on top.
     if top_heads.center_of_geometry()[2] < bottom_heads.center_of_geometry()[2]:
         top_heads,bottom_heads = (bottom_heads,top_heads)
     assert_equal(top_heads.indices, np.arange(1,2150,12), err_msg="Found wrong leaflet lipids")
     assert_equal(bottom_heads.indices, np.arange(2521,4670,12), err_msg="Found wrong leaflet lipids")
Ejemplo n.º 10
0
    def __init__(self, prefix, pre_out=None):
        """
        Reads .data and .xtc into universe
        Defines static atomgroups based on type
        Reads parameter values (nsteps, nlipids)
        Initiates bbox and leaflets based on first frame
        Initiates dictionary out for storage of data
        Writes lipid type to out['lip']
        """
        if not pre_out:
            self.pre_out = prefix
        else:
            self.pre_out = pre_out
        
        self.u = mda.Universe(prefix + '.data', prefix + '.xtc')
        self.ref = mda.Universe(prefix + '.data')
        self.nsteps = len(self.u.trajectory)
        self.ts = 0

        b = self.u.trajectory[0].dimensions[0:3]
        self.bbox = np.array([0, 0, 0, b[0], b[1], b[2]]).reshape(2,3)
        
        # Define atomgroups
        self.atomgroups = {}
        self.atomgroups['nc3'] = self.u.select_atoms('type 1', updating=True)
        self.atomgroups['dopc'] = self.u.select_atoms('type 2', updating=True)
        self.atomgroups['dogl'] = self.u.select_atoms('type 9', updating=True)
        self.atomgroups['tails'] = self.u.select_atoms('type 7', updating=True)
        self.atomgroups['heads'] = self.u.select_atoms('type 2 9', updating=True)
        self.dnlipids = len(self.atomgroups['heads'])

        self.membranes = {}

        # Set leaflets
        self.leaflets = LeafletFinder(self.u, self.atomgroups['dopc'], cutoff=15, pbc=True)
        sizes = np.array(list(self.leaflets.sizes().values()))
        l = [self.leaflets.groups(i) for i in np.argsort(-sizes)[:2]]
        if l[0].center_of_geometry()[2] > l[1].center_of_geometry()[2]:
            self.atomgroups['ul_dopc'], self.atomgroups['ll_dopc'] = l[0], l[1]
        else:
            self.atomgroups['ul_dopc'], self.atomgroups['ll_dopc'] = l[1], l[0]

        # Make out dict
        self.out = {'lip':[],'r':[], 's': [], 'j': [], 'k': [], 'd': [], 'rho': [], 'l': [], 'apl': [], 'd_nc3':[]}
        self.out_box = []

        for key in self.out.keys():
            self.out[key] = [[] for i in range(len(self.atomgroups['heads']))]
            
        # Add lipid types to out['lip']
        for head in self.atomgroups['heads']:
            if head in self.atomgroups['dopc']:
                self.out['lip'][head.resid - 1] = 'dopc'
            else:
                self.out['lip'][head.resid - 1] = 'dogl'
Ejemplo n.º 11
0
def test_sparse_on_off_none(universe, lipid_heads, sparse):
    lfls_ag = LeafletFinder(universe,
                            lipid_heads,
                            cutoff=15.0,
                            pbc=True,
                            sparse=sparse)
    assert_almost_equal(len(lfls_ag.graph.edges), 1903, decimal=4)
Ejemplo n.º 12
0
def determine_leaflets(universe, phosphateSelection="name P*"):
    '''
    From a selection of phosphates, determine which belong to the upper and lower leaflets.
    Keyword arguments:
    universe -- an MDAnalysis Universe object
    phosphateSelection -- a string specifying how to select the phosphate atoms (e.g. "name P1")
    '''
    leaflets = {}
    #print(universe)
    # calculate the z value of the phosphates defining the bilayer (assumes bilayer is in x and y..)
    #po4=universe.atoms.select_atoms(phosphateSelection)
    #bilayerCentre = po4.center_of_geometry()[2]
    #print(bilayerCentre)

    # apply the MDAnalysis LeafletFinder graph-based method to determine the two largest groups which
    #  should correspond to the upper and lower leaflets
    phosphates = LeafletFinder(universe, phosphateSelection)

    # find the two largest groups - required as the first two returned by LeafletFinder, whilst usually are the largest, this is not always so
    (a, b) = largest_groups(phosphates.sizes())
    layer1_avz = np.mean(phosphates.group(a).center_of_geometry()[2])
    layer2_avz = np.mean(phosphates.group(b).center_of_geometry()[2])
    bilayerCentre = (layer1_avz + layer2_avz) / 2.
    # check to see where the first leaflet lies
    if phosphates.group(a).centroid()[2] > bilayerCentre:
        #print(phosphates.group(b).residues.atoms)
        leaflets["upper"] = phosphates.group(a).residues.atoms
        leaflets["lower"] = phosphates.group(b).residues.atoms
    else:
        leaflets["lower"] = phosphates.group(a).residues.atoms
        leaflets["upper"] = phosphates.group(b).residues.atoms

    return leaflets
Ejemplo n.º 13
0
def test_string_vs_atomgroup_proper(universe, lipid_heads):
    lfls_ag = LeafletFinder(universe, lipid_heads, pbc=True)
    lfls_string = LeafletFinder(universe, LIPID_HEAD_STRING, pbc=True)
    groups_ag = lfls_ag.groups()
    groups_string = lfls_string.groups()
    assert_equal(groups_string[0].indices, groups_ag[0].indices)
    assert_equal(groups_string[1].indices, groups_ag[1].indices)
Ejemplo n.º 14
0
 def test_string_vs_atomgroup_proper(self):
     from MDAnalysis.analysis.leaflet import LeafletFinder
     lfls_ag = LeafletFinder(self.universe, self.lipid_heads, pbc=True)
     lfls_string = LeafletFinder(self.universe, self.lipid_head_string, pbc=True)
     groups_ag = lfls_ag.groups()
     groups_string = lfls_string.groups()
     assert_equal(groups_string[0].indices, groups_ag[0].indices)
     assert_equal(groups_string[1].indices, groups_ag[1].indices)
Ejemplo n.º 15
0
def mbrane_density(u, lipid_heads, lipid_heads_z, lipids):

    print "Analysing lipids..."

    #u.trajectory[-1]

    half_box = u.dimensions[2] / 2

    for frame in range(len(u.trajectory)):

        u.trajectory[frame]

        print frame

        for lipid in lipids:

            sel = "resname " + str(
                lipids[lipid]) + " and (name " + str(lipid_heads[lipid] + ")")

            L = LeafletFinder(universe=u, selectionstring=sel, pbc=False)

            leaflet_upper = L.groups(0)
            leaflet_lower = L.groups(1)

            #com_upper = leaflet_upper.center_of_geometry()

            for particle in range(len(leaflet_upper)):
                lipid_heads_z[lipid]['z'].append(
                    leaflet_upper[particle].position[2])

            for particle in range(len(leaflet_lower)):
                lipid_heads_z[lipid]['z'].append(
                    leaflet_lower[particle].position[2])

    lipid_z_populated = lipid_heads_z

    return lipid_z_populated
def Calculate_director_density():
    pass

parser = argparse.ArgumentParser()
parser.add_argument("--echo", help = "echo the string you use here")
parser.add_argument("--square", help = "display a square of a given number", type = int)

args = parser.parse_args()
if args.square:
    print(args.square**2)
elif args.echo:
    print(args.echo)

u = MDAnalysis.Universe("min_bilayer_NP.gro", "traj_comp.xtc")

L = LeafletFinder(u,'name PO4')
leaflet0 = L.groups(0)
leaflet1 = L.groups(1)

l1_id = leaflet0.resids
l2_id = leaflet1.resids

for ids in l1_id:
    residue_id = "resid {}".format(ids)
    head_position = u.select_atoms(residue_id).select_atoms('name PO4')
    tail_position1 = u.select_atoms(residue_id).select_atoms('name C3A or name D3A')
    tail_position2 = u.select_atoms(residue_id).select_atoms('name C3B or name D3B')
    #print(head_position.positions, tail_position1.positions, tail_position2.positions) 
    print(calc_vec(tail_position1.positions[0][0], head_position.positions[0][0], tail_position1.positions[0][1], head_position.positions[0][1], tail_position1.positions[0][2], head_position.positions[0][2]), ids)
    #print (A)
for ids in l2_id:
    canningSigma=2.0
    gaussianSigma=8.0
        
    u = MDAnalysis.Universe("test.pdb")
        
    # create an array with the maximum number of pixels (voxels)
    originalNumberPixels = numpy.array([int((u.dimensions[0]*1.1) * pixelWidth),int((u.dimensions[1]*1.1) * pixelWidth),int((u.dimensions[2]*1.1) * pixelWidth)])

    speciesList = ['unsaturated','saturated','cholesterol']

    # find out where the centre of the bilayer lies
    bilayer = u.select_atoms("name PO4 or name ROH")
    bilayerCentre = bilayer.center_of_geometry()[2]
    
    # use the MDAnalysis analysis function LeafletFinder to identify the two bilayers
    bilayerLeaflets = LeafletFinder(u,'name PO4 or name ROH')
    bilayerLeaflet = {}

    # check to see where the first leaflet lies
    if bilayerLeaflets.group(0).centroid()[2] > bilayerCentre:
        leafletList = ["upper","lower"]
    else:
        leafletList = ["lower","upper"]            
    
    imageLookup = {}
    imageLookup['unsaturated'] = {'colour': 'Blues', 'range': [0,0.0240], 'sigma': 4.1, 'ticks': [0,0.012,0.024]}
    imageLookup['saturated'] = {'colour': 'Reds', 'range': [0,0.0240], 'sigma': 4.1, 'ticks': [0,0.012,0.024]}
    imageLookup['cholesterol'] = {'colour': 'Purples', 'range': [0,0.0240], 'sigma': 4.1, 'ticks': [0,0.012,0.024]}
    imageLookup['mask'] = {'colour': 'RdBu', 'range': [-0.2,1.2], 'ticks': [0,1]}
    imageLookup['edges'] = {'colour': 'Greys', 'range': [0,1], 'ticks': [0,1]}
    
    u = MDAnalysis.Universe(options.topology, structure)

    if options.optimize:
        print "# Finding best cutoff (--optimize)..."
        try:
            cutoff, N = optimize_cutoff(u, options.selection, pbc=options.pbc,
                                        max_imbalance=options.max_imbalance)
        except:
            raise RuntimeError("Failed cutoff optimization, try without --optimize")
        print "# Optimized cutoff={cutoff:.1f} A, finding {N:d} disconnected groups".format(**vars())
    else:
        cutoff = options.cutoff
        print "# Using fixed cutoff={cutoff:.1f} A".format(**vars())

    LF = LeafletFinder(u, options.selection, cutoff=cutoff, pbc=options.pbc)

    print "# group sizes = {0!r} ".format(LF.sizes())

    # two leaflets
    def print_line(symbol="-"):
        print "#" + (12 + 5) * symbol

    print_line("=")
    print "#{0!s:>2}  {1!s:>5}  {2!s:>6}".format("ll", "resn", "count")
    print_line("=")

    for groupindex in xrange(len(LF.components)):
        resnames = [a.resname for a in LF.groups(groupindex)]
        # there CERTAINLY is a better way to count occurrences than this...
        keys = np.unique(resnames)
Ejemplo n.º 19
0
  3. analyse first and second largest graph (assume they are the
     leaflets, anything else are stray micelles or individually
     floating lipids)

One could identify group 1 and 2 as upper and lower leaflet by
comparing the median of the centres of masses; this is left as an
exercise...
"""
import numpy
import MDAnalysis
from MDAnalysis.analysis.leaflet import LeafletFinder


if __name__ == "__main__":
    import sys

    try:
        PDB, selection = sys.argv[1:3]
    except ValueError:
        print "usage: leaflet.py PDB SELECTION"
        sys.exit(1)
    print "PDB=%(PDB)r selection=%(selection)r" % vars()
    L = LeafletFinder(PDB, selection)
    print "Number of lipids in leaflets: %r" % L.sizes()
    macrovmd = PDB + ".vmd"
    L.write_vmd(macrovmd)
    print "Load macros for vmd from file %r" % macrovmd
    


Ejemplo n.º 20
0
    if not options.topology:
        options.topology = structure

    u = MDAnalysis.Universe(options.topology, structure)

    if options.optimize:
        print "# Finding best cutoff (--optimize)..."
        try:
            cutoff, N = optimize_cutoff(u,
                                        options.selection,
                                        pbc=options.pbc,
                                        max_imbalance=options.max_imbalance)
        except:
            raise RuntimeError(
                "Failed cutoff optimization, try without --optimize")
        print "# Optimized cutoff=%(cutoff).1f A, finding %(N)d disconnected groups" % vars(
        )
    else:
        cutoff = options.cutoff
        print "# Using fixed cutoff=%(cutoff).1f A" % vars()

    LF = LeafletFinder(u, options.selection, cutoff=cutoff, pbc=options.pbc)
    p = get_membrane_parameters(u, LF)

    # show results
    print "#" + 60 * "="
    print "thickness tmem = %(thickness).2f A" % p
    print "center    zmem = %(zmem).2f A" % p
    print "#" + 60 * "="
Ejemplo n.º 21
0
def dpth(u):
	L = LeafletFinder(u, 'name P')
	L0 = L.group(0)
	L1 = L.group(1)
	"""bi_cntr = (np.mean(L0.positions,axis=0)[-1]+np.mean(L1.positions,axis=0)[-1])/2"""
	int_cntr=L0.centroid()[-1]
	return int_cntr


if __name__ == "__main__":
    u = MDAnalysis.Universe("gs_dopc_laur.gro","gs_dopc_laur_small.trr")
    #dye=u.select_atoms("resid 28662 and (type N or type O or name C24)", updating = True)
    dye=u.select_atoms("resid 28663 and (not type H)", updating = True)
    leaflet_P = u.select_atoms("name P", updating = True)
    L = LeafletFinder(u, 'name P')
    L0 = L.group(0)
    L1 = L.group(1)
    data=np.empty([len(dye)+1,len(u.trajectory)])  
    for i, ts in enumerate(tqdm.tqdm(u.trajectory[0::1])):
        leaflet_pos_z = L1.centroid()[-1]        
        for j, atom in enumerate(dye):
            data[0,i] = u.trajectory.time
            atom_z = atom.position[-1]
            distance_atom_bound = - atom_z + leaflet_pos_z
            data[j+1,i] = distance_atom_bound
    ax = sns.heatmap(data[1:,:], xticklabels = 1000)
    
	#plotting
    i=0
    fig = plt.figure(figsize=(24,8))	
Ejemplo n.º 22
0
def test_cutoff_update_default(universe, lipid_heads):
    lfls_ag = LeafletFinder(universe, lipid_heads, cutoff=15.0, pbc=True)
    lfls_ag.update()
    assert_almost_equal(lfls_ag.cutoff, 15.0, decimal=4)
    assert_almost_equal(len(lfls_ag.groups()), 2, decimal=4)
    # create an array with the maximum number of pixels (voxels)
    originalNumberPixels = numpy.array([
        int((u.dimensions[0] * 1.1) * pixelWidth),
        int((u.dimensions[1] * 1.1) * pixelWidth),
        int((u.dimensions[2] * 1.1) * pixelWidth)
    ])

    speciesList = ['unsaturated', 'saturated', 'cholesterol']

    # find out where the centre of the bilayer lies
    bilayer = u.select_atoms("name PO4 or name ROH")
    bilayerCentre = bilayer.center_of_geometry()[2]

    # use the MDAnalysis analysis function LeafletFinder to identify the two bilayers
    bilayerLeaflets = LeafletFinder(u, 'name PO4 or name ROH')
    bilayerLeaflet = {}

    # check to see where the first leaflet lies
    if bilayerLeaflets.group(0).centroid()[2] > bilayerCentre:
        leafletList = ["upper", "lower"]
    else:
        leafletList = ["lower", "upper"]

    imageLookup = {}
    imageLookup['unsaturated'] = {
        'colour': 'Blues',
        'range': [0, 0.0240],
        'sigma': 4.1,
        'ticks': [0, 0.012, 0.024]
    }
Ejemplo n.º 24
0
        print "# Finding best cutoff (--optimize)..."
        try:
            cutoff, N = optimize_cutoff(u,
                                        options.selection,
                                        pbc=options.pbc,
                                        max_imbalance=options.max_imbalance)
        except:
            raise RuntimeError(
                "Failed cutoff optimization, try without --optimize")
        print "# Optimized cutoff={cutoff:.1f} A, finding {N:d} disconnected groups".format(
            **vars())
    else:
        cutoff = options.cutoff
        print "# Using fixed cutoff={cutoff:.1f} A".format(**vars())

    LF = LeafletFinder(u, options.selection, cutoff=cutoff, pbc=options.pbc)

    print "# group sizes = {0!r} ".format(LF.sizes())

    # two leaflets
    def print_line(symbol="-"):
        print "#" + (12 + 5) * symbol

    print_line("=")
    print "#{0!s:>2}  {1!s:>5}  {2!s:>6}".format("ll", "resn", "count")
    print_line("=")

    for groupindex in xrange(len(LF.components)):
        resnames = [a.resname for a in LF.groups(groupindex)]
        # there CERTAINLY is a better way to count occurrences than this...
        keys = np.unique(resnames)
Ejemplo n.º 25
0
    u = MDAnalysis.Universe(options.topology, structure)

    if options.optimize:
        print "# Finding best cutoff (--optimize)..."
        try:
            cutoff, N = optimize_cutoff(u, options.selection, pbc=options.pbc,
                                        max_imbalance=options.max_imbalance)
        except:
            raise RuntimeError("Failed cutoff optimization, try without --optimize")
        print "# Optimized cutoff=%(cutoff).1f A, finding %(N)d disconnected groups" % vars()
    else:
        cutoff = options.cutoff
        print "# Using fixed cutoff=%(cutoff).1f A" % vars()

    LF = LeafletFinder(u, options.selection, cutoff=cutoff, pbc=options.pbc)

    print "# group sizes = %r " % LF.sizes()

    # two leaflets
    def print_line(symbol="-"):
        print "#" + (12 + 5) * symbol

    print_line("=")
    print "#%2s  %5s  %6s" % ("ll", "resn", "count")
    print_line("=")

    for groupindex in xrange(len(LF.components)):
        resnames = [a.resname for a in LF.groups(groupindex)]
        # there CERTAINLY is a better way to count occurrences than this...
        keys = np.unique(resnames)
Ejemplo n.º 26
0
def test_component_index_is_not_none(universe, lipid_heads):
    lfls_ag = LeafletFinder(universe, lipid_heads, cutoff=15.0, pbc=True)
    assert_almost_equal(len(lfls_ag.groups(component_index=0)), 180, decimal=4)
Ejemplo n.º 27
0
def test_pbc_on_off(universe, lipid_heads):
    lfls_pbc_on = LeafletFinder(universe, lipid_heads, pbc=True)
    lfls_pbc_off = LeafletFinder(universe, lipid_heads, pbc=False)
    assert lfls_pbc_on.graph.size() > lfls_pbc_off.graph.size()
Ejemplo n.º 28
0
        defFlipFlopHeadgroups += i.getNoneLeafletSelection(syst)

    #LOGGER.info('FlipFlopHeadgroups = {}'.format(defFlipFlopHeadgroups))

    # --------------------------------------------------------------------------
    # Define top/bottom leaflets

    # Get beads that define the bilayer leaflets
    # (not in bilayer middle, but closly packed, use linker + first tail bead of lipids that do not flip-flop)
    defHeadgroups = MDAnalysis.core.groups.AtomGroup([], syst)
    for i in list(lipidTypeDic.values()):
        defHeadgroups += i.getLeafletSelection(syst)

    # get leaflets
    rcutoff, n = optimize_cutoff(syst, defHeadgroups)
    lfls = LeafletFinder(syst, defHeadgroups, cutoff=rcutoff, pbc=True)

    grps = lfls.groups()

    if len(grps) == 2:
        LOGGER.info('Found {} leaflet groups'.format(len(grps)))

    # check if they're even
    top_head = grps[0]
    bot_head = grps[1]

    rt = float(len(top_head)) / len(bot_head)
    if rt > 1.3 or rt < 0.77:
        raise ValueError('Found uneven leaflets. top = {}, bot = {}'.format(
            len(top_head), len(bot_head)))
Ejemplo n.º 29
0
more sophisticated example.

LeafletFinder Algorithm
-----------------------
  1. build a graph of all phosphate distances < cutoff
  2. identify the largest connected subgraphs
  3. analyse first and second largest graph (assume they are the
     leaflets, anything else are stray micelles or individually
     floating lipids)

One could identify group 1 and 2 as upper and lower leaflet by
comparing the median of the centres of masses; this is left as an
exercise...
"""
from MDAnalysis.analysis.leaflet import LeafletFinder

if __name__ == "__main__":
    import sys

    try:
        PDB, selection = sys.argv[1:3]
    except ValueError:
        print "usage: leaflet.py PDB SELECTION"
        sys.exit(1)
    print "PDB=%(PDB)r selection=%(selection)r" % vars()
    L = LeafletFinder(PDB, selection)
    print "Number of lipids in leaflets: %r" % L.sizes()
    macrovmd = PDB + ".vmd"
    L.write_vmd(macrovmd)
    print "Load macros for vmd from file %r" % macrovmd
Ejemplo n.º 30
0
class mem_analysis:
    """
    Class for analysis of membranes from .data and .xtc files
    """

    def __init__(self, prefix, pre_out=None):
        """
        Reads .data and .xtc into universe
        Defines static atomgroups based on type
        Reads parameter values (nsteps, nlipids)
        Initiates bbox and leaflets based on first frame
        Initiates dictionary out for storage of data
        Writes lipid type to out['lip']
        """
        if not pre_out:
            self.pre_out = prefix
        else:
            self.pre_out = pre_out
        
        self.u = mda.Universe(prefix + '.data', prefix + '.xtc')
        self.ref = mda.Universe(prefix + '.data')
        self.nsteps = len(self.u.trajectory)
        self.ts = 0

        b = self.u.trajectory[0].dimensions[0:3]
        self.bbox = np.array([0, 0, 0, b[0], b[1], b[2]]).reshape(2,3)
        
        # Define atomgroups
        self.atomgroups = {}
        self.atomgroups['nc3'] = self.u.select_atoms('type 1', updating=True)
        self.atomgroups['dopc'] = self.u.select_atoms('type 2', updating=True)
        self.atomgroups['dogl'] = self.u.select_atoms('type 9', updating=True)
        self.atomgroups['tails'] = self.u.select_atoms('type 7', updating=True)
        self.atomgroups['heads'] = self.u.select_atoms('type 2 9', updating=True)
        self.dnlipids = len(self.atomgroups['heads'])

        self.membranes = {}

        # Set leaflets
        self.leaflets = LeafletFinder(self.u, self.atomgroups['dopc'], cutoff=15, pbc=True)
        sizes = np.array(list(self.leaflets.sizes().values()))
        l = [self.leaflets.groups(i) for i in np.argsort(-sizes)[:2]]
        if l[0].center_of_geometry()[2] > l[1].center_of_geometry()[2]:
            self.atomgroups['ul_dopc'], self.atomgroups['ll_dopc'] = l[0], l[1]
        else:
            self.atomgroups['ul_dopc'], self.atomgroups['ll_dopc'] = l[1], l[0]

        # Make out dict
        self.out = {'lip':[],'r':[], 's': [], 'j': [], 'k': [], 'd': [], 'rho': [], 'l': [], 'apl': [], 'd_nc3':[]}
        self.out_box = []

        for key in self.out.keys():
            self.out[key] = [[] for i in range(len(self.atomgroups['heads']))]
            
        # Add lipid types to out['lip']
        for head in self.atomgroups['heads']:
            if head in self.atomgroups['dopc']:
                self.out['lip'][head.resid - 1] = 'dopc'
            else:
                self.out['lip'][head.resid - 1] = 'dogl'

    def update_membranes(self):
        """
        Computes all membranes 
        Updates dynamic atomgroups
        """

        self.membranes['ul_dopc'] = Membrane(self.atomgroups['ul_dopc'].atoms.positions, labels=self.atomgroups['ul_dopc'].atoms.resids, periodic=True, bbox=self.bbox, boundary_layer=0.5)
        self.membranes['ul_dopc'].fit_points_to_box_xy()
        self.membranes['ul_dopc'].compute_pnormals(knbrs=36)
        self.membranes['ul_dopc'].compute_approx_surface(exactness_level=8)
        self.membranes['ul_dopc'].compute_membrane_surface()
        self.membranes['ul_dopc'].compute_properties()

        self.membranes['ll_dopc'] = Membrane(self.atomgroups['ll_dopc'].atoms.positions, labels=self.atomgroups['ll_dopc'].atoms.resids, periodic=True, bbox=self.bbox, boundary_layer=0.5)
        self.membranes['ll_dopc'].fit_points_to_box_xy()
        self.membranes['ll_dopc'].compute_pnormals(knbrs=36)
        self.membranes['ll_dopc'].compute_approx_surface(exactness_level=8)
        self.membranes['ll_dopc'].compute_membrane_surface()
        self.membranes['ll_dopc'].compute_properties()
        
        Membrane.compute_thickness(self.membranes['ul_dopc'], self.membranes['ll_dopc'])
        
        # Generate NC3 membranes
        self.atomgroups['ul_nc3'] = self.u.select_atoms('resid ' + ' '.join(map(str, self.atomgroups['ul_dopc'].atoms.resids))).intersection(self.atomgroups['nc3'])
        self.atomgroups['ll_nc3'] = self.u.select_atoms('resid ' + ' '.join(map(str, self.atomgroups['ll_dopc'].atoms.resids))).intersection(self.atomgroups['nc3'])

        self.membranes['ul_nc3'] = Membrane(self.atomgroups['ul_nc3'].atoms.positions, labels=self.atomgroups['ul_nc3'].atoms.resids, periodic=True, bbox=self.bbox, boundary_layer=0.5)
        self.membranes['ul_nc3'].fit_points_to_box_xy()
        self.membranes['ul_nc3'].compute_pnormals(knbrs=36)
        self.membranes['ul_nc3'].compute_approx_surface(exactness_level=8)
        self.membranes['ul_nc3'].compute_membrane_surface()
        self.membranes['ul_nc3'].compute_properties()

        self.membranes['ll_nc3'] = Membrane(self.atomgroups['ll_nc3'].atoms.positions, labels=self.atomgroups['ll_nc3'].atoms.resids, periodic=True, bbox=self.bbox, boundary_layer=0.5)
        self.membranes['ll_nc3'].fit_points_to_box_xy()
        self.membranes['ll_nc3'].compute_pnormals(knbrs=36)
        self.membranes['ll_nc3'].compute_approx_surface(exactness_level=8)
        self.membranes['ll_nc3'].compute_membrane_surface()
        self.membranes['ll_nc3'].compute_properties()

        # Compute all distances from dogl to closest membrane and determine upper / lower / flipflop
        self.membranes['dogl'] = Membrane.compute(self.atomgroups['dogl'].atoms.positions, self.atomgroups['dogl'].atoms.resids, periodic=True, bbox=self.bbox)
        
        Membrane.compute_thickness(self.membranes['dogl'], self.membranes['ul_nc3'], mtype='exact')
        self.ul_dogl_dist = np.column_stack((self.membranes['dogl'].labels, self.membranes['dogl'].properties['thickness']))
        ul_dogl_labels = np.array([int(lip[0]) for lip in self.ul_dogl_dist if lip[1] < flipflop_offset])
        if len(ul_dogl_labels) > 0:
            self.atomgroups['ul_dogl'] = self.u.select_atoms('resid ' + ' '.join(map(str, ul_dogl_labels))).intersection(self.atomgroups['dogl'])
        else:
            self.atomgroups['ul_dogl'] = self.u.atoms[[]]
        
        Membrane.compute_thickness(self.membranes['dogl'], self.membranes['ll_nc3'], mtype='exact')
        self.ll_dogl_dist = np.column_stack((self.membranes['dogl'].labels, self.membranes['dogl'].properties['thickness']))
        ll_dogl_labels = np.array([int(lip[0]) for lip in self.ll_dogl_dist if lip[1] < flipflop_offset])
        if len(ll_dogl_labels) > 0:
            self.atomgroups['ll_dogl'] = self.u.select_atoms('resid ' + ' '.join(map(str, ll_dogl_labels))).intersection(self.atomgroups['dogl'])
        else:
            self.atomgroups['ll_dogl'] = self.u.atoms[[]]

        # Generate ff_dogl membrane from lipids not in ul and ll
        ff_dogl_labels = np.array([lip for lip in self.membranes['dogl'].labels if lip not in np.union1d(ul_dogl_labels, ll_dogl_labels)])
        if len(ff_dogl_labels) > 0:
            self.atomgroups['ff_dogl'] = self.u.select_atoms('resid ' + ' '.join(map(str, ff_dogl_labels))).intersection(self.atomgroups['dogl'])
        else:
            self.atomgroups['ff_dogl'] = self.u.atoms[[]]

        # Generate combines membranes         
        self.atomgroups['ul'] = self.atomgroups['ul_dopc'] + self.atomgroups['ul_dogl']
        self.atomgroups['ll'] = self.atomgroups['ll_dopc'] + self.atomgroups['ll_dogl']

        self.membranes['ul'] = Membrane(self.atomgroups['ul'].atoms.positions, labels=self.atomgroups['ul'].atoms.resids, periodic=True, bbox=self.bbox, boundary_layer=0.5)
        self.membranes['ul'].fit_points_to_box_xy()
        self.membranes['ul'].compute_pnormals(knbrs=36)
        self.membranes['ul'].compute_approx_surface(exactness_level=8)
        self.membranes['ul'].compute_membrane_surface()
        self.membranes['ul'].compute_properties()
        
        self.membranes['ll'] = Membrane(self.atomgroups['ll'].atoms.positions, labels=self.atomgroups['ll'].atoms.resids, periodic=True, bbox=self.bbox, boundary_layer=0.5)
        self.membranes['ll'].fit_points_to_box_xy()
        self.membranes['ll'].compute_pnormals(knbrs=36)
        self.membranes['ll'].compute_approx_surface(exactness_level=8)
        self.membranes['ll'].compute_membrane_surface()
        self.membranes['ll'].compute_properties()
        
        # Compute thickness and densities
        self.membranes['ul'].compute_density(rho_type, sigma, 'density', True, self.membranes['ul'].labels)
        self.membranes['ll'].compute_density(rho_type, sigma, 'density', True, self.membranes['ll'].labels)
        Membrane.compute_thickness(self.membranes['ul_nc3'], self.membranes['ll_nc3'])

        for key in self.membranes:
            self.membranes[key].write_all(self.pre_out + '/' + key + '_' + str(self.ts))

    def write_to_out(self):
    		"""
    		Save all lipids to self.out. Switch case for lipid type and u/l/f
    		"""
        for head in self.atomgroups['heads']:
            if head in self.atomgroups['ul_dopc']:
                i_ul_dopc = np.where(self.membranes['ul_dopc'].labels==head.resid)[0][0]
                i_ul_nc3 = np.where(self.membranes['ul_nc3'].labels==head.resid)[0][0]
                i_ul = np.where(self.membranes['ul'].labels==head.resid)[0][0]
                
                self.out['l'][head.resid - 1].append('u')
                self.out['r'][head.resid - 1].append(head.position)

                self.out['d'][head.resid - 1].append('na')
                self.out['d_nc3'][head.resid - 1].append(self.membranes['ul_nc3'].properties['thickness'][i_ul_nc3])

                self.out['rho'][head.resid - 1].append(self.membranes['ul'].properties['density'][i_ul])
                self.out['j'][head.resid - 1].append(self.membranes['ul'].memb_smooth.mean_curv[i_ul])
                self.out['k'][head.resid - 1].append(self.membranes['ul'].memb_smooth.gaus_curv[i_ul])
                self.out['apl'][head.resid - 1].append(self.membranes['ul'].memb_smooth.pareas[i_ul])

            elif head in self.atomgroups['ll_dopc']:
                i_ll_dopc = np.where(self.membranes['ll_dopc'].labels==head.resid)[0][0]
                i_ll_nc3 = np.where(self.membranes['ll_nc3'].labels==head.resid)[0][0]
                i_ll = np.where(self.membranes['ll'].labels==head.resid)[0][0]
                
                self.out['l'][head.resid - 1].append('l')
                self.out['r'][head.resid - 1].append(head.position)

                self.out['d'][head.resid - 1].append('na')
                self.out['d_nc3'][head.resid - 1].append(self.membranes['ll_nc3'].properties['thickness'][i_ll_nc3])

                self.out['rho'][head.resid - 1].append(self.membranes['ll'].properties['density'][i_ll])
                self.out['j'][head.resid - 1].append(self.membranes['ll'].memb_smooth.mean_curv[i_ll])
                self.out['k'][head.resid - 1].append(self.membranes['ll'].memb_smooth.gaus_curv[i_ll])
                self.out['apl'][head.resid - 1].append(self.membranes['ll'].memb_smooth.pareas[i_ll])

            elif head in self.atomgroups['ul_dogl']:
                i_ul = np.where(self.membranes['ul'].labels==head.resid)[0][0]
                
                self.out['l'][head.resid - 1].append('u')
                self.out['r'][head.resid - 1].append(head.position)

                d_ul = self.ul_dogl_dist[self.ul_dogl_dist[:,0]==head.resid, 1]
                d_ll = self.ll_dogl_dist[self.ll_dogl_dist[:,0]==head.resid, 1]
                self.out['d'][head.resid - 1].append([d_ul, d_ll])
                
                self.out['d_nc3'][head.resid - 1].append('na')

                self.out['rho'][head.resid - 1].append(self.membranes['ul'].properties['density'][i_ul])
                self.out['j'][head.resid - 1].append(self.membranes['ul'].memb_smooth.mean_curv[i_ul])
                self.out['k'][head.resid - 1].append(self.membranes['ul'].memb_smooth.gaus_curv[i_ul])
                self.out['apl'][head.resid - 1].append(self.membranes['ul'].memb_smooth.pareas[i_ul])

            elif head in self.atomgroups['ll_dogl']:
                i_ll = np.where(self.membranes['ll'].labels==head.resid)[0][0]
                
                self.out['l'][head.resid - 1].append('l')
                self.out['r'][head.resid - 1].append(head.position)

                d_ul = self.ul_dogl_dist[self.ul_dogl_dist[:,0]==head.resid, 1]
                d_ll = self.ll_dogl_dist[self.ll_dogl_dist[:,0]==head.resid, 1]
                self.out['d'][head.resid - 1].append([d_ul, d_ll])
                self.out['d_nc3'][head.resid - 1].append('na')

                self.out['rho'][head.resid - 1].append(self.membranes['ll'].properties['density'][i_ll])
                self.out['j'][head.resid - 1].append(self.membranes['ll'].memb_smooth.mean_curv[i_ll])
                self.out['k'][head.resid - 1].append(self.membranes['ll'].memb_smooth.gaus_curv[i_ll])
                self.out['apl'][head.resid - 1].append(self.membranes['ll'].memb_smooth.pareas[i_ll])

            elif head in self.atomgroups['ff_dogl']:
                self.out['l'][head.resid - 1].append('f')
                self.out['r'][head.resid - 1].append(head.position)

                d_ul = self.ul_dogl_dist[self.ul_dogl_dist[:,0]==head.resid, 1]
                d_ll = self.ll_dogl_dist[self.ll_dogl_dist[:,0]==head.resid, 1]
                self.out['d'][head.resid - 1].append([d_ul, d_ll])

                self.out['d_nc3'][head.resid - 1].append('na')

                self.out['rho'][head.resid - 1].append('na')
                self.out['j'][head.resid - 1].append('na')
                self.out['k'][head.resid - 1].append('na')
                self.out['apl'][head.resid - 1].append('na')

    def write_to_json(self):
        with open(self.pre_out + '.json', 'w') as f:
            json.dump(self.out, f, cls=NumpyEncoder)

    def run(self, trange=None):
        """
        Loops over trajectory
        Update ul_dopc and ll_dopc every n steps (dopc's generally don't flipflop)
        Call update_membranes to recalculate membranes
        Call write_out to add properties to self.out
        """
        if not trange:
            trange = (0, self.nsteps)
        elif len(trange) == 1:
            trange = (trange[0], self.nsteps)

        print(trange)
        print(len(self.u.trajectory))
        
        for ts in self.u.trajectory[trange[0] : trange[1] : 1]:
            print(ts.frame)
            self.ts = ts.frame
            b = ts.dimensions[0:3]
            self.bbox = np.array([0,0,0, b[0], b[1], b[2]]).reshape(2,3)
            self.out_box.append(self.bbox)

            self.update_membranes()
            self.write_to_out()

        self.write_to_json()
Ejemplo n.º 31
0
more sophisticated example.

LeafletFinder Algorithm
-----------------------
  1. build a graph of all phosphate distances < cutoff
  2. identify the largest connected subgraphs
  3. analyse first and second largest graph (assume they are the
     leaflets, anything else are stray micelles or individually
     floating lipids)

One could identify group 1 and 2 as upper and lower leaflet by
comparing the median of the centres of masses; this is left as an
exercise...
"""
from MDAnalysis.analysis.leaflet import LeafletFinder

if __name__ == "__main__":
    import sys

    try:
        PDB, selection = sys.argv[1:3]
    except ValueError:
        print "usage: leaflet.py PDB SELECTION"
        sys.exit(1)
    print "PDB={PDB!r} selection={selection!r}".format(**vars())
    L = LeafletFinder(PDB, selection)
    print "Number of lipids in leaflets: {0!r}".format(L.sizes())
    macrovmd = PDB + ".vmd"
    L.write_vmd(macrovmd)
    print "Load macros for vmd from file {0!r}".format(macrovmd)