def main(): spindex = pyqtree.Index(bbox=[0,0,360,180]) cities = loadCities() file.write('============================================================================================') file.write('All cities within the bounding box: [45.011419, -111.071777 , 40.996484, -104.040527]:\n') for c in cities: #{'lat': '-18.01274', 'Country': 'Zimbabwe', 'lon': '31.07555', 'Name': 'Chitungwiza'} item = c['Name'] minLat = float(c['lat'])-.1 minLon = float(c['lon'])-.1 maxLat = float(c['lat'])+.1 maxLon = float(c['lon'])+.1 bbox =[float(c['lat']),float(c['lon']),float(c['lat']),float(c['lon'])] spindex.insert(item=item, bbox=bbox) overlapbbox = (44.9793710,-110.9619141,41.1941565,-104.2822266) matches = spindex.intersect(overlapbbox) file.write(matches) lat1 = 33.912523 lon1 = -98.497925 print(displace(lat1,lon1,270,300))
def __init__(self, D0): self._D0 = 1. * D0 bbox = (-180, -90, 180, 90) self._spidx = pyqtree.Index(bbox) self._points = [] self._clusters_by_item = None self._clusters = None
def init_topology(self): # init spatial index qt_box = None for feature in self.road_features: box = get_feature_box(feature) qt_box = max(qt_box, box) if qt_box else box self.spatial_index = pyqtree.Index(qt_box) # add link feature in index for feature in self.road_features: box = get_feature_box(feature) link = Link(feature) self.spatial_index.insert(link, box) self.link_list.append(link) # build topology relationship for link in self.link_list: geometry = link.feature.GetGeometryRef() points = geometry.GetPoints() s_point = points[0] e_point = points[-1] if not link.snode: self._create_node(s_point) if not link.enode: self._create_node(e_point)
def __init__( self, name: str, max_width: float = 1e8, max_height: float = 1e8 ) -> None: """constructor""" # Construct super(AutoPlacer, self).__init__() # get width and height self.max_width = max_width self.max_height = max_height global COUNTER, AUTOPLACER_REGISTRY if name in ap.AUTOPLACER_REGISTRY: self.name = "{}_{}".format(name, ap.COUNTER) ap.COUNTER += 1 else: self.name = name ap.AUTOPLACER_REGISTRY[self.name] = self # Register ap.WORKING_MEMORY["__AutoPlacer_{}".format(self.name)] = self # Create the quadtree which will enable efficient queries bbox = (0, 0, self.max_width, self.max_height) self.quadtree = pyqtree.Index(bbox=bbox) # Make a topcell self.create_cell(self.name)
def main(): spindex = pyqtree.Index(bbox=[0, 0, 360, 180]) cities = loadCities() for c in cities: #{'lat': '-18.01274', 'Country': 'Zimbabwe', 'lon': '31.07555', 'Name': 'Chitungwiza'} item = c['Name'] minLat = float(c['lat']) - .1 minLon = float(c['lon']) - .1 maxLat = float(c['lat']) + .1 maxLon = float(c['lon']) + .1 bbox = [minLat, minLon, maxLat, maxLon] spindex.insert(item=item, bbox=bbox) overlapbbox = (51, 51, 86, 86) overlapbbox = (44.9793710, -110.9619141, 41.1941565, -104.2822266) matches = spindex.intersect(overlapbbox) print(matches) lat1 = 33.912523 lon1 = -98.497925 print(displace(lat1, lon1, 270, 300))
def calculate_quad_tree(self, subverts=None): """ Recalculate the quad tree with all vertices, or a subselection of vertices """ self.vertex_quad_tree = pyqtree.Index(bbox=self.bbox) verts = self.vertices if subverts is not None: assert (all([isinstance(x, Vertex) for x in subverts])) verts = subverts for vertex in verts: self.vertex_quad_tree.insert(item=vertex, bbox=vertex.bbox())
def main(): start_time = time.time() spindex = pyqtree.Index(bbox=[0, 0, 360, 180]) cities = loadCities() out = open('output.dat', 'w') out.write("Jacob Taylor \n10/22/2015 \nProgram 1 - Intro to Quadtrees\n") out.write( "============================================================================================\n" ) out.write( "1. All cities within the bounding box: [45.011419, -111.071777 , 40.996484, -104.040527]:\n\n" ) """ Loops through all the cities and checks if they are within the given bounding box. If the city is withing the bounding box it is written to the file """ for c in cities: #{'lat': '-18.01274', 'Country': 'Zimbabwe', 'lon': '31.07555', 'Name': 'Chitungwiza'} item = c['Name'] minLat = float(c['lat']) - .1 minLon = float(c['lon']) - .1 maxLat = float(c['lat']) + .1 maxLon = float(c['lon']) + .1 bbox = [minLat, minLon, maxLat, maxLon] spindex.insert(item=item, bbox=bbox) """overlapbbox = (51,51,86,86)""" overlapbbox = (45.011419, -111.071777, 40.996484, -104.040527) matches = spindex.intersect(overlapbbox) out.write("\n".join(str(x) for x in matches)) out.write( "\n============================================================================================\n" ) out.write( "2. All cities within 500 miles of this point: (23.805450, -78.156738):\n" ) """ Loops through all the cities in the csv file and compares their ditance from a given point If the distance is within 500 miles the city is written out to the file """ for c in cities: lat1 = float(c['lat']) lon1 = float(c['lon']) distance = haversine((lat1, lon1), (23.805450, -78.156738), miles=True) if distance <= 500: out.write("\n") out.write(c['Name']) out.write( "\n============================================================================================\n" ) out.write("\nProgram ran in %s seconds." % (time.time() - start_time)) out.close
def __init__(self, *args, **kwargs): self._index = pyqtree.Index(*args, **kwargs) self._bbox = ( self._index.center[0] - self._index.width / 2, self._index.center[1] - self._index.height / 2, self._index.center[0] + self._index.width / 2, self._index.center[1] + self._index.height / 2, ) self._bounds = {}
def main(): start_time = time.time() f = open('output.dat', 'w') #open outfile and write in the file #writ headline in the outfile f.write("Ahla Cho\n") f.write("9-13-2015\n") f.write( "============================================================================\n" ) f.write( "1. All Cities within the bounding box:[45.011419, -111.071777 , 40.996484, -104.040527]:" ) spindex = pyqtree.Index(bbox=[0, 0, 360, 180]) cities = loadCities() for c in cities: #{'lat': '-18.01274', 'Country': 'Zimbabwe', 'lon': '31.07555', 'Name': 'Chitungwiza'} item = c['Name'] bbox = [ float(c['lat']), float(c['lon']), float(c['lat']), float(c['lon']) ] spindex.insert(item=item, bbox=bbox) overlapbbox = (45.011419, -111.071777, 40.996484, -104.040527 ) #new value of overlapbbox matches = spindex.intersect(overlapbbox) for places in matches: f.write(str(places) + "\n") #North lon1 = displace(23.805450, -78.156738, 90, 500) #South lon2 = displace(23.805450, -78.156738, 270, 500) #West lat1 = displace(23.805450, -78.156738, 180, 500) #East lat2 = displace(23.805450, -78.156738, 0, 500) overlapbbox = (lat1[0], lon1[1], lat2[0], lon2[1]) f.write( "============================================================================\n" ) f.write( "2. All Cities within 500 miles of this point: (displace (23.805450,-78.156738):\n" ) matches = spindex.intersect(overlapbbox) for places in matches: f.write(str(places) + "\n") f.write( "============================================================================\n" ) f.write("Program ran in %s seconds." % (time.time() - start_time))
def main(): output = open('output.dat', 'wb') start_time = time.time() spindex = pyqtree.Index(bbox=[0, 0, 360, 180]) cities = loadCities() output.write( "Christopher Silva\n9/15/2015\nProgram 1 - Intro to Quadtrees\n") for c in cities: #{'lat': '-18.01274', 'Country': 'Zimbabwe', 'lon': '31.07555', 'Name': 'Chitungwiza'} item = c['Name'] bbox = [ float(c['lat']), float(c['lon']), float(c['lat']), float(c['lon']) ] spindex.insert(item=item, bbox=bbox) overlapbbox = (45.011419, -111.071777, 40.996484, -104.040527) matches = spindex.intersect(overlapbbox) output.write( "============================================================================================\n" ) output.write( "1. All cities within the bounding box: [45.011419, -111.071777 , 40.996484, -104.040527]:\n" ) for city in matches: output.write(city + "\n") #[23.604285730664866, -70.25584731917634] #[31.041593476111853, -78.156738000000004] #[23.604285730664866, -86.057628680823669] #[16.569306894262152, -78.156738000000004] overlapbbox = (16.569306894262152, -86.057628680823669, 31.041593476111853, -70.25584731917634) matches = spindex.intersect(overlapbbox) output.write( "============================================================================================\n" ) output.write( "2. All cities within 500 miles of this point: (23.805450, -78.156738):\n" ) for city in matches: output.write(city + "\n") output.write( "============================================================================================\n" ) output.write(("Program ran in %s seconds." % (time.time() - start_time))) output.close()
def build_qtree_ref(results): min_lat = min(x[0].lat for x in results) max_lat = max(x[0].lat for x in results) min_lon = min(x[0].lon for x in results) max_lon = max(x[0].lon for x in results) spindex = pyqtree.Index(bbox=(min_lon, min_lat, max_lon, max_lat)) for loc, atype, name in tqdm(results): lat, lon = loc.lat, loc.lon bbox = (lon, lat, lon, lat) spindex.insert(atype, bbox) return spindex
def __init__(self, ctx, sizeTuple, delta=0.001): global DELTA delta = delta self.ctx = ctx self.sX = sizeTuple[0] self.sY = sizeTuple[1] #nodes: self.nodes = np.zeros((NODE_NUM, NODE_NUM)) self.frontier = [] self.paths = [] self.nextPathIndex = 0 self.qtree = pyqtree.Index(bbox=[0.0, 0.0, 1.0, 1.0])
def make_qtree(boxes, **kwargs): xmin = min(map(lambda x: x.x_min, boxes)) xmax = max(map(lambda x: x.x_max, boxes)) ymin = min(map(lambda x: x.y_min, boxes)) ymax = max(map(lambda x: x.y_max, boxes)) bbox = (xmin, ymin, xmax, ymax) qtree = pyqtree.Index(bbox, **kwargs) for box in boxes: qtree.insert(box, box.points) # print(qtree.insert(box, box.points)) return qtree
def insert_item(self, item: WithBounds, position: Position): bounds = item.bounds() corners = [ (bounds.x, bounds.y), (bounds.x + bounds.width, bounds.y), (bounds.x, bounds.y + bounds.height), (bounds.x + bounds.width, bounds.y + bounds.height), ] corners = [ ( (math.cos(position.angle) * x + math.sin(position.angle) * y), (math.sin(position.angle) * x + math.cos(position.angle) * y), ) for x, y in corners ] bbox = ( position.x + min(x for x, y in corners), position.y + min(y for x, y in corners), position.x + max(x for x, y in corners), position.y + max(y for x, y in corners), ) previous_bbox = self._bounds.get(item) if bbox == previous_bbox: return if previous_bbox: self._index.remove(item, previous_bbox) self._bounds[item] = bbox if ( bbox[0] <= self._bbox[0] or bbox[1] <= self._bbox[1] or bbox[2] >= self._bbox[2] or bbox[3] >= self._bbox[3] ): # If it falls outside the quadtree bounds, increase the size of the quadtree to fits minx, miny, maxx, maxy = -80.0, -80.0, 80.0, 80.0 for item_minx, item_miny, item_maxx, item_maxy in self._bounds.values(): minx, miny = min(minx, item_minx), min(miny, item_miny) maxx, maxy = max(maxx, item_maxx), max(maxy, item_maxy) minx, maxx = minx - (maxx - minx) * 0.2, maxx + (maxx - minx) * 0.2 miny, maxy = miny - (maxy - miny) * 0.2, maxy + (maxy - miny) * 0.2 self._index = pyqtree.Index(bbox=(minx, miny, maxx, maxy)) self._bbox = (minx, miny, maxx, maxy) for item, item_bbox in self._bounds.items(): self._index.insert(item, item_bbox) else: self._index.insert(item, bbox)
def __init__(self, points): ''' Create an index over the specified points. Each element must have x and y attributes. ''' # compute bounding box r = get_empty_rectangle() for point in points: r.extend_to_contain(point) self.index = pyqtree.Index(bbox=(r.min_point.x - 1, r.min_point.y - 1, r.max_point.x + 1, r.max_point.y + 1)) # insert points into index, with bounding box being unit square around the point for point in points: self.index.insert(point, (point.x - 0.5, point.y - 0.5, point.x + 0.5, point.y + 0.5))
def create(index_file, bbox, parse_fn, *parse_args): logger = logging.getLogger("index") idx = pyqtree.Index(bbox=bbox) n = 0 with open(index_file, 'r') as f: files = yaml.load(f, Loader=yaml.FullLoader) for f in files: t = parse_fn(f, *parse_args) if t: idx.insert(bbox=t.bbox.bounds, item=t) n += 1 logger.info("Created index with %d objects." % n) return idx
def __init__(self, bbox=None): if bbox is None: bbox = np.array([-200, -200, 200, 200]) assert (isinstance(bbox, np.ndarray)) assert (len(bbox) == 4) self.vertices = set([]) self.faces = set([]) self.halfEdges = set([]) self.bbox = bbox #todo: make this a stack of quadtrees self.vertex_quad_tree = pyqtree.Index(bbox=self.bbox) self.quad_tree_stack = [] self.frontier = set([]) self.should_merge_stacks = True self.data = {}
def build_qtree(): with open("<PATH>/amenity_coords.csv") as f: xs = [(float(lat), float(lon), atype, name) for (lat, lon, atype, name) in [ line.strip().split(",") for line in f.readlines()[1:] if len(line.split(",")) == 4 ]] min_lat = min(x[0] for x in xs) max_lat = max(x[0] for x in xs) min_lon = min(x[1] for x in xs) max_lon = max(x[1] for x in xs) spindex = pyqtree.Index(bbox=(min_lon, min_lat, max_lon, max_lat)) for lat, lon, atype, name in tqdm(xs): bbox = (lon, lat, lon, lat) spindex.insert((atype, name), bbox) return spindex
def main(): spindex = pyqtree.Index(bbox=[45.011419,-111.071777,40.996484,-104.040527]) cities = loadCities() for c in cities: #{'lat': '-18.01274', 'Country': 'Zimbabwe', 'lon': '31.07555', 'Name': 'Chitungwiza'} item = c['Name'] bbox =[float(c['lat']),float(c['lon']),float(c['lat']),float(c['lon'])] spindex.insert(item=item, bbox=bbox) overlapbbox = (51,51,86,86) matches = spindex.intersect(overlapbbox) print(matches) lat1 = 33.912523 lon1 = -98.497925 print(displace(lat1,lon1,270,300))
def _build_quadtree(size, n_loci, n_samples): """Build a quadtree.""" quadtree = pyqtree.Index(bbox=[0, 0, size, size]) # Randomly determine coordinates for each locus loci_coordinates = [] for _ in range(n_loci): locus_x_coord = random.gauss(size/2.0, size/6.0) locus_y_coord = random.gauss(size/2.0, size/6.0) loci_coordinates.append([locus_x_coord, locus_y_coord]) for _ in range(n_samples): center = random.choice(loci_coordinates) point = [ clamp(random.gauss(center[0], size/6.0), 0, size-1), clamp(random.gauss(center[1], size/6.0), 0, size-1) ] point += [point[0]+1, point[1]+1] quadtree.insert(point, point) return quadtree
def main(): start_time = time.time() f = open('output.dat', 'w') spindex = pyqtree.Index(bbox=[0,0,360,180]) cities = loadCities() for c in cities: #{'lat': '-18.01274', 'Country': 'Zimbabwe', 'lon': '31.07555', 'Name': 'Chitungwiza'} item = c['Name'] bbox =[float(c['lat']),float(c['lon']),float(c['lat']),float(c['lon'])] spindex.insert(item=item, bbox=bbox) overlapbbox = (45.011419, -111.071777 , 40.996484, -104.040527) f.write("Michael Ellerkamp\n") f.write("9/14/15\n") f.write("=========================================================================================\n") f.write("1. All cities within the bounding box: [45.011419, -111.071777 , 40.996484, -104.040527]:\n") matches = spindex.intersect(overlapbbox) for place in matches: f.write(str(place) + "\n") #west lat1 = displace(23.805450,-78.156738,180,500) #north lon1 = displace(23.805450,-78.156738,90,500) #east lat2 = displace(23.805450,-78.156738,0,500) #south lon2 = displace(23.805450,-78.156738,270,500) #print lat1 #print lon1 #print lat2 #print lon2 #displace returns an array so now we reference only the data we want from #our displace calls. overlapbbox = (lat1[0], lon1[1], lat2[0], lon2[1]) f.write("=========================================================================================\n") f.write("2. All cities within 500 miles of this point: (23.805450, -78.156738):\n") matches = spindex.intersect(overlapbbox) for place in matches: f.write(str(place) + "\n") f.write("=========================================================================================\n") f.write("Program ran in %s seconds." % (time.time() - start_time))
def main(): start_time = time.time() f = open('output.dat', 'w') f.write( 'Samuel Klose\n9/15/2015\nProgram 1 - Intro to Quadtrees\n============================================================================================\n' ) spindex = pyqtree.Index(bbox=[0, 0, 360, 180]) cities = loadCities() f.write( 'All cities within the bounding box: [45.011419, -111.071777 , 40.996484, -104.040527]:\n' ) for c in cities: #{'lat': '-18.01274', 'Country': 'Zimbabwe', 'lon': '31.07555', 'Name': 'Chitungwiza'} item = c['Name'] bbox = [ float(c['lat']), float(c['lon']), float(c['lat']), float(c['lon']) ] spindex.insert(item=item, bbox=bbox) overlapbbox = (45.011419, -111.071777, 40.996484, -104.040527) matches = spindex.intersect(overlapbbox) s = str(matches) f.write(s) f.write( '\n============================================================================================\nAll cities within 500 miles of this point: (23.805450, -78.156738):\n' ) lat1 = 23.805450 lon1 = -78.156738 minX = displace(lat1, lon1, 270, 500) maxX = displace(lat1, lon1, 90, 500) minY = displace(lat1, lon1, 180, 500) maxY = displace(lat1, lon1, 0, 500) overlapbbox = (minY[0], minX[1], maxY[0], maxX[1]) matches = spindex.intersect(overlapbbox) s = str(matches) f.write(s) f.write("Program ran in %s seconds." % (time.time() - start_time)) f.close()
def main(): spindex = pyqtree.Index(bbox=[0, 0, 100, 100]) points = [(39, 21), (86, 19), (65, 5), (76, 28), (3, 9), (31, 59), (43, 99), (60, 50), (42, 48), (15, 73), (67, 98), (16, 34), (27, 80), (51, 77), (30, 67), (82, 68), (85, 46), (89, 44), (21, 30), (5, 66), (75, 29), (17, 14), (40, 90), (18, 33), (52, 64), (1, 71), (88, 10), (64, 26), (96, 2), (25, 40)] n = 0 for p in points: minx = p[0] - 1 miny = p[1] - 1 maxx = p[0] + 1 maxy = p[1] + 1 it = str(p[0]) + "," + str(p[1]) bbox = [minx, miny, maxx, maxy] spindex.insert(item=it, bbox=bbox) n += 1 printNodes(spindex)
def _build_index(dset, verbose=0): """ """ if verbose: print('Building isect index') qtrees = { img['id']: pyqtree.Index((0, 0, img['width'], img['height'])) for img in ub.ProgIter( dset.dataset['images'], desc='init qtrees', verbose=verbose) } for qtree in qtrees.values(): qtree.aid_to_tlbr = {} # Add extra index to track boxes for ann in ub.ProgIter(dset.dataset['annotations'], desc='populate qtrees', verbose=verbose): bbox = ann.get('bbox', None) if bbox is not None: aid = ann['id'] qtree = qtrees[ann['image_id']] xywh_box = kwimage.Boxes(bbox, 'xywh') tlbr_box = xywh_box.to_tlbr().data qtree.insert(aid, tlbr_box) qtree.aid_to_tlbr[aid] = tlbr_box return qtrees
def push_quad_tree(self): self.quad_tree_stack.append(self.vertex_quad_tree) self.vertex_quad_tree = pyqtree.Index(bbox=self.bbox)
def __init__(self, **kwargs): import pyqtree self._backend = pyqtree.Index(**kwargs)
import pyqtree import random, time class Item: def __init__(self, x, y): left = x-1 right = x+1 top = y-1 bottom = y+1 self.bbox = [left,top,right,bottom] #setup and populate index items = [Item(random.randrange(5,95),random.randrange(5,95)) for _ in range(10000)] spindex = pyqtree.Index(bbox=[-11,-33,100,100]) for item in items: spindex.insert(item, item.bbox) #test intersection print("testing hit") testitem = (51,51,86,86) t = time.time() matches = spindex.intersect(testitem) print(time.time()-t, " seconds")
print len(items) print 'building' spindex = QuadTree(-180, -90, 180, 90) if PROFILE: import cProfile prof = cProfile.Profile() prof.enable() spindex.build(items) if PROFILE: print prof.print_stats('cumtime') #fdsdfd print 'building pyqtree comparison, much faster' # MAYBE CONSIDER USING PYQTREE TO CONSTRUCT, THEN DUMP TO SQL FOR STORAGE AND INTERSECT QUERY import pyqtree pyq = pyqtree.Index(bbox=[-180, -90, 180, 90]) if PROFILE: import cProfile prof = cProfile.Profile() prof.enable() for i, bbox in items: pyq.insert(i, bbox) if PROFILE: print prof.print_stats('cumtime') #fdsdfd print len(pyq) print 'intersecting' testbox = (100, 15, 105, 20) #(100,1,120,20) if PROFILE: import cProfile
class Item: def __init__(self, x, y): left = x - 1 right = x + 1 top = y - 1 bottom = y + 1 self.bbox = [left, top, right, bottom] #setup and populate index items = [ Item(random.randrange(5, 95), random.randrange(5, 95)) for _ in range(10000) ] spindex = pyqtree.Index(bbox=[-11, -33, 100, 100]) for item in items: spindex.insert(item, item.bbox) print("{0} members in this index.".format(len(spindex))) #test intersection print("testing hit") testitem = (51, 51, 86, 86) t = time.time() matches = spindex.intersect(testitem) print("{0} seconds".format(time.time() - t)) #test countmembers() # trivial list of items items = [Item(0.5, 0.5), Item(-0.5, 0.5), Item(-0.5, -0.5), Item(0.5, -0.5)]
import numpy as np import matplotlib.pyplot as plt import pyqtree np.random.seed(5) # Generating data - can also import x = np.arange(1, 101) + 25 y = 20 + 3 * x + np.random.normal(0, 60, 100) spindex = pyqtree.Index(bbox=[0,-100,100,400]) items = [] for i in range(1, len(x)): #print x.item(i), y.item(i) obj = lambda:None obj.x = x.item(i) obj.y = y.item(i) obj.bbox = [x.item(i)-0.5, y.item(i)-0.5, x.item(i)+0.5, y.item(i)+0.5] items.append(obj) #this example assumes you have a list of items with bbox attribute for item in items: spindex.insert(item=item, bbox=item.bbox) overlapbbox = (51,51,86,186) matches = spindex.intersect(overlapbbox) #for m in matches: # print m.bbox