예제 #1
0
파일: model.py 프로젝트: mechtaev/rats
 def update_enemy_index(self, colony, model):
     rats = []
     for other_colony in model.colonies:
         if other_colony == colony:
             continue
         else:
             rats += other_colony.get_rats()
     if len(rats) > 0:
         self.index = quadtree.QuadTree(rats, 5)  # magic number
     else:
         self.index = None
예제 #2
0
def main():
    tree = quadtree.QuadTree(0.0, 0.0, 500.0, 500.0)
    counts = [0]
    i = 1
    while True:
        dC = crater(tree)
        counts.append(counts[i - 1] + dC)
        if counts[i / 2] * 1.05 > counts[i]:
            break
        i += 1
    print 'Time: %d years\tCrater count: %d' % (i * 1000, counts[i])
예제 #3
0
def test_quadtree_query():
    pos = np.random.uniform(size=(100, 2))

    qt = quadtree.QuadTree((0.5, 0.5), 0.5001)
    for i in range(50):
        qt.insert(pos[i])
    qt.insert_points(pos[50:])
    qres = qt.query(np.array([0.5, 0.5]), 0.1001)

    v = (abs(pos - [[0.5, 0.5]]) < 0.1001).all(axis=1)
    orig = set(tuple(q) for q in pos[v])
    proc = set(tuple(q) for q in qres)

    assert (len(proc) == qres.shape[0])
    assert (orig == proc)
예제 #4
0
def test_quadtree_query_self(cutoff):
    pos = np.random.uniform(size=(100, 2))

    qt = quadtree.QuadTree((0.5, 0.5), 0.5001)
    qt.insert_points(pos)

    qres = qt.query_self(cutoff)

    orig = {
        frozenset({
            tuple(pos[i])
            for i in range(pos.shape[0])
            if (i != j) and (abs(pos[i] - pos[j]) < cutoff).all()
        })
        for j in range(pos.shape[0])
    }
    proc = {frozenset({tuple(q) for q in a}) for a in qres}
    assert (orig == proc)
예제 #5
0
    def __init__(self, nodes, fixedEdges, minDistanceEdgeToNode):
        ## List of all nodes in the graph, as GraphNodes
        self.nodes = list(nodes)

        ## Set of GraphNode pairs representing edges that must be in the
        # final graph.
        self.fixedEdges = fixedEdges

        # Figure out the min/max extent of the nodes
        minX = minY = maxX = maxY = None
        for node in nodes:
            if minX is None:
                minX = maxX = node.x
                minY = maxY = node.y
            minX = min(minX, node.x)
            maxX = max(maxX, node.x)
            minY = min(minY, node.y)
            maxY = max(maxY, node.y)
        self.min = Vector2D(minX - 1, minY - 1)
        self.max = Vector2D(maxX + 1, maxY + 1)

        # Make a tree to hold the nodes so we can quickly look up which
        # nodes are near a given edge.
        rect = pygame.rect.Rect(self.min.x, self.min.y, self.max.x, self.max.y)
        self.nodeTree = quadtree.QuadTree(rect)
        self.nodeTree.addObjects([VectorWrap(v) for v in self.nodes])

        ## Maps node to list of nodes it is connected to.
        self.edges = dict()
        ## Minimum distance between an edge and any node not in that edge.
        # Violators will be pruned.
        self.minDistanceEdgeToNode = minDistanceEdgeToNode
        ## Number of times we've drawn, for saving output
        self.drawCount = 0
        ## A font for output; strictly for debugging purposes.
        self.font = pygame.font.Font(
            os.path.join(constants.fontPath, 'MODENINE.TTF'), 14)
예제 #6
0
import quadtree
import random
import pygame
from pygame.locals import *
import sys

##def createNewData():
##    return (random.randint(0,640),random.randint(0,480))

tree = quadtree.QuadTree(0,0,640,480)
points = []

##for i in range(80):
##    newdata = createNewData()
##    newNodeData = quadtree.NodeData(newdata[0], newdata[1], "adat")
##    tree.addData(newNodeData)
##    points.append(newNodeData)
    
pygame.init()
screen = pygame.display.set_mode((640,480), HWSURFACE | DOUBLEBUF)

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == MOUSEBUTTONDOWN:
            newNodeData = quadtree.NodeData(event.pos[0], event.pos[1], "adat")
            tree.addData(newNodeData)
            points.append(newNodeData)
예제 #7
0
	dtb =  db.Database(fields)
	field_idx = dtb.fields()
	
	# Load the data
	data_loader = dl.DataLoader()
	data_loader.load(args,dtb)

	# Create KDTree
	tree = kd.KDTree(dtb, {'max-depth' : args.max_depth, 'max-elements' : args.max_elements})

	plotter = pl.Plotter(tree,dtb,args)


	# Testing: Implementing the QuadTree
	if args.quadtree:
		quadtree = qt.QuadTree(tree.bounding_box(), args.quadtree)
		if args.quadshow:
			plotter.add_quadtree(quadtree)

	# Testing: Implementing the KDTree
	if args.closest:
		# This is for testing, to check if your closest query is correclty implemented

		# Step 1 query and fetch		
		closest_query = np.fromstring(args.closest,dtype=float, sep=' ')
		closest_records = dtb.query(tree.closest(closest_query))

		# Step 2 compare found geometry with closest_point	
		geometries= [ [x[field_idx["x"]],x[field_idx["y"]] ] for x in closest_records]
		distances = [np.linalg.norm(closest_query - geom) for geom in geometries]
		ordered = np.argsort(distances)
예제 #8
0
파일: temp.py 프로젝트: emapple/image_comp
import quadtree as qt
import svd
import makeimage as mi
import matplotlib.pyplot as plt
import numpy as np

if __name__ == '__main__':
    #datalist=mi.read_fits('images/uba10104m_d0m.fits')
    datalist = mi.read_fits('images/icsh10l9q_flt.fits')
    #data=[mi.make2n(datalist[1])]
    data = [datalist[0][:, :-1]]
    tree = qt.QuadTree(data[0])

    print 'done building tree'

    for i in np.arange(.05, .5, .05):
        tree.prune(i)
        tree.decompress()
        recon = qt.makedata(tree)
        data.append(recon.data)
        print 'done with {}'.format(i)

    print 'done pruning'

    for i in range(len(data)):
        plt.figure()
        plt.imshow(data[i], interpolation='none', cmap='gray')
        #plt.xlim([0,800])
        #plt.ylim([800,0])
        plt.title('tolerance={}'.format(i * .05))
예제 #9
0
 def setup(self):
     if self.objectTree is None:
         self.objectTree = quadtree.QuadTree(game.map.getBounds())
예제 #10
0
파일: split.py 프로젝트: Zupicz/Homework
# choose the treshold for the splitting algorithm
# threshold represents the maximal amount of points in one square
NodeCapacity = 50

# load data from the input file and save them in the variable 'data'
data = quadtree.Data('input.geojson')

# extract points from 'data' and save them in the list 'point_list'
point_list = data.extractPoints()

# create an object for class SquareUtil, which will in turn create the initial bounding box
SquareObject = quadtree.SquareUtil()

# create the initial bounding box 'rootSquare' with dimensions corresponding
# to the coordinates of points in 'point_list'
rootSquare = SquareObject.initSquare(point_list)

# create an object of class QuadTree,
# argument here defines the maximal capacity of the individual squares
qt = quadtree.QuadTree(NodeCapacity)

# split the object 'qt' recursively using the QuadTree algorithm
qt.split(rootSquare)

# add property 'cluster_id' to the 'features' list in the input file
# and assign corresponding values of the points in 'point_list',
# export the result as a new geojson file 'output.geojson'
data.addClusterID(point_list)

예제 #11
0
    BLUE = (0, 0, 255)

    dd = [1000, 1000]
    game_display = pygame.display.set_mode(dd)
    pygame.display.set_caption('Quad Tree Test')
    pygame.display.update()

    game_exit = False
    clock = pygame.time.Clock()
    fps = 100
    one_pressed = False
    three_pressed = False
    state = True
    counter = 0
    boundary = qtr.Boundary(0, 0, dd[0], dd[1])
    quadtree = qtr.QuadTree(boundary, 4)
    rectangle = None
    points_in_range = []
    points = []
    # for i in range(1000):
    #     p = qtr.Point(random.gauss(dd[0]/2, dd[0]/8), random.gauss(dd[1]/2, dd[1]/8))
    #     quadtree.insert(p)
    #     points.append(p)
    # for j in range((dd[0]/2)-10, (dd[0]/2)+10):
    #     for k in range((dd[1]/2)-10, (dd[1]/2)+10):
    #         p = qtr.Point(j, k)
    #         points.append(p)
    #         quadtree.insert(p)

    while not game_exit:
        # boundary = qtr.Boundary(0, 0, dd[0], dd[1])
예제 #12
0
파일: scene.py 프로젝트: edric7/Engine2D
 def __init__(self, width, height):
     self.entities = []
     self.width = width
     self.height = height
     self.camera_offset = [0, 0]
     self.quadtree = quadtree.QuadTree(0, (0, 0, width, height), self)