How to use the rtree.index function in Rtree

To help you get started, we’ve selected a few Rtree examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github osmlab / labuildings / merge.py View on Github external
addresses = []

    with collection(addressIn, "r") as input:
        for address in input:
            shape = asShape(address['geometry'])
            shape.original = address
            addresses.append(shape)

    geoid = re.match('^.*-(\d+)\.shp$', buildingIn).groups(0)[0]

#    print "loaded", len(addresses), "addresses"

    # Load and index all buildings.
    buildings = []
    buildingShapes = []
    buildingIdx = index.Index()
    with collection(buildingIn, "r") as input:
        for building in input:
            shape = asShape(building['geometry'])
            building['properties']['addresses'] = []
            buildings.append(building)
            buildingShapes.append(shape)
            buildingIdx.add(len(buildings) - 1, shape.bounds)

#    print "loaded", len(buildings), "buildings"

    addressIntersections = {}

    addressesOnBuildings = 0

    # Map addresses to buildings.
github Jorl17 / open-elevation / gdal_interfaces.py View on Github external
def __init__(self, tiles_folder, summary_file, open_interfaces_size=5):
        super(GDALTileInterface, self).__init__()
        self.tiles_folder = tiles_folder
        self.summary_file = summary_file
        self.index = index.Index()
        self.cached_open_interfaces = []
        self.cached_open_interfaces_dict = {}
        self.open_interfaces_size = open_interfaces_size
github laempy / pyoints / pyoints / indexkd.py View on Github external
def r_tree(self):
        if not hasattr(self, '_r_tree'):

            # define properties
            p = r_treeIndex.Property()
            p.dimension = self.dim()
            p.variant = r_treeIndex.RT_Star
            index = np.concatenate((range(self.dim()), range(self.dim())))

            # Generator provides required point format
            def gen():
                for id, coord in self:
                    yield (id, coord[index], id)
            self._r_tree = Rtree(gen(), properties=p)

        return self._r_tree
github eclipse / sumo / sumo / tools / sumolib / net / __init__.py View on Github external
def _initRTree(self, shapeList, includeJunctions=True):
        import rtree
        self._rtree = rtree.index.Index()
        self._rtree.interleaved = True
        for ri, shape in enumerate(shapeList):
            self._rtree.add(ri, shape.getBoundingBox(includeJunctions))
github CivicSpleen / ambry / ambry / old / geo / util.py View on Github external
from rtree.core import RTreeError
    from shapely.geometry import Point, Polygon
    from shapely.wkt import loads
    from collections import Iterable
    from ..dbexceptions import GeoError

    # Maybe this is only a performance improvement if the data is sorted in
    # the generator ...
    def gen_index():
        for i, wkt, container_obj in containers:
            container_geometry = loads(wkt)

            yield (i, container_geometry.bounds, (container_obj, container_geometry))

    try:
        idx = index.Index(gen_index())
    except RTreeError:
        raise GeoError(
            "Failed to create RTree Index. Check that the container generator produced valud output")

    # Find the point containment
    for contained_coords, contained_obj in containeds:

        locations = idx.intersection(contained_coords, objects=True)

        if len(contained_coords) == 2:
            contained = Point(contained_coords)
        elif len(contained_coords) == 4 and not isinstance(contained_coords[0],
                                                           Iterable):
            # Assume it is bounding box coords. If the elements were iterables ( x,y points ) it
            # could be something else.
            # bounding boxes are: (minx, miny, maxx, maxy)
github su2code / SU2 / SU2_PY / FSI / FSIInterface.py View on Github external
def RBFMeshMapping_B(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc, rad):
        """
        Description
        """

        if self.have_MPI == True:
          myid = self.comm.Get_rank()
        else:
          myid = 0

        # --- Instantiate the spatial indexing ---
	prop_index = index.Property()
	prop_index.dimension = self.nDim
	SolidSpatialTree = index.Index(properties=prop_index)
        
        nSolidNodes = solidInterfaceBuffRcv_X.shape[0]

        for jVertex in range(nSolidNodes):
          posX = solidInterfaceBuffRcv_X[jVertex]
          posY = solidInterfaceBuffRcv_Y[jVertex]
          posZ = solidInterfaceBuffRcv_Z[jVertex]
	  if self.nDim == 2 :
	    SolidSpatialTree.add(jVertex, (posX, posY))
   	  else :
	    SolidSpatialTree.add(jVertex, (posX, posY, posZ))

        for iVertexFluid in range(self.nLocalFluidInterfacePhysicalNodes):
          posX = self.localFluidInterface_array_X_init[iVertexFluid]
          posY = self.localFluidInterface_array_Y_init[iVertexFluid]
          posZ = self.localFluidInterface_array_Z_init[iVertexFluid]
github nismod / digital_comms / digital_comms / mobile_network / transmitter_module.py View on Github external
def find_sites_in_area(self):

        if not self.sites:
            return 0

        area_geometry = ([(d.geometry) for d in self.area.values()][0])

        idx = index.Index()

        for site in self.sites.values():
            idx.insert(0, Point(site.coordinates).bounds, site)

        sites_in_area = []

        for n in idx.intersection(shape(area_geometry).bounds, objects=True):
            point = Point(n.object.coordinates)
            if shape(area_geometry).contains(point):
                sites_in_area.append(n.object)

        return sites_in_area
github pedrocamargo / map_matching / old_code / 02_Finding_Routes_multiprocessed.py View on Github external
print >>f, 'Reading graph'
    graph = Graph()
    graph.add_single_field('real_length')
    graph.load_graph_from_disk(P.shape_folder + P.graph_file)
    graph.set_graph(10, cost_field = 'length')
    orig_cost=graph.cost.copy()

    results= PathResults()
    results.prepare(graph)
    results.reset()

    print >> f,  'Reading network nodes'
    nodes = pd.read_csv(P.shape_folder + P.node_list)
    nodes = nodes.set_index('ID')
    print >> f,  "Assembling spatial index"
    idx = index.Index()
    for q in nodes.index:
        x = nodes.X[q]
        y = nodes.Y[q]
        bbox=(y, x, y, x)
        idx.insert(q, bbox)

    err = 0
    #sleep(chunk * 8)
    succ = False

    for i in range(500):
        try:
            print >> f,  'Loading unique truck IDs'
            retrieve = pd.HDFStore(P.truck_stats_folder + ProcessingFile[0:-8] + 'truck_stats.h5')
            truck_stats = retrieve['truck_stats']
            retrieve.close()
github pedrocamargo / map_matching / old_code / 02_Finding_Routes.py View on Github external
distances = {}
                            origin = stop_sequence[i][0]
                            destination = stop_sequence[i + 1][0]
                            if origin != destination:
                                arrives_tstamps = {}
                                leaves_tstamps = {}
                                path_computation(origin, destination, graph, results)
                                if results.path is not None:
                                    all_links.append(results.path.copy())
                                    all_links.append(x)
                                    all_nodes.append(results.pathnodes)

                                    #Now we build a spatial index with the subset of pings in the truck trace between the origin and destination
                                    ping_subset = truck_trace[(truck_trace.readdate > stop_sequence[i][1] + timedelta(seconds=stop_sequence[i][2])) & (truck_trace.readdate < stop_sequence[i + 1][1])]

                                    temp_idx = index.Index()
                                    for q in all_nodes[-1]:
                                        x = nodes.X[q]
                                        y = nodes.Y[q]
                                        bbox=(x, y, x, y)
                                        temp_idx.insert(q, bbox)

                                    for k in ping_subset.index:
                                        x = truck_trace.x[k]
                                        y = truck_trace.y[k]
                                        near = list(temp_idx.nearest((x, y, x, y), 1))
                                        if len(near) > 0:
                                            q = near[0]
                                            x2 = nodes.X[q]
                                            y2 = nodes.Y[q]
                                            d = gc((y, x), (y2, x2))
                                            if q not in distances:
github pedrocamargo / map_matching / old_code / 02_Finding_Routes_multiprocessed.py View on Github external
distances = {}
                origin = stop_sequence[i]
                destination = stop_sequence[i+1]
                if origin != destination:
                    path_computation(origin, destination, graph, results)
                    if results.path is not None:
                        all_links.append(results.path.copy())
                        all_links.append(x)
                        all_nodes.append(results.pathnodes)

                        # Now we build a spatial index with the subset of pings in the truck trace between the origin and destination
                        ping_subset = truck_trace[
                            (truck_trace.readdate > stop_sequence[i][1] + timedelta(seconds=stop_sequence[i][2])) & (
                            truck_trace.readdate < stop_sequence[i + 1][1])]

                        temp_idx = index.Index()
                        for q in all_nodes[-1]:
                            x = nodes.X[q]
                            y = nodes.Y[q]
                            bbox = (x, y, x, y)
                            temp_idx.insert(q, bbox)

                        for k in ping_subset.index:
                            x = truck_trace.x[k]
                            y = truck_trace.y[k]
                            near = list(temp_idx.nearest((x, y, x, y), 1))
                            if len(near) > 0:
                                q = near[0]
                                x2 = nodes.X[q]
                                y2 = nodes.Y[q]
                                d = gc((y, x), (y2, x2))
                                if q not in distances: