Esempio n. 1
0
    def shrink_to_mols(self, mols):
        """Reduces the grid size to be just large enough to contain all mol objects in mol"""

        blank_grd = Grid.initalise_grid(
            [a.coordinates for l in mols for a in l.atoms])
        for probe, g in self.super_grids.items():
            self.super_grids[probe] = Grid.shrink(blank_grd, g)
Esempio n. 2
0
    def get_residue_vdw(self, residue, res_num, padding=3.0):
        """
        generates a mask for the residue where points within VdW distance of residue heavy atoms are 
        :param residue: `ccdc.prottein.Residue`
        :param res_num: The value which to assign to voxels in the masked area
        :param padding: float, padding around minimal coordinates in Angstroms
        :return: `hotspots.grid_extension.Grid`
        """
        coords = np.array([a.coordinates for a in residue.atoms])
        min_coords = (np.min(coords[:, 0]), np.min(coords[:, 1]),
                      np.min(coords[:, 2]))
        max_coords = (np.max(coords[:, 0]), np.max(coords[:, 1]),
                      np.max(coords[:, 2]))

        # Put some padding around the minimal and maximum values:
        g_origin = tuple(x - padding for x in min_coords)
        g_far_corner = tuple(y + padding for y in max_coords)

        layer = Grid(origin=g_origin,
                     far_corner=g_far_corner,
                     spacing=self.g_spacing,
                     default=0.0,
                     _grid=None)

        for a in residue.atoms:
            layer.set_sphere(point=a.coordinates,
                             radius=a.vdw_radius,
                             value=1,
                             scaling='None')
        layer = self.set_uniform_values(layer, res_num)
        print("Size of layer: {}".format(layer.count_grid()))

        return layer
Esempio n. 3
0
def augmentation(hr, hits):
    # create a grid which can contain all pharmacophore poses
    small_blank = Grid.initalise_grid(coords={
        atm.coordinates
        for mol in hits.hits for atm in mol.molecule.heavy_atoms
    },
                                      padding=3)
    # dilate the grids
    for p, g in hr.super_grids.items():
        hr.super_grids[p] = g.dilate_by_atom()

    # inflate
    prot_g = Grid.initalise_grid(
        [a.coordinates for a in hr.protein.heavy_atoms], padding=1)

    for p, g in hr.super_grids.items():
        hr.super_grids[p] = prot_g.common_boundaries(g)

    # shrink hotspot maps to save time
    sub_grids = {
        p: Grid.shrink(small=small_blank, big=g)
        for p, g in hr.super_grids.items()
    }

    # create single grid
    mask_dic, sg = Grid.get_single_grid(sub_grids)

    hr.super_grids = mask_dic

    # set background to 1
    hr.set_background()
    hr.normalize_to_max()
    return hr
Esempio n. 4
0
    def create_atomic_hotspots(self, superstar_grids_dir):
        """
        
        :param superstar_grids_dir: path to where the superstar grids are stored
        :return: 
        """
        atomic_hotspots = []

        # Read in the SuperStar and Buriedness info
        probes = ['donor', 'acceptor', 'apolar', 'positive', 'negative']
        b_grid = Grid.from_file(
            str(Path(superstar_grids_dir, 'buriedness.ccp4').resolve()))

        for p in probes:
            g_path = Path(superstar_grids_dir, f'superstar_{p}.ccp4')
            if g_path.exists():
                print(f" found grid for probe of type {p}")
                p_grid = Grid.from_file(str(g_path.resolve()))
                ahs = _AtomicHotspotResult(identifier=p,
                                           grid=p_grid,
                                           buriedness=b_grid)
                atomic_hotspots.append(ahs)
            else:
                continue

        return atomic_hotspots
Esempio n. 5
0
    def test_output_grid(self):
        #g_0 = Grid.from_file(self.grid_paths[0])
        g_0 = self.grid_list[0]
        print(g_0.count_grid())
        print(self.max_grid.count_grid())
        max_g, ref_g = Grid.common_grid([self.max_grid, g_0])
        diff_grid = (max_g - ref_g)
        nx, ny, nz = diff_grid.nsteps
        for x in range(nx):
            for y in range(ny):
                for z in range(nz):
                    if diff_grid.value(x, y, z) != 0:
                        print(diff_grid.value(x, y, z))
        self.assertEqual((max_g - ref_g).count_grid(),
                         0,
                         msg="Testing the max_grid")

        means_grid = self.grid_ensemble.output_grid(mode="mean", save=False)
        mean_g, ref_g = Grid.common_grid([means_grid, g_0])
        self.assertEqual((max_g - ref_g).count_grid(),
                         0,
                         msg="Testing the means_grid")

        ranges_grid = self.grid_ensemble.output_grid(mode="ranges", save=False)
        self.assertEqual(ranges_grid.count_grid(),
                         0,
                         msg="Testing the ranges grid")

        other_g = self.grid_ensemble.output_grid(mode="bla", save=False)
        self.assertIsNone(other_g)
Esempio n. 6
0
    def test_neighbourhood(self):
        # check the catchment critera
        neighbours = Grid.neighbourhood(i=0,
                                        j=0,
                                        k=0,
                                        high=self.buriedness.nsteps,
                                        catchment=1)
        self.assertEqual(3, len(neighbours))

        neighbours1 = Grid.neighbourhood(i=5,
                                         j=5,
                                         k=5,
                                         high=self.buriedness.nsteps,
                                         catchment=1)
        self.assertEqual(6, len(neighbours1))

        f = PyMOLFile()
        for i, n in enumerate(neighbours + neighbours1):
            f.commands += PyMOLCommands.sphere(f"sphere_{i}", (0, 0, 1, 1), n,
                                               0.1)
            f.commands += PyMOLCommands.load_cgo(f"sphere_{i}",
                                                 f"sphere_{i}_obj")
        f.commands += PyMOLCommands.sphere("centre", (1, 0, 0, 1), (5, 5, 5),
                                           0.1)
        f.commands += PyMOLCommands.load_cgo("centre", "centre_obj")
        f.commands += PyMOLCommands.sphere("centre1", (1, 0, 0, 1), (0, 0, 0),
                                           0.1)
        f.commands += PyMOLCommands.load_cgo("centre1", "centre1_obj")

        f.write("testdata/grid_extension/neighbourhood.py")
Esempio n. 7
0
    def _as_grid(self, feature_type=None, tolerance=2):
        """
        returns _features as grid
        """
        if feature_type == None:
            filtered_features = self._features

        else:
            filtered_features = [
                feat for feat in self._features
                if feat.feature_type == feature_type
            ]

        x = [feat.feature_coordinates.x for feat in filtered_features]
        y = [feat.feature_coordinates.y for feat in filtered_features]
        z = [feat.feature_coordinates.z for feat in filtered_features]

        origin = [min(x) - tolerance, min(y) - tolerance, min(z) - tolerance]
        far_corner = [
            max(x) + tolerance,
            max(y) + tolerance,
            max(z) + tolerance
        ]
        grd = Grid(origin=origin,
                   far_corner=far_corner,
                   spacing=0.5,
                   default=0,
                   _grid=None)

        for feat in filtered_features:
            grd.set_sphere(point=feat.feature_coordinates,
                           radius=self.settings.radius,
                           value=1,
                           scaling='None')
        return grd
Esempio n. 8
0
    def _generate_result(self, path):
        with PushDir(path):
            files = set(listdir(path))

            # fetch protein - this should always be protein.pdb
            prot_name = [f for f in files if f.split(".")[1] == self.supported_protein_extensions][0]
            prot = Protein.from_file(prot_name)
            files.remove(prot_name)

            # there should only be one grid extension in the directory, if there are more
            # then you can manually read in your results
            grid_extension = {f.split(".")[1] for f in files}.intersection(self.supported_grid_extensions)
            if len(grid_extension) > 1:
                raise IndexError("Too many grid types, create `hotspots.result.Results` manually")

            elif len(grid_extension) < 1:
                raise IndexError("No supported grid types found")

            elif list(grid_extension)[0] == "dat":
                raise NotImplementedError("Will put this in if requested")

            else:
                grid_extension = list(grid_extension)[0]

            # read hotspot grids
            stripped_files = {f.split(".")[0] for f in files}
            hotspot_grids = stripped_files.intersection(self.supported_interactions)
            super_grids = {p: Grid.from_file(f"{p}.{grid_extension}") for p in hotspot_grids}

            # read superstar grids
            if len([f.startswith("superstar") for f in files]) > 0 and self.read_superstar:
                superstar_grids = {p: Grid.from_file(f"superstar_{p}.{grid_extension}") for p in hotspot_grids}
            else:
                superstar_grids = None

            # read weighted_superstar grids
            if len([f.startswith("weighted") for f in files]) > 0 and self.read_weighted:
                weighted_grids = {p: Grid.from_file(f"weighted_{p}.{grid_extension}") for p in hotspot_grids}
            else:
                weighted_grids = None

            # fetch buriedness grid
            try:
                buriedness_name = [f for f in files if f.startswith("buriedness")][0]
            except IndexError:
                buriedness_name = None

            if buriedness_name and self.read_buriedness:
                buriedness = Grid.from_file(buriedness_name)
            else:
                buriedness = None

        return Results(super_grids=super_grids,
                       protein=prot,
                       buriedness=buriedness,
                       superstar=superstar_grids,
                       weighted_superstar=weighted_grids,
                       identifier=basename(path))
Esempio n. 9
0
    def _get_volume_overlap(self, cav_id, other_id, lig_id):
        """
        find the highest median bcv from all cavities, calculate percentage over between the best bcv
        and each query ligand

        :return:
        """

        def nonzero(val):
            if val == 0:
                return 1
            else:
                return val

        # inputs
        mol = io.MoleculeReader(self.extracted_ligands[other_id][lig_id])[0]
        path1 = os.path.join(self.hotspot[cav_id], "out.zip")
        path2 = os.path.join(self.bcv[cav_id][other_id][lig_id], "out.zip")
        thresholds = [10, 14, 17]

        if os.path.exists(path1) and os.path.exists(path2):
            bcv = HotspotReader(path2).read()
            hot = HotspotReader(path1).read()

            # tasks
            other = Grid.from_molecule(mol)

            bcv_sg = Grid.get_single_grid(bcv.super_grids, mask=False)
            bcv_overlap = bcv_sg._mutually_inclusive(other=other).count_grid()

            lig_vol = (other > 0).count_grid()
            bcv_vol = (bcv_sg > 0).count_grid()

            hot_sgs = [(Grid.get_single_grid(hot.super_grids, mask=False) > t)
                       for t in thresholds]
            hot_vols = [nonzero(hot_sg.count_grid())
                        for hot_sg in hot_sgs]
            hot_overlap = [hot_sg._mutually_inclusive(other=other).count_grid() for hot_sg in hot_sgs]

            # output
            with open(self.bcv_lig_overlaps[cav_id][other_id][lig_id], 'w') as writer:
                writer.write(str((bcv_overlap / lig_vol) * 100))

            with open(self.bcv_hot_overlaps[cav_id][other_id][lig_id], 'w') as writer:
                writer.write(str((bcv_overlap / bcv_vol) * 100))

            with open(self.hot_lig_overlaps[cav_id][other_id][lig_id], 'w') as writer:
                hot_lig = [str((a / lig_vol) * 100) for a in hot_overlap]
                print(hot_lig)
                writer.write(",".join(hot_lig))

            with open(self.hot_hot_overlaps[cav_id][other_id][lig_id], 'w') as writer:
                hot_hot = [str((hot_overlap[i] / hot_vols[i]) * 100) for i in range(len(thresholds))]
                writer.write(",".join(hot_hot))

        else:
            print("no BCV for cavity {}, BCV {}".format(cav_id, lig_id))
Esempio n. 10
0
def make_max_difference_maps(io):
    probes = ["donor", "acceptor", "apolar"]
    for probe in probes:
        g1 = Grid.from_file(
            join(io.ensemble_dirs[e1], "{}_{}_max.ccp4".format(e1, probe)))
        g2 = Grid.from_file(
            join(io.ensemble_dirs[e2], "{}_{}_max.ccp4".format(e2, probe)))
        diff_g = g1 - g2
        diff_g.write(
            join(io.params.pipeline_root,
                 "diff_{}_{}_{}.ccp4").format(e1, e2, probe))
Esempio n. 11
0
 def make_grid(offset, vals, idxs, nsteps):
     grid_origin = offset
     grid_far_corner = (
     offset[0] + (nsteps[0] - 1) * 0.5, offset[1] + (nsteps[1] - 1) * 0.5, offset[2] + (nsteps[2] - 1) * 0.5)
     out_grid = Grid(origin=grid_origin,
                     far_corner=grid_far_corner,
                     spacing=0.5,
                     _grid=None,
                     default=0)
     for (nx, ny, nz), v in zip(idxs, vals):
         # print(nx, ny, nz, v)
         # print(int(nx-offset[0]*2), int(ny-offset[1]*2), int(nz-offset[2]*2))
         out_grid.set_value(int(nx - offset[0] * 2), int(ny - offset[1] * 2), int(nz - offset[2] * 2), v)
     return out_grid
Esempio n. 12
0
    def generate_fake(self, buriedness=False, weighted=False, superstar=True):
        """
        create a small set of grids for testing

        :param buriedness:
        :param weighted:
        :param superstar:
        :return:
        """

        def populate_grid(template, num_spheres, radius=1, value=8, scaling='linear'):
            h = template.copy_and_clear()
            for i in range(1, num_spheres):
                x, y, z = [np.random.randint(low=2, high=ax - 2, size=1) for ax in h.nsteps]

                h.set_sphere(point=h.indices_to_point(x, y, z),
                             radius=radius,
                             value=value,
                             scaling=scaling)

            return h

        protein = Protein.from_file("testdata/6y2g_A/binding_site.pdb")
        mol = MoleculeReader("testdata/6y2g_A/A_mol.mol2")[0]
        g = Grid.initalise_grid([a.coordinates for a in mol.atoms])

        if buriedness:
            buriedness_grid = Grid.from_molecule(mol)
        else:
            buriedness_grid = None

        interactions = ["apolar", "donor", "acceptor"]

        super_grids = {p: populate_grid(template=g, num_spheres=3) for p in interactions}

        if superstar:
            superstar_grids = {p: populate_grid(template=g, num_spheres=3) for p in interactions}
        else:
            superstar_grids = None

        if weighted:
            weighted_superstar_grids = {p: populate_grid(template=g, num_spheres=3) for p in interactions}
        else:
            weighted_superstar_grids = None

        return Results(super_grids=super_grids,
                       protein=protein,
                       buriedness=buriedness_grid,
                       superstar=superstar_grids,
                       weighted_superstar=weighted_superstar_grids)
Esempio n. 13
0
    def buriedness_grid(self):

        closed_g = self._multiscale_closing(self.protein_grid)
        out_g = self._open_grid(closed_g, 2) * closed_g
        out_array = out_g.get_array()
        scaled_g = Grid.initalise_grid(self.out_grid.bounding_box,
                                       padding=0,
                                       spacing=0.5)

        scaled_array = resize(out_array, scaled_g.nsteps, anti_aliasing=False)

        # Future tweaking here
        final_array = scaled_array
        return Grid.array_to_grid(final_array.astype(int), scaled_g)
Esempio n. 14
0
    def grid_from_protein(self):
        """
        Puts the protein inside a CCDC Grid object
        :return: a :class: hotspots.grid_extension.Grid instance
        """
        if not self.protein:
            self.get_protein()

        coords = np.array([
            a.coordinates for res in self.protein.residues for a in res.atoms
        ])
        min_coords = (np.min(coords[:, 0]), np.min(coords[:, 1]),
                      np.min(coords[:, 2]))
        max_coords = (np.max(coords[:, 0]), np.max(coords[:, 1]),
                      np.max(coords[:, 2]))

        # Put some padding around the minimal and maximum values:
        g_origin = tuple(x - 3.0 for x in min_coords)
        g_far_corner = tuple(y + 3.0 for y in max_coords)

        prot_grid = Grid(origin=g_origin,
                         far_corner=g_far_corner,
                         spacing=self.g_spacing,
                         default=0.0,
                         _grid=None)
        return prot_grid
def as_grid(origin_coords, far_corner_coords, array, spacing=0.5):
    """
    Given an array, outputs a grid with the dimensions of the GridEnsemble

    :param array: 3D numpy array, usually containing processed ensemble data
    :return: a :class: 'ccdc.utilities.Grid' instance
    """
    # Initialise the Grid
    grid = Grid(origin=origin_coords,
                far_corner=far_corner_coords,
                spacing=spacing,
                default=0.0,
                _grid=None)

    # Get the nonzero indices and values of the array
    nonz = array.nonzero()
    values = array[nonz]
    # Get indices per value
    as_triads = zip(*nonz)

    # Fill in the grid
    for (i, j, k), v in zip(as_triads, values):
        grid._grid.set_value(int(i), int(j), int(k), v)

    return grid
Esempio n. 16
0
def _molecule_as_grid(mol, g=None):
    """
    Produces a grid representation of a molecule split by interaction type

    :param mol: takes any ccdc molecule
    :type mol: `ccdc.molecule.Molecule`
    :param g: a blank grid
    :type g: `hotspots.grid_extension.Grid`

    :return: a dictionary of grids by interaction type
    :rtype: dict
    """
    if not g:
        g = Grid.initalise_grid(coords=[a.coordinates for a in mol.atoms],
                                padding=3)

    grid_dict = {"donor": g.copy(), "acceptor": g.copy(), "apolar": g.copy()}

    for p, g in grid_dict.items():
        atms = [a for a in mol.atoms if Helper.get_atom_type(a) == p]
        for atm in atms:
            g.set_sphere(point=atm.coordinates,
                         radius=atm.vdw_radius,
                         value=1,
                         scaling='None')

    return grid_dict
Esempio n. 17
0
    def _from_molecule(self, mol, scaling=1):
        """
        generate a molecule mask where gp within the vdw radius of the molecule heavy atoms are set to 1.0
        :param mol: `ccdc.molecule.Molecule`
        :param padding: int
        :param scaling: float
        :return: `hotspots.grid_extension.Grid`
        """

        coords = [a.coordinates for a in mol.atoms]
        g = Grid.initalise_grid(coords=coords, padding=15, spacing=1)

        for probe in sorted(self.probe_selem_dict.keys(), reverse=True):
            for a in mol.heavy_atoms:
                g.set_sphere(point=a.coordinates,
                             radius=probe * scaling,
                             value=probe,
                             mode='replace',
                             scaling='None')

        for a in mol.heavy_atoms:
            g.set_sphere(point=a.coordinates,
                         radius=a.vdw_radius,
                         value=100,
                         mode='replace',
                         scaling='None')

        out_bound_box = self.out_grid.bounding_box
        origin_indices = g.point_to_indices(out_bound_box[0])
        far_indices = g.point_to_indices(out_bound_box[1])
        region = origin_indices + far_indices
        print(region)
        return g.sub_grid(region)
Esempio n. 18
0
    def make_difference_maps(self):
        """
        Brings the two results to the same size and subtracts them.
        TODO - think about cases of results with different numbers of probe grids (charged vs not)
        :return: ccdc grids
        """
        diff_maps = {}

        for probe, gr in self.target.super_grids.items():

            try:
                off_gr = self.off_target.super_grids[probe]
            # In case the off-target hotspot result doesn't have a map for that probe
            except KeyError:
                continue

            # if gr.check_same_size_and_coords(off_gr):
            #     c_gr = gr
            #     c_off = off_gr
            # else:
            #     print("Input grids of different size. Converting to same coordinates.")
            c_gr, c_off = Grid.common_grid([gr, off_gr])

            diff_maps[probe] = _GridEnsemble.array_from_grid(c_gr - c_off)

        self.common_grid_dimensions = np.array(c_gr.bounding_box)
        self.common_grid_nsteps = c_gr.nsteps

        return diff_maps
Esempio n. 19
0
def tractability_workflow(protein, tag):
    """
    A very simple tractability workflow.

    :param str protein: PDB identification code
    :param str tag: Tractability tag: either 'druggable' or 'less-druggable'
    :return: `pandas.DataFrame`
    """
    # 1) calculate Fragment Hotspot Result
    runner = Runner()
    result = runner.from_pdb(pdb_code=protein,
                             nprocesses=1,
                             buriedness_method='ghecom')

    # 2) calculate Best Continuous Volume
    extractor = Extractor(hr=result)
    bcv_result = extractor.extract_volume(volume=500)

    # 3) find the median score
    grid = Grid.get_single_grid(bcv_result.super_grids, mask=False)
    values = grid.grid_values(threshold=5)
    median = np.median(values)

    # 4) return the data
    return pd.DataFrame({
        'scores': values,
        'pdb': [protein] * len(values),
        'median': [median] * len(values),
        'tractability': [tag] * len(values),
    })
Esempio n. 20
0
    def __init__(self, hr, settings=None):
        if settings is None:
            self.settings = self.Settings()
        else:
            self.settings = settings
        self._single_grid = None
        self._masked_dic = None
        self.out_dir = None
        self.extracted_hotspots = None
        self.threshold = None

        try:
            hr.super_grids["negative"] = hr.super_grids[
                "negative"].deduplicate(hr.super_grids["acceptor"],
                                        threshold=10,
                                        tolerance=2)

            hr.super_grids["positive"] = hr.super_grids[
                "positive"].deduplicate(hr.super_grids["donor"],
                                        threshold=10,
                                        tolerance=2)
        except KeyError:
            pass

        self.hotspot_result = hr
        self._masked_dic, self._single_grid = Grid.get_single_grid(
            self.hotspot_result.super_grids)
Esempio n. 21
0
    def _grow(self, tolerance=0.2):
        """
        A single grid is iteratively inflated, and the top 20% of neighbouring grid points added until the volume
        is with the tolerance of the target volume.

        :param float tolerance: allowable error in volume extraction
        :return float: threshold
        """

        self.best_island = self._single_grid.common_boundaries(
            self.best_island)
        current_num_gp = self.best_island.count_grid()

        f = 0
        while f < 100 and abs(
            ((self.settings._num_gp - current_num_gp) / self.settings._num_gp
             )) > tolerance and self.settings._num_gp >= current_num_gp:
            grown = Grid.grow(self.best_island, self.single_grid)
            self.best_island = grown
            current_num_gp = self.best_island.count_grid()
            print(current_num_gp, 'out of', self.settings._num_gp)
            f += 1

        tmp_best_island = self.best_island * self.single_grid
        g_vals = tmp_best_island.grid_values()
        g_vals[::-1].sort()

        try:
            threshold = g_vals[self.settings._num_gp]
        except IndexError:
            threshold = min(g_vals)

        # assert abs(((self.settings._num_gp - current_num_gp) / self.settings._num_gp)) < tolerance

        return threshold
Esempio n. 22
0
def _create_grids(pharmacophores):
    g = Grid.initalise_grid(coords=[
        s.centre for p in pharmacophores for f in p.features for s in f.spheres
    ],
                            spacing=0.5)
    fds = {f.identifier for p in pharmacophores for f in p.features}
    return {fd: g.copy() for fd in fds}
Esempio n. 23
0
    def create_projection_grid(self):
        """
        create the projected spheres for the summary pharmacophore features

        :return: `hotspots.grid_extension.Grid`
        """
        # Do the features have projections ?
        if len([f for f in self.features if len(f.spheres) > 1]) == 0:
            return None
        else:
            g = Grid.initalise_grid(coords=[
                feature.spheres[1].centre for feature in self.features
            ],
                                    spacing=0.25,
                                    padding=2)

            for f in self.features:
                if len(f.spheres) > 1:
                    px, py, pz = [
                        f.spheres[1].centre[0], f.spheres[1].centre[1],
                        f.spheres[1].centre[2]
                    ]
                    g.set_sphere(point=[px, py, pz],
                                 value=1,
                                 radius=2,
                                 scaling='linear')
            self.projection_grid = g
            return g
Esempio n. 24
0
def make_thresholded_maps(io, e1, e2):
    """
    
    :param io: EnsembleIO instance. 
    :param str ens1: name of reference ensemble 
    :param str ens2: name of off-target ensemble 
    :return: 
    """
    t_dir = join(io.params.pipeline_root, "thresholded_hotspot_maps")
    if not exists(t_dir):
        os.mkdir(t_dir)
    print(t_dir)
    probes = ["donor", "acceptor", "apolar"]

    for probe in probes:
        ge1 = pickle.load(open(io.ensemble_maps[e1][probe], "r"))
        ge2 = pickle.load(open(io.ensemble_maps[e2][probe], "r"))

        iarr = ge1.get_difference_map(ge2, tolerance=0)
        diff = Grid.from_file(
            join(io.params.pipeline_root,
                 "diff_{}_{}_{}.ccp4").format(e1, e2, probe)).get_array()

        over3 = (iarr > 3) * diff
        gover3 = ge1.save_grid(over3)
        gover3.write(
            join(t_dir, "diff_{}_{}_{}_over3.ccp4".format(e1, e2, probe)))

        under3 = (iarr < 3) * diff
        gunder3 = ge1.save_grid(under3)
        gunder3.write(
            join(t_dir, "diff_{}_{}_{}_under3.ccp4".format(e1, e2, probe)))
Esempio n. 25
0
    def test_features_to_grid(self):
        pm = PharmacophoreModel()
        pm.feature_definitions = ["acceptor"]
        pts = [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [2.5, 2.5, 2.5],
               [3.5, 3.5, 3.5]]

        g = Grid.initalise_grid(pts, padding=3)
        features = [
            Feature(pm.feature_definitions["acceptor"],
                    GeometricDescriptors.Sphere(centre=p, radius=1))
            for p in pts
        ]

        for f in features:
            f.point = f.spheres[0]

        h = _features_to_grid(features, g)

        # should be 3 peaks, all with a value of 1.0
        self.assertEqual(3, len(h.get_peaks(min_distance=1, cutoff=0)))
        self.assertTrue(
            all([
                h.value_at_point(peak) == 1.0
                for peak in h.get_peaks(min_distance=1, cutoff=0)
            ]))
Esempio n. 26
0
    def test_write_real_single(self):
        base = "testdata/1hcl"
        interactions = ["donor", "acceptor", "apolar"]
        super_grids = {p: Grid.from_file(os.path.join(base, f"{p}.grd")) for p in interactions}
        superstar_grids = {p: Grid.from_file(os.path.join(base, f"superstar_{p}.grd")) for p in interactions}
        buriedness = Grid.from_file(os.path.join(base, "buriedness.grd"))
        prot = Protein.from_file(os.path.join(base, "protein.pdb"))

        hr = Results(super_grids=super_grids,
                     protein=prot,
                     buriedness=buriedness,
                     superstar=superstar_grids)

        settings = HotspotWriter.Settings()
        settings.output_superstar = True
        with HotspotWriter("testdata/hs_io/minimal_all_grids_real", settings=settings) as w:
            w.write(hr)
Esempio n. 27
0
    def set_background(self, background_value=1.0):
        spacing = self.super_grids["apolar"]._spacing
        prot_g = Grid.from_molecule(self.protein,
                                    value=background_value,
                                    scaling_type='none',
                                    scaling=1,
                                    spacing=spacing)

        for probe, g in self.super_grids.items():
            common_prot, common_g = Grid.common_grid([prot_g, g])
            bg_mask = (common_prot < 0.1) & (common_g < 1)
            tmp_g = common_g + bg_mask
            new_g = tmp_g - (common_prot)
            origin, corner = g.bounding_box
            i, j, k = new_g.point_to_indices(origin)
            l, m, n = new_g.point_to_indices(corner)
            self.super_grids[probe] = new_g.sub_grid((i, j, k, l, m, n))
Esempio n. 28
0
 def __init__(self, settings):
     self.settings = settings
     if self.settings.out_grid:
         self.grid = self.settings.out_grid
     else:
         self.grid = Grid.initalise_grid([atom.coordinates for atom in self.settings.protein.atoms],
                                         padding=2)
     self.update_grid()
Esempio n. 29
0
    def _get_grids(self, sub_dir=None):
        """
        create a grid dictorionary
        :return:
        """
        if sub_dir:
            base = join(self._base, sub_dir)
            self._files = listdir(base)
            self._extensions = set(
                [splitext(f)[1] for f in self._files if f != '' or f != '.py'])
        else:
            base = self._base

        if ".dat" in self._extensions:
            grid_dic = {
                splitext(fname)[0]: Grid.from_array(join(base, fname))
                for fname in [
                    f for f in self._files if splitext(f)[1] == ".grd"
                    and splitext(f)[0] in self._supported_interactions
                ]
            }
            try:
                buriedness = Grid.from_array(join(self.base, "buriedness.dat"))
            except RuntimeError:
                buriedness = None

        else:
            ext = list(
                set(self._extensions).intersection(self._supported_grids))
            if len(ext) == 1:
                grid_dic = {
                    splitext(fname)[0]: Grid.from_file(join(base, fname))
                    for fname in [
                        f for f in self._files if splitext(f)[1] == ext[0]
                        and splitext(f)[0] in self._supported_interactions
                    ]
                }
                try:
                    buriedness = Grid.from_file("buriedness{}".format(ext[0]))
                except RuntimeError:
                    buriedness = None
            else:
                raise RuntimeError("Opps, something went wrong.")

        return grid_dic, buriedness
Esempio n. 30
0
 def score_hotspot(self, threshold=5, percentile=50):
     """
     Hotspot scored on the median value of all points included in the hotspot.
     NB: grid point with value < 5 are ommited from fragment hotspot map (hence the default threshold)
     :param percentile:
     :return:
     """
     sg = Grid.get_single_grid(self.hotspot_result.super_grids, mask=False)
     return sg.grid_score(threshold=threshold, percentile=percentile)