2531 days ago by macieksk

import matplotlib from matplotlib import pyplot as plt import numpy as np from numpy import zeros import random import threading import Queue import time class Map(object): # Functions which return color arrays to be ploted def black(self): return zeros((self._h,self._w,3), dtype='uint8') def red(self): red = red[:,:,0] = 255 return red def green(self): red = red[:,:,1] = 255 return red def blue(self): red = red[:,:,2] = 255 return red def yellow(self): red = red[:,:,1] = 255 return red def ants(self): from scipy import rand, dstack return dstack([(255*rand(self._h,self._w)).astype('uint8')]*3) def __init__(self, draw_fun, w = 20, h = 20, s=10,interval = 1): self._w, self._h = w*s, h*s self._s = s # One Block size self._sleep_time = interval self._draw_fun = draw_fun self._fig = plt.figure() self._nsub=1 #Number of subplots #Create subplots self._axs = [self._fig.add_subplot(1,self._nsub,i) for i in xrange(self._nsub)] [ax.imshow( for ax in self._axs] #Grab buttonclick self._fig.canvas.mpl_connect('button_press_event', self._on_click) #Setup queues and flags self._upd_flag = threading.Event() self._draw_q = Queue.Queue() def _animate(self,ax): ax.images[0].set_data(self.ants()) ax.figure.canvas.draw() time.sleep(self._sleep_time) try: while True: data = self._draw_q.get(timeout=self._sleep_time) time.sleep(self._sleep_time) #ax.images[0].set_data(random.choice([,,])) ax.images[0].set_data(data) ax.figure.canvas.draw() except: pass #Simply exit if nothing in the queue finally: self._upd_flag.clear() def _on_click(self,event): #if event.inaxes in self.axs: # update_axs = [event.inaxes] #Run animation if no animation already running if not self._upd_flag.is_set(): t =threading.Thread(target=self._animate,args=(self._axs[0],)) t2=threading.Thread(target=self._draw_fun,args=(self,)) t.daemon=True t2.daemon=True self._upd_flag.set() t.start() t2.start() def plot_map(self,arr): ''' Issue a pixel array to draw with cell colors translated appropriately from a logical smaller array 'arr' ''' s=self._s assert(arr.shape == (self._w/s,self._h/s)) todraw = def set_color(col_n, color): for x,y in zip(*np.where(arr==col_n)): todraw[s*x:s*(x+1),s*y:s*(y+1),:] = color[s*x:s*(x+1),s*y:s*(y+1),:] set_color(1, set_color(2, set_color(3, set_color(4,self.yellow()) self._draw_q.put(todraw) ###Example code def test_map(mp): arr=np.zeros((10,10)) arr[1,1]=1 arr[1,2]=1 arr[5,6]=2 arr[9,9]=3 mp.plot_map(arr) def runme(): for i in range(10): arr[i,i]=4 mp.plot_map(arr) runme() def test(): mp=Map(test_map,w=10,h=10,s=15,interval=0.5)