class LassoManager: def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] fig = ax.figure self.collection = RegularPolyCollection( fig.dpi, 6, sizes=(100,), facecolors=facecolors, offsets = self.xys, transOffset = ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) self.ind = None def callback(self, verts): facecolors = self.collection.get_facecolors() ind = nonzero(points_inside_poly(self.xys, verts))[0] for i in range(self.Nxy): if i in ind: facecolors[i] = Datum.colorin else: facecolors[i] = Datum.colorout self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso self.ind = ind def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) self.canvas.widgetlock(self.lasso)
class LassoManager: def __init__(self, ax, data,labels=None, color_on='r', color_off='k'): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.call_list = [] self.Nxy = data.shape[0] self.color_on = colorConverter.to_rgba(color_on) self.color_off = colorConverter.to_rgba(color_off) facecolors = [self.color_on for _ in range(self.Nxy)] fig = ax.figure self.collection = RegularPolyCollection( fig.dpi, 6, sizes=(1,), facecolors=facecolors, edgecolors=facecolors, offsets = self.data, transOffset = ax.transData) ax.add_collection(self.collection, autolim=True) ax.autoscale_view() if labels is not None: ax.set_xlabel(labels[0]) ax.set_ylabel(labels[1]) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) self.ind = None self.canvas.draw() def register(self, callback_func): self.call_list.append(callback_func) def callback(self, verts): facecolors = self.collection.get_facecolors() edgecolors = self.collection.get_edgecolors() ind = nonzero(points_inside_poly(self.data, verts))[0] for i in range(self.Nxy): if i in ind: facecolors[i] = self.color_on edgecolors[i] = self.color_on else: facecolors[i] = self.color_off edgecolors[i] = self.color_off self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso self.ind = ind for func in self.call_list: func(ind) def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso)
class LassoManager: def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data #the lasso lock boolean is used to tell whether another #widget event has priority self.lassoLock = False self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] fig = ax.figure self.collection = RegularPolyCollection( fig.dpi, 6, sizes=(100,), facecolors=facecolors, offsets = self.xys, transOffset = ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) self.cidRelease = self.canvas.mpl_connect('button_release_event', self.onrelease) self.ind = None def callback(self, verts): facecolors = self.collection.get_facecolors() ind = nonzero(points_inside_poly(self.xys, verts))[0] for i in range(self.Nxy): if i in ind: facecolors[i] = Datum.colorin else: facecolors[i] = Datum.colorout self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) #del self.lasso self.ind = ind def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso) # establish boolean that can be used to release the widgetlock self.lassoLock = True def onrelease(self, event): 'on release we reset the press data' # test whether the widgetlock was initiated by the lasso if self.lassoLock: self.canvas.widgetlock.release(self.lasso) self.lassoLock = False print self.ind
class LassoManager(object): def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.Nxy = len(data) facecolors = [d.color for d in data] # print facecolors self.xys = [(d.x, d.y) for d in data] fig = ax.figure self.collection = RegularPolyCollection(fig.dpi, 6, sizes=(20, ), facecolors=facecolors, offsets=self.xys, transOffset=ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) def callback(self, verts): facecolors = self.collection.get_facecolors() p = path.Path(verts) ind = p.contains_points(self.xys) for i in range(len(self.xys)): if ind[i]: facecolors[i] = Datum.colorin self.data[i].color = Datum.colorin else: facecolors[i] = Datum.colorout self.data[i].color = Datum.colorout self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) # print facecolors del self.lasso def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso)
class LassoManager(object): def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] self.collection = RegularPolyCollection(6, sizes=(10, ), facecolors=facecolors, offsets=self.xys, transOffset=ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) def callback(self, verts): facecolors = self.collection.get_facecolors() p = path.Path(verts) ind = p.contains_points(self.xys) for i in range(len(self.xys)): if ind[i]: facecolors[i] = Datum.colorin target = open('badcadences.txt', 'a') target.write('{}, {}'.format(self.xys[i][0], self.xys[i][1])) target.write("\n") target.close() # else: # facecolors[i] = Datum.colorout self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso)
class LassoManager(object): def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] fig = ax.figure self.collection = RegularPolyCollection( fig.dpi, 6, sizes=(100,), facecolors=facecolors, offsets=self.xys, transOffset=ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) def callback(self, verts): facecolors = self.collection.get_facecolors() p = path.Path(verts) ind = p.contains_points(self.xys) for i in range(len(self.xys)): if ind[i]: facecolors[i] = Datum.colorin else: facecolors[i] = Datum.colorout self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso)
class LassoManager: def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] fig = ax.figure self.collection = RegularPolyCollection(fig.dpi, 6, sizes=(100, ), facecolors=facecolors, offsets=self.xys, transOffset=ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) self.ind = None def callback(self, verts): facecolors = self.collection.get_facecolors() ind = nonzero(points_inside_poly(self.xys, verts))[0] for i in range(self.Nxy): if i in ind: facecolors[i] = Datum.colorin else: facecolors[i] = Datum.colorout self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso self.ind = ind def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso)
class LassoManager(object): def __init__(self, ax, data): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.Nxy = len(data) facecolors = [d.color for d in data] self.xys = [(d.x, d.y) for d in data] fig = ax.figure self.collection = RegularPolyCollection( 5, 0, sizes=(30, ), facecolors=facecolors, edgecolor=facecolors, offsets=self.xys, transOffset=ax.transData, ) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) def callback(self, verts): global click global the_table global ind facecolors = self.collection.get_facecolors() p = path.Path(verts) ind = p.contains_points(self.xys) for i in range(len(self.xys)): if ind[i]: facecolors[i] = Datum.colorin else: facecolors[i] = Datum.colorout if sum(ind) > 0: if click > 0: the_table.remove() the_table = plt.table(cellText=[[str(c) for c in show_data[i]] for i in range(len(self.xys)) if ind[i]], colWidths=variablelength_select, colLabels=columns, loc='bottom', bbox=[0.1, -0.6, 0.8, .5]) click = 1 else: if click > 0: the_table.remove() click = 0 self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback)
class MainPanel(wx.Dialog): def __init__(self, parent, pathToPlugins=None):#, main_playlist, nb_playlist): if(not pathToPlugins==None): RESFILE = os.path.join(pathToPlugins,'x2') + os.sep + "layout_x2.xml" wx.Dialog.__init__(self, parent, -1, style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER) self.parent = parent self.nb_playlist = 0 self.main_playlist = self.parent.lc_playlist #self.super_parent = super_parent # XML Resources can be loaded from a file like this: res = xrc.XmlResource(RESFILE) # Now create a panel from the resource data panel = res.LoadPanel(self, "m_pa_x2main") #self.panel = panel #background = 'tulips.jpg' #img = wx.Image(background, wx.BITMAP_TYPE_ANY) #self.buffer = wx.BitmapFromImage(img) #dc = wx.BufferedDC(wx.ClientDC(panel), self.buffer) #self.panel.Bind(wx.EVT_PAINT, self.OnPaint) # control references -------------------- self.pa_x2main = xrc.XRCCTRL(self, 'm_pa_x2main') self.pa_x2_graph = xrc.XRCCTRL(self, 'm_pa_x2_graph') self.lc_x2_plist = xrc.XRCCTRL(self, 'm_lc_x2_plist') self.cl_x2_features = xrc.XRCCTRL(self, 'm_cl_x2_features') self.sl_x2_pointsize = xrc.XRCCTRL(self, 'm_sl_x2_pointsize') self.lc_x2_plist.InsertColumn(0,"Artist") self.lc_x2_plist.InsertColumn(1,"Song") self.lc_x2_plist.SetColumnWidth(0, 100) self.lc_x2_plist.SetColumnWidth(1, 100) self.Bind(wx.EVT_BUTTON, self.OnAutoGenerateX2Playist, id=xrc.XRCID('m_bu_x2_plize')) self.Bind(wx.EVT_BUTTON, self.OnCenterClick, id=xrc.XRCID('m_bu_x2_center')) self.Bind(wx.EVT_SLIDER, self.OnPointSizeClick, id=xrc.XRCID('m_sl_x2_pointsize')) self.Bind(wx.EVT_SPIN, self.OnZoomClick, id=xrc.XRCID('m_sb_x2_zoom')) self.Bind(wx.EVT_SPIN, self.OnPanXClick, id=xrc.XRCID('m_sb_x2_panx')) self.Bind(wx.EVT_SPIN, self.OnPanYClick, id=xrc.XRCID('m_sb_x2_pany')) self.Bind(wx.EVT_CHECKBOX, self.OnXAxisClick, id=xrc.XRCID('m_cb_x2_xlog')) self.Bind(wx.EVT_CHECKBOX, self.OnYAxisClick, id=xrc.XRCID('m_cb_x2_ylog')) self.Bind(wx.EVT_CHECKLISTBOX, self.OnCheckListBox, self.cl_x2_features) self.current_zoom = 0 self.current_panx = 0 self.current_pany = 0 #features array #tag_array = GetTags() self.cl_x2_features.Set(FEATURES_ARRAY) #self.cl_x2_features.AppendItems(tag_array) self.figure = Figure(None, None, (1,1,1), None, 1.0, True, None)#facecolor=0.75, edgecolor='white') #(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=1.0, frameon=True, subplotpars=None) self.MakeScatt([0,1,2,3]) self.build_graph() self.build_collection() self.canvas = FigureCanvas(self.pa_x2_graph, -1, self.figure) self.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel) self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseRightDown) #self.Bind(wx.EVT_MOTION, self.OnMouseMotion) self.Bind(wx.EVT_RIGHT_UP, self.OnMouseRightUp) self.canvas.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseRightDown) #self.canvas.Bind(wx.EVT_MOTION, self.OnMouseMotion) self.canvas.Bind(wx.EVT_RIGHT_UP, self.OnMouseRightUp) # Note that event is a MplEvent #self.canvas.mpl_connect('motion_notify_event', self.OnMouseMotion) #self.canvas.Bind(wx.EVT_ENTER_WINDOW, self.ChangeCursor) #lasso self.mpl = self.canvas.mpl_connect('button_press_event', self.onpress) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.pa_x2main, 1, wx.EXPAND|wx.ALL, 5) self.SetSizer(sizer) self.SetAutoLayout(True) self.Fit() # ----------------------------------------- # ----------------------------------------- def OnPaint(self, evt): dc = wx.BufferedPaintDC(self.panel, self.buffer) def ChangeCursor(self, curtype): self.canvas.SetCursor(wx.StockCursor(curtype)) def OnMouseRightDown(self, evt): self.canvas.mpl_disconnect(self.mpl) self.canvas.Bind(wx.EVT_MOTION, self.OnMouseMotion) self.Bind(wx.EVT_MOTION, self.OnMouseMotion) self.ChangeCursor(wx.CURSOR_HAND) self.Refresh() self.oldx = evt.GetPosition()[0] self.oldy = evt.GetPosition()[1] #self.wPos = self.ClientToScreen((0,0)) self.CaptureMouse() #print 'right-down' def OnMouseMotion(self, evt): if evt.Dragging() and evt.RightIsDown(): dPos = evt.GetPosition() #evt.GetEventObject().ClientToScreen(evt.GetPosition()) #nPos = (self.wPos.x + (dPos.x - self.ldPos.x), -2) #nPos = (self.wPos.x + (dPos.x - self.ldPos.x), self.wPos.y + (dPos.y - self.ldPos.y)) #print(nPos) #print self.ldPos curx = dPos[0] cury = dPos[1] x = self.axes.get_xaxis() y = self.axes.get_yaxis() if (curx - self.oldx) < -10: x.pan(.5) self.oldx = curx if (curx - self.oldx) > 10: x.pan(-.5) self.oldx = curx if (cury - self.oldy) > 10: y.pan(.5) self.oldy = cury if (cury - self.oldy) < -10: y.pan(-.5) self.oldy = cury self.canvas.draw() def OnMouseRightUp(self, evt): try: self.ReleaseMouse() except wx._core.PyAssertionError: pass self.ChangeCursor(wx.CURSOR_DEFAULT) self.canvas.Unbind(wx.EVT_MOTION) self.Unbind(wx.EVT_MOTION) self.mpl = self.canvas.mpl_connect('button_press_event', self.onpress) def UpdateStatusBar(self, event): if event.inaxes: x, y = event.xdata, event.ydata self.statusBar.SetStatusText(( "x= " + str(x) + " y=" +str(y) ), 0) def OnPointSizeClick(self, event): self.point_size = self.sl_x2_pointsize.GetValue() + 50 # range 50 to 300 self.figure.clear() self.build_graph() self.build_collection() self.canvas.draw() def OnCenterClick(self, event): self.figure.clear() self.build_graph() self.build_collection() self.canvas.draw() def OnZoomClick(self, event=None): x = self.axes.get_xaxis() y = self.axes.get_yaxis() if event.GetPosition() > self.current_zoom: x.zoom(1) y.zoom(1) else: x.zoom(-1) y.zoom(-1) self.current_zoom = event.GetPosition() self.canvas.draw() def OnMouseWheel(self, evt): rotation = evt.GetWheelRotation() x = self.axes.get_xaxis() y = self.axes.get_yaxis() if rotation > 0: x.zoom(1) y.zoom(1) else: x.zoom(-1) y.zoom(-1) self.canvas.draw() # Done handling event #evt.Skip() def OnPanXClick(self, event): x = self.axes.get_xaxis() y = self.axes.get_yaxis() if event.GetPosition() > self.current_panx: x.pan(1) else: x.pan(-1) self.current_panx = event.GetPosition() self.canvas.draw() def OnPanYClick(self, event): x = self.axes.get_xaxis() y = self.axes.get_yaxis() if event.GetPosition() > self.current_pany: y.pan(1) else: y.pan(-1) self.current_pany = event.GetPosition() self.canvas.draw() def OnXAxisClick(self, event): if self.axes.get_xscale() == 'log': self.axes.set_xscale('linear') else: self.axes.set_xscale('log') #self.axes.autoscale_view() #self.canvas.draw_idle() #self.axes.autoscale_view() self.canvas.draw() #self.canvas.Refresh(eraseBackground=False) def OnYAxisClick(self, event): if self.axes.get_yscale() == 'log': self.axes.set_yscale('linear') else: self.axes.set_yscale('log') #self.axes.autoscale_view() self.canvas.draw() # ---------------------------------------------------------- def OnCheckListBox(self, event): index = event.GetSelection() label = self.cl_x2_features.GetString(index) #print label #print index self.cl_x2_features.SetSelection(index) # so that (un)checking also selects (moves the highlight) #print self.cl_x2_features.GetCount() selected_array =[] for x in range(0, self.cl_x2_features.GetCount()): if self.cl_x2_features.IsChecked(x) == True: selected_array.append(x) print selected_array if len(selected_array) >= 1: #print 'fofofofof' self.figure.clear() self.MakeScatt(selected_array) self.build_graph() self.build_collection() self.canvas.draw() # ---------------------------------------------------------- # ---------------------------------------------------------- def MakeScatt(self, selected_array): pre_data_array, self.song_array, self.color_array, use_std = GetResultsArray(selected_array) #print pre_data_array pca1, pca2, pca3 = pca_module.PCA_svd(pre_data_array, use_std) #print self.data_array #print pca1 #self.data = pca1 #print pca2 #grab the first 2 components self.data_array = np.array_split(pca1,[2,],axis=1)[0] #print self.data_array #self.axes.set_xlabel(r'$\Delta_i$', fontsize=20) #self.axes.set_ylabel(r'$\Delta_{i+1}$', fontsize=20) #self.axes.set_title('Volume and percent change') #self.axes.grid(True) ### use zoom instead #self.xmin = self.data1.min()# - (self.data1.max() * 0.1) #self.xmax = self.data1.max()# * 1.1 #self.ymin = self.data2.min()# - (self.data2.max() * 0.1) #self.ymax = self.data2.max()# * 1.1 def build_graph(self): self.axes = self.figure.add_subplot(111, axisbg=(1,1,1)) self.figure.subplots_adjust(left=0, right=1, top=1, bottom=0) #self.axes.frame_on(False) #subplot(111, axisbg='darkslategray') #ax = fig.add_subplot(111) #self.axes.scatter(self.data2, self.data1, c=[0.5,0.5,1.0], s=200, alpha=0.5) def build_collection(self): self.point_size = self.sl_x2_pointsize.GetValue() + 50 # range 50 to 300 self.collection = RegularPolyCollection( #self.axes.figure.dpi, numsides = 80, sizes=(self.point_size,), facecolors=self.color_array, offsets = self.data_array, transOffset = self.axes.transData) self.collection.set_alpha(0.7) self.axes.add_collection(self.collection) #self.axes.axis([self.xmin, self.xmax, self.ymin, self.ymax]) self.axes.autoscale_view() x = self.axes.get_xaxis() y = self.axes.get_yaxis() x.zoom(-1) y.zoom(-1) #self.axes.axis('tight') ##self.axes.axis('off') def callback(self, verts): facecolors = self.collection.get_facecolors() ind = nonzero(points_inside_poly(self.data_array, verts))[0] for i in range(len(self.data_array)): if i in ind: facecolors[i] = (1,1,0,.5) #print facecolors[i] #pass else: facecolors[i] = self.color_array[i] #pass #print facecolors[i] self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso #self.ind = ind self.pass_data(ind) def onpress(self, event): #print event.button if self.canvas.widgetlock.locked(): #print 'foo' self.canvas.widgetlock.release(self.lasso) #return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso) def pass_data(self, ind): #populate parents list control self.lc_x2_plist.DeleteAllItems() for x in ind: self.lc_x2_plist.InsertStringItem(0, self.song_array[x][0]) self.lc_x2_plist.SetStringItem(0, 1, self.song_array[x][1]) #pass def update_data(self): pass #self.figure.clf() #build_graph(self) #self.MakeScatt() #self.build_collection() def OnAutoGenerateX2Playist(self, event): # copy the sifted list to the playlist self.parent.CheckClear() insert_at = self.parent.lc_playlist.GetItemCount() for x in range(self.lc_x2_plist.GetItemCount(), 0, -1): artist = self.lc_x2_plist.GetItem(x-1, 0).GetText() song = self.lc_x2_plist.GetItem(x-1, 1).GetText() self.parent.SetPlaylistItem(insert_at, artist, song, '', '') #save the playlist self.parent.SavePlaylist() # switch tabs self.parent.nb_main.SetSelection(self.nb_playlist)
class LassoManager: def __init__(self, ax, data, labels=None, color_on='r', color_off='k'): self.axes = ax self.canvas = ax.figure.canvas self.data = data self.call_list = [] self.Nxy = data.shape[0] self.color_on = colorConverter.to_rgba(color_on) self.color_off = colorConverter.to_rgba(color_off) facecolors = [self.color_on for _ in range(self.Nxy)] fig = ax.figure self.collection = RegularPolyCollection(fig.dpi, 6, sizes=(1, ), facecolors=facecolors, edgecolors=facecolors, offsets=self.data, transOffset=ax.transData) ax.add_collection(self.collection, autolim=True) ax.autoscale_view() if labels is not None: ax.set_xlabel(labels[0]) ax.set_ylabel(labels[1]) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) self.ind = None self.canvas.draw() def register(self, callback_func): self.call_list.append(callback_func) def callback(self, verts): facecolors = self.collection.get_facecolors() edgecolors = self.collection.get_edgecolors() ind = nonzero(points_inside_poly(self.data, verts))[0] for i in range(self.Nxy): if i in ind: facecolors[i] = self.color_on edgecolors[i] = self.color_on else: facecolors[i] = self.color_off edgecolors[i] = self.color_off self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso self.ind = ind for func in self.call_list: func(ind) def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso)
class LassoBrowser(object): def __init__(self, df, ax=None, xcol='x', ycol='y', callback=None): self.df = df self.ax = ax or pl.gca() self.canvas = ax.figure.canvas self.lasso_lock = False # indicates if another widget event has priority self.idxs = array(list( self.df.T)) # look up parallel with point indices self.xys = df[[xcol, ycol]].values self.xcol = xcol self.ycol = ycol # timv: don't think this PolyCollection is needed.. self.collection = RegularPolyCollection( numsides=ax.figure.dpi, rotation=6, sizes=(100, ), facecolors=[to_rgba('green', alpha=0.0)] * len(self.xys), linewidths=0, offsets=self.xys, transOffset=ax.transData) ax.add_collection(self.collection) self.user_callback = callback self.canvas.mpl_connect('key_press_event', self.onpress) self.canvas.mpl_connect('button_press_event', self.onpress) self.canvas.mpl_connect('button_release_event', self.onrelease) self.selected = None self.lasso = None def lasso_callback(self, verts): if verts is not None and len(verts): [selected] = nonzero(points_inside_poly(self.xys, verts)) else: selected = [] # change face colors inplace facecolors = self.collection.get_facecolors() facecolors[:] = to_rgba('green', alpha=0.0) facecolors[selected] = to_rgba('yellow', alpha=0.6) # convert from point indices to dataframe indices idx = self.idxs[selected] m = self.df.ix[idx] # show selected rows of dataframe if self.user_callback is None: print m else: self.user_callback(m) self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) self.selected = selected def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return if event.key in ('escape', ): self.selected = [] self.lasso_callback([]) return # TODO: implement zoom out as undo. # zoom in to selection if event.key in ('+', '='): selected_rows = self.df.ix[self.selected] xs = selected_rows[self.xcol] ys = selected_rows[self.ycol] self.ax.set_xlim(xs.min(), xs.max()) self.ax.set_ylim(ys.min(), ys.max()) self.canvas.draw() return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.lasso_callback) self.canvas.widgetlock(self.lasso) # acquire lock on lasso widget self.lasso_lock = True # used when we release def onrelease(self, event): 'on release we reset the press data' # test whether the widgetlock was initiated by the lasso if self.lasso_lock: self.canvas.widgetlock.release(self.lasso) self.lasso_lock = False
class LassoBrowser(object): def __init__(self, df, ax=None, xcol='x', ycol='y', callback=None): self.df = df self.ax = ax or pl.gca() self.canvas = ax.figure.canvas self.lasso_lock = False # indicates if another widget event has priority self.idxs = array(list(self.df.T)) # look up parallel with point indices self.xys = df[[xcol, ycol]].values self.xcol = xcol self.ycol = ycol # timv: don't think this PolyCollection is needed.. self.collection = RegularPolyCollection(numsides=ax.figure.dpi, rotation=6, sizes=(100,), facecolors = [to_rgba('green', alpha=0.0)]*len(self.xys), linewidths = 0, offsets = self.xys, transOffset = ax.transData) ax.add_collection(self.collection) self.user_callback = callback self.canvas.mpl_connect('key_press_event', self.onpress) self.canvas.mpl_connect('button_press_event', self.onpress) self.canvas.mpl_connect('button_release_event', self.onrelease) self.selected = None self.lasso = None def lasso_callback(self, verts): if verts is not None and len(verts): [selected] = nonzero(points_inside_poly(self.xys, verts)) else: selected = [] # change face colors inplace facecolors = self.collection.get_facecolors() facecolors[:] = to_rgba('green', alpha=0.0) facecolors[selected] = to_rgba('yellow', alpha=0.6) # convert from point indices to dataframe indices idx = self.idxs[selected] m = self.df.ix[idx] # show selected rows of dataframe if self.user_callback is None: print m else: self.user_callback(m) self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) self.selected = selected def onpress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return if event.key in ('escape',): self.selected = [] self.lasso_callback([]) return # TODO: implement zoom out as undo. # zoom in to selection if event.key in ('+', '='): selected_rows = self.df.ix[self.selected] xs = selected_rows[self.xcol] ys = selected_rows[self.ycol] self.ax.set_xlim(xs.min(), xs.max()) self.ax.set_ylim(ys.min(), ys.max()) self.canvas.draw() return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.lasso_callback) self.canvas.widgetlock(self.lasso) # acquire lock on lasso widget self.lasso_lock = True # used when we release def onrelease(self, event): 'on release we reset the press data' # test whether the widgetlock was initiated by the lasso if self.lasso_lock: self.canvas.widgetlock.release(self.lasso) self.lasso_lock = False
class LassoManager(object): def __init__(self, fig, ax, data): self.fig = fig self.axes = ax self.canvas = ax.figure.canvas # 画布 self.data = data self.Nxy = len(data) # 数据长度 self.facecolors = [d.color for d in data] # 所有点的颜色 self.xys = [(d.y, d.x) for d in data] # 所有点的坐标 self.collection = RegularPolyCollection( # 多边形集 4, sizes=(10, ), # 4边形,大小 facecolors=self.facecolors, # 颜色 offsets=self.xys, # 位置 transOffset=ax.transData) ax.add_collection(self.collection) self.cid = self.canvas.mpl_connect( 'button_press_event', self.MousePress) # 事件连接,鼠标按键触发MousePress函数 self.cid = self.canvas.mpl_connect( 'key_press_event', self.KeyboardPress) # 事件连接,按键按下触发key_press_event self.KeyFun = '+' # 当前按键功能 '+':添加点,'-':删除点 ax.set_xlabel('+') # 默认添加点 def callback(self, verts): self.facecolors = self.collection.get_facecolors() p = path.Path(verts) ind = p.contains_points(self.xys) # 路径中包含的点 for i in range(len(self.xys)): if self.KeyFun == '+': # 如果是添加点,则路径中的点变红色 if ind[i]: self.facecolors[i] = Datum.colorin # 路径中包含的点变红色 elif self.KeyFun == '-': # 如果是删除点,则路径中的点变蓝色 if ind[i]: self.facecolors[i] = Datum.colorout # 路径中包含的点变红色 self.canvas.draw_idle() # 套索路径不再显示 # self.canvas.widgetlock.release(self.lasso) # 释放lasso del self.lasso def MousePress(self, event): if self.canvas.widgetlock.locked(): return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing # self.canvas.widgetlock(self.lasso) # 将widget锁定,此时lasso无效 def KeyboardPress(self, event): # print('press', event.key) # event.key按键信息 if event.key in ['+', '-']: self.KeyFun = event.key self.axes.set_xlabel(event.key) self.fig.canvas.draw() # 画布重绘 elif event.key == 'd': # download 保存选中的点 SelPoints = np.empty((0, 2), dtype=np.float32) for i in range(len(self.xys)): if np.sum( np.array(self.facecolors[i]) == np.array( Datum.colorin)) == 4: SelPoints = np.vstack((SelPoints, self.xys[i])) FileName = str(input("Save File Name:")) np.savetxt(FileName + '.txt', SelPoints, '%f') # 保存选中的点坐标,两位有效数字 print('Save Done!!!') elif event.key == 'r': # 复位,重新开始选点 self.KeyFun = '+' # 当前按键功能 '+':添加点,'-':删除点 self.axes.set_xlabel('+') # 默认添加点 for i in range(len(self.xys)): # 点颜色复位 self.facecolors[i] = Datum.colorout
class MainPanel(wx.Dialog): def __init__(self, parent, pathToPlugins=None): #, main_playlist, nb_playlist): if (not pathToPlugins == None): RESFILE = os.path.join(pathToPlugins, 'x2') + os.sep + "layout_x2.xml" wx.Dialog.__init__(self, parent, -1, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) self.parent = parent self.nb_playlist = 0 self.main_playlist = self.parent.lc_playlist #self.super_parent = super_parent # XML Resources can be loaded from a file like this: res = xrc.XmlResource(RESFILE) # Now create a panel from the resource data panel = res.LoadPanel(self, "m_pa_x2main") #self.panel = panel #background = 'tulips.jpg' #img = wx.Image(background, wx.BITMAP_TYPE_ANY) #self.buffer = wx.BitmapFromImage(img) #dc = wx.BufferedDC(wx.ClientDC(panel), self.buffer) #self.panel.Bind(wx.EVT_PAINT, self.OnPaint) # control references -------------------- self.pa_x2main = xrc.XRCCTRL(self, 'm_pa_x2main') self.pa_x2_graph = xrc.XRCCTRL(self, 'm_pa_x2_graph') self.lc_x2_plist = xrc.XRCCTRL(self, 'm_lc_x2_plist') self.cl_x2_features = xrc.XRCCTRL(self, 'm_cl_x2_features') self.sl_x2_pointsize = xrc.XRCCTRL(self, 'm_sl_x2_pointsize') self.lc_x2_plist.InsertColumn(0, "Artist") self.lc_x2_plist.InsertColumn(1, "Song") self.lc_x2_plist.SetColumnWidth(0, 100) self.lc_x2_plist.SetColumnWidth(1, 100) self.Bind(wx.EVT_BUTTON, self.OnAutoGenerateX2Playist, id=xrc.XRCID('m_bu_x2_plize')) self.Bind(wx.EVT_BUTTON, self.OnCenterClick, id=xrc.XRCID('m_bu_x2_center')) self.Bind(wx.EVT_SLIDER, self.OnPointSizeClick, id=xrc.XRCID('m_sl_x2_pointsize')) self.Bind(wx.EVT_SPIN, self.OnZoomClick, id=xrc.XRCID('m_sb_x2_zoom')) self.Bind(wx.EVT_SPIN, self.OnPanXClick, id=xrc.XRCID('m_sb_x2_panx')) self.Bind(wx.EVT_SPIN, self.OnPanYClick, id=xrc.XRCID('m_sb_x2_pany')) self.Bind(wx.EVT_CHECKBOX, self.OnXAxisClick, id=xrc.XRCID('m_cb_x2_xlog')) self.Bind(wx.EVT_CHECKBOX, self.OnYAxisClick, id=xrc.XRCID('m_cb_x2_ylog')) self.Bind(wx.EVT_CHECKLISTBOX, self.OnCheckListBox, self.cl_x2_features) self.current_zoom = 0 self.current_panx = 0 self.current_pany = 0 #features array #tag_array = GetTags() self.cl_x2_features.Set(FEATURES_ARRAY) #self.cl_x2_features.AppendItems(tag_array) self.figure = Figure(None, None, (1, 1, 1), None, 1.0, True, None) #facecolor=0.75, edgecolor='white') #(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=1.0, frameon=True, subplotpars=None) self.MakeScatt([0, 1, 2, 3]) self.build_graph() self.build_collection() self.canvas = FigureCanvas(self.pa_x2_graph, -1, self.figure) self.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel) self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseRightDown) #self.Bind(wx.EVT_MOTION, self.OnMouseMotion) self.Bind(wx.EVT_RIGHT_UP, self.OnMouseRightUp) self.canvas.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseRightDown) #self.canvas.Bind(wx.EVT_MOTION, self.OnMouseMotion) self.canvas.Bind(wx.EVT_RIGHT_UP, self.OnMouseRightUp) # Note that event is a MplEvent #self.canvas.mpl_connect('motion_notify_event', self.OnMouseMotion) #self.canvas.Bind(wx.EVT_ENTER_WINDOW, self.ChangeCursor) #lasso self.mpl = self.canvas.mpl_connect('button_press_event', self.onpress) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.pa_x2main, 1, wx.EXPAND | wx.ALL, 5) self.SetSizer(sizer) self.SetAutoLayout(True) self.Fit() # ----------------------------------------- # ----------------------------------------- def OnPaint(self, evt): dc = wx.BufferedPaintDC(self.panel, self.buffer) def ChangeCursor(self, curtype): self.canvas.SetCursor(wx.StockCursor(curtype)) def OnMouseRightDown(self, evt): self.canvas.mpl_disconnect(self.mpl) self.canvas.Bind(wx.EVT_MOTION, self.OnMouseMotion) self.Bind(wx.EVT_MOTION, self.OnMouseMotion) self.ChangeCursor(wx.CURSOR_HAND) self.Refresh() self.oldx = evt.GetPosition()[0] self.oldy = evt.GetPosition()[1] #self.wPos = self.ClientToScreen((0,0)) self.CaptureMouse() #print 'right-down' def OnMouseMotion(self, evt): if evt.Dragging() and evt.RightIsDown(): dPos = evt.GetPosition( ) #evt.GetEventObject().ClientToScreen(evt.GetPosition()) #nPos = (self.wPos.x + (dPos.x - self.ldPos.x), -2) #nPos = (self.wPos.x + (dPos.x - self.ldPos.x), self.wPos.y + (dPos.y - self.ldPos.y)) #print(nPos) #print self.ldPos curx = dPos[0] cury = dPos[1] x = self.axes.get_xaxis() y = self.axes.get_yaxis() if (curx - self.oldx) < -10: x.pan(.5) self.oldx = curx if (curx - self.oldx) > 10: x.pan(-.5) self.oldx = curx if (cury - self.oldy) > 10: y.pan(.5) self.oldy = cury if (cury - self.oldy) < -10: y.pan(-.5) self.oldy = cury self.canvas.draw() def OnMouseRightUp(self, evt): try: self.ReleaseMouse() except wx._core.PyAssertionError: pass self.ChangeCursor(wx.CURSOR_DEFAULT) self.canvas.Unbind(wx.EVT_MOTION) self.Unbind(wx.EVT_MOTION) self.mpl = self.canvas.mpl_connect('button_press_event', self.onpress) def UpdateStatusBar(self, event): if event.inaxes: x, y = event.xdata, event.ydata self.statusBar.SetStatusText(("x= " + str(x) + " y=" + str(y)), 0) def OnPointSizeClick(self, event): self.point_size = self.sl_x2_pointsize.GetValue( ) + 50 # range 50 to 300 self.figure.clear() self.build_graph() self.build_collection() self.canvas.draw() def OnCenterClick(self, event): self.figure.clear() self.build_graph() self.build_collection() self.canvas.draw() def OnZoomClick(self, event=None): x = self.axes.get_xaxis() y = self.axes.get_yaxis() if event.GetPosition() > self.current_zoom: x.zoom(1) y.zoom(1) else: x.zoom(-1) y.zoom(-1) self.current_zoom = event.GetPosition() self.canvas.draw() def OnMouseWheel(self, evt): rotation = evt.GetWheelRotation() x = self.axes.get_xaxis() y = self.axes.get_yaxis() if rotation > 0: x.zoom(1) y.zoom(1) else: x.zoom(-1) y.zoom(-1) self.canvas.draw() # Done handling event #evt.Skip() def OnPanXClick(self, event): x = self.axes.get_xaxis() y = self.axes.get_yaxis() if event.GetPosition() > self.current_panx: x.pan(1) else: x.pan(-1) self.current_panx = event.GetPosition() self.canvas.draw() def OnPanYClick(self, event): x = self.axes.get_xaxis() y = self.axes.get_yaxis() if event.GetPosition() > self.current_pany: y.pan(1) else: y.pan(-1) self.current_pany = event.GetPosition() self.canvas.draw() def OnXAxisClick(self, event): if self.axes.get_xscale() == 'log': self.axes.set_xscale('linear') else: self.axes.set_xscale('log') #self.axes.autoscale_view() #self.canvas.draw_idle() #self.axes.autoscale_view() self.canvas.draw() #self.canvas.Refresh(eraseBackground=False) def OnYAxisClick(self, event): if self.axes.get_yscale() == 'log': self.axes.set_yscale('linear') else: self.axes.set_yscale('log') #self.axes.autoscale_view() self.canvas.draw() # ---------------------------------------------------------- def OnCheckListBox(self, event): index = event.GetSelection() label = self.cl_x2_features.GetString(index) #print label #print index self.cl_x2_features.SetSelection( index) # so that (un)checking also selects (moves the highlight) #print self.cl_x2_features.GetCount() selected_array = [] for x in range(0, self.cl_x2_features.GetCount()): if self.cl_x2_features.IsChecked(x) == True: selected_array.append(x) print selected_array if len(selected_array) >= 1: #print 'fofofofof' self.figure.clear() self.MakeScatt(selected_array) self.build_graph() self.build_collection() self.canvas.draw() # ---------------------------------------------------------- # ---------------------------------------------------------- def MakeScatt(self, selected_array): pre_data_array, self.song_array, self.color_array, use_std = GetResultsArray( selected_array) #print pre_data_array pca1, pca2, pca3 = pca_module.PCA_svd(pre_data_array, use_std) #print self.data_array #print pca1 #self.data = pca1 #print pca2 #grab the first 2 components self.data_array = np.array_split(pca1, [ 2, ], axis=1)[0] #print self.data_array #self.axes.set_xlabel(r'$\Delta_i$', fontsize=20) #self.axes.set_ylabel(r'$\Delta_{i+1}$', fontsize=20) #self.axes.set_title('Volume and percent change') #self.axes.grid(True) ### use zoom instead #self.xmin = self.data1.min()# - (self.data1.max() * 0.1) #self.xmax = self.data1.max()# * 1.1 #self.ymin = self.data2.min()# - (self.data2.max() * 0.1) #self.ymax = self.data2.max()# * 1.1 def build_graph(self): self.axes = self.figure.add_subplot(111, axisbg=(1, 1, 1)) self.figure.subplots_adjust(left=0, right=1, top=1, bottom=0) #self.axes.frame_on(False) #subplot(111, axisbg='darkslategray') #ax = fig.add_subplot(111) #self.axes.scatter(self.data2, self.data1, c=[0.5,0.5,1.0], s=200, alpha=0.5) def build_collection(self): self.point_size = self.sl_x2_pointsize.GetValue( ) + 50 # range 50 to 300 self.collection = RegularPolyCollection( #self.axes.figure.dpi, numsides=80, sizes=(self.point_size, ), facecolors=self.color_array, offsets=self.data_array, transOffset=self.axes.transData) self.collection.set_alpha(0.7) self.axes.add_collection(self.collection) #self.axes.axis([self.xmin, self.xmax, self.ymin, self.ymax]) self.axes.autoscale_view() x = self.axes.get_xaxis() y = self.axes.get_yaxis() x.zoom(-1) y.zoom(-1) #self.axes.axis('tight') ##self.axes.axis('off') def callback(self, verts): facecolors = self.collection.get_facecolors() ind = nonzero(points_inside_poly(self.data_array, verts))[0] for i in range(len(self.data_array)): if i in ind: facecolors[i] = (1, 1, 0, .5) #print facecolors[i] #pass else: facecolors[i] = self.color_array[i] #pass #print facecolors[i] self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso #self.ind = ind self.pass_data(ind) def onpress(self, event): #print event.button if self.canvas.widgetlock.locked(): #print 'foo' self.canvas.widgetlock.release(self.lasso) #return if event.inaxes is None: return self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.canvas.widgetlock(self.lasso) def pass_data(self, ind): #populate parents list control self.lc_x2_plist.DeleteAllItems() for x in ind: self.lc_x2_plist.InsertStringItem(0, self.song_array[x][0]) self.lc_x2_plist.SetStringItem(0, 1, self.song_array[x][1]) #pass def update_data(self): pass #self.figure.clf() #build_graph(self) #self.MakeScatt() #self.build_collection() def OnAutoGenerateX2Playist(self, event): # copy the sifted list to the playlist self.parent.CheckClear() insert_at = self.parent.lc_playlist.GetItemCount() for x in range(self.lc_x2_plist.GetItemCount(), 0, -1): artist = self.lc_x2_plist.GetItem(x - 1, 0).GetText() song = self.lc_x2_plist.GetItem(x - 1, 1).GetText() self.parent.SetPlaylistItem(insert_at, artist, song, '', '') #save the playlist self.parent.SavePlaylist() # switch tabs self.parent.nb_main.SetSelection(self.nb_playlist)