def do_3d_projection(self, renderer): """ Perform the 3D projection for this object. """ # FIXME: This may no longer be needed? if self._A is not None: self.update_scalarmappable() self._facecolors3d = self._facecolors txs, tys, tzs = proj3d.proj_transform_vec(self._vec, renderer.M) xyzlist = [(txs[si:ei], tys[si:ei], tzs[si:ei]) for si, ei in self._segis] # This extra fuss is to re-order face / edge colors cface = self._facecolors3d cedge = self._edgecolors3d if len(cface) != len(xyzlist): cface = cface.repeat(len(xyzlist), axis=0) if len(cedge) != len(xyzlist): if len(cedge) == 0: cedge = cface else: cedge = cedge.repeat(len(xyzlist), axis=0) # if required sort by depth (furthest drawn first) if self._zsort: z_segments_2d = sorted( ((self._zsortfunc(zs), np.column_stack([xs, ys]), fc, ec, idx) for idx, ((xs, ys, zs), fc, ec) in enumerate(zip(xyzlist, cface, cedge))), key=lambda x: x[0], reverse=True) else: raise ValueError("whoops") segments_2d = [s for z, s, fc, ec, idx in z_segments_2d] if self._codes3d is not None: codes = [self._codes3d[idx] for z, s, fc, ec, idx in z_segments_2d] PolyCollection.set_verts_and_codes(self, segments_2d, codes) else: PolyCollection.set_verts(self, segments_2d, self._closed) self._facecolors2d = [fc for z, s, fc, ec, idx in z_segments_2d] if len(self._edgecolors3d) == len(cface): self._edgecolors2d = [ec for z, s, fc, ec, idx in z_segments_2d] else: self._edgecolors2d = self._edgecolors3d # Return zorder value if self._sort_zpos is not None: zvec = np.array([[0], [0], [self._sort_zpos], [1]]) ztrans = proj3d.proj_transform_vec(zvec, renderer.M) return ztrans[2][0] elif tzs.size > 0: # FIXME: Some results still don't look quite right. # In particular, examine contourf3d_demo2.py # with az = -54 and elev = -45. return np.min(tzs) else: return np.nan
def do_3d_projection(self, renderer): """ Perform the 3D projection for this object. """ # FIXME: This may no longer be needed? if self._A is not None: self.update_scalarmappable() self._facecolors3d = self._facecolors txs, tys, tzs = proj3d.proj_transform_vec(self._vec, renderer.M) xyzlist = [(txs[si:ei], tys[si:ei], tzs[si:ei]) for si, ei in self._segis] # This extra fuss is to re-order face / edge colors cface = self._facecolors3d cedge = self._edgecolors3d if len(cface) != len(xyzlist): cface = cface.repeat(len(xyzlist), axis=0) if len(cedge) != len(xyzlist): if len(cedge) == 0: cedge = cface else: cedge = cedge.repeat(len(xyzlist), axis=0) # if required sort by depth (furthest drawn first) if self._zsort: z_segments_2d = sorted( ((self._zsortfunc(zs), np.column_stack([xs, ys]), fc, ec, idx) for idx, ((xs, ys, zs), fc, ec) in enumerate(zip(xyzlist, cface, cedge))), key=lambda x: x[0], reverse=True) else: raise ValueError("whoops") segments_2d = [s for z, s, fc, ec, idx in z_segments_2d] if self._codes3d is not None: codes = [self._codes3d[idx] for z, s, fc, ec, idx in z_segments_2d] PolyCollection.set_verts_and_codes(self, segments_2d, codes) else: PolyCollection.set_verts(self, segments_2d, self._closed) self._facecolors2d = [fc for z, s, fc, ec, idx in z_segments_2d] if len(self._edgecolors3d) == len(cface): self._edgecolors2d = [ec for z, s, fc, ec, idx in z_segments_2d] else: self._edgecolors2d = self._edgecolors3d # Return zorder value if self._sort_zpos is not None: zvec = np.array([[0], [0], [self._sort_zpos], [1]]) ztrans = proj3d.proj_transform_vec(zvec, renderer.M) return ztrans[2][0] elif tzs.size > 0 : # FIXME: Some results still don't look quite right. # In particular, examine contourf3d_demo2.py # with az = -54 and elev = -45. return np.min(tzs) else : return np.nan
def do_3d_projection(self, renderer=None): """ Perform the 3D projection for this object. """ # see _update_scalarmappable docstring for why this must be here _update_scalarmappable(self) txs, tys, tzs = proj3d._proj_transform_vec(self._vec, self.axes.M) xyzlist = [(txs[sl], tys[sl], tzs[sl]) for sl in self._segslices] # This extra fuss is to re-order face / edge colors cface = self._facecolor3d cedge = self._edgecolor3d if len(cface) != len(xyzlist): cface = cface.repeat(len(xyzlist), axis=0) if len(cedge) != len(xyzlist): if len(cedge) == 0: cedge = cface else: cedge = cedge.repeat(len(xyzlist), axis=0) if xyzlist: # sort by depth (furthest drawn first) z_segments_2d = sorted( ((self._zsortfunc(zs), np.column_stack([xs, ys]), fc, ec, idx) for idx, ((xs, ys, zs), fc, ec) in enumerate(zip(xyzlist, cface, cedge))), key=lambda x: x[0], reverse=True) _, segments_2d, self._facecolors2d, self._edgecolors2d, idxs = \ zip(*z_segments_2d) else: segments_2d = [] self._facecolors2d = np.empty((0, 4)) self._edgecolors2d = np.empty((0, 4)) idxs = [] if self._codes3d is not None: codes = [self._codes3d[idx] for idx in idxs] PolyCollection.set_verts_and_codes(self, segments_2d, codes) else: PolyCollection.set_verts(self, segments_2d, self._closed) if len(self._edgecolor3d) != len(cface): self._edgecolors2d = self._edgecolor3d # Return zorder value if self._sort_zpos is not None: zvec = np.array([[0], [0], [self._sort_zpos], [1]]) ztrans = proj3d._proj_transform_vec(zvec, self.axes.M) return ztrans[2][0] elif tzs.size > 0: # FIXME: Some results still don't look quite right. # In particular, examine contourf3d_demo2.py # with az = -54 and elev = -45. return np.min(tzs) else: return np.nan
def do_3d_projection(self, renderer): ''' Perform the 3D projection for this object. ''' if self._A is not None: self.update_scalarmappable() self._facecolors3d = self._facecolors txs, tys, tzs = proj3d.proj_transform_vec(self._vec, renderer.M) xyzlist = [(txs[si:ei], tys[si:ei], tzs[si:ei]) \ for si, ei in self._segis] # This extra fuss is to re-order face / edge colors cface = self._facecolors3d cedge = self._edgecolors3d if len(cface) != len(xyzlist): cface = cface.repeat(len(xyzlist), axis=0) if len(cedge) != len(xyzlist): if len(cedge) == 0: cedge = cface cedge = cedge.repeat(len(xyzlist), axis=0) # if required sort by depth (furthest drawn first) if self._zsort: z_segments_2d = [(self._zsortfunc(zs), zip(xs, ys), fc, ec) for (xs, ys, zs), fc, ec in zip(xyzlist, cface, cedge)] z_segments_2d.sort(cmp=lambda x, y: cmp(y[0], x[0])) else: raise ValueError, "whoops" segments_2d = [s for z, s, fc, ec in z_segments_2d] PolyCollection.set_verts(self, segments_2d) self._facecolors2d = [fc for z, s, fc, ec in z_segments_2d] if len(self._edgecolors3d) == len(cface): self._edgecolors2d = [ec for z, s, fc, ec in z_segments_2d] else: self._edgecolors2d = self._edgecolors3d # Return zorder value if self._sort_zpos is not None: zvec = np.array([[0], [0], [self._sort_zpos], [1]]) ztrans = proj3d.proj_transform_vec(zvec, renderer.M) return ztrans[2][0] elif tzs.size > 0: # FIXME: Some results still don't look quite right. # In particular, examine contourf3d_demo2.py # with az = -54 and elev = -45. return np.min(tzs) else: return np.nan
def do_3d_projection(self, renderer): ''' Perform the 3D projection for this object. ''' # FIXME: This may no longer be needed? if self._A is not None: self.update_scalarmappable() self._facecolors3d = self._facecolors txs, tys, tzs = proj3d.proj_transform_vec(self._vec, renderer.M) xyzlist = [(txs[si:ei], tys[si:ei], tzs[si:ei]) \ for si, ei in self._segis] # This extra fuss is to re-order face / edge colors cface = self._facecolors3d cedge = self._edgecolors3d if len(cface) != len(xyzlist): cface = cface.repeat(len(xyzlist), axis=0) if len(cedge) != len(xyzlist): if len(cedge) == 0: cedge = cface cedge = cedge.repeat(len(xyzlist), axis=0) # if required sort by depth (furthest drawn first) if self._zsort: z_segments_2d = [(self._zsortfunc(zs), zip(xs, ys), fc, ec) for (xs, ys, zs), fc, ec in zip(xyzlist, cface, cedge)] z_segments_2d.sort(cmp=lambda x, y: cmp(y[0], x[0])) else: raise ValueError, "whoops" segments_2d = [s for z, s, fc, ec in z_segments_2d] PolyCollection.set_verts(self, segments_2d) self._facecolors2d = [fc for z, s, fc, ec in z_segments_2d] if len(self._edgecolors3d) == len(cface): self._edgecolors2d = [ec for z, s, fc, ec in z_segments_2d] else: self._edgecolors2d = self._edgecolors3d # Return zorder value if self._sort_zpos is not None: zvec = np.array([[0], [0], [self._sort_zpos], [1]]) ztrans = proj3d.proj_transform_vec(zvec, renderer.M) return ztrans[2][0] elif tzs.size > 0 : # FIXME: Some results still don't look quite right. # In particular, examine contourf3d_demo2.py # with az = -54 and elev = -45. return np.min(tzs) else : return np.nan
class ScatterPlotCC(ScatterPlot): def get_polygon(self, x, y, c): color_map = ('c', 'r', 'b', 'm', 'y', 'g') d = defaultdict(list) for p, cc in zip(zip(x, y), c): d[cc].append(p) polygons = [] colors = [] for k in set(c): if len(d[k]) == 2: pt1 = d[k][0] pt2 = d[k][1] dist = math.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2) xmid = (pt1[0] + pt2[0]) / 2 ymid = (pt1[1] + pt2[1]) / 2 polygons.append(d[k]) colors.append(color_map[k]) elif len(d[k]) == 1: pass else: ch = ConvexHull(d[k]) points = ch.points pts = zip(points[ch.vertices, 0], points[ch.vertices, 1]) polygons.append(pts) colors.append(color_map[k]) return polygons, colors def setup_plot(self): ax = plt.gca() x, y, c = next(self.stream) po, co = self.get_polygon(x, y, c) self.poly = PolyCollection(po, facecolors = co, edgecolors='none') ax.add_collection(self.poly) self.scat = ax.scatter(x, y, c='k', marker = self.marker, s = 25) return self.scat def update_plot(self): x, y, c = next(self.stream) new_data = np.array(zip(x, y)) po, co = self.get_polygon(x, y, c) self.poly.set_facecolor(co) self.poly.set_verts(po) self.scat.set_offsets(new_data) return self.scat
def do_3d_projection(self, renderer): ''' Perform the 3D projection for this object. ''' if self._A is not None: self.update_scalarmappable() self._facecolors3d = self._facecolors txs, tys, tzs = proj3d.proj_transform_vec(self._vec, renderer.M) xyzlist = [(txs[si:ei], tys[si:ei], tzs[si:ei]) \ for si, ei in self._segis] # This extra fuss is to re-order face / edge colors cface = self._facecolors3d cedge = self._edgecolors3d if len(cface) != len(xyzlist): cface = cface.repeat(len(xyzlist), axis=0) if len(cedge) != len(xyzlist): if len(cedge) == 0: cedge = cface cedge = cedge.repeat(len(xyzlist), axis=0) # if required sort by depth (furthest drawn first) if self._zsort: z_segments_2d = [(self._zsortfunc(zs), zip(xs, ys), fc, ec) for (xs, ys, zs), fc, ec in zip(xyzlist, cface, cedge)] z_segments_2d.sort(key=lambda x: x[0], reverse=True) else: raise ValueError, "whoops" segments_2d = [s for z, s, fc, ec in z_segments_2d] PolyCollection.set_verts(self, segments_2d) self._facecolors2d = [fc for z, s, fc, ec in z_segments_2d] if len(self._edgecolors3d) == len(cface): self._edgecolors2d = [ec for z, s, fc, ec in z_segments_2d] else: self._edgecolors2d = self._edgecolors3d # Return zorder value if self._sort_zpos is not None: zvec = np.array([[0], [0], [self._sort_zpos], [1]]) ztrans = proj3d.proj_transform_vec(zvec, renderer.M) return ztrans[2][0] else: return np.min(tzs)
class PolygonFormat(LineFormat): clt=Typed(PolyCollection) antialiased=Bool(True) def polygon_plot(self, *args, **kwargs): kwargs=process_kwargs(self, kwargs) #self.xdata=[arg[0] for arg in args[0][0]] #self.zdata=[[vert[1] for vert in line] for line in args[0]] self.clt=PolyCollection(args[0], alpha=self.alpha, antialiased=self.antialiased) self.clt.set_color(self.color) #from matplotlib.colors import colorConverter colorConverter.to_rgba( self.plotter.axes.add_collection(self.clt) def alter_xy(self, *args, **kwargs): self.color=kwargs.pop("color", self.color) zdata=args[0] self.clt.set_verts(zdata) self.clt.set_color(self.color)
class PolygonFormat(LineFormat): clt = Typed(PolyCollection) antialiased = Bool(True) def polygon_plot(self, *args, **kwargs): kwargs = process_kwargs(self, kwargs) #self.xdata=[arg[0] for arg in args[0][0]] #self.zdata=[[vert[1] for vert in line] for line in args[0]] self.clt = PolyCollection(args[0], alpha=self.alpha, antialiased=self.antialiased) self.clt.set_color( self.color ) #from matplotlib.colors import colorConverter colorConverter.to_rgba( self.plotter.axes.add_collection(self.clt) def alter_xy(self, *args, **kwargs): self.color = kwargs.pop("color", self.color) zdata = args[0] self.clt.set_verts(zdata) self.clt.set_color(self.color)
class Cube(): """ A simple cube """ def __init__(self, ax, transform): self.vertices = np.array([[+1, +1, +1], [-1, +1, +1], [-1, -1, +1], [+1, -1, +1], [+1, -1, -1], [+1, +1, -1], [-1, +1, -1], [-1, -1, -1]]) / 2 self.faces = [[0, 1, 2, 3], [0, 3, 4, 5], [0, 5, 6, 1], [1, 6, 7, 2], [7, 4, 3, 2], [4, 7, 6, 5]] self.collection = PolyCollection([], closed=True, linewidths=1.0, facecolors=(1, 1, 1, 0.75), edgecolors=(0, 0, 0, 1)) self.update(transform) ax.add_collection(self.collection, autolim=False) def update(self, transform): V = glm.transform(self.vertices, transform) F = np.array([V[face] for face in self.faces]) I = np.argsort(-np.mean(F[:, :, 2].squeeze(), axis=-1)) verts = F[I][..., :2] self.collection.set_verts(verts)
def do_3d_projection(self, renderer): ''' Perform the 3D projection for this object. ''' if self._A is not None: self.update_scalarmappable() self._facecolors3d = self._facecolors txs, tys, tzs = proj3d.proj_transform_vec(self._vec, renderer.M) xyzlist = [(txs[si:ei], tys[si:ei], tzs[si:ei]) \ for si, ei in self._segis] cface = self._facecolors3d cedge = self._edgecolors3d if len(cface) != len(xyzlist): cface = cface.repeat(len(xyzlist), axis=0) if len(cedge) != len(xyzlist): if len(cedge) == 0: cedge = cface cedge = cedge.repeat(len(xyzlist), axis=0) if self._zsort: z_segments_2d = [(np.average(zs), zip(xs, ys), fc, ec) for (xs, ys, zs), fc, ec in zip(xyzlist, cface, cedge)] z_segments_2d.sort(cmp=lambda x, y: cmp(y[0], x[0])) else: raise ValueError, "whoops" segments_2d = [s for z, s, fc, ec in z_segments_2d] PolyCollection.set_verts(self, segments_2d) self._facecolors2d = [fc for z, s, fc, ec in z_segments_2d] if len(self._edgecolors3d) == len(cface): self._edgecolors2d = [ec for z, s, fc, ec in z_segments_2d] else: self._edgecolors2d = self._edgecolors3d if self._sort_zpos is not None: zvec = np.array([[0], [0], [self._sort_zpos], [1]]) ztrans = proj3d.proj_transform_vec(zvec, renderer.M) return ztrans[2][0] else: return np.min(tzs)
def do_3d_projection(self, renderer=None): """ Perform the 3D projection for this object. """ if self._A is not None: # force update of color mapping because we re-order them # below. If we do not do this here, the 2D draw will call # this, but we will never port the color mapped values back # to the 3D versions. # # We hold the 3D versions in a fixed order (the order the user # passed in) and sort the 2D version by view depth. self.update_scalarmappable() if self._face_is_mapped: self._facecolor3d = self._facecolors if self._edge_is_mapped: self._edgecolor3d = self._edgecolors txs, tys, tzs = proj3d._proj_transform_vec(self._vec, self.axes.M) xyzlist = [(txs[sl], tys[sl], tzs[sl]) for sl in self._segslices] # This extra fuss is to re-order face / edge colors cface = self._facecolor3d cedge = self._edgecolor3d if len(cface) != len(xyzlist): cface = cface.repeat(len(xyzlist), axis=0) if len(cedge) != len(xyzlist): if len(cedge) == 0: cedge = cface else: cedge = cedge.repeat(len(xyzlist), axis=0) if xyzlist: # sort by depth (furthest drawn first) z_segments_2d = sorted( ((self._zsortfunc(zs), np.column_stack([xs, ys]), fc, ec, idx) for idx, ((xs, ys, zs), fc, ec) in enumerate(zip(xyzlist, cface, cedge))), key=lambda x: x[0], reverse=True) _, segments_2d, self._facecolors2d, self._edgecolors2d, idxs = \ zip(*z_segments_2d) else: segments_2d = [] self._facecolors2d = np.empty((0, 4)) self._edgecolors2d = np.empty((0, 4)) idxs = [] if self._codes3d is not None: codes = [self._codes3d[idx] for idx in idxs] PolyCollection.set_verts_and_codes(self, segments_2d, codes) else: PolyCollection.set_verts(self, segments_2d, self._closed) if len(self._edgecolor3d) != len(cface): self._edgecolors2d = self._edgecolor3d # Return zorder value if self._sort_zpos is not None: zvec = np.array([[0], [0], [self._sort_zpos], [1]]) ztrans = proj3d._proj_transform_vec(zvec, self.axes.M) return ztrans[2][0] elif tzs.size > 0: # FIXME: Some results still don't look quite right. # In particular, examine contourf3d_demo2.py # with az = -54 and elev = -45. return np.min(tzs) else: return np.nan
class Animator(object): def __init__(self, positions, diameter): self.circ_count = positions.shape[0] plt.ion() fig = plt.figure(figsize=(10, 10)) ax = fig.gca() self.ax = ax diameters = np.ones(self.circ_count) * diameter circ_colors = [(0.0, 0.0, 1.0) for _ in range(self.circ_count)] #add circles self.circles = EllipseCollection(widths=diameters, heights=diameters, angles=np.zeros_like(diameters), units='xy', offsets=positions, transOffset=ax.transData, edgecolor='face', facecolor=circ_colors) ax.add_collection(self.circles) #add polygons self.poly_count = 3 verts = [[(0, 1), (1, 0), (2, 2)], [(6, 5), (3, 7), (7, 6)], [(0, -1), (-1, 0), (4, 5)]] poly_colors = [(0.0, 0.0, 1.0) for _ in range(self.poly_count)] self.polygons = PolyCollection(verts, facecolors=poly_colors) ax.add_collection(self.polygons) ax.axis([-20, 20, -20, 20]) ax.get_xaxis().set_visible(True) ax.get_yaxis().set_visible(True) #ax.set_axis_bgcolor('black') plt.draw() plt.pause(0.1) def update(self, positions): #update number of balls self.circles.set_offsets(positions) colors = [(1.0, 0.0, 0.0) for _ in range(self.circ_count)] self.circles.set_facecolors(colors) #redefine circles diameter = 2 diameters = np.ones(self.circ_count + 100) * diameter circ_colors = [(0.0, 0.0, 1.0) for _ in range(self.circ_count)] #add circles self.circles.remove() self.circles = EllipseCollection(widths=diameters, heights=diameters, angles=np.zeros_like(diameters), units='xy', offsets=positions, transOffset=self.ax.transData, edgecolor='face', facecolor=circ_colors) self.ax.add_collection(self.circles) #label text_labels = [None] * positions.shape[0] for i in range(positions.shape[0]): text_labels[i] = plt.text(positions[i, 0], positions[i, 1], str(i), color='white') #remove polygon #self.polygons.remove() poly_color = np.random.uniform(0.0, 0.89, (3, )) + 0.1 verts = [[(10, 1), (9, 0), (8, 2), (10, 2)], [(8, 8), (9, 9), (6, 7)]] self.polygons.set_verts(verts) plt.draw() plt.pause(0.1) #remove labels for i in range(positions.shape[0]): text_labels[i].remove()
class Animator(object): def __init__(self, template_w, template_h): #set up figure plt.ion() fig = plt.figure(figsize = (10,10)) ax = fig.gca() ax.axis([-template_w/2.0, template_w/2.0,-template_h/2.0,template_h/2.0]) ax.get_xaxis().set_visible(True) ax.get_yaxis().set_visible(True) #draw template self.plot_template(template_w,template_h) #draw to screen plt.draw() plt.pause(0.1) #save axes to object self.ax = ax #plot template def plot_template(self,l = 20.0, w = 20.0): x_pos = [-l/2, l/2, l/2, -l/2, -l/2 ] y_pos = [-w/2, -w/2, w/2, w/2, -w/2] plt.plot(x_pos,y_pos,'k-',linewidth = 3.0) plt.xlabel('x') plt.ylabel('y') def generate_color_array(self,collision): #define colors (red = collision, blue = no collision) colors = [None] * len(collision) for i in range(len(collision)): if collision[i] == True: colors[i] = (1.0,0.0,0.0) else: colors[i] = (0.0,0.0,1.0) return colors #add circular objects def add_circular_objects(self,diameters,positions,collision): circ_colors = self.generate_color_array(collision) self.circles = EllipseCollection(widths=diameters, heights=diameters, angles=np.zeros_like(diameters), units='xy', offsets=positions, transOffset=self.ax.transData, edgecolor='k', facecolor=circ_colors) self.ax.add_collection(self.circles) #add text label text_labels = [None] * len(collision) for i in range(len(collision)): text_labels[i]= plt.text(positions[i,0],positions[i,1],str(i),color = 'w') self.circle_labels = text_labels #draw to screen plt.draw() plt.pause(0.1) #remove text labels #for i in range(len(collision)): # text_labels[i].remove() #add polygon objects def add_polygon_objects(self,verts,collision): poly_colors = self.generate_color_array(collision) self.polygons = PolyCollection(verts, facecolors=poly_colors) self.ax.add_collection(self.polygons) #add text label num_circles = self.circles.get_offsets().shape[1] text_labels = [None] * len(collision) for i in range(len(collision)): temp = np.array(verts[i]) x = np.mean(temp[:,0]) y = np.mean(temp[:,1]) text_labels[i]= plt.text(x,y,str(i+num_circles),color = 'w') self.polygon_labels = text_labels plt.draw() plt.pause(0.1) #remove text labels #for i in range(len(collision)): # text_labels[i].remove() #remove circular objects: def remove_circles(self): self.circles.remove() for label in self.circle_labels: label.remove() #remove polygon objects: def remove_polygons(self): self.polygons.remove() for label in self.polygon_labels: label.remove() #update circular objects def update_circular_objects(self,positions,collision): #set circle colors circ_colors = self.generate_color_array(collision) self.circles.set_facecolors(circ_colors) #set circle positions self.circles.set_offsets(positions) #remove labels for label in self.circle_labels: label.remove() #add labels text_labels = [None] * len(collision) for i in range(len(collision)): text_labels[i]= plt.text(positions[i,0],positions[i,1],str(i),color = 'w') self.circle_labels = text_labels plt.draw() plt.pause(0.1) #update polygon objects def update_polygon_objects(self,positions,collision): #set polygon colors poly_colors = self.generate_color_array(collision) self.polygons.set_facecolors(poly_colors) #set polygon positions #print 'new verts positions=' , positions self.polygons.set_verts(positions) #remove labels for label in self.polygon_labels: label.remove() #add new labels num_circles = self.circles.get_offsets().shape[1] #print self.polygons.get_offsets() #assert(0) text_labels = [None] * len(collision) for i in range(len(collision)): temp = np.array(positions[i]) x = np.mean(temp[:,0]) y = np.mean(temp[:,1]) text_labels[i]= plt.text(x,y,str(i+num_circles),color = 'w') self.polygon_labels = text_labels plt.draw() plt.pause(0.1)
def set_verts(self, verts, closed=True): '''Set 3D vertices.''' self.get_vector(verts) PolyCollection.set_verts(self, [], closed)
class Bar: """ Bar (histogram) """ def __init__(self, ax, transform, Z, facecolors="white", edgecolors="black", linewidth=0, clip=False): """ """ self.Z = Z if isinstance(facecolors, np.ndarray): shape = facecolors.shape facecolors = facecolors.reshape(-1, shape[-1]) facecolors = mpl.colors.to_rgba_array(facecolors) self.facecolors = facecolors.reshape(shape[0], shape[1], 4) else: shape = Z.shape self.facecolors = np.zeros((shape[0], shape[1], 4)) self.facecolors[...] = mpl.colors.to_rgba(facecolors) if isinstance(edgecolors, np.ndarray): shape = edgecolors.shape edgecolors = edgecolors.reshape(-1, shape[-1]) edgecolors = mpl.colors.to_rgba_array(edgecolors) self.edgecolors = edgecolors.reshape(shape[0], shape[1], 4) else: shape = Z.shape self.edgecolors = np.zeros((shape[0], shape[1], 4)) self.edgecolors[...] = mpl.colors.to_rgba(edgecolors) self.linewidth = linewidth self.xlim = -0.5, +0.50 self.ylim = -0.5, +0.50 self.zlim = -0.5, +0.50 self.clip = clip # Because all the bars have the same orientation, we can use a hack to # shade each face at once instead of computing individual face lighting. self.shade = np.array([[1.00, 1.00, 0.75, 1.00, 0.50, 1.00]]) self.collection = PolyCollection([], clip_on=self.clip, snap=False) self.update(transform) ax.add_collection(self.collection, autolim=False) def update(self, transform): """ """ Z = self.Z xmin, xmax = self.xlim ymin, ymax = self.ylim zmin, zmax = self.zlim dx, dy = 0.5 * 1 / Z.shape[0], 0.5 * 1 / Z.shape[1] # Each bar is described by 8 vertices and 6 faces V = np.zeros((Z.shape[0], Z.shape[1], 8, 3)) F = np.zeros((Z.shape[0], Z.shape[1], 6, 4), dtype=int) # Face and edge colors for the six faces FC = np.zeros((Z.shape[0], Z.shape[1], 6, 4)) FC[:, :] = self.facecolors.reshape(Z.shape[0], Z.shape[1], 1, 4) FC *= self.shade.T FC[:, :, :, 3] = 1 EC = np.zeros((Z.shape[0], Z.shape[1], 6, 4)) EC[:, :] = self.edgecolors.reshape(Z.shape[0], Z.shape[1], 1, 4) # Build vertices X, Y = np.meshgrid(np.linspace(xmin, xmax, Z.shape[0]), np.linspace(ymin, ymax, Z.shape[1])) V[..., 0] = X.reshape(Z.shape[0], Z.shape[1], 1) V[..., 1] = Y.reshape(Z.shape[0], Z.shape[1], 1) V[:, :, 0] += [+dx, +dy, zmin] V[:, :, 1] += [+dx, -dy, zmin] V[:, :, 2] += [-dx, -dy, zmin] V[:, :, 3] += [-dx, +dy, zmin] V[:, :, 4] += [+dx, +dy, zmin] V[:, :, 5] += [+dx, -dy, zmin] V[:, :, 6] += [-dx, -dy, zmin] V[:, :, 7] += [-dx, +dy, zmin] V[:, :, 4:, 2] += Z.reshape(Z.shape[0], Z.shape[1], 1) # Build faces I = 8 * np.arange(Z.shape[0] * Z.shape[1]) F[:, :] = I.reshape(Z.shape[0], Z.shape[1], 1, 1) F[:, :] += [ [0, 1, 2, 3], # -Z [0, 1, 5, 4], # +X [2, 3, 7, 6], # -X [1, 2, 6, 5], # -Y [0, 3, 7, 4], # +Y [4, 5, 6, 7] ] # +Z # Actual transformation V = V.reshape(-1, 3) V = glm.transform(V[F], transform) #[...,:2] # Depth computation # We combine the global "depth" of the bar (depth of the bottom face) # and the local depth of each face. This trick avoids problems when # sorting all the different faces. Z1 = (V[:, :, 0, :, 2].mean(axis=2)).reshape(Z.shape[0], Z.shape[1], 1) Z2 = (V[..., 2].mean(axis=3) + 10 * Z1).ravel() # Sorting I = np.argsort(-Z2) V = (V[..., :2].reshape(Z.shape[0] * Z.shape[1] * 6, 4, 2)) self.collection.set_verts(V[I]) self.collection.set_facecolors(FC.reshape(-1, 4)[I]) self.collection.set_edgecolors(EC.reshape(-1, 4)[I]) self.collection.set_linewidths(self.linewidth) if self.linewidth == 0.0: self.collection.set_antialiased(False) else: self.collection.set_antialiased(True)
def set_verts(self, verts, closed=True): """Set 3D vertices.""" self.get_vector(verts) # 2D verts will be updated at draw time PolyCollection.set_verts(self, [], False) self._closed = closed
class Mesh(): """ Mesh described by vertices and faces """ def __init__(self, ax, transform, vertices, faces, cmap=None, facecolors="white", edgecolors="black", linewidths=0.5, mode="front"): """ """ self.collection = PolyCollection([], clip_on=False, snap=False) self.vertices = vertices self.faces = faces self.cmap = cmap self.facecolors = mpl.colors.to_rgba_array(facecolors) self.edgecolors = mpl.colors.to_rgba_array(edgecolors) self.linewidths = linewidths self.mode = mode self.update(transform) ax.add_collection(self.collection, autolim=False) def update(self, transform): """ Update mesh according to transform (4x4 array) """ T = glm.transform(self.vertices, transform)[self.faces] Z = -T[:, :, 2].mean(axis=1) if self.cmap is not None: # Facecolors using depth buffer norm = mpl.colors.Normalize(vmin=Z.min(), vmax=Z.max()) facecolors = self.cmap(norm(Z)) else: facecolors = self.facecolors edgecolors = self.edgecolors linewidths = self.linewidths # Back face culling if self.mode == "front": front, back = glm.frontback(T) T, Z = T[front], Z[front] if len(facecolors) == len(self.faces): facecolors = facecolors[front] if len(edgecolors) == len(self.faces): edgecolors = edgecolors[front] # Front face culling elif self.mode == "back": front, back = glm.frontback(T) T, Z = T[back], Z[back] if len(facecolors) == len(faces): facecolors = facecolors[back] if len(edgecolor) == len(faces): edgecolors = edgecolors[back] # Separate 2d triangles from zbuffer triangles = T[:, :, :2] antialiased = linewidths > 0 # Sort triangles according to z buffer I = np.argsort(Z) triangles = triangles[I, :] if len(facecolors) == len(I): facecolors = facecolors[I, :] if len(edgecolors) == len(I): edgecolors = edgecolors[I, :] self.collection.set_verts(triangles) self.collection.set_linewidths(linewidths) self.collection.set_facecolors(facecolors) self.collection.set_edgecolors(edgecolors) self.collection.set_antialiased(antialiased)
def set_verts(self, verts, closed=True): '''Set 3D vertices.''' self.get_vector(verts) # 2D verts will be updated at draw time PolyCollection.set_verts(self, [], closed)
class Animator(object): def __init__(self, template_w, template_h): #set up figure plt.ion() #fig = plt.figure(figsize = (10,10)) fig = plt.figure(figsize=(template_w, template_h)) #print template_w, template_h #raw_input() ax = fig.gca() #set axis dimension ax.axis([ -2 * template_w / 2.0, 2 * template_w / 2.0, -2 * template_h / 2.0, 2 * template_h / 2.0 ]) #ax.axis([-template_w/2.0, template_w/2.0,-template_h/2.0,template_h/2.0]) ax.get_xaxis().set_visible(True) ax.get_yaxis().set_visible(True) #draw template self.plot_template(template_w, template_h) #draw to screen plt.draw() plt.pause(0.1) #save axes to object self.ax = ax #save animator canvas area self.width = template_w self.height = template_h self.title = plt.text(0, 20, 'start title', color='k') #plot template def plot_template(self, l=20.0, w=20.0): x_pos = [-l / 2, l / 2, l / 2, -l / 2, -l / 2] y_pos = [-w / 2, -w / 2, w / 2, w / 2, -w / 2] plt.plot(x_pos, y_pos, 'k-', linewidth=3.0) plt.xlabel('x') plt.ylabel('y') def generate_color_array(self, collision): #define colors (red = collision, blue = no collision) colors = [None] * len(collision) for i in range(len(collision)): if collision[i] == True: colors[i] = (1.0, 0.0, 0.0) else: colors[i] = (0.0, 0.0, 1.0) return colors #add circular objects def add_circular_objects(self, diameters, positions, collision, pause_time=0.1): circ_colors = self.generate_color_array(collision) self.circles = EllipseCollection(widths=diameters, heights=diameters, angles=np.zeros_like(diameters), units='xy', offsets=positions, transOffset=self.ax.transData, edgecolor='k', facecolor=circ_colors) self.ax.add_collection(self.circles) #add text label text_labels = [None] * len(collision) for i in range(len(collision)): text_labels[i] = plt.text(positions[i, 0], positions[i, 1], str(i), color='k') self.circle_labels = text_labels #draw to screen #plt.draw() #plt.pause(pause_time) #remove text labels #for i in range(len(collision)): # text_labels[i].remove() #add polygon objects def add_polygon_objects(self, verts, collision, pause_time=0.1): poly_colors = self.generate_color_array(collision) self.polygons = PolyCollection(verts, facecolors=poly_colors) self.ax.add_collection(self.polygons) #add text label num_circles = self.circles.get_offsets().shape[0] #print 'number of circles =', num_circles text_labels = [None] * len(collision) for i in range(len(collision)): temp = np.array(verts[i]) x = np.mean(temp[:, 0]) y = np.mean(temp[:, 1]) text_labels[i] = plt.text(x, y, str(i + num_circles), color='k') self.polygon_labels = text_labels plt.draw() plt.pause(pause_time) #remove text labels #for i in range(len(collision)): # text_labels[i].remove() #remove circular objects: def remove_circles(self): self.circles.remove() for label in self.circle_labels: label.remove() #remove polygon objects: def remove_polygons(self): self.polygons.remove() for label in self.polygon_labels: label.remove() #update circular objects def update_circular_objects(self, positions, collision, pause_time=0.1): #set circle colors circ_colors = self.generate_color_array(collision) self.circles.set_facecolors(circ_colors) #set circle positions self.circles.set_offsets(positions) #remove labels for label in self.circle_labels: label.remove() #add labels text_labels = [None] * len(collision) for i in range(len(collision)): text_labels[i] = plt.text(positions[i, 0], positions[i, 1], str(i), color='k') self.circle_labels = text_labels plt.draw() plt.pause(pause_time) #update polygon objects def update_polygon_objects(self, positions, collision, pause_time=0.1): #set polygon colors poly_colors = self.generate_color_array(collision) self.polygons.set_facecolors(poly_colors) #set polygon positions #print 'new verts positions=' , positions self.polygons.set_verts(positions) #remove labels for label in self.polygon_labels: label.remove() #self.title.remove() #add new labels num_circles = self.circles.get_offsets().shape[0] #print self.polygons.get_offsets() #assert(0) text_labels = [None] * len(collision) for i in range(len(collision)): temp = np.array(positions[i]) x = np.mean(temp[:, 0]) y = np.mean(temp[:, 1]) text_labels[i] = plt.text(x, y, str(i + num_circles), color='k') self.polygon_labels = text_labels plt.draw() plt.pause(pause_time) #display the total area covered def show_title(self, area, pause_time=0.1): title = plt.text(-self.width / 4, self.height, 'total covered area = ' + str(area), color='k', fontsize=20) self.title.remove() self.title = title