Ejemplo n.º 1
0
def generate(points):
    """Given a list of points construct balanced kd-tree."""
    if len(points) == 0:
        return None

    # VERTICAL=1 is the initial division
    tree = KDTree()
    tree.root = generateSubTree(1, 2, points, 0, len(points) - 1)
    propagate(tree.root, maxRegion)
    return tree
Ejemplo n.º 2
0
def generate(points):
    """Given a list of points construct balanced kd-tree."""
    if len(points) == 0:
        return None

    # VERTICAL=1 is the initial division
    tree = KDTree()
    tree.root = generateSubTree(1, 2, points, 0, len(points) - 1)
    propagate(tree.root, maxRegion)
    return tree
Ejemplo n.º 3
0
class TestKDMethods(unittest.TestCase):

    def setUp(self):
        self.kd = KDTree()
        
    def tearDown(self):
        self.kd = None
        
    def test_basic(self):
        self.assertTrue(self.kd.add((10, 20)))
        self.assertFalse(self.kd.add((10, 20)))
        self.assertTrue(self.kd.find((10,20)))
        
        self.assertFalse(self.kd.find((5, 5)))

    def expand(self, region):
        """When Full Sub-trees returned as nodes traverse to expand nodes."""
        result = [p for p in self.kd.range(region)]
        expanded = []
        for pair in result:
            if pair[1]:
                expanded = expanded + [d.point for d in pair[0].inorder()]
            else:
                expanded.append(pair[0].point)
                
        return expanded
        
    def test_adding(self):
        for _ in range(5000):
            self.kd.add((random.randint(250,750), random.randint(250,750)))
        
        # make sure not to overlap!
        q_ne = self.expand(Region(500, 500, 1000, 1000))
        q_nw = self.expand(Region(0, 500, 499, 1000))
        q_sw = self.expand(Region(0, 0, 499, 499))
        q_se = self.expand(Region(500, 0, 1000, 499))
        
        q_all = self.expand(Region(0,0, 1000, 1000))
        
        # quick check to see if any were missing
        combined = q_ne + q_nw + q_sw + q_se
        for q in q_all:
            if q not in combined:
                print (q, " missing ")
        
        self.assertEquals(len(q_all), len(combined))
        
        # validate searches are true
        for p in combined:
            self.assertTrue(self.kd.find(p))
            
        # validate can't add these points anymore
        for p in combined:
            self.assertFalse(self.kd.add(p))
Ejemplo n.º 4
0
    def __init__(self):
        """App for creating KD tree dynamically and executing nearest neighbor queries."""

        self.tree = KDTree()
        self.match = None
        self.shortline = None

        # set to true when you want to view a set of points that
        # were set not by user control.
        self.static = False

        self.master = tkinter.Tk()
        self.master.title('KD Tree Nearest Neighbor Application')
        self.w = tkinter.Frame(self.master, width=410, height=410)
        self.canvas = tkinter.Canvas(self.w, width=400, height=400)

        self.paint()

        self.canvas.bind("<Button-1>", self.click)
        self.canvas.bind("<Motion>", self.moved)
        self.w.pack()
Ejemplo n.º 5
0
    def __init__(self):
        """App for creating KD tree dynamically and executing range queries."""

        self.tree = KDTree()
        self.static = False

        # for range query
        self.selectedRegion = None
        self.queryRect = None

        self.master = tkinter.Tk()
        self.master.title('KD Tree Range Query Application')
        self.w = tkinter.Frame(self.master, width=410, height=410)
        self.canvas = tkinter.Canvas(self.w, width=400, height=400)

        self.paint()

        self.canvas.bind("<Button-1>", self.click)
        self.canvas.bind("<Motion>", self.moved)
        self.canvas.bind("<Button-3>", self.range)  # when right mouse clicked
        self.canvas.bind("<ButtonRelease-3>", self.clear)
        self.canvas.bind("<B3-Motion>",
                         self.range)  # only when right mouse dragged
        self.w.pack()
    def __init__(self):
        """App for creating KD tree dynamically and executing nearest neighbor queries."""
        
        self.tree = KDTree()
        self.match = None
        self.shortline = None
        
        # set to true when you want to view a set of points that
        # were set not by user control.
        self.static = False
        
        self.master = tkinter.Tk()
        self.master.title('KD Tree Nearest Neighbor Application')
        self.w = tkinter.Frame(self.master, width=410, height=410)
        self.canvas = tkinter.Canvas(self.w, width=400, height=400)        
                        
        self.paint()

        self.canvas.bind("<Button-1>", self.click)
        self.canvas.bind("<Motion>", self.moved)
        self.w.pack()
Ejemplo n.º 7
0
    def __init__(self):
        """App for creating KD tree dynamically and executing range queries."""
        
        self.tree = KDTree()
        self.static = False
        
        # for range query
        self.selectedRegion = None
        self.queryRect = None
        
        self.master = tkinter.Tk()
        self.master.title('KD Tree Range Query Application')
        self.w = tkinter.Frame(self.master, width=410, height=410)
        self.canvas = tkinter.Canvas(self.w, width=400, height=400)        
                        
        self.paint()

        self.canvas.bind("<Button-1>", self.click)
        self.canvas.bind("<Motion>", self.moved)
        self.canvas.bind("<Button-3>", self.range)   # when right mouse clicked
        self.canvas.bind("<ButtonRelease-3>", self.clear)
        self.canvas.bind("<B3-Motion>", self.range)  # only when right mouse dragged
        self.w.pack()
Ejemplo n.º 8
0
 def setUp(self):
     self.kd = KDTree()
Ejemplo n.º 9
0
class KDTreeApp:
    
    def __init__(self):
        """App for creating KD tree dynamically and executing range queries."""
        
        self.tree = KDTree()
        self.static = False
        
        # for range query
        self.selectedRegion = None
        self.queryRect = None
        
        self.master = tkinter.Tk()
        self.master.title('KD Tree Range Query Application')
        self.w = tkinter.Frame(self.master, width=410, height=410)
        self.canvas = tkinter.Canvas(self.w, width=400, height=400)        
                        
        self.paint()

        self.canvas.bind("<Button-1>", self.click)
        self.canvas.bind("<Motion>", self.moved)
        self.canvas.bind("<Button-3>", self.range)   # when right mouse clicked
        self.canvas.bind("<ButtonRelease-3>", self.clear)
        self.canvas.bind("<B3-Motion>", self.range)  # only when right mouse dragged
        self.w.pack()
        

    def toCartesian(self, y):
        """Convert tkinter point into Cartesian."""
        return self.w.winfo_height() - y

    def toTk(self,y):
        """Convert Cartesian into tkinter point."""
        if y == maxValue: return 0
        tk_y = self.w.winfo_height()
        if y != minValue:
            tk_y -= y
        return tk_y
         
    def clear(self, event):
        """End of range search."""
        self.selectedRegion = None
        self.paint()
        
    def range(self, event):
        """Initiate a range search using a selected rectangular region."""
        
        p = (event.x, self.toCartesian(event.y))
         
        if self.selectedRegion is None:
            self.selectedStart = Region(p[X],p[Y],  p[X],p[Y])
        self.selectedRegion = self.selectedStart.unionPoint(p)
        
        self.paint()
        
        # return (node,status) where status is True if draining entire tree rooted at node. Draw these
        # as shaded red rectangle to identify whole sub-tree is selected.
        for pair in self.tree.range(self.selectedRegion):
            p = pair[0].point
            
            if pair[1]:
                self.canvas.create_rectangle(pair[0].region.x_min, self.toTk(pair[0].region.y_min), 
                                             pair[0].region.x_max, self.toTk(pair[0].region.y_max),
                                             fill='Red', stipple='gray12')
            else:
                self.canvas.create_rectangle(p[X] - RectangleSize, self.toTk(p[Y]) - RectangleSize, 
                                             p[X] + RectangleSize, self.toTk(p[Y]) + RectangleSize, fill='Red')
        
        self.queryRect = self.canvas.create_rectangle(self.selectedRegion.x_min, self.toTk(self.selectedRegion.y_min),  
                                                     self.selectedRegion.x_max, self.toTk(self.selectedRegion.y_max), 
                                                     outline='Red', dash=(2, 4))
        
        
    def moved(self, event):
        """Only here for static option."""
        if self.static:
            self.paint()
        
    def click(self, event):
        """Add point to KDtree."""
        p = (event.x, self.toCartesian(event.y))
        
        self.tree.add(p)
             
        self.paint()

    def drawPartition (self, r, p, orient):
        """Draw partitioning line and points itself as a small square."""
        if orient == VERTICAL:
            self.canvas.create_line(p[X], self.toTk(r.y_min), p[X], self.toTk(r.y_max))
        else:
            xlow = r.x_min
            if r.x_min <= minValue: xlow = 0
            xhigh = r.x_max
            if r.x_max >= maxValue: xhigh = self.w.winfo_width()

            self.canvas.create_line(xlow, self.toTk(p[Y]), xhigh, self.toTk(p[Y]))

        self.canvas.create_rectangle(p[X] - RectangleSize, self.toTk(p[Y]) - RectangleSize,
                                     p[X] + RectangleSize, self.toTk(p[Y]) + RectangleSize, fill='Black')

    def visit (self, n):
        """ Visit node to paint properly."""
        if n == None: return

        self.drawPartition(n.region, n.point, n.orient)

        self.visit (n.below)
        self.visit (n.above)

    def prepare(self, event):
        """prepare to add points."""
        if self.label:
            self.label.destroy()
            self.label = None
            self.canvas.pack()
        
    def paint(self):
        """Paint quad tree by visiting all nodes, or show introductory message."""
        if self.tree.root:
            self.canvas.delete(tkinter.ALL)
            self.visit(self.tree.root)
        else:
            self.label = tkinter.Label(self.w, width=100, height = 40, text="Click To Add Points")
            self.label.bind("<Button-1>", self.prepare)
            self.label.pack()
Ejemplo n.º 10
0
class KDTreeApp:
    def __init__(self):
        """App for creating KD tree dynamically and executing nearest neighbor queries."""

        self.tree = KDTree()
        self.match = None
        self.shortline = None

        # set to true when you want to view a set of points that
        # were set not by user control.
        self.static = False

        self.master = tkinter.Tk()
        self.master.title('KD Tree Nearest Neighbor Application')
        self.w = tkinter.Frame(self.master, width=410, height=410)
        self.canvas = tkinter.Canvas(self.w, width=400, height=400)

        self.paint()

        self.canvas.bind("<Button-1>", self.click)
        self.canvas.bind("<Motion>", self.moved)
        self.w.pack()

    def toCartesian(self, y):
        """Convert tkinter point into Cartesian."""
        return self.w.winfo_height() - y

    def toTk(self, y):
        """Convert Cartesian into tkinter point."""
        if y == maxValue: return 0
        tk_y = self.w.winfo_height()
        if y != minValue:
            tk_y -= y
        return tk_y

    def moved(self, event):
        """React to mouse move events."""
        if self.static:
            self.paint()
            return

        p = (event.x, self.toCartesian(event.y))

        match = self.tree.find(p)
        if match:
            p = match.point
            self.canvas.create_rectangle(p[X] - RectangleSize,
                                         self.toTk(p[Y]) - RectangleSize,
                                         p[X] + RectangleSize,
                                         self.toTk(p[Y]) + RectangleSize,
                                         fill='Red',
                                         tags=closest)
            self.canvas.delete(self.shortline)
            self.shortline = None
        else:
            self.canvas.delete(closest)
            n = self.tree.nearest(p)
            if n:
                pn = n.point
                if self.shortline is None:
                    self.shortline = self.canvas.create_line(pn[X],
                                                             self.toTk(pn[Y]),
                                                             p[X],
                                                             self.toTk(p[Y]),
                                                             fill='Red',
                                                             dash=(2, 4),
                                                             tags=shortline)
                else:
                    self.canvas.coords(shortline, pn[X], self.toTk(pn[Y]),
                                       p[X], self.toTk(p[Y]))

    def click(self, event):
        """Add point to KDTree."""
        p = (event.x, self.toCartesian(event.y))

        self.tree.add(p)
        if self.shortline:
            self.canvas.delete(self.shortline)
            self.shortline = None

        self.paint()

    def drawPartition(self, r, p, orient):
        """Draw proper partition for given node (r,p) and orientation."""
        if orient == VERTICAL:
            self.canvas.create_line(p[X], self.toTk(r.y_min), p[X],
                                    self.toTk(r.y_max))
        else:
            xlow = r.x_min
            if r.x_min <= minValue: xlow = 0
            xhigh = r.x_max
            if r.x_max >= maxValue: xhigh = self.w.winfo_width()

            self.canvas.create_line(xlow, self.toTk(p[Y]), xhigh,
                                    self.toTk(p[Y]))

        self.canvas.create_rectangle(p[X] - RectangleSize,
                                     self.toTk(p[Y]) - RectangleSize,
                                     p[X] + RectangleSize,
                                     self.toTk(p[Y]) + RectangleSize,
                                     fill='Black')

    def visit(self, n):
        """Draw KDNode properly partitioned and its sub-children."""
        if n == None: return

        self.drawPartition(n.region, n.point, n.orient)

        self.visit(n.below)
        self.visit(n.above)

    def prepare(self, event):
        """prepare to add points."""
        if self.label:
            self.label.destroy()
            self.label = None
            self.canvas.pack()

    def paint(self):
        """Paint KDTree by visiting all nodes, or show introductory message."""
        if self.tree.root:
            self.canvas.delete(tkinter.ALL)
            self.visit(self.tree.root)
        else:
            self.label = tkinter.Label(self.w,
                                       width=100,
                                       height=40,
                                       text="Click To Add Points")
            self.label.bind("<Button-1>", self.prepare)
            self.label.pack()
Ejemplo n.º 11
0
class KDTreeApp:
    def __init__(self):
        """App for creating KD tree dynamically and executing range queries."""

        self.tree = KDTree()
        self.static = False

        # for range query
        self.selectedRegion = None
        self.queryRect = None

        self.master = tkinter.Tk()
        self.master.title('KD Tree Range Query Application')
        self.w = tkinter.Frame(self.master, width=410, height=410)
        self.canvas = tkinter.Canvas(self.w, width=400, height=400)

        self.paint()

        self.canvas.bind("<Button-1>", self.click)
        self.canvas.bind("<Motion>", self.moved)
        self.canvas.bind("<Button-3>", self.range)  # when right mouse clicked
        self.canvas.bind("<ButtonRelease-3>", self.clear)
        self.canvas.bind("<B3-Motion>",
                         self.range)  # only when right mouse dragged
        self.w.pack()

    def toCartesian(self, y):
        """Convert tkinter point into Cartesian."""
        return self.w.winfo_height() - y

    def toTk(self, y):
        """Convert Cartesian into tkinter point."""
        if y == maxValue: return 0
        tk_y = self.w.winfo_height()
        if y != minValue:
            tk_y -= y
        return tk_y

    def clear(self, event):
        """End of range search."""
        self.selectedRegion = None
        self.paint()

    def range(self, event):
        """Initiate a range search using a selected rectangular region."""

        p = (event.x, self.toCartesian(event.y))

        if self.selectedRegion is None:
            self.selectedStart = Region(p[X], p[Y], p[X], p[Y])
        self.selectedRegion = self.selectedStart.unionPoint(p)

        self.paint()

        # return (node,status) where status is True if draining entire tree rooted at node. Draw these
        # as shaded red rectangle to identify whole sub-tree is selected.
        for pair in self.tree.range(self.selectedRegion):
            p = pair[0].point

            if pair[1]:
                self.canvas.create_rectangle(pair[0].region.x_min,
                                             self.toTk(pair[0].region.y_min),
                                             pair[0].region.x_max,
                                             self.toTk(pair[0].region.y_max),
                                             fill='Red',
                                             stipple='gray12')
            else:
                self.canvas.create_rectangle(p[X] - RectangleSize,
                                             self.toTk(p[Y]) - RectangleSize,
                                             p[X] + RectangleSize,
                                             self.toTk(p[Y]) + RectangleSize,
                                             fill='Red')

        self.queryRect = self.canvas.create_rectangle(
            self.selectedRegion.x_min,
            self.toTk(self.selectedRegion.y_min),
            self.selectedRegion.x_max,
            self.toTk(self.selectedRegion.y_max),
            outline='Red',
            dash=(2, 4))

    def moved(self, event):
        """Only here for static option."""
        if self.static:
            self.paint()

    def click(self, event):
        """Add point to KDtree."""
        p = (event.x, self.toCartesian(event.y))

        self.tree.add(p)

        self.paint()

    def drawPartition(self, r, p, orient):
        """Draw partitioning line and points itself as a small square."""
        if orient == VERTICAL:
            self.canvas.create_line(p[X], self.toTk(r.y_min), p[X],
                                    self.toTk(r.y_max))
        else:
            xlow = r.x_min
            if r.x_min <= minValue: xlow = 0
            xhigh = r.x_max
            if r.x_max >= maxValue: xhigh = self.w.winfo_width()

            self.canvas.create_line(xlow, self.toTk(p[Y]), xhigh,
                                    self.toTk(p[Y]))

        self.canvas.create_rectangle(p[X] - RectangleSize,
                                     self.toTk(p[Y]) - RectangleSize,
                                     p[X] + RectangleSize,
                                     self.toTk(p[Y]) + RectangleSize,
                                     fill='Black')

    def visit(self, n):
        """ Visit node to paint properly."""
        if n == None: return

        self.drawPartition(n.region, n.point, n.orient)

        self.visit(n.below)
        self.visit(n.above)

    def prepare(self, event):
        """prepare to add points."""
        if self.label:
            self.label.destroy()
            self.label = None
            self.canvas.pack()

    def paint(self):
        """Paint quad tree by visiting all nodes, or show introductory message."""
        if self.tree.root:
            self.canvas.delete(tkinter.ALL)
            self.visit(self.tree.root)
        else:
            self.label = tkinter.Label(self.w,
                                       width=100,
                                       height=40,
                                       text="Click To Add Points")
            self.label.bind("<Button-1>", self.prepare)
            self.label.pack()
class KDTreeApp:
    
    def __init__(self):
        """App for creating KD tree dynamically and executing nearest neighbor queries."""
        
        self.tree = KDTree()
        self.match = None
        self.shortline = None
        
        # set to true when you want to view a set of points that
        # were set not by user control.
        self.static = False
        
        self.master = tkinter.Tk()
        self.master.title('KD Tree Nearest Neighbor Application')
        self.w = tkinter.Frame(self.master, width=410, height=410)
        self.canvas = tkinter.Canvas(self.w, width=400, height=400)        
                        
        self.paint()

        self.canvas.bind("<Button-1>", self.click)
        self.canvas.bind("<Motion>", self.moved)
        self.w.pack()
        

    def toCartesian(self, y):
        """Convert tkinter point into Cartesian."""
        return self.w.winfo_height() - y

    def toTk(self,y):
        """Convert Cartesian into tkinter point."""
        if y == maxValue: return 0
        tk_y = self.w.winfo_height()
        if y != minValue:
            tk_y -= y
        return tk_y

    def moved(self, event):
        """React to mouse move events."""
        if self.static:
            self.paint()
            return
        
        p = (event.x, self.toCartesian(event.y))

        match = self.tree.find(p)
        if match:
            p = match.point
            self.canvas.create_rectangle(p[X] - RectangleSize, self.toTk(p[Y]) - RectangleSize, 
                                         p[X] + RectangleSize, self.toTk(p[Y]) + RectangleSize, fill='Red', 
                                         tags=closest)
            self.canvas.delete(self.shortline)
            self.shortline = None
        else:
            self.canvas.delete(closest)
            n = self.tree.nearest(p)
            if n:
                pn = n.point
                if self.shortline is None:
                    self.shortline = self.canvas.create_line(pn[X], self.toTk(pn[Y]), p[X], self.toTk(p[Y]), 
                                                             fill='Red', dash=(2, 4), tags=shortline)
                else:
                    self.canvas.coords(shortline, pn[X], self.toTk(pn[Y]), p[X], self.toTk(p[Y]))
         
          
    def click(self, event):
        """Add point to KDTree."""
        p = (event.x, self.toCartesian(event.y))
        
        self.tree.add(p)
        if self.shortline:
            self.canvas.delete(self.shortline)
            self.shortline = None
            
        self.paint()

    def drawPartition (self, r, p, orient):
        """Draw proper partition for given node (r,p) and orientation."""
        if orient == VERTICAL:
            self.canvas.create_line(p[X], self.toTk(r.y_min), p[X], self.toTk(r.y_max))
        else:
            xlow = r.x_min
            if r.x_min <= minValue: xlow = 0
            xhigh = r.x_max
            if r.x_max >= maxValue: xhigh = self.w.winfo_width()

            self.canvas.create_line(xlow, self.toTk(p[Y]), xhigh, self.toTk(p[Y]))

        self.canvas.create_rectangle(p[X] - RectangleSize, self.toTk(p[Y]) - RectangleSize,
                                     p[X] + RectangleSize, self.toTk(p[Y]) + RectangleSize, fill='Black')

    def visit (self, n):
        """Draw KDNode properly partitioned and its sub-children."""
        if n == None: return

        self.drawPartition(n.region, n.point, n.orient)

        self.visit (n.below)
        self.visit (n.above)

    def prepare(self, event):
        """prepare to add points."""
        if self.label:
            self.label.destroy()
            self.label = None
            self.canvas.pack()
        
    def paint(self):
        """Paint KDTree by visiting all nodes, or show introductory message."""
        if self.tree.root:
            self.canvas.delete(tkinter.ALL)
            self.visit(self.tree.root)
        else:
            self.label = tkinter.Label(self.w, width=100, height = 40, text="Click To Add Points")
            self.label.bind("<Button-1>", self.prepare)
            self.label.pack()