class Canvas(object): def __init__(self, img, name='misc', patch_size=(100, 100), axes=None): """ Parameters ---------- img : 2-D ndarray Image to crop from. name : str Basename of output files for images cropped from this canvas. patch_size : tuple of ints Size of the patch to crop (rows, cols). axes : matplotlib axes object Axes on which to draw the patch. """ self.name = name self.img = img self.x = 0 self.y = 0 self.patch_size = patch_size h, w = self.patch_size self.patch = Rectangle((self.x, self.y), h, w, alpha=0.3) self.axes = axes axes.add_patch(self.patch) def paint(self): self.patch.set_x(self.x) self.patch.set_y(self.y) # This is probably not the right call. Should call redraw on canvas? plt.draw() print self.name
def __plot_volume(self, ax, params=None): if params is None: width = 0.6 else: width = params["width"] prices = self.prices.tail(self.candlestick_num) for i in self.indices: p = prices.iloc[i, :] open = p["Open"] close = p["Close"] volume = p["Volume"] if close >= open: color = "red" else: color = "green" rect = Rectangle( xy = (i - width/2, 0), width = width, height = volume, facecolor = color, edgecolor = color, ) rect.set_alpha(0.5) ax.add_patch(rect) ax.set_ylim([0, prices["Volume"].max() * 1.25]) ax.grid(b=True, axis='x')
def candlestick(self, axis, prices, width=0.5, colorup='green', colordown='red', alpha=1.0): """ Plot the time, open, close, high, low as a vertical line ranging from low to high. Use a rectangular bar to represent the open-close span. If close >= open, use colorup to color the bar, otherwise use colordown ax : an Axes instance to plot to width : fraction of a day for the rectangle width colorup : the color of the rectangle where close >= open colordown : the color of the rectangle where close < open alpha : the rectangle alpha level """ dates = [] lines = [] for date in self.dates: t = date2num(date) close = prices.close[date] open_ = prices.open[date] if close >= open_: color = colorup lower = open_ height = close - open_ else: color = colordown lower = close height = open_ - close lines.extend([prices.low[date], prices.high[date], None]) dates.extend([t, t, None]) rect = Rectangle(xy=(t - width/2, lower), width=width, height=height, facecolor=color, edgecolor=color, zorder=2) rect.set_alpha(alpha) axis.add_patch(rect) axis.plot(dates, lines, linewidth=0.5, zorder=1, antialiased=True) return min(y for y in lines if y is not None), max(lines)
def __init__(self, ax, labels, actives): """ Add check buttons to :class:`matplotlib.axes.Axes` instance *ax* *labels* A len(buttons) list of labels as strings *actives* A len(buttons) list of booleans indicating whether the button is active """ ax.set_xticks([]) ax.set_yticks([]) ax.set_navigate(False) if len(labels)>1: dy = 1./(len(labels)+1) ys = np.linspace(1-dy, dy, len(labels)) else: dy = 0.25 ys = [0.5] cnt = 0 axcolor = ax.get_axis_bgcolor() self.labels = [] self.lines = [] self.rectangles = [] lineparams = {'color':'k', 'linewidth':1.25, 'transform':ax.transAxes, 'solid_capstyle':'butt'} for y, label in zip(ys, labels): t = ax.text(0.25, y, label, transform=ax.transAxes, horizontalalignment='left', verticalalignment='center') w, h = dy/2., dy/2. x, y = 0.05, y-h/2. p = Rectangle(xy=(x,y), width=0.9, height=h, facecolor=axcolor,transform=ax.transAxes) l1 = Rectangle(xy=(x,y), width=0.9, height=h, facecolor='red',alpha=0.5, transform=ax.transAxes) l1.set_visible(actives[cnt]) #l2.set_visible(actives[cnt]) self.labels.append(t) self.rectangles.append(p) self.lines.append((l1))#,l2)) ax.add_patch(p) ax.add_patch(l1) #ax.add_line(l2) cnt += 1 ax.figure.canvas.mpl_connect('button_press_event', self._clicked) self.ax = ax self.cnt = 0 self.observers = {}
def plotKLine(self, data, timescale=1.0, width=0.9, colorup='r', colorflat = 'w', colordown='g', alpha=1.0): self.priceChart.set_xlim(data[0]-50*timescale/86400,data[0]+8*timescale/86400) t, open, close, high, low = data[:5] if close > open: color = colorup elif close == open: color = colorflat else: color = colordown if close == open: close = open + 0.005 shadowline = Line2D(xdata=(t, t), ydata=(low, high), color=color,linewidth=0.5,antialiased=True,) rect = Rectangle(xy = (t-width*timescale/172800, open), width = width*timescale/86400, height = close-open, facecolor=color, edgecolor=color,) rect.set_alpha(alpha) #self.priceChart.axhline(y=close,xmin=0.2,xmax=0.8) self.priceChart.add_line(shadowline) self.priceChart.add_patch(rect) #返回画的图形,方便后面adjust return shadowline, rect
def get_gate_patch(self): '''Returns a matplotlib patch to be drawn on the canvas whose dimensions have been computed from the current gate. ''' x_min, x_max = self.subplot.get_xlim() x_range = x_max - x_min y_min, y_max = self.subplot.get_ylim() y_range = y_max - y_min for subgate in self.gate.get_subgates(): col = subgate.get_column() if col == self.x_column: x_min = subgate.get_min() x_range = subgate.get_max() - subgate.get_min() if col == self.y_column: y_min = subgate.get_min() y_range = subgate.get_max() - subgate.get_min() if self.patch not in self.subplot.patches: rect = Rectangle((x_min, y_min), x_range, y_range, animated=True) rect.set_fill(False) rect.set_linestyle('dashed') self.patch = self.subplot.add_patch(rect) else: self.patch.set_bounds(x_min, y_min, x_range, y_range) return self.patch
def candlestick(ax, quotes, width=0.2, colorup="k", colordown="r", alpha=1.0): OFFSET = width / 2.0 lines = [] patches = [] for q in quotes: t, open, close, high, low = q[:5] if close >= open: color = colorup lower = open height = close - open else: color = colordown lower = close height = open - close vline = Line2D(xdata=(t, t), ydata=(low, high), color=color, linewidth=0.5, antialiased=True) rect = Rectangle(xy=(t - OFFSET, lower), width=width, height=height, facecolor=color, edgecolor=color) rect.set_alpha(alpha) lines.append(vline) patches.append(rect) ax.add_line(vline) ax.add_patch(rect) ax.autoscale_view() return lines, patches
def plot_window(self, component, starttime, endtime, window_weight): if component == "Z": axis = self.plot_axis_z elif component == "N": axis = self.plot_axis_n elif component == "E": axis = self.plot_axis_e else: raise NotImplementedError trace = self.data["synthetics"][0] ymin, ymax = axis.get_ylim() xmin = starttime - trace.stats.starttime width = endtime - starttime height = ymax - ymin rect = Rectangle((xmin, ymin), width, height, facecolor="0.6", alpha=0.5, edgecolor="0.5", picker=True) axis.add_patch(rect) attached_text = axis.text( x=xmin + 0.02 * width, y=ymax - 0.02 * height, s=str(window_weight), verticalalignment="top", horizontalalignment="left", color="0.4", weight=1000) # Monkey patch to trigger text removal as soon as the rectangle is # removed. def remove(): super(Rectangle, rect).remove() attached_text.remove() rect.remove = remove
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): p = Rectangle(xy=(-xdescent, -ydescent), width=width, height=height) self.update_prop(p, orig_handle, legend) p.set_transform(trans) return [p]
def addItem(self, x, y, legend, shape, color, fill, overlay, z): xView = numpy.array(x, copy=False) yView = numpy.array(y, copy=False) if shape == "line": item = self.ax.plot(x, y, label=legend, color=color, linestyle='-', marker=None)[0] elif shape == "hline": if hasattr(y, "__len__"): y = y[-1] item = self.ax.axhline(y, label=legend, color=color) elif shape == "vline": if hasattr(x, "__len__"): x = x[-1] item = self.ax.axvline(x, label=legend, color=color) elif shape == 'rectangle': xMin = numpy.nanmin(xView) xMax = numpy.nanmax(xView) yMin = numpy.nanmin(yView) yMax = numpy.nanmax(yView) w = xMax - xMin h = yMax - yMin item = Rectangle(xy=(xMin, yMin), width=w, height=h, fill=False, color=color) if fill: item.set_hatch('.') self.ax.add_patch(item) elif shape in ('polygon', 'polylines'): xView = xView.reshape(1, -1) yView = yView.reshape(1, -1) item = Polygon(numpy.vstack((xView, yView)).T, closed=(shape == 'polygon'), fill=False, label=legend, color=color) if fill and shape == 'polygon': item.set_hatch('/') self.ax.add_patch(item) else: raise NotImplementedError("Unsupported item shape %s" % shape) item.set_zorder(z) if overlay: item.set_animated(True) self._overlays.add(item) return item
def __init__(self, x, y, dx, dy, border_tol=0.1, resize=True, plotview=None, **opts): shape = Rectangle((float(x),float(y)), float(dx), float(dy), **opts) if 'linewidth' not in opts: shape.set_linewidth(1.0) if 'facecolor' not in opts: shape.set_facecolor('r') super(NXrectangle, self).__init__(shape, border_tol, resize, plotview) self.shape.set_label('Rectangle') self.rectangle = self.shape
def _get_emptiest_area(ax, factor, target_x, areas_to_avoid=[]): """ Get's the emptiest area of size (1/factor x 1/factor) compared to the overall size of the plot area. ax - the axes of the plot factor - 1 / the fraction of the size the area should be target_x - the ideal x-value for the area to be centred on areas_to_avoid - a list of figure-space Rectangles which must be avoided returns a Rectangle in figure-space which """ lines = ax.get_lines() min_points = np.inf min_rect = None x_range = ax.get_xlim() coord_width = x_range[1] - x_range[0] plot_width = coord_width / factor y_range = ax.get_ylim() coord_height = y_range[1] - y_range[0] plot_height = coord_height / factor # Change the target x so that the centre will be at the target x target_x -= plot_width / 2 if target_x < x_range[0]: target_x = x_range[0] # Start from the target x as an ideal position, then go right, then left for i in np.concatenate([np.linspace(target_x, x_range[1] - plot_width, 10), np.linspace(target_x, x_range[0], 10)]): # Start from the TOP of the plot as ideal, then downwards for j in np.linspace(y_range[1] - plot_height, y_range[0], 10): rect = Rectangle([i, j], plot_width, plot_height) overlap = False # Check that this rectangle will not overlap any of the explicitly-banned areas rect_bbox = _coord_space_rect_to_figure_space_rect(rect, ax).get_bbox() for area in areas_to_avoid: if rect_bbox.overlaps(area.get_bbox()): overlap = True break if overlap: continue points = 0 for line in lines: for point in line.get_xydata(): if rect.contains_point(point, radius=0.0): points += 1 if points < min_points: min_points = points min_rect = rect if min_points == 0: break if min_points == 0: break return _coord_space_rect_to_figure_space_rect(min_rect, ax)
def highlight_artist(self, val, artist=None): # print val, artist figure=self.get_figpage()._artists[0] ax = self.get_figaxes() if artist is None: alist=self._artists else: alist=artist if val == True: container = self.get_container() if container is None: return de = self.get_data_extent() from ifigure.matplotlib_mod.art3d_gl import AxesImageGL if isinstance(alist[0], AxesImageGL): hl = alist[0].add_hl_mask() for item in hl: alist[0].figobj_hl.append(item) # hl = alist[0].make_hl_artist(container) # rect_alpha = 0.0 else: x=[de[0],de[1],de[1],de[0],de[0]] y=[de[2],de[2],de[3],de[3],de[2]] hl= container.plot(x, y, marker='s', color='k', linestyle='None', markerfacecolor='None', markeredgewidth = 0.5, scalex=False, scaley=False) rect_alpha = 0.3 hlp = Rectangle((de[0],de[2]), de[1]-de[0], de[3]-de[2], alpha=rect_alpha, facecolor='k', figure = figure, transform= container.transData) if ax is not None: x0, y0 = ax._artists[0].transAxes.transform((0,0)) x1, y1 = ax._artists[0].transAxes.transform((1,1)) bbox = Bbox([[x0,y0],[x1,y1]]) hlp.set_clip_box(bbox) hlp.set_clip_on(True) figure.patches.append(hlp) for item in (hl[0], hlp): alist[0].figobj_hl.append(item) else: for a in alist: if len(a.figobj_hl) != 0: a.figobj_hl[0].remove() figure.patches.remove(a.figobj_hl[1]) a.figobj_hl=[]
def _on_figure_motion(self, event): if event.inaxes == None: return self._motion_wait -= 1 if self._motion_wait > 0: return x0, y0, x1, y1 = event.inaxes.dataLim.bounds number_of_points = len(event.inaxes.lines[-1].get_ydata()) index = int(round((number_of_points-1) * (event.xdata-x0)/x1)) if len(self._data[0]) < index + 1: return if self._background is None: self._background = self._figure.canvas.copy_from_bbox(self._graphs[0].bbox) # restore the clean slate background self._figure.canvas.restore_region(self._background) polygon = None if self._select_start == None: linev = self._graphs[-1].axvline(x=event.xdata, linewidth=1, color="#000000", alpha=0.5) lineh = self._graphs[7].axhline(y=event.ydata, linewidth=1, color="#000000", alpha=0.5) self._graphs[-1].draw_artist(linev) self._graphs[-1].draw_artist(lineh) else: width = abs(event.xdata - self._select_start) start = self._select_start if (event.xdata < start): start = event.xdata if width < 20: col = "#aa4444" else: col = "#888888" polygon = Rectangle((start, 0), width, y1 + 10000, facecolor=col, alpha=0.5) self._graphs[-1].add_patch(polygon) self._graphs[-1].draw_artist(polygon) self._figure.canvas.blit(self._graphs[-1].bbox) if self._select_start == None: linev.remove() lineh.remove() if polygon != None: polygon.remove() for i in xrange(0, 8): if (i < 2): val = str(self._data[i][index]) else: val = str(int(self._data[i][index])) self._mouse_texts[i].setText(val)
def __init__(self, tgi, node, time, type, msg, fullmsg, fulltime): Rectangle.__init__(self, xy= (time + tgi.type_to_offset[type][0], \ node + tgi.type_to_offset[type][1]) , \ width=.5, height=.1, \ fc=tgi.type_to_color[type][0], \ ec=tgi.type_to_color[type][0], \ linewidth=0.0) self.fulltime = fulltime self.msg = msg self.fullmsg = fullmsg
def _init_rectangles(self): self.rectangles = [] n_row = len(self.axes) for row_i, all_axes in enumerate(self.axes): self.rectangles.append([]) for col_i, axes in enumerate(all_axes): rect = Rectangle( (0, 0), 0, 0 ) rect.set_visible(False) axes.add_patch(rect) self.rectangles[-1].append(rect) return
def on_press(event): global id_motion, xs, ys, r print 'INAXES: ', event.inaxes if event.inaxes!=ax: return xs, ys = event.xdata, event.ydata print 'PRESS button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % ( event.button, event.x, event.y, event.xdata, event.ydata) r = Rectangle(xy=(xs,ys), height=0, width=0, fill=False, lw=2, alpha=0.2) ax.add_artist(r) r.set_clip_box(ax.bbox) draw() id_motion = fig.canvas.mpl_connect('motion_notify_event', on_motion)
def PlotPatchLine(ax,prop): length = ((prop['yEnd']-prop['yStart'])**2+(prop['zEnd']-prop['zStart'])**2) ** 0.5 ang = arctan((prop['zEnd']-prop['zStart'])/(prop['yEnd']-prop['yStart'])) ang = ang / 3.1415926*180 width = prop['widthLine'] patchi = Rectangle((prop['yStart'],prop['zStart']-width/2.0),length,width,color='blue',alpha=0.5) t2 = matplotlib.transforms.Affine2D().rotate_deg(ang) + ax.transData patchi.set_transform(t2) ax.add_patch(patchi)
def __plot_candlestick(self, ax, width=0.5, colorup='red', colordown='green', alpha=0.8): offset = width / 2.0 line_width = width * 2 prices = self.prices.tail(self.candlestick_num) for i in self.indices: p = prices.iloc[i, :] open = p["Open"] close = p["Close"] high = p["High"] low = p["Low"] box_high = max(open, close) box_low = min(open, close) height = box_high - box_low if close >= open: color = colorup else: color = colordown vline_low = Line2D( xdata=(i, i), ydata=(low, box_low), color = 'black', linewidth=line_width, antialiased=True, ) vline_high = Line2D( xdata=(i, i), ydata=(box_high, high), color = 'black', linewidth=line_width, antialiased=True, ) rect = Rectangle( xy = (i - offset, box_low), width = width, height = height, facecolor = color, edgecolor = color, ) rect.set_alpha(alpha) ax.add_line(vline_low) ax.add_line(vline_high) ax.add_patch(rect) ax.autoscale_view()
def showBitPositions(self,ax,color=[0,0,255]): color=[c/255. for c in color] px,py,tx,ty=self.descriptor.getBits(self.cell) truth=np.hstack((tx,ty)) for i,pos in enumerate(np.vstack((px,py))): if truth[i]: fc="r" else: fc="none" xy=self.invTransForm([(pos[0]-0.5/self.scale),(pos[1]-0.5/self.scale)]) p = Rectangle(xy,width=self.descriptor.bitDistance/self.scale,height=-self.descriptor.bitDistance/self.scale, fc=fc,lw=1,alpha=0.3) t = MPLTransforms.Affine2D().rotate_around(xy[0],xy[1],-self.angle/180.*np.pi) + ax.transData p.set_transform(t) ax.add_artist(p)
def on_motion(self, event): """Draw a selection rect""" if self.press == False: return x = event.xdata; y = event.ydata if x == None or y==None: return '''print self.prevx, self.x xmin, xmax = self.ax.get_xlim() ymin, ymax = self.ax.get_ylim() if self.prevx<self.x: x=xmin elif self.prevx>self.x: x=xmax if self.prevy<self.y: y=ymin elif self.prevy>self.y: y=ymax''' dx = x-self.x; dy=y-self.y if self.rect == None: #print 'new' self.rect = Rectangle((self.x,self.y),dx,dy, fc='lightblue',ec='blue',alpha=0.6) self.ax.add_patch(self.rect) else: self.rect.set_width(dx) self.rect.set_height(dy) #draw selection rect self.ax.figure.canvas.draw() self.parent.selection = (self.x, self.y, x, y) if x!=None: self.prevx=x if y!=None: self.prevy=y return
def on_press(self, event): if event.inaxes == self.ax: for x_marker in self.previous_rects_x: x_min,y_min=x_marker.xy x_max=x_min+x_marker.get_width() y_max=y_min+x_marker.get_height() if event.xdata > x_min and event.xdata <x_max and event.ydata>y_min and event.ydata<y_max: for i in [np.where(self.xdata==x)[0][0] for x in self.xdata if (x>x_min and x<x_max)]: self.mask[i]=1 del self.previous_rects[self.previous_rects_x.index(x_marker)] del self.previous_rects_x[self.previous_rects_x.index(x_marker)] return if event.ydata==None: return self.rect = Rectangle((0,0), 0, 0, facecolor='red', edgecolor='red', alpha=0.2) self.ax.add_patch(self.rect) self.is_pressed=True self.is_drawing_new_rect=True self.x0 = event.xdata self.x1 = event.xdata self.rect.set_width(self.x1 - self.x0) self.rect.set_xy((self.x0, self.y0)) self.rect.set_linestyle('dashed') self.ax.figure.canvas.draw() elif event.inaxes == self.fit_increment_ax: self.inc_clicked() elif event.inaxes == self.fit_decrement_ax: self.dec_clicked()
def __init__(self, ax, profile, errs, profnm, minspanx=None, minspany=None, useblit=True): self.ax = ax.axes self.profile = profile self.proflen = len(profile) self.profnm = profnm self.phases = Num.arange(self.proflen, dtype='d')/self.proflen self.errs = errs self.visible = True self.DCguess = sorted(profile)[len(profile)/10+1] self.init_params = [self.DCguess] self.numgaussians = 0 self.canvas = ax.figure.canvas self.canvas.mpl_connect('motion_notify_event', self.onmove) self.canvas.mpl_connect('button_press_event', self.press) self.canvas.mpl_connect('button_release_event', self.release) self.canvas.mpl_connect('draw_event', self.update_background) self.background = None self.rectprops = dict(facecolor='white', edgecolor = 'black', alpha=0.5, fill=False) self.to_draw = Rectangle((0,0), 0, 1, visible=False, **self.rectprops) self.ax.add_patch(self.to_draw) self.useblit = useblit self.minspanx = minspanx self.minspany = minspany # will save the data (position at mouseclick) self.eventpress = None # will save the data (pos. at mouserelease) self.eventrelease = None self.plot_gaussians(self.init_params)
def __init__(self,x,y,shape,anomaly,ax,ax2,points2pad): self.x = x self.y = y self.shape = shape self.ax = ax self.ax2 = ax2 self.points2pad = points2pad self.anomaly = anomaly self.dx = (max(x)-min(x))/(self.shape[1]-1) self.half_width = (min(self.shape)/16)*self.dx self.x_center = None self.y_center = None self.rect = Rectangle((0,0), 1, 1,fc='None') self.x1 = None self.y1 = None self.x2 = None self.y2 = None self.shape_window = None self.l, = self.ax.plot([self.x_center],[self.y_center],'o') self.ax.add_patch(self.rect) self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press) self.ax.figure.canvas.mpl_connect('scroll_event', self.on_scroll) self.ax.figure.canvas.mpl_connect('key_press_event', self.on_key) print "\nINSTRUCTIONS:" print "Click to select the window center" print "Move the center with arrows or click again" print "Resize the window with the mouse scroll or with '+' and '-'" print "Press 'i' to show information about the window" print "Press Enter or Right Click to plot the spectrum of the current window\n"
def __init__(self, axis, m, x0, x0_prime): self._t = 0 self._pot = Rectangle((x0, -CUBE_HEIGHT/2), CUBE_WIDTH, CUBE_HEIGHT, color='red') self._ax = axis axis.add_patch(self._pot) self._cubePos = CubePhysics(m, x0, x0_prime)
def __init__(self, fig, rect, *args, **kwargs): self.aln = kwargs.pop("aln") nrows = len(self.aln) ncols = self.aln.get_alignment_length() self.alnidx = numpy.arange(ncols) self.app = kwargs.pop("app", None) self.showy = kwargs.pop('showy', True) Axes.__init__(self, fig, rect, *args, **kwargs) rgb = mpl_colors.colorConverter.to_rgb gray = rgb('gray') d = defaultdict(lambda:gray) d["A"] = rgb("red") d["a"] = rgb("red") d["C"] = rgb("blue") d["c"] = rgb("blue") d["G"] = rgb("green") d["g"] = rgb("green") d["T"] = rgb("yellow") d["t"] = rgb("yellow") self.cmap = d self.selector = RectangleSelector( self, self.select_rectangle, useblit=True ) def f(e): if e.button != 1: return True else: return RectangleSelector.ignore(self.selector, e) self.selector.ignore = f self.selected_rectangle = Rectangle( [0,0],0,0, facecolor='white', edgecolor='cyan', alpha=0.3 ) self.add_patch(self.selected_rectangle) self.highlight_find_collection = None
def __init__(self, parent): wx.Frame.__init__(self, None, size=(300,500), pos=(650, 50), title='Plot Frame') self.parent = parent # initialize plot self.figure = Figure() self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvas(self, -1, self.figure) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(self.sizer) # Connect the mouse events to their relevant callbacks self.canvas.mpl_connect('button_press_event', self._onPress) self.canvas.mpl_connect('button_release_event', self._onRelease) self.canvas.mpl_connect('motion_notify_event', self._onMotion) self.pressed = False # Initialise the rectangle self.rect = Rectangle((0,0), 1, 1, facecolor='None', visible=False, edgecolor='k', linestyle='dashed') self.x0 = 0#None self.y0 = 0#None self.x1 = 0#None self.y1 = 0#None self.axes.add_patch(self.rect) self.Fit()
def new_axes(self, ax, nrect): self.ax = ax if self.canvas is not ax.figure.canvas: if self.canvas is not None: self.disconnect_events() self.canvas = ax.figure.canvas self.connect_default_events() # span trans = blended_transform_factory(self.ax.transData, self.ax.transAxes) w, h = 0, 1 self.rect = Rectangle((0, 0), w, h, transform=trans, visible=False, animated=True, **self.rectprops) self.ax.add_patch(self.rect) self.artists = [self.rect] # stay rect self.stay_rects = [] for set in range(0, len(nrect)): self.stay_rects.append([]) for n in range(0, nrect[set]): stay_rect = Rectangle((0, 0), w, h, transform=trans, visible=False, animated=True, **self.stay_rectprops[set]) self.ax.add_patch(stay_rect) self.stay_rects[set].append(stay_rect) self.artists.extend(self.stay_rects[set]) # bar self.bar = ax.axvline(0, w, h, visible=False, **self.lineprops) self.artists.append(self.bar)
def __init__(self, img, name='misc', patch_size=(100, 100), axes=None): """ Parameters ---------- img : 2-D ndarray Image to crop from. name : str Basename of output files for images cropped from this canvas. patch_size : tuple of ints Size of the patch to crop (rows, cols). axes : matplotlib axes object Axes on which to draw the patch. """ self.name = name self.img = img self.x = 0 self.y = 0 self.patch_size = patch_size h, w = self.patch_size self.patch = Rectangle((self.x, self.y), h, w, alpha=0.3) self.axes = axes axes.add_patch(self.patch)
def __init__(self,scatterplot,toolbar,listbox,infobox,x_points,y_points,colors,dir,points,sizes): self.path = dir + '/selected.fas' self.x_points = x_points self.y_points = y_points self.selectedpoints = [] self.selectedseqs = [] self.scatter = scatterplot self.toolbar = toolbar self.listbox = listbox self.infobox = infobox self.colors = colors self.points = points self.sizes = sizes self.cmaps = [cm.prism,cm.Accent,cm.gist_ncar,cm.Paired,cm.rainbow,cm.Blues] self.cmapindex = 0 self.scatter.scatter(self.x_points, self.y_points,c=self.colors,cmap=self.cmaps[self.cmapindex],s=self.sizes) self.rect = Rectangle((0,0), 0, 0,facecolor='grey', alpha=0.3) self.scatter.add_patch(self.rect) self.x0 = 0 self.y0 = 0 self.x1 = 0 self.y1 = 0 self.isPressed = False self.scatter.figure.canvas.draw() self.connect()
def draw_full_court(ax=None, color="gray", lw=1, zorder=0): if ax is None: ax = plt.gca() # Creates the out of bounds lines around the court outer = Rectangle((0, -50), width=94, height=50, color=color, zorder=zorder, fill=False, lw=lw) # The left and right basketball hoops l_hoop = Circle((5.35, -25), radius=.75, lw=lw, fill=False, color=color, zorder=zorder) r_hoop = Circle((88.65, -25), radius=.75, lw=lw, fill=False, color=color, zorder=zorder) # Left and right backboards l_backboard = Rectangle((4, -28), 0, 6, lw=lw, color=color, zorder=zorder) r_backboard = Rectangle((90, -28), 0, 6, lw=lw, color=color, zorder=zorder) # Left and right paint areas l_outer_box = Rectangle((0, -33), 19, 16, lw=lw, fill=False, color=color, zorder=zorder) l_inner_box = Rectangle((0, -31), 19, 12, lw=lw, fill=False, color=color, zorder=zorder) r_outer_box = Rectangle((75, -33), 19, 16, lw=lw, fill=False, color=color, zorder=zorder) r_inner_box = Rectangle((75, -31), 19, 12, lw=lw, fill=False, color=color, zorder=zorder) # Left and right free throw circles l_free_throw = Circle((19, -25), radius=6, lw=lw, fill=False, color=color, zorder=zorder) r_free_throw = Circle((75, -25), radius=6, lw=lw, fill=False, color=color, zorder=zorder) # Left and right corner 3-PT lines # a represents the top lines # b represents the bottom lines l_corner_a = Rectangle((0, -3), 14, 0, lw=lw, color=color, zorder=zorder) l_corner_b = Rectangle((0, -47), 14, 0, lw=lw, color=color, zorder=zorder) r_corner_a = Rectangle((80, -3), 14, 0, lw=lw, color=color, zorder=zorder) r_corner_b = Rectangle((80, -47), 14, 0, lw=lw, color=color, zorder=zorder) # Left and right 3-PT line arcs l_arc = Arc((5, -25), 47.5, 47.5, theta1=292, theta2=68, lw=lw, color=color, zorder=zorder) r_arc = Arc((89, -25), 47.5, 47.5, theta1=112, theta2=248, lw=lw, color=color, zorder=zorder) # half_court # ax.axvline(470) half_court = Rectangle((47, -50), 0, 50, lw=lw, color=color, zorder=zorder) hc_big_circle = Circle((47, -25), radius=6, lw=lw, fill=False, color=color, zorder=zorder) hc_sm_circle = Circle((47, -25), radius=2, lw=lw, fill=False, color=color, zorder=zorder) court_elements = [ l_hoop, l_backboard, l_outer_box, outer, l_inner_box, l_free_throw, l_corner_a, l_corner_b, l_arc, r_hoop, r_backboard, r_outer_box, r_inner_box, r_free_throw, r_corner_a, r_corner_b, r_arc, half_court, hc_big_circle, hc_sm_circle ] # Add the court elements onto the axes for element in court_elements: ax.add_patch(element) return ax
def create_plots(robot, obstacles, dist_est, checker): from matplotlib.cm import get_cmap cmaps = [get_cmap('Reds'), get_cmap('Blues')] plt.rcParams.update({ "text.usetex": True, "font.family": "sans-serif", "font.sans-serif": ["Helvetica"] }) if robot.dof > 2: fig = plt.figure(figsize=(3, 3)) ax = fig.add_subplot(111) #, projection='3d' elif robot.dof == 2: # Show C-space at the same time num_class = getattr(checker, 'num_class', 1) fig = plt.figure(figsize=(3 * (num_class + 1), 3 * num_class)) gs = fig.add_gridspec(num_class, num_class + 1) ax = fig.add_subplot(gs[:, :-1]) cfg_path_plots = [] size = [400, 400] yy, xx = torch.meshgrid(torch.linspace(-np.pi, np.pi, size[0]), torch.linspace(-np.pi, np.pi, size[1])) grid_points = torch.stack([xx, yy], axis=2).reshape((-1, 2)) score_spline = dist_est(grid_points).reshape(size + [num_class]) c_axes = [] with sns.axes_style('ticks'): for cat in range(num_class): c_ax = fig.add_subplot(gs[cat, -1]) # score_DiffCo = checker.score(grid_points).reshape(size) # score = (torch.sign(score_DiffCo)+1)/2*(score_spline-score_spline.min()) + (-torch.sign(score_DiffCo)+1)/2*(score_spline-score_spline.max()) score = score_spline[:, :, cat] color_mesh = c_ax.pcolormesh(xx, yy, score, cmap=cmaps[cat], vmin=-torch.abs(score).max(), vmax=torch.abs(score).max()) c_support_points = checker.support_points[ checker.gains[:, cat] != 0] c_ax.scatter(c_support_points[:, 0], c_support_points[:, 1], marker='.', c='black', s=1.5) contour_plot = c_ax.contour( xx, yy, score, levels=[-18, -10, 0, 3.5 if cat == 0 else 2.5], linewidths=1, alpha=0.4, colors='k') #-1.5, -0.75, 0, 0.3 ax.clabel(contour_plot, inline=1, fmt='%.1f', fontsize=8) # Comment these out if you want colorbars, grad arrows for debugging purposes # fig.colorbar(color_mesh, ax=c_ax) # sparse_score = score[5:-5:10, 5:-5:10] # score_grad_x = -ndimage.sobel(sparse_score.numpy(), axis=1) # score_grad_y = -ndimage.sobel(sparse_score.numpy(), axis=0) # score_grad = np.stack([score_grad_x, score_grad_y], axis=2) # score_grad /= np.linalg.norm(score_grad, axis=2, keepdims=True) # score_grad_x, score_grad_y = score_grad[:, :, 0], score_grad[:, :, 1] # c_ax.quiver(xx[5:-5:10, 5:-5:10], yy[5:-5:10, 5:-5:10], score_grad_x, score_grad_y, color='red', width=2e-3, headwidth=2, headlength=5) # cfg_point = Circle(collision_cfgs[0], radius=0.05, facecolor='orange', edgecolor='black', path_effects=[path_effects.withSimplePatchShadow()]) # c_ax.add_patch(cfg_point) cfg_path, = c_ax.plot([], [], '-o', c='orange', markersize=3) cfg_path_plots.append(cfg_path) c_ax.set_aspect('equal', adjustable='box') # c_ax.axis('equal') c_ax.set_xlim(-np.pi, np.pi) c_ax.set_ylim(-np.pi, np.pi) c_ax.set_xticks([-np.pi, 0, np.pi]) c_ax.set_xticklabels(['$-\pi$', '$0$', '$\pi$'], fontsize=18) c_ax.set_yticks([-np.pi, 0, np.pi]) c_ax.set_yticklabels(['$-\pi$', '$0$', '$\pi$'], fontsize=18) # Plot ostacles # ax.axis('tight') ax.set_xlim(-8, 8) ax.set_ylim(-8, 8) ax.set_aspect('equal', adjustable='box') ax.set_xticks([-4, 0, 4]) ax.set_yticks([-4, 0, 4]) ax.tick_params(labelsize=18) for obs in obstacles: cat = obs[3] if len(obs) >= 4 else 1 print('{}, cat {}, {}'.format(obs[0], cat, obs)) if obs[0] == 'circle': ax.add_patch( Circle(obs[1], obs[2], path_effects=[path_effects.withSimplePatchShadow()], color=cmaps[cat](0.5))) elif obs[0] == 'rect': ax.add_patch( Rectangle((obs[1][0] - float(obs[2][0]) / 2, obs[1][1] - float(obs[2][1]) / 2), obs[2][0], obs[2][1], path_effects=[path_effects.withSimplePatchShadow()], color=cmaps[cat](0.5))) # Placeholder of the robot plot trans = ax.transData.transform lw = ((trans((1, robot.link_width)) - trans( (0, 0))) * 72 / ax.figure.dpi)[1] link_plot, = ax.plot( [], [], color='silver', alpha=0.1, lw=lw, solid_capstyle='round', path_effects=[path_effects.SimpleLineShadow(), path_effects.Normal()]) joint_plot, = ax.plot([], [], 'o', color='tab:red', markersize=lw) eff_plot, = ax.plot([], [], 'o', color='black', markersize=lw) if robot.dof > 2: return fig, ax, link_plot, joint_plot, eff_plot elif robot.dof == 2: return fig, ax, link_plot, joint_plot, eff_plot, cfg_path_plots
def play_trajectory(self): w = self.game_params['width'] d_mines = self.game_params['d_mines'] x_h_3D = self.x_h_test x_t_3D = self.x_t_test x_mines = self.x_mines_test goal_0_2D = self.goal_0_test goal_1 = self.goal_1_test d_host_mins = self.d_host_mines # loop over trajectory points and plot self.ax.clear() host_scatter = self.ax.scatter(x_h_3D[0][0][0], x_h_3D[0][0][1], facecolor='r', edgecolor='none', s=150) target_scatter = self.ax.scatter(x_t_3D[0][0][0], x_t_3D[0][0][1], facecolor='y', edgecolor='none', s=30) # mines_scatter = self.ax.scatter(x_mines[:,0], x_mines[:,1], facecolor = 'k', edgecolor='none', s=80) goal_0_scatter = self.ax.scatter(goal_0_2D[0][0], goal_0_2D[0][1], marker='x', s=80, color='b') goal_1_scatter = self.ax.scatter(goal_1[0], goal_1[1], marker='x', s=80, color='r') self.fig.canvas.draw() self.ax.add_patch( Rectangle((0, 0), w, w, alpha=0.1, edgecolor='k', facecolor='b')) self.ax.set_xlim([-10, w + 10]) self.ax.set_ylim([-10, w + 10]) self.ax.set_xticklabels([]) self.ax.set_yticklabels([]) i = 0 for x_h_2D, x_t_2D, goal_0 in zip(x_h_3D, x_t_3D, goal_0_2D): goal_0_scatter.set_offsets(goal_0) for x_h, x_t in zip(x_h_2D, x_t_2D): self.ax.set_title(('Sample Trajectory\n time: %d' % i)) host_scatter.set_offsets(x_h) self.ax.scatter(x_h[0], x_h[1], c='k', s=10) target_scatter.set_offsets(x_t) # draw mines d_host_mines = ((x_h - x_mines)**2).sum(axis=1) activated = d_host_mines <= d_mines # mines_scatter.set_array(activated) self.ax.scatter(x_mines[:, 0], x_mines[:, 1], c=activated, s=80) self.fig.canvas.draw() plt.pause(0.01) i += 1
def _waffle(self, loc, **kwargs): # _pa is the arguments for this single plot self._pa = kwargs # Append figure args to plot args plot_fig_args = copy.deepcopy(self.fig_args) for arg, v in plot_fig_args.items(): if arg not in self._pa: self._pa[arg] = v if len(self._pa['values']) == 0 or not self._pa['rows']: raise ValueError("Argument values or rows is required.") self.values_len = len(self._pa['values']) if self._pa['colors'] and len(self._pa['colors']) != self.values_len: raise ValueError("Length of colors doesn't match the values.") if isinstance(self._pa['values'], dict): if not self._pa['labels']: self._pa['labels'] = self._pa['values'].keys() self._pa['values'] = list(self._pa['values'].values()) if self._pa['labels'] and len(self._pa['labels']) != self.values_len: raise ValueError("Length of labels doesn't match the values.") if self._pa['icons']: from pywaffle.fontawesome_mapping import icons if self._pa['icon_set'] not in icons.keys(): raise KeyError('icon_set should be one of {}'.format(', '.join( icons.keys()))) # If icons is a string, convert it into a list of same icon. It's length is the label's length # '\uf26e' -> ['\uf26e', '\uf26e', '\uf26e', ] if isinstance(self._pa['icons'], str): self._pa['icons'] = [self._pa['icons']] * self.values_len if len(self._pa['icons']) != self.values_len: raise ValueError("Length of icons doesn't match the values.") self._pa['icons'] = [ icons[self._pa['icon_set']][i] for i in self._pa['icons'] ] self.ax = self.add_subplot(loc, aspect='equal') # Alignment of subplots self.ax.set_anchor(self._pa['plot_anchor']) self.value_sum = float(sum(self._pa['values'])) # if column number is not given, use the values as number of blocks if self._pa['columns'] is None: self._pa['columns'] = ceil(self.value_sum, self._pa['rows']) block_number_per_cat = self._pa['values'] else: block_number_per_cat = [ round(v * self._pa['columns'] * self._pa['rows'] / self.value_sum) for v in self._pa['values'] ] # Absolute height of the plot figure_height = 1 block_y_length = figure_height / (self._pa['rows'] + self._pa['rows'] * self._pa['interval_ratio_y'] - self._pa['interval_ratio_y']) block_x_length = self._pa['block_aspect'] * block_y_length # Define the limit of X, Y axis self.ax.axis(xmin=0, xmax=(self._pa['columns'] + self._pa['columns'] * self._pa['interval_ratio_x'] - self._pa['interval_ratio_x']) * block_x_length, ymin=0, ymax=figure_height) # Default font size if self._pa['icons']: x, y = self.ax.transData.transform([(0, 0), (0, block_x_length)]) prop = fm.FontProperties( fname=FONTAWESOME_FILES[self._pa['icon_set']], size=self._pa['icon_size'] or int((y[1] - x[1]) / 16 * 12)) # Build a color sequence if colors is empty if not self._pa['colors']: default_colors = cm.get_cmap(self._pa['cmap_name']).colors default_color_num = cm.get_cmap(self._pa['cmap_name']).N self._pa['colors'] = array_resize(array=default_colors, length=self.values_len, array_len=default_color_num) # Plot blocks class_index = 0 block_index = 0 x_full = (1 + self._pa['interval_ratio_x']) * block_x_length y_full = (1 + self._pa['interval_ratio_y']) * block_y_length plot_direction = self._pa['plot_direction'].upper() try: column_order = self._direction_values[plot_direction][ 'column_order'] row_order = self._direction_values[plot_direction]['row_order'] except KeyError: raise KeyError( "plot_direction should be one of 'NW', 'SW', 'NE', 'SE'") for col, row in product( range(self._pa['columns'])[::column_order], range(self._pa['rows'])[::row_order]): x = x_full * col y = y_full * row if self._pa['icons']: self.ax.text(x=x, y=y, s=self._pa['icons'][class_index], color=self._pa['colors'][class_index], fontproperties=prop) else: self.ax.add_artist( Rectangle(xy=(x, y), width=block_x_length, height=block_y_length, color=self._pa['colors'][class_index])) block_index += 1 if block_index >= sum(block_number_per_cat[:class_index + 1]): class_index += 1 if class_index > self.values_len - 1: break # Add title if self._pa['title'] is not None: self.ax.set_title(**self._pa['title']) # Add legend if self._pa['labels'] or 'labels' in self._pa['legend']: if self._pa['icons'] and self._pa['icon_legend']: self._pa['legend']['handles'] = [ TextLegend(color=c, text=i) for c, i in zip(self._pa['colors'], self._pa['icons']) ] self._pa['legend']['handler_map'] = { TextLegend: TextLegendHandler(self._pa['icon_set']) } # elif not self._pa['legend'].get('handles'): elif 'handles' not in self._pa['legend']: self._pa['legend']['handles'] = [ Patch(color=c, label=str(l)) for c, l in zip(self._pa['colors'], self._pa['labels']) ] # labels is an alias of legend['labels'] if 'labels' not in self._pa['legend'] and self._pa['labels']: self._pa['legend']['labels'] = self._pa['labels'] if 'handles' in self._pa['legend'] and 'labels' in self._pa[ 'legend']: self.ax.legend(**self._pa['legend']) # Remove borders, ticks, etc. self.ax.axis('off')
def plot(self, binFile, markerGeneStats, binStats): binId = binIdFromFilename(binFile) markerGenesPerSeq, _markerGeneNum = self.getMarkerGenesPerSeq(markerGeneStats) if len(markerGenesPerSeq) == 0: return False # Get length of sequences with one or more marker genes seqs = readFasta(binFile) seqLens = {} longestSeq = 0 binSize = 0 for seqId, seq in seqs.items(): seqLen = len(seq) binSize += seqLen if seqId not in markerGenesPerSeq: continue seqLens[seqId] = seqLen if seqLen > longestSeq: longestSeq = seqLen sortedSeqLens = sorted(seqLens.items(), key=operator.itemgetter(1), reverse=True) result_str = 'Markers reside on {:,} of {:,} sequences which span {:.2f} of {:.2f} ({:.1f}%) Mb'.format( len(seqLens), len(seqs), sum([s for s in seqLens.values()])/1e6, binSize/1e6, sum([s for s in seqLens.values()])*100.0/binSize) self.logger.info(result_str) MAX_BINS = 100 plotBinSize = self.roundUpToNearest100(float(longestSeq) / MAX_BINS) yLabels = [x[0] for x in sortedSeqLens] # get position of genes in bin prodigalFastaParser = ProdigalFastaParser() geneFile = os.path.join(self.options.results_dir, 'bins', binId, DefaultValues.PRODIGAL_AA) genePos = prodigalFastaParser.genePositions(geneFile) # Set size of figure self.fig.clear() self.fig.set_size_inches(self.options.width, self.options.height) yLabelBounds = self.yLabelExtents(yLabels, self.options.font_size) heightBottomLabels = 0.4 + self.options.fig_padding # inches widthSideLabel = yLabelBounds.width * self.options.width + self.options.fig_padding # inches widthPerBin = (self.options.width - widthSideLabel - self.options.fig_padding) / MAX_BINS titleHeight = 0.2 HEIGHT_PER_ROW = 0.2 height = HEIGHT_PER_ROW * len(sortedSeqLens) + heightBottomLabels + self.options.fig_padding + titleHeight rowBinHeight = widthPerBin / HEIGHT_PER_ROW self.fig.set_size_inches(self.options.width, height) axes = self.fig.add_axes([widthSideLabel / self.options.width, heightBottomLabels / height, \ 1.0 - (widthSideLabel + self.options.fig_padding) / self.options.width, \ 1.0 - (heightBottomLabels + self.options.fig_padding + titleHeight) / height]) # set plot axis axes.set_xlim([0, MAX_BINS + 0.1]) axes.set_xlabel('Position ({:,} bp/bin)'.format(plotBinSize)) axes.set_ylim([0, len(sortedSeqLens)]) axes.set_yticks(np.arange(0.5, len(sortedSeqLens) + 0.5, 1.0)) axes.set_yticklabels(yLabels) # legend colours = [(1.0, 1.0, 1.0), (127 / 255.0, 201 / 255.0, 127 / 255.0), (255 / 255.0, 192 / 255.0, 134 / 255.0), (190 / 255.0, 174 / 255.0, 212 / 255.0), (0.0, 0.0, 0.0)] discreteColourMap = mpl.colors.ListedColormap(colours) axisColourMap = self.fig.add_axes([self.options.fig_padding / self.options.width, self.options.fig_padding / height, 0.15, 0.03 * (self.options.width / height)]) colourBar = mpl.colorbar.ColorbarBase(axisColourMap, cmap=discreteColourMap, norm=mpl.colors.Normalize(vmin=0, vmax=1), orientation='horizontal', drawedges=True) colourBar.set_ticks([0.1, 0.3, 0.5, 0.7, 0.9]) colourBar.set_ticklabels(['0', '1', '2', '3', '4+']) colourBar.outline.set_linewidth(0.5) colourBar.dividers.set_linewidth(0.5) for a in axisColourMap.xaxis.majorTicks: a.tick1On = False a.tick2On = False # plot each bin binPosX = 0.5 for seqId, seqLen in sortedSeqLens: markerCount = [0] * int(math.ceil(float(seqLen) / plotBinSize)) for geneId, _markerGeneId, geneStartPos, _geneEndPos in markerGenesPerSeq[seqId]: binPos = int(float(genePos[geneId][0] + geneStartPos) / plotBinSize) markerCount[binPos] += 1 for i in range(0, len(markerCount)): if markerCount[i] < len(colours): axes.add_patch(Rectangle((i + 0.1, binPosX - 0.4 * rowBinHeight), 0.8, 0.8 * rowBinHeight, facecolor=colours[markerCount[i]], lw=0.2)) else: axes.add_patch(Rectangle((i + 0.1, binPosX - 0.4 * rowBinHeight), 0.8, 0.8 * rowBinHeight, facecolor=colours[-1], lw=0.2)) binPosX += 1.0 # set plot title titleStr = binId titleStr += '\n' titleStr += '({:.1f}% complete, {:.1f}% contamination)'.format( binStats['Completeness'], binStats['Contamination']) titleStr += '\n' titleStr += '({})'.format(result_str) axes.set_title(titleStr) # Prettify plot for a in axes.yaxis.majorTicks: a.tick1On = False a.tick2On = False for a in axes.xaxis.majorTicks: a.tick1On = True a.tick2On = False for line in axes.yaxis.get_ticklines(): line.set_color(self.axesColour) for line in axes.xaxis.get_ticklines(): line.set_color(self.axesColour) line.set_ms(2) for loc, spine in axes.spines.items(): if loc in ['left', 'right', 'top']: spine.set_color('none') else: spine.set_color(self.axesColour) self.draw() return True
def test(testFilename, testGTFilename, charts=False): #testFilename = 'test2.bmp' #testGTFilename = 'test2_gt.pkl' knnClassifier = False otherClassifier = False all_features = [] all_labels = [] all_regions = [] all_files = {} all_imgs = {} all_imgs_features = {} img_counter = 0 feat_counter = 0 for file in os.listdir(os.getcwd()): if file.endswith('.bmp') and len( file) == 5 and file[0].isalpha() and file[0].islower(): print file letter_features, letter_regions, img_binary = train(file, charts) letter = file[0] all_files[img_counter] = letter all_labels = all_labels + [ letter for ii in range(0, len(letter_features)) ] all_features = all_features + letter_features all_regions = all_regions + letter_regions all_imgs[img_counter] = img_binary feat_numbers = [] for feat in letter_features: feat_numbers.append(feat_counter) feat_counter = feat_counter + 1 all_imgs_features[img_counter] = feat_numbers img_counter = img_counter + 1 # Get the test file features test_features, test_regions, test_img_binary = train(testFilename, False) stand_train_feats = [] stand_test_feats = [] B = np.asmatrix(all_features) B_test = np.asmatrix(test_features) # Finding the means mean_0 = np.mean(B[:, 0]) mean_1 = np.mean(B[:, 1]) mean_2 = np.mean(B[:, 2]) mean_3 = np.mean(B[:, 3]) mean_4 = np.mean(B[:, 4]) mean_5 = np.mean(B[:, 5]) mean_6 = np.mean(B[:, 6]) # Finding the standard deviations std_0 = np.std(B[:, 0]) std_1 = np.std(B[:, 1]) std_2 = np.std(B[:, 2]) std_3 = np.std(B[:, 3]) std_4 = np.std(B[:, 4]) std_5 = np.std(B[:, 5]) std_6 = np.std(B[:, 6]) for ii in range(0, len(all_features)): B[ii, 0] = (B[ii, 0] - mean_0) / std_0 B[ii, 1] = (B[ii, 1] - mean_1) / std_1 B[ii, 2] = (B[ii, 2] - mean_2) / std_2 B[ii, 3] = (B[ii, 3] - mean_3) / std_3 B[ii, 4] = (B[ii, 4] - mean_4) / std_4 B[ii, 5] = (B[ii, 5] - mean_5) / std_5 B[ii, 6] = (B[ii, 6] - mean_6) / std_6 for ii in range(0, len(test_features)): B_test[ii, 0] = (B_test[ii, 0] - mean_0) / std_0 B_test[ii, 1] = (B_test[ii, 1] - mean_1) / std_1 B_test[ii, 2] = (B_test[ii, 2] - mean_2) / std_2 B_test[ii, 3] = (B_test[ii, 3] - mean_3) / std_3 B_test[ii, 4] = (B_test[ii, 4] - mean_4) / std_4 B_test[ii, 5] = (B_test[ii, 5] - mean_5) / std_5 B_test[ii, 6] = (B_test[ii, 6] - mean_6) / std_6 # Normalized features stand_train_feats = B.tolist() stand_test_feats = B_test.tolist() stand_all_feats = stand_train_feats + stand_test_feats # RECOGNITION ON TRAINING DATA D = cdist(stand_test_feats, stand_train_feats) if charts: io.imshow(D) plt.title('Distance Matrix') plt.savefig('distmatrix_' + testFilename[0:len(testFilename) - 4] + '.png') io.show() D_index = np.argsort(D, axis=1) # Find matches result_labels = [] for ii in range(0, len(test_features)): result_labels = result_labels + [all_labels[D_index[ii, 0]]] if knnClassifier: neigh = KNeighborsClassifier( n_neighbors=4) #, metric='euclidean')#euclidean neigh.fit(stand_train_feats, all_labels[0:len(stand_train_feats)]) result_labels = [] for ii in range(0, len(test_features)): #was test_features result_labels = result_labels + [ neigh.predict(stand_test_feats[ii]) ] if otherClassifier: result_labels = [] clf = GaussianNB() clf = DecisionTreeClassifier() #clf = RandomForestClassifier() clf.fit(stand_train_feats, all_labels[0:len(stand_train_feats)]) result_labels = [] for ii in range(0, len(test_features)): #was test_features result_labels = result_labels + [clf.predict(stand_test_feats[ii])] # Load the test file ground truth pkl_file = open(testGTFilename, 'rb') mydict = pickle.load(pkl_file) classes = mydict['classes'] locations = mydict['locations'] # Displaying result if charts: io.imshow(test_img_binary) ax = plt.gca() counter = 0 for ii in range(0, len(locations)): locs = locations[ii] posx = locs[0] posy = locs[1] for jj in range(0, len(test_regions)): props = test_regions[jj] minr, minc, maxr, maxc = props.bbox if posx <= maxc and posx >= minc and posy <= maxr and posy >= minr and classes[ ii] == result_labels[jj]: counter = counter + 1 if charts: ax.add_patch( Rectangle((minc, minr), maxc - minc, maxr - minr, fill=False, edgecolor='green', linewidth=1)) break elif posx <= maxc and posx >= minc and posy <= maxr and posy >= minr: if charts: ax.add_patch( Rectangle((minc, minr), maxc - minc, maxr - minr, fill=False, edgecolor='red', linewidth=1)) break # print counter if charts: plt.title('Recognition results for test file ' + testFilename + ' - ' + str(counter * 100 / len(locations)) + '%') plt.savefig('hysteresisThresholdMethod_' + testFilename[0:len(testFilename) - 4] + '.png') io.show()
def vis_eval_im(model, num_actions, index, root, gt_bbox_all=None): root = os.path.join(root, str(num_actions), str(index).zfill(5)) pickles_root = os.path.join(root, 'pickles') frames_root = os.path.join(root, 'frames') frame_paths = depickle_data(pickles_root, 'frame_paths') entities = depickle_data(pickles_root, 'entities') actions = depickle_data(pickles_root, 'actions_list') actions.append('[NULL]') candidates = depickle_data(pickles_root, 'candidates') vid_id = depickle_data(pickles_root, 'vid_id') steps = depickle_data(pickles_root, 'steps') entity_count = depickle_data(pickles_root, 'entity_count') bboxes = torch.stack(list(zip(*candidates))[0]).squeeze(1).reshape( -1, BOUNDING_BOX_DIM) features = torch.stack(list(zip(*candidates))[1]).squeeze(1).reshape( -1, DETECTION_EMBEDDING_DIM) steps = remove_unused2([steps])[0] # UNUSED2 = entities steps = remove_unused3([steps])[0] # UNUSED3 = actions if gt_bbox_all is None: gt_bbox_all = read_json(FI_VG) gt_vid_bbox = gt_bbox_all[vid_id] VG, RR = model_inference(model, num_actions, steps, entities, entity_count, bboxes, features) #print(VG) # calculate mean grounding IoU #1) if gt doesn't have bbox, we skip (doesn't count towards IoU) - since model must ground all entities #2) we look for gt bbox in nearest frame to model grounded one # this may lead to addition leniency in IoU score mean_iou = 0.0 num_ents = 0 for action_idx, action_entities in enumerate(entities[:-1]): print('--------------------------------------------------') print('Action {}: {}'.format(action_idx + 1, actions[action_idx])) if len(action_entities) == 0: print('No entities detected for this action.') frame_path = None prev_frame_path = None fig = None axes = None for ent_idx, entity in enumerate(action_entities): # VG processing. offset = NUM_FRAMES_PER_STEP * action_idx candidate = int(VG[action_idx][ent_idx]) vg_idx = offset + math.floor(candidate / NUM_CANDIDATES_PER_FRAME) prev_frame_path = frame_path frame_path = frame_paths[vg_idx] #correct the frame_path ################################################# path_split = frame_path.split('/') user = path_split[2] if user != 'sagar': path_split[2] = 'sagar' frame_path = '/'.join(path_split) ################################################### frame_candidate_bboxes = bboxes[NUM_CANDIDATES_PER_STEP * action_idx:( NUM_CANDIDATES_PER_STEP * (action_idx + 1))] bbox = frame_candidate_bboxes[candidate] ################################################ ## processing for ground truth entity bbox #index into gt as (action_idx, entity_idx, instance of entity) #str_action_id = '('+str(action_idx)+', '+str(ent_idx) + ', ' + str(0) + ')' vg_keys = get_vg_key(action_idx, ent_idx, gt_vid_bbox) print(vg_keys) #gt_vid_box[str_action_id]['bboxes'] gt_bbox = nearest_in_time(vg_keys_gt_ent=vg_keys, model_frame=frame_path, gt_vid_bbox=gt_vid_bbox) if gt_bbox is None: print('This entity has no ground truth bounding box') continue #gt_bbox_list, gt_frame gt_bbox_list = [ gt_bbox['bbox']['x'], gt_bbox['bbox']['y'], gt_bbox['bbox']['w'], gt_bbox['bbox']['h'] ] gt_frame = gt_bbox['img'] #print(gt_frame) gt_box = Rectangle((gt_bbox_list[0], gt_bbox_list[1]), gt_bbox_list[2], gt_bbox_list[3], linewidth=1, edgecolor='red', facecolor='none') gt_bbox_width = gt_bbox_list[2] gt_bbox_height = gt_bbox_list[3] gt_x0 = gt_bbox_list[0] gt_y0 = gt_bbox_list[1] #print('GT frame is {}, model frame is {}'.format(gt_frame, frame_path)) print(frame_path) frame = cv2.imread(frame_path) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame_height = frame.shape[0] frame_width = frame.shape[1] if prev_frame_path != frame_path: fig = plt.figure() plt.imshow(frame) axes = plt.gca() x0, y0 = bbox[0] * frame_width, bbox[1] * frame_height x1, y1 = bbox[2] * frame_width, bbox[3] * frame_height bbox_width = x1 - x0 bbox_height = y1 - y0 vg_box = [x0, y0, bbox_width, bbox_height] box = Rectangle((x0, y0), bbox_width, bbox_height, linewidth=1, edgecolor='lime', facecolor='none') iou = compute_iou(vg_box, gt_bbox_list) print('IoU is: {}'.format(iou)) mean_iou += iou num_ents += 1 axes.add_patch(box) axes.add_patch(gt_box) axes.annotate(entity, (gt_x0 + (gt_bbox_width / 2), gt_y0 + (gt_bbox_height / 2)), color='white', fontsize=18, ha='center', va='center') # RR processing. rr_idx = int(RR[action_idx][ent_idx]) print( '\u001b[38;5;82m {} \u001b[38;5;208m -> Action {} ({}) \u001b[0m' .format(entity, rr_idx + 1, actions[rr_idx])) plt.show() mean_iou = mean_iou / num_ents return VG, RR, mean_iou
def showAnn(self, image_name, if_result=False, if_visualize=False, if_save=False, plot_path='tmp', is_training=False): """Show the annotation of a pose file in an image Input: image_name: the name of image Output: depth: a rendered depth map of each car masks: an instance mask of the label image_vis: an image show the overlap of car model and image """ image_file = '%s/%s.jpg' % (self._data_config['image_dir'], image_name) image = cv2.imread(image_file, cv2.IMREAD_UNCHANGED)[:, :, ::-1] # print 'Original and rescaled image size: ', image.shape, self.image_size intrinsic = self.dataset.get_intrinsic(image_name, 'Camera_5') image_rescaled, self.intrinsic = self.rescale(image, intrinsic) if is_training: car_pose_file = '%s/%s.json' % ( self._data_config['pose_dir'] if not (if_result) else self._data_config['pose_dir_result'], image_name) with open(car_pose_file) as f: car_poses = json.load(f) self.depth = self.MAX_DEPTH * np.ones(self.image_size) self.mask = np.zeros(self.depth.shape) self.shape_id_map = np.zeros(self.depth.shape) self.pose_map = np.zeros( (self.depth.shape[0], self.depth.shape[1], 6)) + np.inf self.shape_map = np.zeros( (self.depth.shape[0], self.depth.shape[1], 10)) + np.inf self.pose_list = [] self.rot_uvd_list = [] self.bbox_list = [] self.shape_id_list = [] plt.figure(figsize=(20, 10)) plt.imshow(image_rescaled) for i, car_pose in enumerate(car_poses): car_name = car_models.car_id2name[car_pose['car_id']].name # if if_result: # car_pose['pose'][-1] = 1./car_pose['pose'][-1] depth, mask, vert, K = self.render_car(car_pose['pose'], car_name) self.mask, self.shape_id_map, self.depth, self.pose_map = self.merge_inst( depth, i + 1, car_pose['car_id'] + 1, self.mask, self.shape_id_map, self.depth, self.pose_map, car_pose['pose']) self.pose_list.append(car_pose['pose']) self.shape_id_list.append(car_pose['car_id']) scale = np.ones((3, )) car = self.car_models[car_name] pose = np.array(car_pose['pose']) print 'GT pose: ', pose[3:] vert = car['vertices'] vert = np.zeros((1, 3)) vert_transformed = uts.project(pose, scale, vert) # [*, 3] print 'Center transformed: ', vert_transformed vert_hom = np.hstack( (vert_transformed, np.ones((vert.shape[0], 1)))) K_hom = np.hstack((K, np.zeros((3, 1)))) proj_uv_hom = np.matmul(K_hom, vert_hom.T) proj_uv = np.vstack((proj_uv_hom[0, :] / proj_uv_hom[2, :], proj_uv_hom[1, :] / proj_uv_hom[2, :])) u = proj_uv[0:1, :] # [1, 1] v = proj_uv[1:2, :] d = proj_uv_hom[2:3, :] rot_uvd = [ car_pose['pose'][0], car_pose['pose'][1], car_pose['pose'][2], u[0, 0], v[0, 0], car_pose['pose'][5] ] self.rot_uvd_list.append(rot_uvd) plt.scatter(u, v, linewidths=20) F1 = K_hom[0, 0] W = K_hom[0, 2] F2 = K_hom[1, 1] H = K_hom[1, 2] K_T = np.array([[1. / F1, 0., -W / F1], [0, 1. / F2, -H / F2], [0., 0., 1.]]) # print K_T # print self.intrinsic # print F1, W, F2, H uvd = np.vstack((u * d, v * d, d)) xyz = np.matmul(K_T, uvd) print 'xyz / pose recovered: ', xyz # print 'uvd:', rot_uvd # print car_pose['pose'].shape, vert_transformed.shape ## Get bbox from mask arr = np.expand_dims(np.int32(mask), -1) # number of highest label: labmax = 1 # maximum and minimum positions along each axis (initialized to very low and high values) b_first = np.iinfo('int32').max * np.ones( (3, labmax + 1), dtype='int32') b_last = np.iinfo('int32').max * np.ones( (3, labmax + 1), dtype='int32') # run through all dimensions making 2D slices and marking all existing labels to b for dim in range(2): # create a generic slice object to make the slices sl = [slice(None), slice(None), slice(None)] bf = b_first[dim] bl = b_last[dim] # go through all slices in this dimension for k in range(arr.shape[dim]): # create the slice object sl[dim] = k # update the last "seen" vector bl[arr[sl].flatten()] = k # if we have smaller values in "last" than in "first", update bf[:] = np.clip(bf, None, bl) bbox = [ b_first[1, 1], b_last[1, 1], b_first[0, 1], b_last[0, 1] ] # [x_min, x_max, y_min, y_max] self.bbox_list.append(bbox) plt.imshow(mask) print mask.shape currentAxis = plt.gca() # print (bbox[0], bbox[2]), bbox[1]-bbox[0], bbox[3]-bbox[2] currentAxis.add_patch( Rectangle((bbox[0], bbox[2]), bbox[1] - bbox[0], bbox[3] - bbox[2], alpha=1, edgecolor='r', facecolor='none')) # plt.show() # break plt.show() self.depth[self.depth == self.MAX_DEPTH] = -1.0 image = 0.5 * image_rescaled for i in range(len(car_poses)): frame = np.float32(self.mask == i + 1) frame = np.tile(frame[:, :, None], (1, 1, 3)) image = image + frame * 0.5 * self.colors[i, :] if if_visualize: uts.plot_images( { 'image_vis': np.uint8(image), 'shape_id': self.shape_id_map, 'mask': self.mask, 'depth': self.depth }, np.asarray(self.rot_uvd_list), self.bbox_list, layout=[1, 4], fig_size=10, save_fig=if_save, fig_name=plot_path) return image, self.mask, self.shape_id_map, self.depth, self.pose_map, image_rescaled, self.pose_list, self.shape_id_list, self.rot_uvd_list, self.bbox_list else: return None, None, None, None, None, image_rescaled, None, None, None, None
def visualize(self, file_name=None, fig_size: (float, float) = (6.5, 6.5), size_auv_path: float = 0.8, size_max_radius: float = 0.3, size_min_radius: float = 0.1, tick_size: float = 14, grid_width: float = 0.25, size_arrow_h_width: float = 0.4, size_arrow_h_length: float = 0.3, size_arrow_width: float = 0.4, color_obstacle: str = 'firebrick', color_target: str = 'deepskyblue', color_auv: str = 'darkorange', color_auv_path: str = 'peachpuff', visited_reward_opacity: float = 0.15) -> Figure: if (fig_size[0] <= 0 or fig_size[1] <= 0 or size_auv_path <= 0 or size_max_radius <= 0 or size_arrow_h_width <= 0 or size_arrow_h_length <= 0 or size_arrow_width <= 0 or tick_size <= 0 or grid_width <= 0): raise ValueError("Size must be positive") max_reward = self._environment.max_reward title_font = {'fontname': 'Sans Serif', 'size': '16', 'color': 'black', 'weight': 'bold'} z = {'auv_path': 1, 'target': 2, 'obstacle': 3, 'auv': 5} # Initialize the figure fig = plt.figure(figsize=fig_size) ax = fig.add_subplot(111) # Plot obstacles for i, j in self._environment.obstacles: ax.add_patch(Rectangle(xy=(i, j), width=1, height=1, color=color_obstacle, zorder=z['obstacle'])) # Plot rewards for position, reward in self._environment.rewards.items(): target_radius = ((reward / max_reward) * (size_max_radius - size_min_radius) + size_min_radius) centroid = (position[0] + 0.5, position[1] + 0.5) ax.add_patch(Circle(xy=centroid, radius=target_radius, color=color_target, zorder=z['target'], alpha=(visited_reward_opacity if position in self.visited else 1.0))) # Plot agents for path in self._paths: x, y = path[-1] dx, dy = 0, 1 if len(path) >= 2: x_p, y_p = path[-2] if x == x_p + 1 and y == y_p: dx, dy = 1, 0 elif x == x_p - 1 and y == y_p: dx, dy = -1, 0 elif x == x_p and y == y_p - 1: dx, dy = 0, -1 x += 0.5 * float(1 - dx) y += 0.5 * float(1 - dy) ax.add_patch(FancyArrow(x=x, y=y, dx=dx, dy=dy, fc=color_auv, width=size_arrow_width, head_width=size_arrow_h_width, head_length=size_arrow_h_length, zorder=z['auv'], length_includes_head=True)) # plot trajectories for i in range(1, len(path)): x, y = path[i] x_p, y_p = path[i - 1] ax.add_line(Line2D(xdata=(x + 0.5, x_p + 0.5), ydata=(y + 0.5, y_p + 0.5), linewidth=size_auv_path * 10, color=color_auv_path, zorder=z['auv_path'])) # Plotting plt.title('Agents Trajectory \n Accumulated Reward: ' + str(round(self.reward, 2)) + "\nRemaining time: {0}". format(self.time_remains), title_font) plt.xlabel('x', title_font) plt.ylabel('y', title_font) x_ticks = np.arange(self._environment.x_min, self._environment.x_max + 1 , 1) y_ticks = np.arange(self._environment.y_min, self._environment.y_max + 1 , 1) plt.xticks(x_ticks + 0.5, x_ticks.astype(int)) plt.yticks(y_ticks + 0.5, y_ticks.astype(int)) ax.tick_params(labelsize=tick_size) ax.grid(False) ax.axis('equal') ax.set_xlim(self._environment.x_min - 0.5, self._environment.x_max + 1.5) ax.set_ylim(self._environment.y_min - 0.5, self._environment.y_max + 1.5) # Save and display plt.show() if file_name is not None: plt.savefig(file_name) return fig
def alt_scenario1(ax): borders(ax) patches = [Rectangle((3.25, -0.5), 0.5, 2.0)] collection = PatchCollection(patches) ax.add_collection(collection)
# To create a CombigridOperation object with our own configuration, we have to provide a # LevelManager as well: levelManager = pysgpp.WeightedRatioLevelManager() operation = pysgpp.CombigridOperation(grids, evaluators, levelManager, func) # We can add regular levels like before: levelManager.addRegularLevels(args.level) # We can also fetch the used grid points and plot the grid: grid = levelManager.getGridPointMatrix() gridList = [[grid.get(r, c) for c in range(grid.getNcols())] for r in range(grid.getNrows())] fig = plt.figure() plt.plot(gridList[0], gridList[1], " ", color=load_color(0), marker='o', markersize=10) plt.axis('off') currentAxis = plt.gca() currentAxis.add_patch( Rectangle((0, 0), 1, 1, fill=None, alpha=1, linewidth=2)) plt.xlim(0, 1) plt.ylim(0, 1) plt.title(r"Sparse Grid $\ell=%i$" % args.level, fontproperties=load_font_properties()) savefig(fig, "/tmp/sparse_grid_l%i_%s" % (args.level, args.marginalType))
def _plot_new_seismogram_sub(trwin, outputdir, cmtsource, figure_format): obsd = trwin.datalist['obsd'] synt = trwin.datalist['synt'] new_synt = trwin.datalist['new_synt'] station = obsd.stats.station network = obsd.stats.network channel = obsd.stats.channel location = obsd.stats.location outputfig = os.path.join( outputdir, "%s.%s.%s.%s.%s" % (network, station, location, channel, figure_format)) if cmtsource is None: offset = 0 else: offset = obsd.stats.starttime - cmtsource.cmt_time times = [offset + obsd.stats.delta * i for i in range(obsd.stats.npts)] fig = plt.figure(figsize=(15, 5)) plt.rcParams.update({'font.size': 13, 'lines.linewidth': 1.5}) # plot seismogram ax1 = plt.subplot(211) ax1.plot(times, obsd.data, color="black", linewidth=0.8, alpha=0.6, label="obsd") ax1.plot(times, synt.data, color="blue", linewidth=1, label="synt") ax1.plot(times, new_synt.data, color="red", linewidth=1, label="new synt") ax1.set_xlim(times[0], times[-1]) ax1.legend(loc='upper right', frameon=False, ncol=3, prop={'size': 11}) # Setting top left corner text manually fontsize = 11 ax1.text(0.005, 0.8, "Network: %2s Station: %s\n" "Location: %2s Channel: %3s" % (network, station, location, channel), fontsize=fontsize, transform=ax1.transAxes) for win in trwin.windows: left = win[0] + offset right = win[1] + offset re = Rectangle((left, plt.ylim()[0]), right - left, plt.ylim()[1] - plt.ylim()[0], color="blue", alpha=0.25) plt.gca().add_patch(re) # plot envelope ax2 = plt.subplot(212) ax2.plot(times, _envelope(obsd.data), color="black", linewidth=0.8, alpha=0.6, label="obsd") ax2.plot(times, _envelope(synt.data), color="blue", linewidth=1, label="synt") ax2.plot(times, _envelope(new_synt.data), color="red", linewidth=1, label="new synt") ax2.set_xlim(times[0], times[-1]) ax2.set_xlabel("Time [s]", fontsize=13) for win in trwin.windows: left = win[0] + offset right = win[1] + offset re = Rectangle((left, plt.ylim()[0]), right - left, plt.ylim()[1] - plt.ylim()[0], color="blue", alpha=0.25) plt.gca().add_patch(re) logger.info("output figname: %s" % outputfig) ax2.legend(loc='upper right', frameon=False, ncol=3, prop={'size': 11}) plt.savefig(outputfig) plt.close(fig)
def draw_court(ax=None, color='white', lw=2, outer_lines=False): from matplotlib.patches import Circle, Rectangle, Arc if ax is None: ax = plt.gca() hoop = Circle((0, 0), radius=7.5, linewidth=lw, color=color, fill=False) backboard = Rectangle((-30, -7.5), 60, -1, linewidth=lw, color=color) outer_box = Rectangle((-80, -47.5), 160, 190, linewidth=lw, color=color, fill=False) inner_box = Rectangle((-60, -47.5), 120, 190, linewidth=lw, color=color, fill=False) top_free_throw = Arc((0, 142.5), 120, 120, theta1=0, theta2=180, linewidth=lw, color=color, fill=False) bottom_free_throw = Arc((0, 142.5), 120, 120, theta1=180, theta2=0, linewidth=lw, color=color, linestyle='dashed') restricted = Arc((0, 0), 80, 80, theta1=0, theta2=180, linewidth=lw, color=color) corner_three_a = Rectangle((-220, -50.0), 0, 140, linewidth=lw, color=color) corner_three_b = Rectangle((219.75, -50.0), 0, 140, linewidth=lw, color=color) three_arc = Arc((0, 0), 475, 475, theta1=22, theta2=158, linewidth=lw, color=color) center_outer_arc = Arc((0, 422.5), 120, 120, theta1=180, theta2=0, linewidth=lw, color=color) center_inner_arc = Arc((0, 422.5), 40, 40, theta1=180, theta2=0, linewidth=lw, color=color) court_elements = [ hoop, backboard, outer_box, inner_box, top_free_throw, bottom_free_throw, restricted, corner_three_a, corner_three_b, three_arc, center_outer_arc, center_inner_arc ] if outer_lines: outer_lines = Rectangle((-250, -47.5), 500, 470, linewidth=lw, color=color, fill=False) court_elements.append(outer_lines) for element in court_elements: ax.add_patch(element) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_xticks([]) ax.set_yticks([]) return ax
def sim(param, env, controllers, initial_state, visualize): # environment times = param.sim_times device = "cpu" if initial_state is None: initial_state = env.reset() # run sim SimResult = namedtuple( 'SimResult', ['states', 'observations', 'actions', 'steps', 'name']) for name, controller in controllers.items(): print("Running simulation with " + name) print("Initial State: ", initial_state) if hasattr(controller, 'policy'): result = SimResult._make( run_sim(param, env, controller, initial_state) + (name, )) else: observations = [] result = SimResult._make( (controller.states, observations, controller.actions, controller.steps, name)) sim_results = [] sim_results.append(result) # plot state space if param.env_name in [ 'SingleIntegrator', 'SingleIntegratorVelSensing', 'DoubleIntegrator' ]: fig, ax = plotter.make_fig() ax.set_title('State Space') ax.set_aspect('equal') for o in env.obstacles: ax.add_patch( Rectangle(o, 1.0, 1.0, facecolor='gray', alpha=0.5)) for agent in env.agents: line = ax.plot( result.states[0:result.steps, env.agent_idx_to_state_idx(agent.i)], result.states[0:result.steps, env.agent_idx_to_state_idx(agent.i) + 1], alpha=0.5) color = line[0].get_color() # plot velocity vectors: X = [] Y = [] U = [] V = [] for k in np.arange(0, result.steps, 100): X.append( result.states[k, env.agent_idx_to_state_idx(agent.i)]) Y.append( result.states[k, env.agent_idx_to_state_idx(agent.i) + 1]) if param.env_name in [ 'SingleIntegrator', 'SingleIntegratorVelSensing' ]: # Singleintegrator: plot actions U.append(result.actions[k, 2 * agent.i + 0]) V.append(result.actions[k, 2 * agent.i + 1]) elif param.env_name in ['DoubleIntegrator']: # doubleintegrator: plot velocities U.append( result.states[k, env.agent_idx_to_state_idx(agent.i) + 2]) V.append( result.states[k, env.agent_idx_to_state_idx(agent.i) + 3]) ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=0.5, color=color, width=0.005) plotter.plot_circle( result.states[1, env.agent_idx_to_state_idx(agent.i)], result.states[1, env.agent_idx_to_state_idx(agent.i) + 1], param.r_agent, fig=fig, ax=ax, color=color) plotter.plot_square(agent.s_g[0], agent.s_g[1], param.r_agent, angle=45, fig=fig, ax=ax, color=color) # draw state for each time step robot = 0 if param.env_name in ['SingleIntegrator']: for step in np.arange(0, result.steps, 1000): fig, ax = plotter.make_fig() ax.set_title('State at t={} for robot={}'.format( times[step], robot)) ax.set_aspect('equal') # plot all obstacles for o in env.obstacles: ax.add_patch( Rectangle(o, 1.0, 1.0, facecolor='gray', alpha=0.5)) # plot overall trajectory line = ax.plot( result.states[0:result.steps, env.agent_idx_to_state_idx(robot)], result.states[0:result.steps, env.agent_idx_to_state_idx(robot) + 1], "--") color = line[0].get_color() # plot current position plotter.plot_circle( result.states[step, env.agent_idx_to_state_idx(robot)], result.states[step, env.agent_idx_to_state_idx(robot) + 1], param.r_agent, fig=fig, ax=ax, color=color) # plot current observation observation = result.observations[step][robot][0] num_neighbors = int(observation[0]) num_obstacles = int( (observation.shape[0] - 3 - 2 * num_neighbors) / 2) robot_pos = result.states[ step, env.agent_idx_to_state_idx(robot):env. agent_idx_to_state_idx(robot) + 2] idx = 3 for i in range(num_neighbors): pos = observation[idx:idx + 2] + robot_pos ax.add_patch( Circle(pos, 0.25, facecolor='gray', edgecolor='red', alpha=0.5)) idx += 2 for i in range(num_obstacles): # pos = observation[idx : idx+2] + robot_pos - np.array([0.5,0.5]) # ax.add_patch(Rectangle(pos, 1.0, 1.0, facecolor='gray', edgecolor='red', alpha=0.5)) pos = observation[idx:idx + 2] + robot_pos ax.add_patch( Circle(pos, 0.5, facecolor='gray', edgecolor='red', alpha=0.5)) idx += 2 # plot goal goal = observation[1:3] + robot_pos ax.add_patch( Rectangle(goal - np.array([0.2, 0.2]), 0.4, 0.4, alpha=0.5, color=color)) # # import matplotlib.pyplot as plt # # plt.savefig("test.svg") # # exit() elif param.env_name in ['DoubleIntegrator']: for step in np.arange(0, result.steps, 1000): fig, ax = plotter.make_fig() ax.set_title('State at t={} for robot={}'.format( times[step], robot)) ax.set_aspect('equal') # plot all obstacles for o in env.obstacles: ax.add_patch( Rectangle(o, 1.0, 1.0, facecolor='gray', alpha=0.5)) # plot overall trajectory line = ax.plot( result.states[0:result.steps, env.agent_idx_to_state_idx(robot)], result.states[0:result.steps, env.agent_idx_to_state_idx(robot) + 1], "--") color = line[0].get_color() # plot current position plotter.plot_circle( result.states[step, env.agent_idx_to_state_idx(robot)], result.states[step, env.agent_idx_to_state_idx(robot) + 1], param.r_agent, fig=fig, ax=ax, color=color) # plot current observation observation = result.observations[step][robot][0] num_neighbors = int(observation[0]) num_obstacles = int( (observation.shape[0] - 5 - 4 * num_neighbors) / 2) robot_pos = result.states[ step, env.agent_idx_to_state_idx(robot):env. agent_idx_to_state_idx(robot) + 2] X = [] Y = [] U = [] V = [] idx = 5 for i in range(num_neighbors): pos = observation[idx:idx + 2] + robot_pos X.append(pos[0]) Y.append(pos[1]) U.append(observation[idx + 2]) V.append(observation[idx + 3]) # print(np.linalg.norm(observation[idx+2:idx+4])) ax.add_patch( Circle(pos, param.r_agent, facecolor='gray', edgecolor='red', alpha=0.5)) idx += 4 for i in range(num_obstacles): pos = observation[idx:idx + 2] + robot_pos - np.array( [0.5, 0.5]) ax.add_patch( Rectangle(pos, 1.0, 1.0, facecolor='gray', edgecolor='red', alpha=0.5)) # pos = observation[idx : idx+2] + robot_pos # ax.add_patch(Circle(pos, 0.5, facecolor='gray', edgecolor='red', alpha=0.5)) idx += 2 # plot goal goal = observation[1:3] + robot_pos ax.add_patch( Rectangle(goal - np.array([0.2, 0.2]), 0.4, 0.4, alpha=0.5, color=color)) X.append(robot_pos[0]) Y.append(robot_pos[1]) U.append(observation[3]) V.append(observation[4]) # plot velocity vectors ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=0.5, color='red', width=0.005) # plot time varying states if param.env_name in ['SingleIntegrator', 'DoubleIntegrator']: for i_config in range(env.state_dim_per_agent): fig, ax = plotter.make_fig() ax.set_title(env.states_name[i_config]) for agent in env.agents: for result in sim_results: ax.plot( times[1:result.steps], result.states[1:result.steps, env.agent_idx_to_state_idx(agent.i) + i_config], label=result.name) # plot time varying actions if param.env_name in ['SingleIntegrator', 'DoubleIntegrator']: for i_config in range(env.action_dim_per_agent): fig, ax = plotter.make_fig() ax.set_title(env.actions_name[i_config]) for agent in env.agents: for result in sim_results: ax.plot( times[1:result.steps], result.actions[1:result.steps, agent.i * env.action_dim_per_agent + i_config], label=result.name) # if i_config == 5: ax.set_yscale('log') plotter.save_figs(param.plots_fn) plotter.open_figs(param.plots_fn) # visualize if visualize: # plotter.visualize(param, env, states_deeprl) env.visualize(sim_results[0].states[0:result.steps], 0.1)
def get_boxes4deforming_area(vel_file, mask_file, step=2, num_pixel=30**2, min_percentage=0.2, cutoff=3, ramp_type='quadratic', display=False): """Get list of boxes to cover the deforming areas. A pixel is identified as deforming if its velocity exceeds the MAD of the whole image. Parameters: vel_file : str, path of velocity file mask_file : str, path of mask file win_size : int, length and width of the output box min_percentage : float between 0 and 1, minimum percentage of deforming points in the box ramp_type : str, type of phase ramps to be removed while evaluating the deformation display : bool, plot the identification result or not Returns: box_list : list of t-tuple of int, each indicating (col0, row0, col1, row1) """ win_size = int(np.sqrt(num_pixel) * step) print('-' * 30) print('get boxes on deforming areas with step: {} pixels'.format(step)) mask = readfile.read(mask_file)[0] vel, atr = readfile.read(vel_file) print('removing a {} phase ramp from input velocity before the evaluation'. format(ramp_type)) vel = deramp(vel, mask, ramp_type=ramp_type, metadata=atr)[0] #remove ramp before the evaluation # get deforming pixels mad = ut.median_abs_deviation_threshold( vel[mask], cutoff=cutoff) #deformation threshold print('velocity threshold / median abs dev: {:.3f} cm/yr'.format(mad)) vel[mask == 0] = 0 mask_aoi = (vel >= mad) + (vel <= -1. * mad) print('number of points: {}'.format(np.sum(mask_aoi))) # get deforming boxes box_list = [] min_num = min_percentage * (win_size**2) length, width = vel.shape num_row = np.ceil(length / win_size).astype(int) num_col = np.ceil(width / win_size).astype(int) for i in range(num_row): r0 = i * win_size r1 = min([length, r0 + win_size]) for j in range(num_col): c0 = j * win_size c1 = min([width, c0 + win_size]) box = (c0, r0, c1, r1) if np.sum(mask_aoi[r0:r1, c0:c1]) >= min_num: box_list.append(box) print('number of boxes : {}'.format(len(box_list))) if display: fig, axs = plt.subplots(nrows=1, ncols=2, figsize=[8, 4], sharey=True) vel[mask == 0] = np.nan axs[0].imshow(vel, cmap='jet') axs[1].imshow(mask_aoi, cmap='gray_r') for box in box_list: for ax in axs: rect = Rectangle((box[0], box[1]), width=(box[2] - box[0]), height=(box[3] - box[1]), linewidth=2, edgecolor='r', fill=False) ax.add_patch(rect) fig.tight_layout() out_fig = os.path.join(os.path.dirname(vel_file), 'defo_area.png') fig.savefig(out_fig, bbox_inches='tight', transparent=True, dpi=300) print('save figure to {}'.format(out_fig)) plt.show() return box_list
def plot_7box(figure, title, case_title, case_description, proj_number, section_name, fig_name, company_name="Deltares", software_version="Wanda 4.6", company_image=None, date=None, fontsize=8): """ Creates box around and in the plot window. Also fills in some info about the calculation. Based on the 7-box WL-layout. """ # Define locations of vertical and horizontal lines xo = 0.04 yo = 0.03 textbox_height = 0.75 v0 = 0.0 + xo v1 = 0.62 + xo v2 = 0.81 v3 = 1.0 - xo h0 = 0.0 + yo h1 = 1.2 * textbox_height / 29.7 + yo h2 = 2.4 * textbox_height / 29.7 + yo h3 = 3.6 * textbox_height / 29.7 + yo ax = plt.axes([0, 0, 1, 1], facecolor=(1, 1, 1, 0)) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) l1 = ax.axhline(y=h3, xmin=v0, xmax=v3, linewidth=1.5, color='k') # noqa: F841 l2 = ax.axvline(x=v1, ymin=h0, ymax=h3, linewidth=1.5, color='k') # noqa: F841 l3 = ax.axhline(y=h1, xmin=v0, xmax=v3, linewidth=1.5, color='k') # noqa: F841 l4 = ax.axvline(x=v2, ymin=h0, ymax=h1, linewidth=1.5, color='k') # noqa: F841 l5 = ax.axvline(x=v2, ymin=h2, ymax=h3, linewidth=1.5, color='k') # noqa: F841 l6 = ax.axhline(y=h2, xmin=v1, xmax=v3, linewidth=1.5, color='k') # noqa: F841 # bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) # width, height = bbox.width * fig.dpi, bbox.height * fig.dpi # linewidth = 2 rect = Rectangle((xo, yo), 1 - (2 * xo), 1 - (2 * yo), fill=False, linewidth=1.5) ax.add_patch(rect) # Case title and description text1 = "\n".join((title, case_title, case_description)) figure.text(v0 + 0.01, (h3 - (h3 - h1) / 2.), text1, verticalalignment='center', horizontalalignment='left', color='black', fontsize=fontsize) # Section name/number figure.text((v1 + (v2 - v1) / 2.), h2 + (h3 - h2) / 2., section_name, verticalalignment='center', horizontalalignment='center', color='black', fontsize=fontsize) # Project number figure.text((v1 + (v2 - v1) / 2.), (h0 + (h1 - h0) / 2.), int(proj_number), verticalalignment='center', horizontalalignment='center', color='black', fontsize=fontsize) # Company name figure.text((v0 + (v1 - v0) / 2.), (h0 + (h1 - h0) / 2.), company_name, verticalalignment='center', horizontalalignment='center', color='black', fontsize=fontsize) # Create datestamp if date != date or date is None: today = datetime.date(datetime.now()) else: today = date figure.text((v2 + (v3 - v2) / 2.), h2 + (h3 - h2) / 2., today.strftime('%d-%m-%Y'), verticalalignment='center', horizontalalignment='center', color='black', fontsize=fontsize) # Figure name figure.text((v2 + (v3 - v2) / 2.), (h0 + (h1 - h0) / 2.), fig_name, verticalalignment='center', horizontalalignment='center', color='black', fontsize=fontsize) # Print WANDA version figure.text((v1 + (v3 - v1) / 2.), h1 + (h2 - h1) / 2., software_version, verticalalignment='center', horizontalalignment='center', color='black', fontsize=fontsize) img = company_image if company_image is None: import os module_dir, module_filename = os.path.split(__file__) image_path = os.path.join(module_dir, "image_data", "Deltares_logo.png") img = plt.imread(image_path) imgax = figure.add_axes([v1, h0, v3 - v1, h3 - h0], zorder=-10) imgax.imshow(img, alpha=0.3, interpolation='none') imgax.axis('off')
rinds, _ = np.unique(in_a_stamp, return_counts=True) reg = [regions[int(i)] for i in rinds] regions = reg ngal = np.array([in_region(mmse_cat["x"], mmse_cat["y"], c).sum() for c in regions]) sizes = np.array([c[1] - c[0] for c in regions]) # --- write and plot the regions --- colors = ["tomato"] #rfile = open(outfile, "w") #rfile.write("xlo xhi ylo yhi npix nsource\n") #line = "{:3.0f} {:3.0f} {:3.0f} {:3.0f} {:4.0f} {:2.0f}\n" for i,corners in enumerate(regions): xy = (corners[0], corners[2]) r = Rectangle(xy, corners[1] - corners[0], corners[3] - corners[2], alpha=0.2, color=colors[np.mod(i, len(colors))]) ax.add_patch(r) ax.text(xy[0], xy[1], "{:3.0f}:{:2.0f}".format(i, ngal[i])) vals = list(corners) + [sizes[i]**2, ngal[i]] # rfile.write(line.format(*vals)) #rfile.close() #pl.show() fig.savefig("figures/regions.pdf") sys.exit() CANDELS_Cat = Vizier.get_catalogs(catalog="J/ApJS/207/24")[0] # just keep galaxies and good objects idx_good_sources = (CANDELS_Cat['Q'] == 0.0)
def plot(self, outfile=None, show=True, fig=None, plot_x=True, plot_gaps=True, print_gaps=False, event_times=None, starttime=None, endtime=None, seed_ids=None): """ Plot the information on parsed waveform files. :type outfile: str :param outfile: Filename for image output (e.g. ``"folder/image.png"``). No interactive plot is shown if an output filename is specified. :type show: bool :param show: Whether to open up any interactive plot after plotting. :type fig: :class:`matplotlib.figure.Figure` :param fig: Figure instance to reuse. :type plot_x: bool :param plot_x: Whether to plot "X" markers at start of all parsed ``Trace``s. :type plot_gaps: bool :param plot_gaps: Whether to plot filled rectangles at data gaps (red) and overlaps (blue). :type print_gaps: bool :param print_gaps: Whether to print information on all encountered gaps and overlaps. :type event_times: list of :class:`~obspy.core.utcdatetime.UTCDateTime` :param event_times: Highlight given times (e.g. of events or phase onsets for visual inspection of data availability) by plotting vertical lines. :type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime` :param starttime: Whether to use a fixed start time for the plot and data percentage calculation. :type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime` :param endtime: Whether to use a fixed end time for the plot and data percentage calculation. :type seed_ids: list of str :param seed_ids: Whether to consider only a specific set of SEED IDs (e.g. ``seed_ids=["GR.FUR..BHZ", "GR.WET..BHZ"]``) or just all SEED IDs encountered in data (if left ``None``). Given SEED IDs may contain ``fnmatch``-style wildcards (e.g. ``"BW.UH?..[EH]H*"``). """ import matplotlib.pyplot as plt data_keys = list(self.data.keys()) if seed_ids is not None: ids = [] for id_ in seed_ids: # allow fnmatch type wildcards in given seed ids if any(special in id_ for special in '*?[]!'): ids.extend(fnmatch.filter(data_keys, id_)) else: ids.append(id_) # make sure we don't have duplicates in case multiple wildcard # patterns were given and some ids were matched by more than one # pattern ids = list(set(ids)) seed_ids = ids if fig: if fig.axes: ax = fig.axes[0] else: ax = fig.add_subplot(111) else: fig = plt.figure() ax = fig.add_subplot(111) self.analyze_parsed_data(print_gaps=print_gaps, starttime=starttime, endtime=endtime, seed_ids=seed_ids) if starttime is not None: starttime = starttime.matplotlib_date if endtime is not None: endtime = endtime.matplotlib_date # Plot vertical lines if option 'event_time' was specified if event_times: times = [date2num(t.datetime) for t in event_times] for time in times: ax.axvline(time, color='k') labels = [""] * len(self._info) for _i, (id_, info) in enumerate(sorted(self._info.items(), reverse=True)): offset = np.ones(len(info["data_starts"])) * _i if plot_x: ax.plot(info["data_starts"], offset, 'x', linewidth=2) if len(info["data_startends_compressed"]): ax.hlines(offset[:len(info["data_startends_compressed"])], info["data_startends_compressed"][:, 0], info["data_startends_compressed"][:, 1], 'b', linewidth=2, zorder=3) label = id_ if info["percentage"] is not None: label = label + "\n%.1f%%" % (info["percentage"]) labels[_i] = label if plot_gaps: for key, color in zip(("gaps", "overlaps"), ("r", "b")): data_ = info[key] if len(data_): rects = [ Rectangle((start_, _i - 0.4), end_ - start_, 0.8) for start_, end_ in data_ ] ax.add_collection(PatchCollection(rects, color=color)) # Pretty format the plot ax.set_ylim(0 - 0.5, len(labels) - 0.5) ax.set_yticks(np.arange(len(labels))) ax.set_yticklabels(labels, family="monospace", ha="right") fig.autofmt_xdate() # rotate date ax.xaxis_date() # set custom formatters to always show date in first tick formatter = ObsPyAutoDateFormatter(ax.xaxis.get_major_locator()) formatter.scaled[1 / 24.] = \ FuncFormatter(decimal_seconds_format_date_first_tick) formatter.scaled.pop(1 / (24. * 60.)) ax.xaxis.set_major_formatter(formatter) plt.subplots_adjust(left=0.2) # set x-axis limits according to given start/end time if starttime and endtime: ax.set_xlim(left=starttime, right=endtime) elif starttime: ax.set_xlim(left=starttime, auto=None) elif endtime: ax.set_xlim(right=endtime, auto=None) else: left, right = ax.xaxis.get_data_interval() x_axis_range = right - left ax.set_xlim(left - 0.05 * x_axis_range, right + 0.05 * x_axis_range) if outfile: fig.set_dpi(72) height = len(labels) * 0.5 height = max(4, height) fig.set_figheight(height) plt.tight_layout() if not starttime or not endtime: days = ax.get_xlim() days = days[1] - days[0] else: days = endtime - starttime width = max(6, days / 30.) width = min(width, height * 4) fig.set_figwidth(width) plt.subplots_adjust(top=1, bottom=0, left=0, right=1) plt.tight_layout() fig.savefig(outfile) plt.close(fig) else: if show: plt.show() if self.verbose: sys.stdout.write('\n') return fig
rms_int_sort = sorted(rms_int) rms_int_conf = [rms_int_sort[i] for i in [int(round(nMC*alpha-1)), int(round(nMC*(1-alpha)-1))]] ## plotting import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from matplotlib.lines import Line2D colors = ['cyan','blue','red','green','yellow','purple'] # importances plt.figure() ca = plt.gca() for f in range(ncol): ca.add_patch(Rectangle((f+0.3,fimp_conf_rms[f][0]),0.4,fimp_conf_rms[f][1]-fimp_conf_rms[f][0],fill=False)) plt.plot([f+0.3, f+0.7],[fimp_rms[f],fimp_rms[f]],color=colors[f]) plt.plot([0, ncol],[0, 0],'k--',alpha=0.5) plt.ylim(1.1*min([fimp_conf_rms[i][0] for i in range(ncol)]),1.1*max([fimp_conf_rms[i][1] for i in range(ncol)])) # only works if min is negative, max is positive plt.xlim(0,ncol) plt.xticks([.5+i for i in range(ncol)],X.columns) plt.ylabel("RMSE Change") plt.title("Feature Importance Predicting " + predict) plt.show() # special comparisons plt.figure() ca = plt.gca() ca.add_patch(Rectangle((.3,rms_conf[0]),0.4,rms_conf[1]-rms_conf[0],fill=False)) plt.plot([0.3,0.7],[np.median(rms),np.median(rms)])
_, ax = plt.subplots(figsize=(15, 7.35)) ax.imshow(np.array(pix, dtype='uint8')) show_mode = [0, 2, 3] if 0 in show_mode: for i in range(len(bboxes)): box = bboxes[i][:4] clz = bboxes[i][4] frame = [box[1], box[0], box[3] - box[1], box[2] - box[0]] ax.add_patch( Rectangle((frame[0], frame[1]), frame[2], frame[3], linewidth=0.8, edgecolor='yellow', facecolor='none', linestyle='-')) if 1 in show_mode: for i in range(fg_bbox2d.shape[0]): box = fg_bbox2d[i] clz = fg_clz1d[i] frame = [box[1], box[0], box[3] - box[1], box[2] - box[0]] color = 'cyan' if clz == 0 else 'white' ax.add_patch( Rectangle((frame[0], frame[1]), frame[2], frame[3], linewidth=0.8,
def _n_profiles_H_V(arrayH, arrayV, virtual_pixelsize, zlabel=r'z', titleH='Horiz', titleV='Vert', nprofiles=5, filter_width=0, remove1stOrderDPC=False, saveFileSuf='', saveFigFlag=True): xxGrid, yyGrid = wpu.grid_coord(arrayH, virtual_pixelsize) fit_coefs = [[], []] data2saveH = None data2saveV = None labels_H = None labels_V = None plt.rcParams['lines.markersize'] = 4 plt.rcParams['lines.linewidth'] = 2 # Horizontal if np.all(np.isfinite(arrayH)): plt.figure(figsize=(12, 12 * 9 / 16)) xvec = xxGrid[0, :] data2saveH = np.c_[xvec] header = ['x [m]'] if filter_width != 0: arrayH_filtered = uniform_filter1d(arrayH, filter_width, 0) else: arrayH_filtered = arrayH ls_cycle, lc_jet = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'], ncurves=nprofiles, cmap_str='gist_rainbow_r') lc = [] labels_H = [] for i, row in enumerate( np.linspace(filter_width // 2, np.shape(arrayV)[0] - filter_width // 2 - 1, nprofiles + 2, dtype=int)): if i == 0 or i == nprofiles + 1: continue yvec = arrayH_filtered[row, :] lc.append(next(lc_jet)) p01 = np.polyfit(xvec, yvec, 1) fit_coefs[0].append(p01) if remove1stOrderDPC: yvec -= p01[0] * xvec + p01[1] plt.plot(xvec * 1e6, yvec, next(ls_cycle), color=lc[i - 1], label=str(row)) if not remove1stOrderDPC: plt.plot(xvec * 1e6, p01[0] * xvec + p01[1], '--', color=lc[i - 1], lw=3) data2saveH = np.c_[data2saveH, yvec] header.append(str(row)) labels_H.append(str(row)) if remove1stOrderDPC: titleH = titleH + ', 2nd order removed' plt.legend(title='Pixel Y', loc=0, fontsize=12) plt.xlabel(r'x [$\mu m$]', fontsize=18) plt.ylabel(zlabel, fontsize=18) plt.title(titleH + ', Filter Width = {:d} pixels'.format(filter_width), fontsize=20) if saveFigFlag: wpu.save_figs_with_idx(saveFileSuf + '_H') plt.show(block=False) header.append(zlabel + ', Filter Width = {:d} pixels'.format(filter_width)) wpu.save_csv_file(data2saveH, wpu.get_unique_filename( saveFileSuf + '_WF_profiles_H', 'csv'), headerList=header) plt.figure(figsize=(12, 12 * 9 / 16)) plt.imshow(arrayH, cmap='RdGy', vmin=wpu.mean_plus_n_sigma(arrayH, -3), vmax=wpu.mean_plus_n_sigma(arrayH, 3)) plt.xlabel('Pixel') plt.ylabel('Pixel') plt.title(titleH + ', Profiles Position') currentAxis = plt.gca() _, lc_jet = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'], ncurves=nprofiles, cmap_str='gist_rainbow_r') for i, row in enumerate( np.linspace(filter_width // 2, np.shape(arrayV)[0] - filter_width // 2 - 1, nprofiles + 2, dtype=int)): if i == 0 or i == nprofiles + 1: continue currentAxis.add_patch( Rectangle((-.5, row - filter_width // 2 - .5), np.shape(arrayH)[1], filter_width, facecolor=lc[i - 1], alpha=.5)) plt.axhline(row, color=lc[i - 1]) if saveFigFlag: wpu.save_figs_with_idx(saveFileSuf + '_H') plt.show(block=True) # Vertical if np.all(np.isfinite(arrayV)): plt.figure(figsize=(12, 12 * 9 / 16)) xvec = yyGrid[:, 0] data2saveV = np.c_[xvec] header = ['y [m]'] if filter_width != 0: arrayV_filtered = uniform_filter1d(arrayV, filter_width, 1) else: arrayV_filtered = arrayV ls_cycle, lc_jet = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'], ncurves=nprofiles, cmap_str='gist_rainbow_r') lc = [] labels_V = [] for i, col in enumerate( np.linspace(filter_width // 2, np.shape(arrayH)[1] - filter_width // 2 - 1, nprofiles + 2, dtype=int)): if i == 0 or i == nprofiles + 1: continue yvec = arrayV_filtered[:, col] lc.append(next(lc_jet)) p10 = np.polyfit(xvec, yvec, 1) fit_coefs[1].append(p10) if remove1stOrderDPC: yvec -= p10[0] * xvec + p10[1] plt.plot(xvec * 1e6, yvec, next(ls_cycle), color=lc[i - 1], label=str(col)) if not remove1stOrderDPC: plt.plot(xvec * 1e6, p10[0] * xvec + p10[1], '--', color=lc[i - 1], lw=3) data2saveV = np.c_[data2saveV, yvec] header.append(str(col)) labels_V.append(str(col)) if remove1stOrderDPC: titleV = titleV + ', 2nd order removed' plt.legend(title='Pixel X', loc=0, fontsize=12) plt.xlabel(r'y [$\mu m$]', fontsize=18) plt.ylabel(zlabel, fontsize=18) plt.title(titleV + ', Filter Width = {:d} pixels'.format(filter_width), fontsize=20) if saveFigFlag: wpu.save_figs_with_idx(saveFileSuf + '_Y') plt.show(block=False) header.append(zlabel + ', Filter Width = {:d} pixels'.format(filter_width)) wpu.save_csv_file(data2saveV, wpu.get_unique_filename( saveFileSuf + '_WF_profiles_V', 'csv'), headerList=header) plt.figure(figsize=(12, 12 * 9 / 16)) plt.imshow(arrayV, cmap='RdGy', vmin=wpu.mean_plus_n_sigma(arrayV, -3), vmax=wpu.mean_plus_n_sigma(arrayV, 3)) plt.xlabel('Pixel') plt.ylabel('Pixel') plt.title(titleV + ', Profiles Position') currentAxis = plt.gca() for i, col in enumerate( np.linspace(filter_width // 2, np.shape(arrayH)[1] - filter_width // 2 - 1, nprofiles + 2, dtype=int)): if i == 0 or i == nprofiles + 1: continue currentAxis.add_patch( Rectangle((col - filter_width // 2 - .5, -.5), filter_width, np.shape(arrayV)[0], facecolor=lc[i - 1], alpha=.5)) plt.axvline(col, color=lc[i - 1]) if saveFigFlag: wpu.save_figs_with_idx(saveFileSuf + '_Y') plt.show(block=True) return data2saveH, data2saveV, labels_H, labels_V, fit_coefs
mask_house = nibabel.load(data.mask_house[0]).get_data() plt.contour(mask_house[:, 4:58, z].astype(np.bool).T, contours=1, antialiased=False, linewidths=4., levels=[0], interpolation='nearest', colors=['blue'], origin='lower') mask_face = nibabel.load(data.mask_face[0]).get_data() plt.contour(mask_face[:, 4:58, z].astype(np.bool).T, contours=1, antialiased=False, linewidths=4., levels=[0], interpolation='nearest', colors=['limegreen'], origin='lower') # We generate a legend using the trick described on # http://matplotlib.sourceforge.net/users/legend_guide.httpml#using-proxy-artist from matplotlib.patches import Rectangle p_v = Rectangle((0, 0), 1, 1, fc="red") p_h = Rectangle((0, 0), 1, 1, fc="blue") p_f = Rectangle((0, 0), 1, 1, fc="limegreen") plt.legend([p_v, p_h, p_f], ["vt", "house", "face"]) plt.show()
def get_rectangle(cube, T, **kwargs): corner1 = cube.points[:, 0] corner2 = cube.points[:, -1] return Rectangle(corner1 - T, *(corner2 - corner1), **kwargs)
zlim1 = np.max(predictions) # color normalization cmap = cm.get_cmap('YlOrRd') norm = Normalize(vmin=zlim0, vmax=zlim1) cells = [] colors = [] #predictions = [] for hash in hashes: x0 = model[hash]['chx0'] x1 = model[hash]['chx1'] y0 = model[hash]['chy0'] y1 = model[hash]['chy1'] cell = Rectangle((x0, y0), x1 - x0, y1 - y0) cells.append(cell) col = cmap(norm(model[hash]['pred_absT'])) colors.append(col) pc = PatchCollection(cells, facecolor=colors, alpha=0.3) ax.add_collection(pc) mappable = cm.ScalarMappable(cmap=cmap) mappable.set_array([zlim0, zlim1]) fig.colorbar(mappable) factor = 400 fig.set_size_inches((maxx - minx) / factor, (maxy - miny) / factor) fig.tight_layout()
alpha=1, label="target", linewidth=2)) axis.add_patch( get_rectangle(c2, T, edgecolor='g', fill=None, alpha=1, linewidth=2)) axis.add_patch( Rectangle((translations[0, 0] - shapes[0, 0], translations[0, 1] - shapes[0, 1]), 2 * shapes[0, 0], 2 * shapes[0, 1], edgecolor='r', fill=None, linestyle='--', alpha=1, linewidth=2, label="primitive 1")) axis.add_patch( Rectangle((translations[0, 3] - shapes[0, 3], translations[0, 4] - shapes[0, 4]), 2 * shapes[0, 3], 2 * shapes[0, 4], edgecolor='b', fill=None, linestyle='--', alpha=1, linewidth=2, label="primitive 2"))
def __init__(self, rows=224, cols=224, dpi=112, nboxes=(0,5), n_heading = 4, slant_scale = 1, thick=40, thick_scale=2): img = np.zeros((rows,cols)) patches=[] thick = np.random.normal(scale=thick_scale)+thick xy = (np.random.normal(loc=-thick/2, scale=1),np.random.normal(loc=-thick/2, scale=1)) #randint(-20,-10), np.random.randint(-20,-10)) wh = (cols*1.2, thick) angle = np.random.normal(scale=slant_scale) wall = Rectangle(xy, wh[0],wh[1], angle=angle) patches.append(wall) xy = (np.random.normal(loc=-thick/2, scale=1),np.random.normal(loc=rows-thick/2, scale=1)) #np.random.randint(-20,-10), np.random.randint(rows-20, rows-10)) wh = (cols*1.2, thick) angle = np.random.normal(scale=slant_scale) wall = Rectangle(xy, wh[0],wh[1], angle=angle) patches.append(wall) xy = (np.random.normal(loc=-thick/2, scale=1),np.random.normal(loc=-thick/2, scale=1)) #np.random.randint(-20,-10), np.random.randint(-20, -10)) wh = (thick, rows*1.2) angle = np.random.normal(scale=slant_scale) wall = Rectangle(xy, wh[0],wh[1], angle=angle) patches.append(wall) xy = (np.random.normal(loc=cols-thick/2, scale=1),np.random.normal(loc=-thick/2, scale=1)) #np.random.randint(cols-20,cols-10), np.random.randint(-20, -10)) wh = (thick, rows*1.2) angle = np.random.normal(scale=slant_scale) wall = Rectangle(xy, wh[0],wh[1], angle=angle) patches.append(wall) # xy = (np.random.randint(5,35), np.random.randint(5,35)) # room_height = np.random.randint(180,200) # room_width = np.random.randint(180,200) # angle = np.random.randint(-5,5) # room = Rectangle(xy, room_height, room_width, angle=angle) # print (xy, room_height, room_width) fig = plt.figure(figsize=(cols/dpi,rows/dpi), dpi=dpi) ax = fig.gca() ax.imshow(img,cmap=plt.cm.binary) # ax.add_artist(room) ax.add_collection(PatchCollection(patches))#,cmap=plt.cm.binary)) ax.set_xlim([0,cols]) ax.set_ylim([0,rows]) # ax.axis('tight') plt.subplots_adjust(0,0,1,1,0,0) fig.canvas.draw() data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') w, h = fig.canvas.get_width_height() data = data.reshape((h,w,3)) # data = cv2.resize(data, (cols,rows)) data = np.sum(data, axis=2) if np.max(data)>0: data = np.round(data/np.max(data)) plt.close() self.room = data ## generate random boxes patches=[] for i in range(np.random.randint(nboxes[0],nboxes[1])): rs = min(rows,cols) hbox = np.random.randint(rs/10, rs/2) wbox = np.random.randint(rs/10, rs/2) xy = (np.random.randint(0,cols), np.random.randint(0,rows)) angle = np.random.normal(scale=3)+np.random.randint(n_heading)*360/n_heading box = Rectangle(xy, hbox,wbox,angle=angle) patches.append(box) fig = plt.figure(figsize=(cols/dpi,rows/dpi), dpi=dpi) ax = fig.gca() ax.imshow(img,cmap=plt.cm.binary) ax.add_collection(PatchCollection(patches))#,cmap=plt.cm.binary)) ax.set_xlim([0,cols]) ax.set_ylim([0,rows]) # ax.axis('tight') plt.subplots_adjust(0,0,1,1,0,0) fig.canvas.draw() data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') w, h = fig.canvas.get_width_height() data = data.reshape((h,w,3)) # data = cv2.resize(data, (cols,rows)) data = np.sum(data, axis=2) if np.max(data)>0: data = np.round(data/np.max(data)) plt.close() self.boxes = data
def draw_multilayer_default(network_list, display=True, node_size=10, alphalevel=0.13, rectanglex=1, rectangley=1, background_shape="circle", background_color="rainbow", networks_color="rainbow", labels=False, arrowsize=0.5, label_position=1, verbose=False, remove_isolated_nodes=False, axis=None, edge_size=1, node_labels=False, node_font_size=5, scale_by_size=False): """Core multilayer drawing method Args: network_list (list): a list of networks display (bool): Whether to display or not (directly) node_size (int): size of the nodes alphalevel (float): transparency level rectanglex (float): size of rectangles (background) (horizontal part) rectangley (float): size of vertical parts of rectangles background_shape (string): Background shape, either circle or rectangle background_color (string): Background color networks_color (string): Color of individual networks labels (bool): Display labels? arrowsize (float): Sizes of individual arrows label_position (int): position of labels (diagonal right) verbose (bool): Verbose printout? remove_isolated_nodes (bool): Remove isolated nodes? axis (bools): axis are displayed edge_size (float): Size of edges node_labels (bool): Display node labels? node_font_size (int): Size of the font scale_by_size (bool): Scale nodes according to their degrees? Returns: None """ if background_color == "default": facecolor_list_background = colors.linear_gradient( "#4286f4", n=len(network_list))['hex'] elif background_color == "rainbow": facecolor_list_background = colors.colors_default elif background_color == None: facecolor_list_background = colors.colors_default alphalevel = 0 else: pass if networks_color == "rainbow": facecolor_list = colors.colors_default elif networks_color == "black": facecolor_list = ["black"] * len(network_list) else: pass start_location_network = 0 start_location_background = 0 color = 0 shadow_size = 0.5 circle_size = 1.05 for network in network_list: if remove_isolated_nodes: isolates = list(nx.isolates(network)) network = network.copy() network.remove_nodes_from(isolates) if verbose: print(nx.info(network)) degrees = dict(nx.degree(nx.Graph(network))) cntr = 0 cntr_all = 0 no_position = [] all_positions = [] for node in network.nodes(data=True): if 'pos' not in node[1]: no_position.append(node[0]) cntr += 1 else: all_positions.append(node[1]['pos']) cntr_all += 1 if len(no_position) > 0: network = network.copy() network.remove_nodes_from(no_position) # print("No position for {}. Found position for {}.".format(cntr,cntr_all)) positions = nx.get_node_attributes(network, 'pos') cntr = 0 for position in positions: if np.abs(positions[position][0]) > 0.5 or np.abs( positions[position][1]) > 0.5: positions[position] = positions[position] / np.linalg.norm( positions[position]) try: positions[position][ 0] = positions[position][0] + 0.5 + start_location_network positions[position][ 1] = positions[position][1] + 0.5 + start_location_network except Exception as es: print(es, "err") ## this is the default delay for matplotlib canvas if labels != False: try: shape_subplot.text(start_location_network + label_position, start_location_network - label_position, labels[color]) except Exception as es: print(es) if background_shape == "rectangle": shape_subplot.add_patch( Rectangle( (start_location_background, start_location_background), rectanglex, rectangley, alpha=alphalevel, linestyle="dotted", fill=True, facecolor=facecolor_list_background[color])) elif background_shape == "circle": shape_subplot.add_patch( Circle((start_location_background + shadow_size, start_location_background + shadow_size), circle_size, color=facecolor_list_background[color], alpha=alphalevel)) else: pass start_location_network += 1.5 start_location_background += 1.5 if len(network.nodes()) > 10000: correction = 10 else: correction = 1 if scale_by_size: node_sizes = [vx * node_size for vx in degrees.values()] else: node_sizes = [node_size for vx in degrees.values()] if np.sum(node_sizes) == 0: node_sizes = [node_size for vx in degrees.values()] # node_sizes = [(np.log(v) * node_size)/correction if v > 400 else node_size/correction for v in degrees.values()] # cntr+=1 # for position in positions: # if cntr<15: # print(positions[position][0], positions[position][1]) drawing_machinery.draw(network, positions, node_color=facecolor_list[color], with_labels=node_labels, edge_size=edge_size, node_size=node_sizes, arrowsize=arrowsize, ax=axis, font_size=node_font_size) color += 1 if display == True: plt.show()
def draw_half_court(ax=None, color='black', lw=2, outer_lines=False): # If an axes object isn't provided to plot onto, just get current one if ax is None: ax = plt.gca() # Create the various parts of an NBA basketball court # Create the basketball hoop # Diameter of a hoop is 18" so it has a radius of 9", which is a value # 7.5 in our coordinate system hoop = Circle((0, 0), radius=7.5, linewidth=lw, color=color, fill=False) # Create backboard backboard = Rectangle((-30, -7.5), 60, -1, linewidth=lw, color=color) # The paint # Create the outer box 0f the paint, width=16ft, height=19ft outer_box = Rectangle((-80, -47.5), 160, 190, linewidth=lw, color=color, fill=False) # Create the inner box of the paint, widt=12ft, height=19ft inner_box = Rectangle((-60, -47.5), 120, 190, linewidth=lw, color=color, fill=False) # Create free throw top arc top_free_throw = Arc((0, 142.5), 120, 120, theta1=0, theta2=180, linewidth=lw, color=color, fill=False) # Create free throw bottom arc bottom_free_throw = Arc((0, 142.5), 120, 120, theta1=180, theta2=0, linewidth=lw, color=color, linestyle='dashed') # Restricted Zone, it is an arc with 4ft radius from center of the hoop restricted = Arc((0, 0), 80, 80, theta1=0, theta2=180, linewidth=lw, color=color) # Three point line # Create the side 3pt lines, they are 14ft long before they begin to arc corner_three_a = Rectangle((-220, -47.5), 0, 140, linewidth=lw, color=color) corner_three_b = Rectangle((220, -47.5), 0, 140, linewidth=lw, color=color) # 3pt arc - center of arc will be the hoop, arc is 23'9" away from hoop # I just played around with the theta values until they lined up with the # threes three_arc = Arc((0, 0), 475, 475, theta1=22, theta2=158, linewidth=lw, color=color) # Center Court center_outer_arc = Arc((0, 422.5), 120, 120, theta1=180, theta2=0, linewidth=lw, color=color) center_inner_arc = Arc((0, 422.5), 40, 40, theta1=180, theta2=0, linewidth=lw, color=color) # List of the court elements to be plotted onto the axes court_elements = [ hoop, backboard, outer_box, inner_box, top_free_throw, bottom_free_throw, restricted, corner_three_a, corner_three_b, three_arc, center_outer_arc, center_inner_arc ] if outer_lines: # Draw the half court line, baseline and side out bound lines outer_lines = Rectangle((-250, -47.5), 500, 470, linewidth=lw, color=color, fill=False) court_elements.append(outer_lines) # Add the court elements onto the axes for element in court_elements: ax.add_patch(element) return ax
class RectangleSelectImagePanel(wx.Panel): ''' Panel that contains an image that allows the users to select an area of the image with the mouse. The user clicks and holds the mouse to create a dotted rectangle, and when the mouse is released the rectangles origin, width and height can be read. The dimensions of these readings are always relative to the original image, so even if the image is scaled up larger to fit the panel the measurements will always refer to the original image.''' def __init__(self, parent, pathToImage=None): ''' Initialise the panel. Setting an initial image is optional.''' # Initialise the parent wx.Panel.__init__(self, parent) # Intitialise the matplotlib figure self.figure = plt.figure() # Create an axes, turn off the labels and add them to the figure self.axes = plt.Axes(self.figure, [0, 0, 1, 1]) self.axes.set_axis_off() self.figure.add_axes(self.axes) # Add the figure to the wxFigureCanvas self.canvas = FigureCanvas(self, -1, self.figure) # Initialise the rectangle self.rect = Rectangle((0, 0), 1, 1, facecolor='None', edgecolor='green') self.x0 = None self.y0 = None self.x1 = None self.y1 = None self.axes.add_patch(self.rect) # Sizer to contain the canvas self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 3, wx.ALL) self.SetSizer(self.sizer) self.Fit() # Connect the mouse events to their relevant callbacks self.canvas.mpl_connect('button_press_event', self._onPress) self.canvas.mpl_connect('button_release_event', self._onRelease) self.canvas.mpl_connect('motion_notify_event', self._onMotion) # Lock to stop the motion event from behaving badly when the mouse isn't pressed self.pressed = False # If there is an initial image, display it on the figure if pathToImage is not None: self.setImage(pathToImage) def _onPress(self, event): ''' Callback to handle the mouse being clicked and held over the canvas''' # Check the mouse press was actually on the canvas if event.xdata is not None and event.ydata is not None: # Upon initial press of the mouse record the origin and record the mouse as pressed self.pressed = True self.rect.set_linestyle('dashed') self.x0 = event.xdata self.y0 = event.ydata def _onRelease(self, event): '''Callback to handle the mouse being released over the canvas''' # Check that the mouse was actually pressed on the canvas to begin with and this isn't a rouge mouse # release event that started somewhere else if self.pressed: # Upon release draw the rectangle as a solid rectangle self.pressed = False self.rect.set_linestyle('solid') # Check the mouse was released on the canvas, and if it wasn't then just leave the width and # height as the last values set by the motion event if event.xdata is not None and event.ydata is not None: self.x1 = event.xdata self.y1 = event.ydata # Set the width and height and origin of the bounding rectangle self.boundingRectWidth = self.x1 - self.x0 self.boundingRectHeight = self.y1 - self.y0 self.bouningRectOrigin = (self.x0, self.y0) # Draw the bounding rectangle self.rect.set_width(self.boundingRectWidth) self.rect.set_height(self.boundingRectHeight) self.rect.set_xy((self.x0, self.y0)) self.canvas.draw() def _onMotion(self, event): '''Callback to handle the motion event created by the mouse moving over the canvas''' # If the mouse has been pressed draw an updated rectangle when the mouse is moved so # the user can see what the current selection is if self.pressed: # Check the mouse was released on the canvas, and if it wasn't then just leave the width and # height as the last values set by the motion event if event.xdata is not None and event.ydata is not None: self.x1 = event.xdata self.y1 = event.ydata # Set the width and height and draw the rectangle self.rect.set_width(self.x1 - self.x0) self.rect.set_height(self.y1 - self.y0) self.rect.set_xy((self.x0, self.y0)) self.canvas.draw() def setImage(self, pathToImage): '''Sets the background image of the canvas''' # Load the image into matplotlib and PIL image = matplotlib.image.imread(pathToImage) imPIL = Image.open(pathToImage) # Save the image's dimensions from PIL self.imageSize = imPIL.size # Add the image to the figure and redraw the canvas. Also ensure the aspect ratio of the image is retained. self.axes.imshow(image, aspect='equal') self.canvas.draw()
def compute_eval_ious(model, num_actions, index, root, gt_bbox_all, acc_thresh=0.5, print_stuff=False): """ Return the mean IoUs and accuracy for model output, random, and best candidates model: model for inferencing num_actions: number of actions in video index: video index in dataset directory root: directory path to dataset base acc_thresh: IoU threshold for accuracy Returns mean_best_iou: upper bound mean IoU of candidate bboxes and ground truth bboxes Returns mean_rand_iou: mean IoU of randomly selected bboxes and ground truth bboxes Returns mean_ours_iou: mean IoU of model output bboxes and ground truth bboxes Returns best_acc: Top-1 accuracy for proposal upper bound Returns rand_acc: Top-1 accuracy for random selection Returns ours_acc: Top-1 accuracy for model output """ # Load data from disk root = os.path.join(root, str(num_actions), str(index).zfill(5)) pickles_root = os.path.join(root, 'pickles') frames_root = os.path.join(root, 'frames') frame_paths = depickle_data(pickles_root, 'frame_paths') entities = depickle_data(pickles_root, 'entities') actions = depickle_data(pickles_root, 'actions_list') actions.append('[NULL]') candidates = depickle_data(pickles_root, 'candidates') vid_id = depickle_data(pickles_root, 'vid_id') steps = depickle_data(pickles_root, 'steps') entity_count = depickle_data(pickles_root, 'entity_count') bboxes = torch.stack(list(zip(*candidates))[0]).squeeze(1).reshape( -1, BOUNDING_BOX_DIM) features = torch.stack(list(zip(*candidates))[1]).squeeze(1).reshape( -1, DETECTION_EMBEDDING_DIM) steps = remove_unused2([steps])[0] steps = remove_unused3([steps])[0] #steps = steps.replace('[unused3]', '[ unused 3 ]') # Extract ground truth bbox info for entire video if gt_bbox_all is None: gt_bbox_all = read_json(FI_VG) gt_vid_bbox = gt_bbox_all[vid_id] # Run model inference VG, RR = model_inference(model, steps, entities, entity_count, bboxes, features) # Calculate mean grounding IoU mean_best_iou = 0.0 mean_rand_iou = 0.0 mean_ours_iou = 0.0 best_correct = 0 # number of correctly matched bboxes (based on given threshold) rand_correct = 0 ours_correct = 0 num_ents = 0 for action_idx, action_entities in enumerate(entities[:-1]): if print_stuff: print('--------------------------------------------------') print('Action {}: {}'.format(action_idx + 1, actions[action_idx])) # if gt doesn't have bbox, skip (doesn't count towards IoU) - since model must ground all entities if len(action_entities) == 0: if print_stuff: print('No entities detected for this action.') frame_path = None prev_frame_path = None # all candidates for the current action frame_candidate_bboxes = bboxes[NUM_CANDIDATES_PER_STEP * action_idx:(NUM_CANDIDATES_PER_STEP * (action_idx + 1))] for ent_idx, entity in enumerate(action_entities): # VG processing offset = NUM_FRAMES_PER_STEP * action_idx candidate = int(VG[action_idx][ent_idx]) vg_idx = offset + math.floor(candidate / NUM_CANDIDATES_PER_FRAME) prev_frame_path = frame_path frame_path = frame_paths[vg_idx] bbox = bboxes[offset * NUM_CANDIDATES_PER_FRAME + candidate] ################################################ ## processing for ground truth entity bbox #index into gt as (action_idx, entity_idx, instance of entity) #str_action_id = '('+str(action_idx)+', '+str(ent_idx) + ', ' + str(0) + ')' vg_keys = get_vg_key(action_idx, ent_idx, gt_vid_bbox) # look for gt bbox in nearest frame to model output bbox - this may lead to addition leniency in IoU score #gt_vid_box[str_action_id]['bboxes'] gt_bbox_info = nearest_in_time(vg_keys_gt_ent=vg_keys, model_frame=frame_path, gt_vid_bbox=gt_vid_bbox) if gt_bbox_info is None: if print_stuff: print('This entity has no ground truth bounding box') continue #gt_frame, gt_bbox gt_frame = gt_bbox_info['img'] gt_bbox = [ gt_bbox_info['bbox']['x'], gt_bbox_info['bbox']['y'], gt_bbox_info['bbox']['w'], gt_bbox_info['bbox']['h'] ] if gt_bbox[0] is None or gt_bbox[1] is None or gt_bbox[ 2] is None or gt_bbox[3] is None: if print_stuff: print( 'Atleast one of the bounding box coordinates is missing.' ) continue #print(gt_frame) gt_box = Rectangle((gt_bbox[0], gt_bbox[1]), gt_bbox[2], gt_bbox[3], linewidth=1, edgecolor='red', facecolor='none') gt_x0 = gt_bbox[0] gt_y0 = gt_bbox[1] gt_bbox_width = gt_bbox[2] gt_bbox_height = gt_bbox[3] #print('GT frame is {}, model frame is {}'.format(gt_frame, frame_path)) path_split = frame_path.split('/') user = path_split[2] if user != 'sagar': path_split[2] = 'sagar' frame_path = '/'.join(path_split) frame = cv2.imread(frame_path) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame_height = frame.shape[0] frame_width = frame.shape[1] # Calculate best IoU possible from all candidates for current action best_iou = 0.0 for candidate_bbox in frame_candidate_bboxes: candidate_iou = compute_iou_from_normalized_coords( candidate_bbox, frame_width, frame_height, gt_bbox) best_iou = max(best_iou, candidate_iou) if print_stuff: print('Best IoU possible = {}'.format(best_iou)) if best_iou >= acc_thresh: best_correct += 1 # Pick a random candidate from all candidates for current action rand_bbox = frame_candidate_bboxes[random.randint( 0, NUM_CANDIDATES_PER_STEP - 1)] rand_iou = compute_iou_from_normalized_coords( rand_bbox, frame_width, frame_height, gt_bbox) if print_stuff: print('Random Candidate IoU = {}'.format(rand_iou)) if rand_iou >= acc_thresh: rand_correct += 1 # Calculate model output IoU ours_iou = compute_iou_from_normalized_coords( bbox, frame_width, frame_height, gt_bbox) if print_stuff: print('Chosen Frame IoU: {}'.format(ours_iou)) if ours_iou >= acc_thresh: ours_correct += 1 if ours_iou > best_iou: if print_stuff: print('ERROR: Best IoU < Chosen IoU') mean_best_iou += best_iou mean_rand_iou += rand_iou mean_ours_iou += ours_iou num_ents += 1 mean_best_iou /= num_ents mean_ours_iou /= num_ents mean_rand_iou /= num_ents if print_stuff: print( 'Mean Upper Bound IoU: {}, Mean Random IoU: {}, Mean Model IoU: {}' .format(mean_best_iou, mean_rand_iou, mean_ours_iou)) best_acc = best_correct / num_ents rand_acc = rand_correct / num_ents ours_acc = ours_correct / num_ents if print_stuff: print('Top-1 acc@{}:\nProposal Upper Bound: {}, Random: {}, Model: {}'. format(acc_thresh, best_acc, rand_acc, ours_acc)) return mean_best_iou, mean_rand_iou, mean_ours_iou, best_acc, rand_acc, ours_acc