Exemplo n.º 1
0
 def load_pdb(self, num_proteins_seen, screenshotting, pdb_file_name=""): # use pymol wiki
     cmd.delete("all") # prevent memory issues
     # choose a pdb id
     if num_proteins_seen > len(self.pedagogy):
         self.pdb_file_name = random.sample(self.pedagogy, 1)[0]
     elif (num_proteins_seen < len(self.pedagogy) and pdb_file_name == ""):
         self.pdb_file_name = self.pedagogy[num_proteins_seen]
     # fetch or load pdb
     self.pdb_file_path = "./pdbs/"+self.pdb_file_name+".pdb"
     if not os.path.exists(self.pdb_file_path):
         cmd.fetch(self.pdb_file_name, path="./inputs/pdbs", type="pdb")
     elif os.path.exists(self.pdb_file_path):
         cmd.load(self.pdb_file_path)
     cmd.remove("solvent")
     # summarize
     print(self.params.run_time_stamp, " is loading ", num_proteins_seen, self.pdb_file_path)
     print("")
     num_atoms = cmd.count_atoms("all")
     print("noise mean", self.params.noise_mean, "noise scale", self.params.noise_scale)
     # convert pdb2tensor
     original_model = cmd.get_model('all', 1)
     original_coords_list = cmd.get_model('all', 1).get_coord_list()
     original = tf.convert_to_tensor(np.array(original_coords_list), dtype=tf.float32)
     chains = cmd.get_chains()
     if (screenshotting):
         self.current_pdb_screenshot_path = self.params.screenshot_folder_path + "/" + self.pdb_file_name + "-" + str(num_proteins_seen) + "/"
         os.makedirs(self.current_pdb_screenshot_path)
         prepare_pymol()
         take_screenshot(self.params, self.pdb_file_name, num_proteins_seen, "0")
     num_steps = random.randint(self.params.min_steps_in_undock, self.params.max_steps_in_undock)
     self.undock(num_proteins_seen, screenshotting, num_steps, chains)
     undocked_coords_list = cmd.get_model('all', 1).get_coord_list()
     undocked = tf.convert_to_tensor(np.array(undocked_coords_list), dtype=tf.float32)
     # calculate center of mass dict
     self.center_of_mass_dict = AttrDict()
     self.center_of_mass_dict["all"] = cmd.centerofmass("all")
     for chain in chains:
         self.center_of_mass_dict[chain] = cmd.centerofmass("chain {}".format(chain))
     features = np.array([self.extract(atom) for atom in original_model.atom])
     features = tf.convert_to_tensor(features, dtype=tf.float32)
     #outputs
     output_tuple = (self.center_of_mass_dict, num_steps, undocked, features, original, chains)
     return output_tuple
Exemplo n.º 2
0
def calc_gc(filename, select):
    # IUPAC definition
    cmd.load(filename)
    cmd.hide('everything')

    model = cmd.get_model(select).atom
    center = np.array(cmd.centerofmass(select))

    pos = np.array([atom.coord for atom in model])
    pos_c_m = np.linalg.norm(pos - center, axis=1)

    mass = np.array([atom.get_mass() for atom in model])
    upper = mass * np.square(pos_c_m)    # m * r^2

    total_upper = np.sum(upper)
    total_mass = np.sum(mass)

    return np.sqrt(total_upper/ total_mass)
Exemplo n.º 3
0
def center(selection):
    # center a molecule
    com = cmd.centerofmass(selection, -1.0)
    shift = np.array2string(np.negative(np.array(com)), separator=', ')
    cmd.translate(shift, selection)
    print(f'Shifting {selection} to center')
Exemplo n.º 4
0
def drawgridbox(selection="(all)",
                volume=256.0,
                voxel_size=1.0,
                lw=2.0,
                r=1.0,
                g=1.0,
                b=1.0,
                show_binding_sites=True,
                oversample=False,
                undersample=False):
    """
    DESCRIPTION
        Given selection, draw a grid box around it.

    USAGE:
        drawgridbox [selection, [nx, [ny, [nz, [padding, [lw, [r, [g, b]]]]]]]]

    PARAMETERS:
        selection,    the selection to enboxen
                      defaults to (all)

        nx,           number of grids on axis X
                      defaults to 10

        ny,           number of grids on axis Y
                      defaults to 10

        nz,           number of grids on axis Z
                      defaults to 10

        padding,      defaults to 0

        lw,           line width
                      defaults to 2.0

        r,            red color component, valid range is [0.0, 1.0]
                      defaults to 1.0

        g,            green color component, valid range is [0.0, 1.0]
                      defaults to 1.0

        b,            blue color component, valid range is [0.0, 1.0]
                      defaults to 1.0

    RETURNS
        string, the name of the CGO box

    NOTES
        * This function creates a randomly named CGO grid box. The user can
        specify the number of grids on X/Y/Z axis, the width of the lines,
        the padding and also the color.
    """

    all_coords = Counter()

    extent_min, extent_max = cmd.get_extent(selection)
    extent_x = np.arange(
        np.floor(extent_min[0]) - 5,
        np.ceil(extent_max[0]) + 5, voxel_size)
    extent_y = np.arange(
        np.floor(extent_min[1]) - 5,
        np.ceil(extent_max[1]) + 5, voxel_size)
    extent_z = np.arange(
        np.floor(extent_min[2]) - 5,
        np.ceil(extent_max[2]) + 5, voxel_size)

    com = cmd.centerofmass(selection)
    r = 256 / 2.
    min_coord = com - np.floor(r)
    max_coord = com + np.ceil(r)
    drawBoundingBox(minX=min_coord[0],
                    minY=min_coord[1],
                    minZ=min_coord[2],
                    maxX=max_coord[0],
                    maxY=max_coord[1],
                    maxZ=max_coord[2])

    model = cmd.get_model(selection)

    coords = np.array([a.coord for a in model.atom])
    mean_coord = np.mean(coords, axis=0)
    volume_center = np.array((extent_x.shape[0] / 2., extent_y.shape[0] / 2.,
                              extent_z.shape[0] / 2.))
    shift_by = volume_center - mean_coord
    print volume_center, shift_by

    if show_binding_sites:
        volume_center = np.array((128., 128., 128.))
        shift_by = volume_center - mean_coord
        pdb = cmd.get_names("objects",
                            selection=selection)[0].split(".", 1)[0].upper()
        for a in model.atom:
            chain = a.chain
            break

        print pdb, chain

        ibis_dataset = IBISDataset(os.path.join(molpath, "molmimic",
                                                "ibis_luca.tab"),
                                   transform=False,
                                   input_shape=(256, 256, 256),
                                   balance_classes=bool(undersample))

        print ibis_dataset.data.iloc[0]

        index = ibis_dataset.data.loc[(ibis_dataset.data['pdb'] == pdb) & (
            ibis_dataset.data["chain"] == chain)].index[0]
        print index
        grids = ibis_dataset[0]

        voxels = CGO("{}_VOXELS".format(pdb))

        for grid, truth in izip(grids["indices"], grids["truth"]):
            grid -= shift_by
            g = float(not truth)
            b = float(truth)
            if oversample and not truth:
                continue
            voxels.add_cube(grid[0], grid[1], grid[2], r=0, g=g, b=b)
        voxels.load()

    else:
        xs = np.arange(0, extent_x.shape[0] + 1)
        ys = np.arange(0, extent_y.shape[0] + 1)
        zs = np.arange(0, extent_z.shape[0] + 1)

        mx, my, mz = np.meshgrid(xs, ys, zs)
        voxel_tree = spatial.cKDTree(zip(mx.ravel(), my.ravel(), mz.ravel()))

        for a in model.atom:
            vdw = vdw_radii.get(a.name.strip()[0].title(), 2.0)

            neighbors = voxel_tree.query_ball_point(np.array(a.coord) +
                                                    shift_by,
                                                    r=vdw)

            for idx in neighbors:
                voxel = voxel_tree.data[idx].astype(int)
                voxel = voxel - shift_by
                all_coords[tuple(voxel.tolist())] += 1

        bonded_boxes = CGO(name="bonded")
        nonbonded_boxes = CGO(name="nonbonded", r=0.0, b=1.0)

        for voxel, count in all_coords.iteritems():
            if count > 1:
                bonded_boxes.add_box(voxel[0], voxel[1], voxel[2], voxel_size)
            else:
                nonbonded_boxes.add_box(voxel[0], voxel[1], voxel[2],
                                        voxel_size)

        nonbonded_boxes.load()
        bonded_boxes.load()

    cmd.rotate()
Exemplo n.º 5
0
def shift_to_center(selection):
    # center a molecule
    com = cmd.centerofmass(selection, -1.0)
    shift = np.array2string(np.negative(np.array(com)), separator=', ')
    cmd.translate(shift, selection, camera=0)
    print('Shifting {} to {}'.format(selection, shift))
Exemplo n.º 6
0
def main(d1, d2):
    ## Make an output folder
    outdir = 'output_dd/' + input_protein + '+' + d1 + '+' + d2 + '/'
    #print (outdir)
    if os.path.isdir(outdir) == False:
        os.system('mkdir ' + outdir)

    domains = d1 + '+' + d2
    for pdb in dd[domains]:
        download_pdb_cif(pdb)
        for coordinates in dd[domains][pdb]:
            #print (pdb, domains, dd[domains][pdb][coordinates])
            chainA = coordinates.split('+')[0].split(':')[0]
            chainA_res = coordinates.split('+')[0].split(':')[1]
            chainB = coordinates.split('+')[1].split(':')[0]
            chainB_res = coordinates.split('+')[1].split(':')[1]
            cmd.load('pdbs/' + pdb.upper() + '.pdb')
            cmd.hide('everything')
            cmd.show('cartoon', 'chain ' + chainA + '+' + chainB)
            cmd.set('cartoon_fancy_helices', 1)
            print(pdb, chainA, chainA_res, chainB, chainB_res)
            try:
                x = cmd.centerofmass('chain ' + chainA)
                print('Success chainA')
                cmd.pseudoatom('chainA_label', pos=x)
                global nameA
                nameA = id_to_name[d1] + '(' + d1 + ')'
                cmd.label('chainA_label', 'nameA')
            except:
                print('Failed chainA')
            try:
                x = cmd.centerofmass('chain ' + chainB)
                print('Success chainB')
                cmd.pseudoatom('chainB_label', pos=x)
                global nameB
                nameB = id_to_name[d2] + '(' + d2 + ')'
                cmd.label('chainB_label', 'nameB')
                x = cmd.centerofmass('chain ' + chainA + '+' + chainB)
                cmd.origin(position=x)
                cmd.center('origin')
            except:
                print('Failed chainB')
            cmd.set('label_size', 7.5)
            cmd.set('cartoon_fancy_helices', 1)
            cmd.color('red', 'chain ' + chainA)
            cmd.color('orange', 'chain ' + chainB)
            for row in dd[domains][pdb][coordinates]:
                res1 = row[2]
                res2 = row[3]
                #cmd.distance('chain '+chainA+' and i. '+res1+' and n. CB', 'chain '+chainB+' and i. '+res2+' and n. CB')
                cutoff = 6.5
                m = cmd.distance(
                    'dist',
                    'chain ' + chainA + ' and i. ' + res1 + ' and n. CB',
                    'chain ' + chainB + ' and i. ' + res2 + ' and n. CB',
                    cutoff, 0)
                #m = cmd.get_distance(atom1='chain '+chainA+' and i. '+res1+' and n. CB',atom2='chain '+chainB+' and i. '+res2+' and n. CB',state=0)
                #print (pdb, m, chainA, res1, chainB, res2)
                cmd.select('res1', 'chain ' + chainA + ' and resi ' + res1)
                cmd.select('res2', 'chain ' + chainB + ' and resi ' + res2)

                if float(m) != 0.0:
                    cmd.show('sticks', 'res1')
                    cmd.show('sticks', 'res2')
                    cmd.color('cyan', 'res1')
                    cmd.color('yellow', 'res2')

            cmd.save(outdir + pdb + '_' + input_protein + '_' + d1 + '_' +
                     d2 + '_' + coordinates.replace(':', '_').replace(
                         '+', '_').replace('-', '_') + '.pse')
            cmd.save(outdir + pdb + '_' + input_protein + '_' + d1 + '_' +
                     d2 + '_' + coordinates.replace(':', '_').replace(
                         '+', '_').replace('-', '_') + '.pdb')
            cmd.delete('all')
        #break
    '''
Exemplo n.º 7
0
# UKOL 2 - podukol 2
# Autori: Petr Dvoracek <*****@*****.**>
# Datum: 8. listopad
# Soubor: ukol2b.py

from pymol import cmd
from pymol.cgo import *

# Hmm tak jo:
coords = cmd.centerofmass()
spherelist = [
    COLOR, 0.700, 0.300, 1.000, SPHERE, coords[0], coords[1], coords[2], 1
]
cmd.load_cgo(spherelist, 'CENTER_BALL', 0)
print coords
Exemplo n.º 8
0
from pymol import cmd
from m2_7 import calc_gc
filename = "data/1buw.pdb"
cmd.load(filename)
cmd.hide("everything")
c = cmd.centerofmass("chain A")
cmd.origin(position=c)
cmd.center('origin')
print(cmd.get_position())
cmd.select(
    "inside",
    "chain A within {:.2f} of origin".format(calc_gc(filename, "chain A")))
cmd.select("outside", "not inside")

cmd.color("red", "inside")
cmd.color("blue", "outside")

cmd.show("sphere", "inside")
cmd.show("sphere", "outside")
Exemplo n.º 9
0
from pymol import cmd

molec = "/home/aziza/Downloads/basa/pymol/ppfmft/centers/mol_test/1avx_l_nmin.pdb"

cmd.load(molec, 'molec')
cmd.pseudoatom('com', pos=cmd.centerofmass('molec'))
ceom = cmd.centerofmass('molec')
# cmd.centerofmass()

# def inert(name):
#     # print(name)
#     print(cmd.get_distance(atom1='com', atom2=name))

# myspace = {'inert': inert}
# print(cmd.iterate('molec', 'inert(name)', space=myspace))

atoms = cmd.get_model('molec')
iner = {'xx': 0, 'yy': 0, 'zz': 0, 'xy': 0, 'yz': 0, 'xz': 0}
for a in atoms.atom:
    if a.name != 'H':
        iner['xx'] += (a.coord[1] - ceom[1])**2 + (a.coord[2] - ceom[2])**2
        iner['yy'] += (a.coord[0] - ceom[0])**2 + (a.coord[2] - ceom[2])**2
        iner['zz'] += (a.coord[0] - ceom[0])**2 + (a.coord[1] - ceom[1])**2
        iner['xy'] += (a.coord[0] - ceom[0]) * (a.coord[1] - ceom[1])
        iner['yz'] += (a.coord[1] - ceom[1]) * (a.coord[2] - ceom[2])
        iner['xz'] += (a.coord[0] - ceom[0]) * (a.coord[2] - ceom[2])

print(iner)