示例#1
0
def render_2d(header, blocks):
    from Tkinter import Tk, Label, mainloop, PhotoImage
    # Create a random color map from the set of blocks values
    colors = {}
    for unique_item in set(chain.from_iterable(blocks)):
        if unique_item == 0:
            colors[0] = (0, 0, 0)
        else:
            colors[unique_item] = (randrange(128), randrange(128), randrange(128))
    master = Tk()
    # Build image
    photo = PhotoImage(width=header["z"], height=header["y"])
    #{#ff0000 #ff0000 #ff0000} {#ff0000 #ff0000 #ff0000} {#ff0000 #ff0000 #ff0000} {#ff0000 #ff0000 #ff0000}
    horizontal_line = " ".join(["{" + " ".join(["#%02x%02x%02x" % tuple(colors[blockId]) for blockId in row]) + "}" for row in blocks])
    photo.put(horizontal_line)
    photo = photo.zoom(4, 4)
    label = Label(master, image=photo)
    label.pack()
    mainloop()
示例#2
0
class MapCanvas(Canvas):
    """
    Visual representation of map instantiated as a Tkinter.Canvas object.
    """
    def __init__(self, parent, top, lmap):
        """Constructor. Initialises class attributes, calls drawMap. parent = mapcontainer
           created in Gui. Ref to Gui (top) supplied in case needed for future use."""
        Canvas.__init__(self, parent, width=512, height=512)
        # Bind drag and drop events to canvas and pack it in mapcontainer
        self.bind('<ButtonPress-1>', self.grab)
        self.bind('<ButtonRelease-1>', self.drop)
        self.bind('<B1-Motion>', self.drag)
        self.pack(side='left', fill=BOTH, expand=1)

        self.xpos = 0  # X coord of mouse grab event
        self.ypos = 0  # Y coord of mouse grab event
        self.scale = 1  # Current zoom level
        self.im = None  # Ref to original image, on which zoom is based
        self.original = None  # image id, as first added to canvas
        self.zoomed = None  # image id, as zoomed on canvas

        self.lmap = lmap
        self.drawMap(lmap)

    def grab(self, event):
        """Event handler. Displays fleur cursor and gets grab position"""
        self.ypos = event.y
        self.xpos = event.x
        self.config(cursor='fleur')

    def drop(self, event):
        """Event handler. Redisplays arrow cursor"""
        self.config(cursor='arrow')

    def drag(self, event):
        """Event handler. Scrolls canvas to new pos and updates old"""
        self.yview('scroll', self.ypos - event.y, 'units')
        self.xview('scroll', self.xpos - event.x, 'units')
        self.ypos = event.y
        self.xpos = event.x

    def reset(self):
        """Resets canvas to zoomlevel 1 and repositions top left"""
        self.xview_moveto(0)
        self.yview_moveto(0)
        self.zoomMap(1, 0, 0)

    def colorMap(self, char):
        """Effectively a switch statement to return color based on char"""
        return {
            #'.': 'sienna',
            #'G': 'sienna',
            '.': 'moccasin',
            'G': 'moccasin',
            'O': 'black',
            '@': 'black',
            'S': 'OliveDrab1',
            'T': 'green4',
            'W': 'SkyBlue3',
            'k': 'green3',
            'D': 'red'
        }[char]

    def drawMap(self, lmap):
        """Creates new map image based on LogicalMap passed in lmap"""
        w = lmap.width
        h = lmap.height
        # set size of canvas and create bitmap of same size
        self.config(width=w, height=h, xscrollincrement=1, yscrollincrement=1)
        self.im = PhotoImage(width=w, height=h)
        # copy colors corresponding to lmap characters into bitmap and create on canvas
        for row in range(h):
            for col in range(w):
                if lmap.isKey((col, row)):
                    color = 'green3'
                elif lmap.isDoor((col, row)):
                    color = 'red'
                else:
                    color = self.colorMap(lmap.getCell((col, row)))
                self.im.put(color, (col, row))
        self.original = self.create_image(0, 0, image=self.im, anchor=NW)

    def clear(self, points, lmap):
        """Clears set of points by replacing each point with its original color,
           based on data in lmap"""
        for coord in points:
            if lmap.cellWithinBoundaries(coord):
                color = self.colorMap(lmap.getCell(coord))
                self.im.put(color, coord)
        self.zoomMap(self.scale)

    def clearCross(self, coord, lmap):
        """Clears cross at coord by replacing each point with its original color,
           based on data in lmap"""
        for n in range(-3, 3):
            color = self.colorMap(lmap.getCell((coord[0] + n, coord[1] + n)))
            self._drawPoint(color, (coord[0] + n, coord[1] + n))
            color = self.colorMap(lmap.getCell((coord[0] + n, coord[1] - n)))
            self._drawPoint(color, (coord[0] + n, coord[1] - n))
        self.zoomMap(self.scale)

    def drawCross(self, coord, color):
        """Draws cross at coord in nominiated color"""
        for n in range(-2, 3):
            self._drawPoint(color, (coord[0] + n, coord[1] + n))
            self._drawPoint(color, (coord[0] + n, coord[1] - n))
        self.zoomMap(self.scale)

    def drawSet(self, points, color):
        """Draws set of points in nominated color"""
        for coord in points:
            try:
                self.im.put(color, coord)
            except TclError:
                continue
        self.zoomMap(self.scale)

    def drawPoint(self, coord, color):
        """Draws individual point in nominated color"""
        try:
            self.im.put(color, coord)
            self.zoomMap(self.scale)
        except TclError:
            pass

    def _drawPoint(self, color, coord):
        """Internal. Draws individual point in nominated color without forcing displayed
        As elsewhere in view_map, assumes calling prog has checked for validity and forgives errors."""
        try:
            self.im.put(color, coord)
        except TclError:
            pass

    def zoomMap(self, scale, x=0, y=0):
        """Zooms map to scale. Also used to force changes to be displayed"""
        if self.zoomed:
            self.delete(self.zoomed)
        self.zoomed = self.im.zoom(scale, scale)
        zoomed_id = self.create_image(x, y, image=self.zoomed, anchor=NW)
        self.delete(self.original)
        self.scale = scale

    def getScale(self):
        """Getter. Returns scale.
        :rtype : float
        """
        return self.scale
示例#3
0
    def clustering(self):
        self.nClust = self.clustersNum.get()
        self.nRuns = self.clustersRun.get()
        if not self.hasPre:
            tkMessageBox.showerror("K Means Clustering",
                                   "Please preprocess data before..")
        elif self.nClust == "" or self.nClust <= 0:
            tkMessageBox.showerror("K Means Clustering",
                                   "Please fill positive number of clusters")
        elif self.nRuns == "" or self.nRuns <= 0:
            tkMessageBox.showerror("K Means Clustering",
                                   "Please fill positive number of runs")
        else:
            #run the KMeans model
            doneCluster, self.complete_ready_data = clusterData.cluster(
                self.complete_ready_data, self.nClust, self.nRuns)

            if not doneCluster:
                tkMessageBox.showerror("K Means Clustering",
                                       "Clustering problems")
            else:
                # Generate scatter plot & show on GUI
                fig = Figure(figsize=(6, 6), dpi=70)
                a = fig.add_subplot(111)
                a.scatter(x=self.complete_ready_data["Generosity"],
                          y=self.complete_ready_data["Social support"],
                          c=self.complete_ready_data['Clustering'])
                a.set_title(
                    "Scatter plot for Generosity and Social support by cluster"
                )
                a.set_xlabel('Generosity', fontsize=12)
                a.set_ylabel('Social support', fontsize=12)

                canvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(
                    fig, master=self.window)
                canvas.get_tk_widget().grid(row=17, column=18)
                canvas.draw()

                # Generate second plot - Horopleth map & save to disk & show on GUI
                self.complete_ready_data.reset_index(inplace=True)
                # scl = [[0.0, 'rgb(242,240,247)'], [0.2, 'rgb(218,218,235)'], [0.4, 'rgb(188,189,220)'], \
                #        [0.6, 'rgb(158,154,200)'], [0.8, 'rgb(117,107,177)'], [1.0, 'rgb(84,39,143)']]
                scl = [[0.0, 'rgb(242,240,247)'], [0.4, 'rgb(188,189,220)'],
                       [0.8, 'rgb(117,107,177)']]
                data = [
                    dict(
                        type='choropleth',
                        colorscale=scl,
                        autocolorscale=False,
                        locations=self.complete_ready_data['country'],
                        z=self.complete_ready_data['Clustering'].astype(float),
                        locationmode='country names',
                        text=self.complete_ready_data['country'],
                        marker=dict(
                            line=dict(color='rgb(255,255,255)', width=2)),
                        colorbar=dict(title="Cluster", dtick=1))
                ]

                layout = dict(
                    title='Cluster by country on world map',
                    geo=dict(scope='world',
                             projection=dict(type='Mercator'),
                             showlakes=True,
                             lakecolor='rgb(255, 255, 255)'),
                )

                fig2 = dict(data=data, layout=layout)
                py.plot(fig2, filename='d3-cloropleth-map', auto_open=False)
                py.image.save_as(fig2, filename="world.png")

                im = Image.open('world.png')
                im = im.resize((520, 420), Image.ANTIALIAS)
                im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE)
                im.save('world.gif')

                photo = PhotoImage(file='world.gif')
                photo.zoom(2)
                self.worldImg = Label(master=self.window, image=photo)
                self.worldImg.image = photo
                self.worldImg.grid(row=17, column=19)

                if tkMessageBox.askokcancel(
                        "K Means Clustering",
                        "Clustering completed successfully!"):
                    root.destroy()
                    sys.exit()