Ejemplo n.º 1
0
    def bounding_box(self, data, ax, label, bBoundingBoxes, bLabels):
        """Draw bounding box around data."""

        data = np.array(data)

        width = max(data[:, 0]) - min(data[:, 0])
        height = max(data[:, 1]) - min(data[:, 1])
        r = Rectangle((min(data[:, 0]), min(data[:, 1])), width, height)

        if bBoundingBoxes:
            ax.add_artist(r)
            r.set_clip_box(ax.bbox)
            r.set_alpha(0.1)
            r.set_facecolor((0.5, 0.5, 0.5))

        if bLabels:
            ax.annotate(label,
                        xy=(min(data[:, 0]), max(data[:, 1])),
                        xytext=(0, 0),
                        textcoords='offset points',
                        ha='right',
                        va='bottom',
                        bbox=dict(boxstyle='round,pad=0.5',
                                  fc=(0.5, 0.5, 0.5),
                                  alpha=0.1))
Ejemplo n.º 2
0
def draw_box(x1, x2, y1, y2, ax, col):
    c = array([[x1], [y1]])
    rect = Rectangle(c, width=x2 - x1, height=y2 - y1, angle=0)
    rect.set_facecolor(array([0.4, 0.3, 0.6]))
    ax.add_patch(rect)
    rect.set_clip_box(ax.bbox)
    rect.set_alpha(0.7)
    rect.set_facecolor(col)
Ejemplo n.º 3
0
    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 = []
Ejemplo n.º 4
0
 def draw_filled_rectangle(self, x, y, width, height):
     r = Rectangle((x, y),
                   width,
                   height,
                   self.angle,
                   color=self.draw_color,
                   fill=True)
     r.set_clip_box(self.a.bbox)
     self.a.add_artist(r)
Ejemplo n.º 5
0
    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_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)
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
0
class rectSelection(GuiSelection):
    """Interactive selection of a rectangular region on the axis.

    Used by hist2d_alex().
    """
    def on_press_draw(self):
        if 'r' in self.__dict__:
            self.r.set_height(0)
            self.r.set_width(0)
            self.r.set_xy((self.xs, self.ys))
            self.e.height = 0
            self.e.width = 0
            self.e.center = (self.xs, self.ys)
        else:
            self.r = Rectangle(xy=(self.xs, self.ys),
                               height=0,
                               width=0,
                               fill=False,
                               lw=2,
                               alpha=0.5,
                               color='blue')
            self.e = Ellipse(xy=(self.xs, self.ys),
                             height=0,
                             width=0,
                             fill=False,
                             lw=2,
                             alpha=0.6,
                             color='blue')
            self.ax.add_artist(self.r)
            self.ax.add_artist(self.e)
            self.r.set_clip_box(self.ax.bbox)
            self.r.set_zorder(10)
            self.e.set_clip_box(self.ax.bbox)
            self.e.set_zorder(10)

    def on_motion_draw(self):
        self.r.set_height(self.ye - self.ys)
        self.r.set_width(self.xe - self.xs)
        self.e.height = (self.ye - self.ys)
        self.e.width = (self.xe - self.xs)
        self.e.center = (np.mean([self.xs,
                                  self.xe]), np.mean([self.ys, self.ye]))
        self.fig.canvas.draw()

    def on_release_print(self):
        # This is the only custom method for hist2d_alex()
        E1, E2 = min((self.xs, self.xe)), max((self.xs, self.xe))
        S1, S2 = min((self.ys, self.ye)), max((self.ys, self.ye))
        self.selection = dict(E1=E1, E2=E2, S1=S1, S2=S2)
        pprint("Selection: \nE1=%.2f, E2=%.2f, S1=%.2f, S2=%.2f\n" %\
                (E1,E2,S1,S2))
    def plot_rectangle(bboxes, ax, step, c='#ff7f0e'):

        for bbox in bboxes[bboxes['ts'] % step == 0]:
            s_phi_offset, c_phi_offset = np.sin(bbox['orientation']), np.cos(bbox['orientation'])
            rot = np.array([[c_phi_offset, - s_phi_offset], [s_phi_offset, c_phi_offset]])
            offset_xy = np.dot(rot, 0.5 * bbox['dimension'])

            r = Rectangle(xy=bbox['center_xy'] - offset_xy, width=bbox['dimension'][0], height=bbox['dimension'][1],
                          angle=np.rad2deg(bbox['orientation']))

            ax.add_artist(r)
            r.set_clip_box(ax.bbox)
            r.set_alpha(0.8)
            r.set_facecolor('none')
            r.set_edgecolor(c)
Ejemplo n.º 10
0
    def highlight_artist(self, val, artist=None):
        figure = self.get_figpage()._artists[0]
        ax = self.get_figaxes()
        if val:
            if len(self._artists[0].figobj_hl) != 0:
                return
            box = self.get_artist_extent_all()
            self._artist_extent = box
            if box[0] is None:
                return
            x = [box[0], box[0], box[1], box[1], box[0]]
            y = [box[3], box[2], box[2], box[3], box[3]]

            hl = Line2D(x,
                        y,
                        marker='s',
                        color='k',
                        linestyle='None',
                        markerfacecolor='k',
                        markeredgewidth=0.5,
                        figure=figure,
                        alpha=0.3)
            figure.lines.append(hl)
            xy = (box[0], box[2])
            w = box[1] - box[0]
            h = box[3] - box[2]
            hlp = Rectangle(xy, w, h, alpha=0.3, facecolor='k', figure=figure)
            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)
            #           if ax is not None and ax.get_3d():
            #               import mpl_toolkits.mplot3d.art3d as art3d
            #               art3d.patch_2d_to_3d(hl)
            #               if len(ax._artists) != 0:
            #                   a.axes = self.get_figaxes()._artists[0]
            self._artists[0].figobj_hl.extend([hl, hlp])
        else:
            if len(self._artists[0].figobj_hl) == 2:
                figure.lines.remove(self._artists[0].figobj_hl[0])
                figure.patches.remove(self._artists[0].figobj_hl[1])
            self._artists[0].figobj_hl = []
Ejemplo n.º 11
0
	def boundingBox(self, data, ax, label, bBoundingBoxes, bLabels):
		''' Draw bounding box around data.'''
		data = np.array(data)
	
		width = max(data[:,0]) - min(data[:,0])
		height = max(data[:,1]) - min(data[:,1])
		r = Rectangle((min(data[:,0]), min(data[:,1])), width, height)
	
		if bBoundingBoxes:
			ax.add_artist(r)
			r.set_clip_box(ax.bbox)
			r.set_alpha(0.1)
			r.set_facecolor((0.5, 0.5, 0.5))
			
		if bLabels:
			ax.annotate(label, xy = (min(data[:,0]), max(data[:,1])), xytext = (0, 0),
							textcoords = 'offset points', ha = 'right', va = 'bottom',
							bbox = dict(boxstyle = 'round,pad=0.5', fc = (0.5, 0.5, 0.5), alpha = 0.1))
Ejemplo n.º 12
0
    def visualize_generation(self, generation):
        """
        Draw each ab combination color and size coded
        :param generation:
        :param ax:
        :return:
        """

        fig, ax = plt.subplots()

        # ax.clear()
        for ind in range(len(self.ga_solver.population[generation])):

            child = self.ga_solver.population[generation][ind]

            xy = self._ab_to_xy(child)
            rect = Rectangle(xy=xy, width=0.5, height=0.5, angle=90)
            ax.add_artist(rect)

            rect.set_clip_box(ax.bbox)
            # alpha = float(child[3]) / ANTIBODY_CNT
            # rgb = [float(child[0])/ANTIBODY_CNT, float(child[1])/ANTIBODY_CNT, float(child[2])/ANTIBODY_CNT/ ANTIBODY_CNT]
            #
            # rect.set_alpha(alpha)
            # rect.set_facecolor(rgb)

            fitness = self.ga_solver.get_fitness_value(child)

            if fitness > 0.5:
                rect.set_facecolor('r')
            else:
                rect.set_facecolor('b')

            rect.set_width(fitness * 100)
            rect.set_height(fitness * 100)

        ax.set_xlim(
            0, self.ga_solver.antibody_cnt * self.ga_solver.antibody_cnt + 10)
        ax.set_ylim(
            0, self.ga_solver.antibody_cnt * self.ga_solver.antibody_cnt + 10)

        plt.show()
        plt.pause(1)
        plt.close()
Ejemplo n.º 13
0
class rectSelection(GuiSelection):
    """Interactive selection of a rectangular region on the axis.

    Used by hist2d_alex().
    """
    def on_press_draw(self):
        if 'r' in self.__dict__:
            self.r.set_height(0)
            self.r.set_width(0)
            self.r.set_xy((self.xs, self.ys))
            self.e.height = 0
            self.e.width = 0
            self.e.center = (self.xs, self.ys)
        else:
            self.r = Rectangle(xy=(self.xs, self.ys), height=0, width=0,
                               fill=False, lw=2, alpha=0.5, color='blue')
            self.e = Ellipse(xy=(self.xs, self.ys), height=0, width=0,
                    fill=False, lw=2, alpha=0.6, color='blue')
            self.ax.add_artist(self.r)
            self.ax.add_artist(self.e)
            self.r.set_clip_box(self.ax.bbox)
            self.r.set_zorder(10)
            self.e.set_clip_box(self.ax.bbox)
            self.e.set_zorder(10)

    def on_motion_draw(self):
        self.r.set_height(self.ye - self.ys)
        self.r.set_width(self.xe - self.xs)
        self.e.height = (self.ye - self.ys)
        self.e.width = (self.xe - self.xs)
        self.e.center = (np.mean([self.xs, self.xe]),
                         np.mean([self.ys, self.ye]))
        self.fig.canvas.draw()

    def on_release_print(self):
        # This is the only custom method for hist2d_alex()
        E1, E2 = min((self.xs, self.xe)), max((self.xs, self.xe))
        S1, S2 = min((self.ys, self.ye)), max((self.ys, self.ye))
        self.selection = dict(E1=E1, E2=E2, S1=S1, S2=S2)
        pprint("Selection: \nE1=%.2f, E2=%.2f, S1=%.2f, S2=%.2f\n" %\
                (E1,E2,S1,S2))
Ejemplo n.º 14
0
    def highlight_artist(self, val, artist=None):
        figure=self.get_figpage()._artists[0]
        ax = self.get_figaxes()
        if val:
           if len(self._artists[0].figobj_hl) != 0: return
           box = self.get_artist_extent_all()
           self._artist_extent = box
           if box[0] is None: return
           x = [box[0], box[0], box[1], box[1], box[0]]
           y = [box[3], box[2], box[2], box[3], box[3]]

           hl= Line2D(x, y, marker='s', 
                                 color='k', linestyle='None',
                                 markerfacecolor='k',
                                 markeredgewidth =  0.5,                      
                                 figure=figure, alpha=0.3)
           figure.lines.append(hl)
           xy = (box[0], box[2])
           w = box[1] - box[0]
           h = box[3] - box[2]
           hlp = Rectangle(xy, w, h, alpha=0.3, facecolor='k',
                     figure = figure)
           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)
#           if ax is not None and ax.get_3d():
#               import mpl_toolkits.mplot3d.art3d as art3d
#               art3d.patch_2d_to_3d(hl)
#               if len(ax._artists) != 0:
#                   a.axes = self.get_figaxes()._artists[0]
           self._artists[0].figobj_hl.extend([hl, hlp])
        else:
           if len(self._artists[0].figobj_hl) == 2:
              figure.lines.remove(self._artists[0].figobj_hl[0])
              figure.patches.remove(self._artists[0].figobj_hl[1])
           self._artists[0].figobj_hl = []
Ejemplo n.º 15
0
class xspanSelection(GuiSelection):
    """Interactive selection of an x range on the axis"""
    def on_press_draw(self):
        if 'r' in self.__dict__:
            self.r.set_width(0)
            self.r.set_xy((self.xs, self.ax.get_ylim()[0]))
            self.r.set_height(self.ax.get_ylim()[1] - self.ax.get_ylim()[0])
        else:
            self.r = Rectangle(xy=(self.xs, self.ax.get_ylim()[0]),
                               height=self.ax.get_ylim()[1] - \
                                      self.ax.get_ylim()[0],
                               width=0, fill=True, lw=2, alpha=0.5,
                               color='blue')
            self.ax.add_artist(self.r)
            self.r.set_clip_box(self.ax.bbox)
            self.r.set_zorder(10)

    def on_motion_draw(self):
        self.r.set_width(self.xe - self.xs)

    def on_release_print(self):
        pprint('X Span: (%d, %d)\n' % (self.xs, self.xe))
Ejemplo n.º 16
0
class xspanSelection(GuiSelection):
    """Interactive selection of an x range on the axis"""
    def on_press_draw(self):
        if 'r' in self.__dict__:
            self.r.set_width(0)
            self.r.set_xy((self.xs, self.ax.get_ylim()[0]))
            self.r.set_height(self.ax.get_ylim()[1] - self.ax.get_ylim()[0])
        else:
            self.r = Rectangle(xy=(self.xs, self.ax.get_ylim()[0]),
                               height=self.ax.get_ylim()[1] - \
                                      self.ax.get_ylim()[0],
                               width=0, fill=True, lw=2, alpha=0.5,
                               color='blue')
            self.ax.add_artist(self.r)
            self.r.set_clip_box(self.ax.bbox)
            self.r.set_zorder(10)

    def on_motion_draw(self):
        self.r.set_width(self.xe - self.xs)

    def on_release_print(self):
        pprint('X Span: (%d, %d)\n' % (self.xs, self.xe))
Ejemplo n.º 17
0
    def _init_legend_box(self, handles, labels):
        """
        Initiallize the legend_box. The legend_box is an instance of
        the OffsetBox, which is packed with legend handles and
        texts. Once packed, their location is calculated during the
        drawing time.
        """

        fontsize = self.fontsize

        # legend_box is a HPacker, horizontally packed with
        # columns. Each column is a VPacker, vertically packed with
        # legend items. Each legend item is HPacker packed with
        # legend handleBox and labelBox. handleBox is an instance of
        # offsetbox.DrawingArea which contains legend handle. labelBox
        # is an instance of offsetbox.TextArea which contains legend
        # text.

        text_list = []  # the list of text instances
        handle_list = []  # the list of text instances

        label_prop = dict(
            verticalalignment='baseline',
            horizontalalignment='left',
            fontproperties=self.prop,
        )

        labelboxes = []

        for l in labels:
            textbox = TextArea(l,
                               textprops=label_prop,
                               multilinebaseline=True,
                               minimumdescent=True)
            text_list.append(textbox._text)
            labelboxes.append(textbox)

        handleboxes = []

        # The approximate height and descent of text. These values are
        # only used for plotting the legend handle.
        height = self._approx_text_height() * 0.7
        descent = 0.

        # each handle needs to be drawn inside a box of (x, y, w, h) =
        # (0, -descent, width, height).  And their corrdinates should
        # be given in the display coordinates.

        # NOTE : the coordinates will be updated again in
        # _update_legend_box() method.

        # The transformation of each handle will be automatically set
        # to self.get_trasnform(). If the artist does not uses its
        # default trasnform (eg, Collections), you need to
        # manually set their transform to the self.get_transform().

        for handle in handles:
            if isinstance(handle, RegularPolyCollection):
                npoints = self.scatterpoints
            else:
                npoints = self.numpoints
            if npoints > 1:
                # we put some pad here to compensate the size of the
                # marker
                xdata = np.linspace(0.3 * fontsize,
                                    (self.handlelength - 0.3) * fontsize,
                                    npoints)
                xdata_marker = xdata
            elif npoints == 1:
                xdata = np.linspace(0, self.handlelength * fontsize, 2)
                xdata_marker = [0.5 * self.handlelength * fontsize]

            if isinstance(handle, Line2D):
                ydata = ((height - descent) / 2.) * np.ones(xdata.shape, float)
                legline = Line2D(xdata, ydata)

                legline.update_from(handle)
                self._set_artist_props(legline)  # after update
                legline.set_clip_box(None)
                legline.set_clip_path(None)
                legline.set_drawstyle('default')
                legline.set_marker('None')

                handle_list.append(legline)

                legline_marker = Line2D(xdata_marker,
                                        ydata[:len(xdata_marker)])
                legline_marker.update_from(handle)
                self._set_artist_props(legline_marker)
                legline_marker.set_clip_box(None)
                legline_marker.set_clip_path(None)
                legline_marker.set_linestyle('None')
                # we don't want to add this to the return list because
                # the texts and handles are assumed to be in one-to-one
                # correpondence.
                legline._legmarker = legline_marker

            elif isinstance(handle, Patch):
                p = Rectangle(
                    xy=(0., 0.),
                    width=self.handlelength * fontsize,
                    height=(height - descent),
                )
                p.update_from(handle)
                self._set_artist_props(p)
                p.set_clip_box(None)
                p.set_clip_path(None)
                handle_list.append(p)
            elif isinstance(handle, LineCollection):
                ydata = ((height - descent) / 2.) * np.ones(xdata.shape, float)
                legline = Line2D(xdata, ydata)
                self._set_artist_props(legline)
                legline.set_clip_box(None)
                legline.set_clip_path(None)
                lw = handle.get_linewidth()[0]
                dashes = handle.get_dashes()[0]
                color = handle.get_colors()[0]
                legline.set_color(color)
                legline.set_linewidth(lw)
                legline.set_dashes(dashes)
                handle_list.append(legline)

            elif isinstance(handle, RegularPolyCollection):

                #ydata = self._scatteryoffsets
                ydata = height * self._scatteryoffsets

                size_max, size_min = max(handle.get_sizes()),\
                                     min(handle.get_sizes())
                # we may need to scale these sizes by "markerscale"
                # attribute. But other handle types does not seem
                # to care about this attribute and it is currently ignored.
                if self.scatterpoints < 4:
                    sizes = [.5 * (size_max + size_min), size_max, size_min]
                else:
                    sizes = (size_max - size_min) * np.linspace(
                        0, 1, self.scatterpoints) + size_min

                p = type(handle)(
                    handle.get_numsides(),
                    rotation=handle.get_rotation(),
                    sizes=sizes,
                    offsets=zip(xdata_marker, ydata),
                    transOffset=self.get_transform(),
                )

                p.update_from(handle)
                p.set_figure(self.figure)
                p.set_clip_box(None)
                p.set_clip_path(None)
                handle_list.append(p)

            else:
                handle_list.append(None)

            handlebox = DrawingArea(width=self.handlelength * fontsize,
                                    height=height,
                                    xdescent=0.,
                                    ydescent=descent)

            handle = handle_list[-1]
            handlebox.add_artist(handle)
            if hasattr(handle, "_legmarker"):
                handlebox.add_artist(handle._legmarker)
            handleboxes.append(handlebox)

        # We calculate number of lows in each column. The first
        # (num_largecol) columns will have (nrows+1) rows, and remaing
        # (num_smallcol) columns will have (nrows) rows.
        nrows, num_largecol = divmod(len(handleboxes), self._ncol)
        num_smallcol = self._ncol - num_largecol

        # starting index of each column and number of rows in it.
        largecol = safezip(range(0, num_largecol * (nrows + 1), (nrows + 1)),
                           [nrows + 1] * num_largecol)
        smallcol = safezip(
            range(num_largecol * (nrows + 1), len(handleboxes), nrows),
            [nrows] * num_smallcol)

        handle_label = safezip(handleboxes, labelboxes)
        columnbox = []
        for i0, di in largecol + smallcol:
            # pack handleBox and labelBox into itemBox
            itemBoxes = [
                HPacker(pad=0,
                        sep=self.handletextpad * fontsize,
                        children=[h, t],
                        align="baseline") for h, t in handle_label[i0:i0 + di]
            ]
            # minimumdescent=False for the text of the last row of the column
            itemBoxes[-1].get_children()[1].set_minimumdescent(False)

            # pack columnBox
            columnbox.append(
                VPacker(pad=0,
                        sep=self.labelspacing * fontsize,
                        align="baseline",
                        children=itemBoxes))

        if self._mode == "expand":
            mode = "expand"
        else:
            mode = "fixed"

        sep = self.columnspacing * fontsize

        self._legend_box = HPacker(pad=self.borderpad * fontsize,
                                   sep=sep,
                                   align="baseline",
                                   mode=mode,
                                   children=columnbox)

        self._legend_box.set_figure(self.figure)

        self.texts = text_list
        self.legendHandles = handle_list
Ejemplo n.º 18
0
    def highlight_artist(self, val, artist=None):
        from ifigure.matplotlib_mod.art3d_gl import Poly3DCollectionGL
        from ifigure.matplotlib_mod.art3d_gl import Line3DCollectionGL        
        figure=self.get_figpage()._artists[0]
        ax = self.get_figaxes()
        if artist is None:
           alist=self._artists
        else:
           alist=artist 

        if val == True:
           if self._parent is None: return
           container = self.get_container()
           if container is None: return

           if isinstance(alist[0], Poly3DCollectionGL):
               hl = alist[0].add_hl_mask()               
               for item in hl:
                   alist[0].figobj_hl.append(item)
           else:          
               de = self.get_data_extent()
               x=(de[0], de[1],de[1],de[0],de[0])
               y=(de[2], de[2],de[3],de[3],de[2])

               facecolor='k'
               if isinstance(alist[0], Poly3DCollectionGL):
                   hl = alist[0].make_hl_artist(container)
                   facecolor = 'none'
                   self._hit_path = None               
               elif isinstance(alist[0], Line3DCollectionGL):
                   hl = alist[0].make_hl_artist(container)
                   facecolor = 'none'
                   self._hit_path = None
               else:
                   hl= container.plot(x, y, marker='s', 
                                     color='k', linestyle='None',
                                     markerfacecolor='None',
                                     markeredgewidth =  0.5,                                  
                                     scalex=False, scaley=False)
               for item in hl:
                  alist[0].figobj_hl.append(item)


               if self._hit_path is not None:
                  v = self._hit_path.vertices
                  hl= container.plot(v[:,0], v[:,1], marker='s', 
                                     color='k', linestyle='None',
                                     markerfacecolor='None',
                                     markeredgewidth =  0.5,  
                                     scalex=False, scaley=False)
                  for item in hl:
                     alist[0].figobj_hl.append(item)

               hlp = Rectangle((de[0],de[2]),
                                de[1]-de[0],
                                de[3]-de[2],
                                alpha=0.3, facecolor=facecolor,
                                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)
               alist[0].figobj_hl.append(hlp)
        else:
           for a in alist:
              if len(a.figobj_hl) == 0: continue
              for hl in a.figobj_hl[:-1]:
                 hl.remove()
              if isinstance(alist[0], Poly3DCollectionGL):
                 a.figobj_hl[-1].remove()
              else:
                  figure.patches.remove(a.figobj_hl[-1])
              a.figobj_hl=[]
Ejemplo n.º 19
0
def plot_state_dependency_matrix(model, direct=False, knockout=[], axes=None):
    """
    Creates a matrix showing state variable dependency distances.

    To show only direct (first-order) dependencies, set the optional argument
    ``direct`` to ``True``.

    Variables can be "knocked out" by adding them to the list in the
    ``knockout`` parameter. If x depends on y and y depends on z, knocking out
    y will prevent the method from findind x's dependency on z.

    Returns a matplotlib axes object.
    """
    import matplotlib.pyplot as plt

    # Create dependency matrix
    m = create_state_dependency_matrix(model, direct, knockout)
    n = len(m)

    # Configure axes
    a = axes if axes is not None else plt.gca()
    a.set_aspect('equal')
    a.set_xlim(0, n + 2)
    a.set_ylim(0, n)

    # Create matrix plot
    from matplotlib.patches import Rectangle
    w = 1.0 / (max(max(m)))  # color weight
    p1 = 0.1  # Padding
    p2 = 1.0 - 2 * p1  # Square size

    def c(v):
        # Colormap
        if v == 1:
            return (0, 0, 0)
        else:
            vv = v * w
            if (vv > 1.0):
                return (0, 1.0, 0)
            return (vv, vv, 1.0)

    for y, row in enumerate(m):
        y = n - y - 1
        for x, v in enumerate(row):
            r = Rectangle((x + p1, y + p1), p2, p2, color=c(v))
            a.add_patch(r)
            r.set_clip_box(a.bbox)

        # Add colorbar
        r = Rectangle((1 + n + p1, y + p1), p2, p2, color=c(1 + y))
        a.add_patch(r)
        r.set_clip_box(a.bbox)
        a.text(1.5 + n,
               y + 0.5,
               str(y + 1),
               horizontalalignment='center',
               verticalalignment='center')

    # Set tick labels
    names = [i.qname() for i in model.states()]
    a.set_xticks([i + 0.5 for i in range(0, n)])
    a.set_xticklabels(names, rotation=90)
    a.xaxis.set_ticks_position('top')

    a.set_yticks([i + 0.5 for i in range(0, n)])
    rnames = list(names)
    rnames.reverse()
    a.set_yticklabels(rnames)

    # Add axes labels
    a.set_xlabel('Affecting variable')
    a.set_ylabel('Affected variable')

    # Return
    return a
Ejemplo n.º 20
0
def draw_regions2d(regions: RegionSet, plot: Axes, **kwargs):
    """
  Draws the Regions on a 2D plot, to visualize the
  overlapping or intersecting Regions (or rectangles).

  Args:
    regions:  The set of 2D Regions to draw.
    plot:     The matplotlib plot to draw on.
    kwargs:   Additional arguments and options.

  Keyword Args:
    colored:
      Boolean flag for colored output or greyscale.
      If True, color codes the Regions based on the
      Region's stored 'color' data property. Otherwise,
      all Regions have black edges with transparent faces.
    communities:
      Boolean flag for whether or not to show the
      connected communities (or Regions with same color).
      Requires colored to be True.
    tightbounds:
      Boolean flag for whether or not to reduce the
      bounding size to the minimum bounding Region,
      instead of the defined bounds.
  """
    assert regions.dimension == 2

    black = (0, 0, 0)
    groups = {}

    colored = kwargs.get('colored', False)
    communities = kwargs.get('communities', False)
    tightbounds = kwargs.get('tightbounds', False)

    bbox = regions.bbox if tightbounds else regions.minbounds

    def mkrectangle(region: Region):
        lower = tuple(region[d].lower for d in range(2))
        w, h = tuple(region[d].length for d in range(2))

        return lower, w, h

    if colored and communities:
        for region in regions:
            color = region.getdata('color')
            if color is not None:
                group = groups.setdefault(tuple(color), RegionSet(dimension=2))
                group.add(region)

        for color, group in groups.items():
            rectangle = Rectangle(*mkrectangle(group.bbox),
                                  facecolor=(*color, 0.05),
                                  edgecolor='none')
            rectangle.set_clip_box(plot)
            plot.add_artist(rectangle)

    for region in regions:
        color = region.getdata('color', black) if colored else black
        rectangle = Rectangle(*mkrectangle(region),
                              facecolor=(*color, 0.1),
                              edgecolor=color)
        rectangle.set_clip_box(plot)
        plot.add_artist(rectangle)

    plot.set_xlim(astuple(bbox[0]))
    plot.set_ylim(astuple(bbox[1]))
Ejemplo n.º 21
0
    def _init_legend_box(self, handles, labels):
        """
        Initiallize the legend_box. The legend_box is an instance of
        the OffsetBox, which is packed with legend handles and
        texts. Once packed, their location is calculated during the
        drawing time.
        """

        fontsize = self.fontsize

        # legend_box is a HPacker, horizontally packed with
        # columns. Each column is a VPacker, vertically packed with
        # legend items. Each legend item is HPacker packed with
        # legend handleBox and labelBox. handleBox is an instance of
        # offsetbox.DrawingArea which contains legend handle. labelBox
        # is an instance of offsetbox.TextArea which contains legend
        # text.


        text_list = []  # the list of text instances
        handle_list = []  # the list of text instances

        label_prop = dict(verticalalignment='baseline',
                          horizontalalignment='left',
                          fontproperties=self.prop,
                          )

        labelboxes = []

        for l in labels:
            textbox = TextArea(l, textprops=label_prop,
                               multilinebaseline=True, minimumdescent=True)
            text_list.append(textbox._text)
            labelboxes.append(textbox)

        handleboxes = []


        # The approximate height and descent of text. These values are
        # only used for plotting the legend handle.
        height = self._approx_text_height() * 0.7
        descent = 0.

        # each handle needs to be drawn inside a box of (x, y, w, h) =
        # (0, -descent, width, height).  And their corrdinates should
        # be given in the display coordinates.

        # NOTE : the coordinates will be updated again in
        # _update_legend_box() method.

        # The transformation of each handle will be automatically set
        # to self.get_trasnform(). If the artist does not uses its
        # default trasnform (eg, Collections), you need to
        # manually set their transform to the self.get_transform().

        for handle in handles:
            if isinstance(handle, RegularPolyCollection):
                npoints = self.scatterpoints
            else:
                npoints = self.numpoints
            if npoints > 1:
                # we put some pad here to compensate the size of the
                # marker
                xdata = np.linspace(0.3*fontsize,
                                    (self.handlelength-0.3)*fontsize,
                                    npoints)
                xdata_marker = xdata
            elif npoints == 1:
                xdata = np.linspace(0, self.handlelength*fontsize, 2)
                xdata_marker = [0.5*self.handlelength*fontsize]

            if isinstance(handle, Line2D):
                ydata = ((height-descent)/2.)*np.ones(xdata.shape, float)
                legline = Line2D(xdata, ydata)

                legline.update_from(handle)
                self._set_artist_props(legline) # after update
                legline.set_clip_box(None)
                legline.set_clip_path(None)
                legline.set_drawstyle('default')
                legline.set_marker('None')

                handle_list.append(legline)

                legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)])
                legline_marker.update_from(handle)
                self._set_artist_props(legline_marker)
                legline_marker.set_clip_box(None)
                legline_marker.set_clip_path(None)
                legline_marker.set_linestyle('None')
                # we don't want to add this to the return list because
                # the texts and handles are assumed to be in one-to-one
                # correpondence.
                legline._legmarker = legline_marker

            elif isinstance(handle, Patch):
                p = Rectangle(xy=(0., 0.),
                              width = self.handlelength*fontsize,
                              height=(height-descent),
                              )
                p.update_from(handle)
                self._set_artist_props(p)
                p.set_clip_box(None)
                p.set_clip_path(None)
                handle_list.append(p)
            elif isinstance(handle, LineCollection):
                ydata = ((height-descent)/2.)*np.ones(xdata.shape, float)
                legline = Line2D(xdata, ydata)
                self._set_artist_props(legline)
                legline.set_clip_box(None)
                legline.set_clip_path(None)
                lw = handle.get_linewidth()[0]
                dashes = handle.get_dashes()[0]
                color = handle.get_colors()[0]
                legline.set_color(color)
                legline.set_linewidth(lw)
                legline.set_dashes(dashes)
                handle_list.append(legline)

            elif isinstance(handle, RegularPolyCollection):

                #ydata = self._scatteryoffsets
                ydata = height*self._scatteryoffsets

                size_max, size_min = max(handle.get_sizes()),\
                                     min(handle.get_sizes())
                # we may need to scale these sizes by "markerscale"
                # attribute. But other handle types does not seem
                # to care about this attribute and it is currently ignored.
                if self.scatterpoints < 4:
                    sizes = [.5*(size_max+size_min), size_max,
                             size_min]
                else:
                    sizes = (size_max-size_min)*np.linspace(0,1,self.scatterpoints)+size_min

                p = type(handle)(handle.get_numsides(),
                                 rotation=handle.get_rotation(),
                                 sizes=sizes,
                                 offsets=zip(xdata_marker,ydata),
                                 transOffset=self.get_transform(),
                                 )

                p.update_from(handle)
                p.set_figure(self.figure)
                p.set_clip_box(None)
                p.set_clip_path(None)
                handle_list.append(p)

            else:
                handle_list.append(None)

            handlebox = DrawingArea(width=self.handlelength*fontsize,
                                    height=height,
                                    xdescent=0., ydescent=descent)

            handle = handle_list[-1]
            handlebox.add_artist(handle)
            if hasattr(handle, "_legmarker"):
                handlebox.add_artist(handle._legmarker)
            handleboxes.append(handlebox)


        # We calculate number of lows in each column. The first
        # (num_largecol) columns will have (nrows+1) rows, and remaing
        # (num_smallcol) columns will have (nrows) rows.
        nrows, num_largecol = divmod(len(handleboxes), self._ncol)
        num_smallcol = self._ncol-num_largecol

        # starting index of each column and number of rows in it.
        largecol = safezip(range(0, num_largecol*(nrows+1), (nrows+1)),
                           [nrows+1] * num_largecol)
        smallcol = safezip(range(num_largecol*(nrows+1), len(handleboxes), nrows),
                           [nrows] * num_smallcol)

        handle_label = safezip(handleboxes, labelboxes)
        columnbox = []
        for i0, di in largecol+smallcol:
            # pack handleBox and labelBox into itemBox
            itemBoxes = [HPacker(pad=0,
                                 sep=self.handletextpad*fontsize,
                                 children=[h, t], align="baseline")
                         for h, t in handle_label[i0:i0+di]]
            # minimumdescent=False for the text of the last row of the column
            itemBoxes[-1].get_children()[1].set_minimumdescent(False)

            # pack columnBox
            columnbox.append(VPacker(pad=0,
                                        sep=self.labelspacing*fontsize,
                                        align="baseline",
                                        children=itemBoxes))

        if self._mode == "expand":
            mode = "expand"
        else:
            mode = "fixed"

        sep = self.columnspacing*fontsize

        self._legend_box = HPacker(pad=self.borderpad*fontsize,
                                      sep=sep, align="baseline",
                                      mode=mode,
                                      children=columnbox)

        self._legend_box.set_figure(self.figure)

        self.texts = text_list
        self.legendHandles = handle_list
Ejemplo n.º 22
0
def draw_regions1d(regions: RegionSet, plot: Axes, **kwargs):
    """
  Draws the Regions on a 1D plot, to visualize the
  overlapping or intersecting Regions (or intervals).

  Args:
    regions:  The set of 1D Regions to draw.
    plot:     The matplotlib plot to draw on.
    kwargs:   Additional arguments and options.

  Keyword Args:
    colored:
      Boolean flag for colored output or greyscale.
      If True, color codes the Regions based on the
      Region's stored 'color' data property. Otherwise,
      all Regions have black edges with transparent faces.
    communities:
      Boolean flag for whether or not to show the
      connected communities (or Regions with same color).
      Requires colored to be True.
    tightbounds:
      Boolean flag for whether or not to reduce the
      bounding size to the minimum bounding Region,
      instead of the defined bounds.
  """
    assert regions.dimension == 1

    black = (0, 0, 0)
    groups = {}

    colored = kwargs.get('colored', False)
    communities = kwargs.get('communities', False)
    tightbounds = kwargs.get('tightbounds', False)

    bbox = regions.bbox if tightbounds else regions.minbounds
    spacing = max(bbox[0].length / len(regions), 10)

    if colored and communities:
        for region in regions:
            color = region.getdata('color')
            if color is not None:
                group = groups.setdefault(tuple(color), RegionSet(dimension=1))
                group.add(region)

        for color, group in groups.items():
            gbbox = group.bbox[0]
            lows = (gbbox.lower, 0)
            w, h = (gbbox.length, spacing * (len(regions) + 2))

            rectangle = Rectangle(lows,
                                  w,
                                  h,
                                  facecolor=(*color, 0.05),
                                  edgecolor='none')
            rectangle.set_clip_box(plot)
            plot.add_artist(rectangle)

    for i, region in enumerate(regions):
        color = region.getdata('color', black) if colored else black
        plot.plot(list(astuple(region[0])), [spacing * (i + 1)] * 2,
                  color=color)

    plot.set_xlim(astuple(bbox[0]))
    plot.yaxis.set_visible(False)
Ejemplo n.º 23
0
 def _init_legend_box(self, handles, labels):
     """
     Initiallize the legend_box. The legend_box is an instance of
     the OffsetBox, which is packed with legend handles and
     texts. Once packed, their location is calculated during the
     drawing time.
     """
     fontsize = self._fontsize
     text_list = []  # the list of text instances
     handle_list = []  # the list of text instances
     label_prop = dict(verticalalignment='baseline',
                       horizontalalignment='left',
                       fontproperties=self.prop,
                       )
     labelboxes = []
     handleboxes = []
     height = self._approx_text_height() * 0.7
     descent = 0.
     for handle, lab in zip(handles, labels):
         if isinstance(handle, RegularPolyCollection) or \
                isinstance(handle, CircleCollection):
             npoints = self.scatterpoints
         else:
             npoints = self.numpoints
         if npoints > 1:
             xdata = np.linspace(0.3*fontsize,
                                 (self.handlelength-0.3)*fontsize,
                                 npoints)
             xdata_marker = xdata
         elif npoints == 1:
             xdata = np.linspace(0, self.handlelength*fontsize, 2)
             xdata_marker = [0.5*self.handlelength*fontsize]
         if isinstance(handle, Line2D):
             ydata = ((height-descent)/2.)*np.ones(xdata.shape, float)
             legline = Line2D(xdata, ydata)
             legline.update_from(handle)
             self._set_artist_props(legline) # after update
             legline.set_clip_box(None)
             legline.set_clip_path(None)
             legline.set_drawstyle('default')
             legline.set_marker('None')
             handle_list.append(legline)
             legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)])
             legline_marker.update_from(handle)
             self._set_artist_props(legline_marker)
             legline_marker.set_clip_box(None)
             legline_marker.set_clip_path(None)
             legline_marker.set_linestyle('None')
             legline._legmarker = legline_marker
         elif isinstance(handle, Patch):
             p = Rectangle(xy=(0., 0.),
                           width = self.handlelength*fontsize,
                           height=(height-descent),
                           )
             p.update_from(handle)
             self._set_artist_props(p)
             p.set_clip_box(None)
             p.set_clip_path(None)
             handle_list.append(p)
         elif isinstance(handle, LineCollection):
             ydata = ((height-descent)/2.)*np.ones(xdata.shape, float)
             legline = Line2D(xdata, ydata)
             self._set_artist_props(legline)
             legline.set_clip_box(None)
             legline.set_clip_path(None)
             lw = handle.get_linewidth()[0]
             dashes = handle.get_dashes()[0]
             color = handle.get_colors()[0]
             legline.set_color(color)
             legline.set_linewidth(lw)
             if dashes[0] is not None: # dashed line
                 legline.set_dashes(dashes[1])
             handle_list.append(legline)
         elif isinstance(handle, RegularPolyCollection):
             ydata = height*self._scatteryoffsets
             size_max, size_min = max(handle.get_sizes()),\
                                  min(handle.get_sizes())
             if self.scatterpoints < 4:
                 sizes = [.5*(size_max+size_min), size_max,
                          size_min]
             else:
                 sizes = (size_max-size_min)*np.linspace(0,1,self.scatterpoints)+size_min
             p = type(handle)(handle.get_numsides(),
                              rotation=handle.get_rotation(),
                              sizes=sizes,
                              offsets=zip(xdata_marker,ydata),
                              transOffset=self.get_transform(),
                              )
             p.update_from(handle)
             p.set_figure(self.figure)
             p.set_clip_box(None)
             p.set_clip_path(None)
             handle_list.append(p)
         elif isinstance(handle, CircleCollection):
             ydata = height*self._scatteryoffsets
             size_max, size_min = max(handle.get_sizes()),\
                                  min(handle.get_sizes())
             if self.scatterpoints < 4:
                 sizes = [.5*(size_max+size_min), size_max,
                          size_min]
             else:
                 sizes = (size_max-size_min)*np.linspace(0,1,self.scatterpoints)+size_min
             p = type(handle)(sizes,
                              offsets=zip(xdata_marker,ydata),
                              transOffset=self.get_transform(),
                              )
             p.update_from(handle)
             p.set_figure(self.figure)
             p.set_clip_box(None)
             p.set_clip_path(None)
             handle_list.append(p)
         else:
             handle_type = type(handle)
             warnings.warn("Legend does not support %s\nUse proxy artist instead.\n\nhttp://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n" % (str(handle_type),))
             handle_list.append(None)
         handle = handle_list[-1]
         if handle is not None: # handle is None is the artist is not supproted
             textbox = TextArea(lab, textprops=label_prop,
                                multilinebaseline=True, minimumdescent=True)
             text_list.append(textbox._text)
             labelboxes.append(textbox)
             handlebox = DrawingArea(width=self.handlelength*fontsize,
                                     height=height,
                                     xdescent=0., ydescent=descent)
             handlebox.add_artist(handle)
             if isinstance(handle, RegularPolyCollection) or \
                    isinstance(handle, CircleCollection):
                 handle._transOffset = handlebox.get_transform()
                 handle.set_transform(None)
             if hasattr(handle, "_legmarker"):
                 handlebox.add_artist(handle._legmarker)
             handleboxes.append(handlebox)
     if len(handleboxes) > 0:
         ncol = min(self._ncol, len(handleboxes))
         nrows, num_largecol = divmod(len(handleboxes), ncol)
         num_smallcol = ncol-num_largecol
         largecol = safezip(range(0, num_largecol*(nrows+1), (nrows+1)),
                            [nrows+1] * num_largecol)
         smallcol = safezip(range(num_largecol*(nrows+1), len(handleboxes), nrows),
                            [nrows] * num_smallcol)
     else:
         largecol, smallcol = [], []
     handle_label = safezip(handleboxes, labelboxes)
     columnbox = []
     for i0, di in largecol+smallcol:
         itemBoxes = [HPacker(pad=0,
                              sep=self.handletextpad*fontsize,
                              children=[h, t], align="baseline")
                      for h, t in handle_label[i0:i0+di]]
         itemBoxes[-1].get_children()[1].set_minimumdescent(False)
         columnbox.append(VPacker(pad=0,
                                     sep=self.labelspacing*fontsize,
                                     align="baseline",
                                     children=itemBoxes))
     if self._mode == "expand":
         mode = "expand"
     else:
         mode = "fixed"
     sep = self.columnspacing*fontsize
     self._legend_handle_box = HPacker(pad=0,
                                       sep=sep, align="baseline",
                                       mode=mode,
                                       children=columnbox)
     self._legend_title_box = TextArea("")
     self._legend_box = VPacker(pad=self.borderpad*fontsize,
                                sep=self.labelspacing*fontsize,
                                align="center",
                                children=[self._legend_title_box,
                                          self._legend_handle_box])
     self._legend_box.set_figure(self.figure)
     self.texts = text_list
     self.legendHandles = handle_list
Ejemplo n.º 24
0
addEntry('Car Battery With CFL', cost = 1.0,  cpLh = 0.12)
#addEntry('SharedSolar With CFL', cost = 1.0,  cpLh = 0.10)
#addEntry('Grid Mali With CFL',   cost = 16,   cpLh = 16/0.2)

fig = plt.figure()
axes = fig.add_subplot(111)

for key in dict.keys():
    axes.loglog(dict[key]['cost'], dict[key]['cpLh'], 'ko')
    axes.text(dict[key]['cost'], dict[key]['cpLh'], key)

from matplotlib.patches import Rectangle

rect = Rectangle((1, .017), 5, .07, facecolor="#dddddd")
axes.add_artist(rect)
rect.set_clip_box(axes.bbox)

axes.text(1.1,0.03, 'Shared Solar With CFL')

plt.xlim((0.1,10))
plt.ylim((0.01,10))

plt.title('Lumen-Hour Cost vs. Purchase Price')
plt.xlabel('Purchase Cost (USD)')
plt.ylabel('Cost Per Lumen-Hour')

plt.grid()
plt.savefig('costVsLumens.pdf')
plt.show()

plt.close()
Ejemplo n.º 25
0
    def visualise(cls,
                  sensor,
                  sL=None,
                  show_sun=False,
                  sides=True,
                  interactive=False,
                  colormap=None,
                  scale=[0, 1],
                  title=None):
        """
        :param sensor:
        :type sensor: CompassSensor
        :return:
        """
        import matplotlib.pyplot as plt
        from matplotlib.patches import Ellipse, Rectangle
        from matplotlib.cm import get_cmap
        import matplotlib as mpl

        if interactive:
            plt.ion()

        if colormap is not None:
            get_colour = lambda x: get_cmap(colormap)(x)
        else:
            get_colour = lambda x: x * np.array([.5, .5, 1.])
        xyz = sph2vec(np.pi / 2 - sensor.theta_local, np.pi + sensor.phi_local,
                      sensor.R_c)
        xyz[0] *= -1

        lat, lon = hp.Rotator(rot=(np.rad2deg(-sensor.yaw),
                                   np.rad2deg(-sensor.pitch),
                                   np.rad2deg(-sensor.roll)))(
                                       sensor.sky.lat, np.pi - sensor.sky.lon)
        xyz_sun = sph2vec(np.pi / 2 - lat, np.pi + lon, sensor.R_c)
        xyz_sun[0] *= -1

        if sides:
            figsize = (10, 10)
        else:
            if colormap is None or scale is None:
                figsize = (5, 5)
            else:
                figsize = (5.05, 5.05)
        plt.figure("Sensor Design" if title is None else title,
                   figsize=figsize)

        # top view
        if sides:
            ax_t = plt.subplot2grid((4, 4), (1, 1),
                                    colspan=2,
                                    rowspan=2,
                                    aspect="equal",
                                    adjustable='box-forced')
        else:
            if colormap is not None and scale is not None:
                ax_t = plt.subplot2grid((10, 10), (0, 0),
                                        colspan=9,
                                        rowspan=9,
                                        aspect="equal",
                                        adjustable='box-forced')
            else:
                ax_t = plt.subplot(111)
        outline = Ellipse(xy=np.zeros(2),
                          width=2 * sensor.R_c,
                          height=2 * sensor.R_c)
        sensor_outline = Ellipse(xy=np.zeros(2),
                                 width=2 * sensor.alpha + 2 * sensor.R_l,
                                 height=2 * sensor.alpha + 2 * sensor.R_l)
        ax_t.add_artist(outline)
        outline.set_clip_box(ax_t.bbox)
        outline.set_alpha(.2)
        outline.set_facecolor("grey")
        ax_t.add_artist(sensor_outline)
        sensor_outline.set_clip_box(ax_t.bbox)
        sensor_outline.set_alpha(.5)
        sensor_outline.set_facecolor("grey")

        stheta, sphi = sensor.theta_local, np.pi + sensor.phi_local
        sL = sL if sL is not None else sensor.L
        if sensor.mode == "event":
            sL = np.clip(1. * sL + .5, 0., 1.)
        for (x, y, z), th, ph, L in zip(xyz.T, stheta, sphi, sL):

            lens = Ellipse(xy=[x, y],
                           width=1.5 * sensor.r_l,
                           height=1.5 * np.cos(th) * sensor.r_l,
                           angle=np.rad2deg(ph))
            ax_t.add_artist(lens)
            lens.set_clip_box(ax_t.bbox)
            lens.set_facecolor(get_colour(np.asscalar(L)))
        if show_sun:
            ax_t.plot(xyz_sun[0], xyz_sun[1], 'ro', markersize=22)

        ax_t.set_xlim(-sensor.R_c - 2, sensor.R_c + 2)
        ax_t.set_ylim(-sensor.R_c - 2, sensor.R_c + 2)
        ax_t.set_xticklabels([])
        ax_t.set_yticklabels([])

        if sides:
            # side view #1 (x, z)
            ax = plt.subplot2grid((4, 4), (0, 1),
                                  colspan=2,
                                  aspect="equal",
                                  adjustable='box-forced',
                                  sharex=ax_t)
            outline = Ellipse(xy=np.zeros(2),
                              width=2 * sensor.R_c,
                              height=2 * sensor.R_c)
            fade_one = Rectangle(xy=[-sensor.R_c, -sensor.R_c],
                                 width=2 * sensor.R_c,
                                 height=2 * sensor.R_c - sensor.height -
                                 sensor.R_l)
            ax.add_artist(outline)
            outline.set_clip_box(ax.bbox)
            outline.set_alpha(.5)
            outline.set_facecolor("grey")
            ax.add_artist(fade_one)
            fade_one.set_clip_box(ax.bbox)
            fade_one.set_alpha(.6)
            fade_one.set_facecolor("white")
            for (x, y, z), th, ph, L in zip(xyz.T, stheta, sphi, sL):
                if y > 0:
                    continue
                lens = Ellipse(xy=[x, z],
                               width=1.5 * sensor.r_l,
                               height=np.sin(-y / sensor.R_c) * 1.5 *
                               sensor.r_l,
                               angle=np.rad2deg(np.arcsin(-x / sensor.R_c)))
                ax.add_artist(lens)
                lens.set_clip_box(ax.bbox)
                lens.set_facecolor(get_colour(L))

            ax.set_xlim(-sensor.R_c - 2, sensor.R_c + 2)
            ax.set_ylim(0, sensor.R_c + 2)
            ax.set_xticks([])
            ax.set_yticks([])

            # side view #2 (-x, z)
            ax = plt.subplot2grid((4, 4), (3, 1),
                                  colspan=2,
                                  aspect="equal",
                                  adjustable='box-forced',
                                  sharex=ax_t)
            outline = Ellipse(xy=np.zeros(2),
                              width=2 * sensor.R_c,
                              height=2 * sensor.R_c)
            fade_one = Rectangle(
                xy=[-sensor.R_c, -sensor.R_c + sensor.height + sensor.R_l],
                width=2 * sensor.R_c,
                height=2 * sensor.R_c - sensor.height - sensor.R_l)
            ax.add_artist(outline)
            outline.set_clip_box(ax.bbox)
            outline.set_alpha(.5)
            outline.set_facecolor("grey")
            ax.add_artist(fade_one)
            fade_one.set_clip_box(ax.bbox)
            fade_one.set_alpha(.6)
            fade_one.set_facecolor("white")
            for (x, y, z), th, ph, L in zip(xyz.T, stheta, sphi, sL):
                if y < 0:
                    continue
                lens = Ellipse(xy=[x, -z],
                               width=1.5 * sensor.r_l,
                               height=np.sin(-y / sensor.R_c) * 1.5 *
                               sensor.r_l,
                               angle=np.rad2deg(np.arcsin(x / sensor.R_c)))
                ax.add_artist(lens)
                lens.set_clip_box(ax.bbox)
                lens.set_facecolor(get_colour(L))

            ax.set_xlim(-sensor.R_c - 2, sensor.R_c + 2)
            ax.set_ylim(-sensor.R_c - 2, 0)
            ax.set_yticks([])

            # side view #3 (y, z)
            ax = plt.subplot2grid((4, 4), (1, 3),
                                  rowspan=2,
                                  aspect="equal",
                                  adjustable='box-forced',
                                  sharey=ax_t)
            outline = Ellipse(xy=np.zeros(2),
                              width=2 * sensor.R_c,
                              height=2 * sensor.R_c)
            fade_one = Rectangle(xy=[-sensor.R_c, -sensor.R_c],
                                 width=2 * sensor.R_c - sensor.height -
                                 sensor.R_l,
                                 height=2 * sensor.R_c)
            ax.add_artist(outline)
            outline.set_clip_box(ax.bbox)
            outline.set_alpha(.5)
            outline.set_facecolor("grey")
            ax.add_artist(fade_one)
            fade_one.set_clip_box(ax.bbox)
            fade_one.set_alpha(.6)
            fade_one.set_facecolor("white")
            for (x, y, z), th, ph, L in zip(xyz.T, stheta, sphi, sL):
                if x > 0:
                    continue
                lens = Ellipse(
                    xy=[z, y],
                    width=1.5 * sensor.r_l,
                    height=np.sin(-x / sensor.R_c) * 1.5 * sensor.r_l,
                    angle=np.rad2deg(np.arcsin(y / sensor.R_c)) + 90)
                ax.add_artist(lens)
                lens.set_clip_box(ax.bbox)
                lens.set_facecolor(get_colour(L))

            ax.set_ylim(-sensor.R_c - 2, sensor.R_c + 2)
            ax.set_xlim(0, sensor.R_c + 2)
            ax.set_yticks([])
            ax.set_xticks([])

            # side view #4 (-y, z)
            ax = plt.subplot2grid((4, 4), (1, 0),
                                  rowspan=2,
                                  aspect="equal",
                                  adjustable='box-forced',
                                  sharey=ax_t)
            outline = Ellipse(xy=np.zeros(2),
                              width=2 * sensor.R_c,
                              height=2 * sensor.R_c)
            fade_one = Rectangle(
                xy=[-sensor.R_c + sensor.height + sensor.R_l, -sensor.R_c],
                width=2 * sensor.R_c - sensor.height - sensor.R_l,
                height=2 * sensor.R_c)
            ax.add_artist(outline)
            outline.set_clip_box(ax.bbox)
            outline.set_alpha(.5)
            outline.set_facecolor("grey")
            ax.add_artist(fade_one)
            fade_one.set_clip_box(ax.bbox)
            fade_one.set_alpha(.6)
            fade_one.set_facecolor("white")
            for (x, y, z), th, ph, L in zip(xyz.T, stheta, sphi, sL):
                if x < 0:
                    continue
                lens = Ellipse(
                    xy=[-z, y],
                    width=1.5 * sensor.r_l,
                    height=np.sin(-x / sensor.R_c) * 1.5 * sensor.r_l,
                    angle=np.rad2deg(np.arcsin(-y / sensor.R_c)) - 90)
                ax.add_artist(lens)
                lens.set_clip_box(ax.bbox)
                lens.set_facecolor(get_colour(L))

            ax.set_ylim(-sensor.R_c - 2, sensor.R_c + 2)
            ax.set_xlim(-sensor.R_c - 2, 0)
            ax.set_xticks([])
        else:
            plt.axis('off')

        if colormap is not None and not sides and scale is not None:
            ax = plt.subplot2grid((10, 10), (9, 9),
                                  aspect="equal",
                                  adjustable='box-forced',
                                  projection='polar')
            ax._direction = 2 * np.pi
            ax.set_theta_zero_location("N")

            # quant_steps = 360
            cb = mpl.colorbar.ColorbarBase(ax,
                                           cmap=get_cmap(colormap),
                                           norm=mpl.colors.Normalize(
                                               0.0, 2 * np.pi),
                                           orientation='horizontal',
                                           ticks=np.linspace(0,
                                                             2 * np.pi,
                                                             4,
                                                             endpoint=False))

            cb.outline.set_visible(False)
            # cb.ax.set_xticks([0, np.pi/6, np.pi/3, np.pi/2, 2*np.pi/3, 5*np.pi/6, np.pi])
            cb.ax.set_xticklabels(
                np.linspace(scale[0], scale[1], 4, endpoint=False))
            cb.ax.tick_params(pad=1, labelsize=8)

        plt.tight_layout(pad=0.)

        if interactive:
            plt.draw()
            plt.pause(.1)
        else:
            plt.show()
Ejemplo n.º 26
0
def plot_state_dependency_matrix(model, direct=False, knockout=[], axes=None):
    """
    Creates a matrix showing state variable dependency distances.

    To show only direct (first-order) dependencies, set the optional argument
    ``direct`` to ``True``.

    Variables can be "knocked out" by adding them to the list in the
    ``knockout`` parameter. If x depends on y and y depends on z, knocking out
    y will prevent the method from findind x's dependency on z.

    Returns a matplotlib axes object.
    """
    import matplotlib.pyplot as pl
    # Create dependency matrix
    m = create_state_dependency_matrix(model, direct, knockout)
    n = len(m)
    # Configure axes
    #a = f.add_subplot(111, aspect='equal')
    a = axes if axes is not None else pl.gca()
    a.set_aspect('equal')
    a.set_xlim(0, n + 2)
    a.set_ylim(0, n)
    # Create matrix plot
    from matplotlib.patches import Rectangle
    w = 1.0 / (max(max(m)))  # color weight
    p1 = 0.1  # Padding
    p2 = 1.0 - 2 * p1  # Square size

    def c(v):
        # Colormap
        if v == 1:
            return (0, 0, 0)
        else:
            vv = v * w
            if (vv > 1.0):
                return (0, 1.0, 0)
            return (vv, vv, 1.0)

    for y, row in enumerate(m):
        y = n - y - 1
        for x, v in enumerate(row):
            r = Rectangle((x + p1, y + p1), p2, p2, color=c(v))
            a.add_patch(r)
            r.set_clip_box(a.bbox)
        # Add colorbar
        r = Rectangle((1 + n + p1, y + p1), p2, p2, color=c(1 + y))
        a.add_patch(r)
        r.set_clip_box(a.bbox)
        a.text(1.5 + n,
               y + 0.5,
               str(y + 1),
               horizontalalignment='center',
               verticalalignment='center')
    # Set tick labels
    names = [i.qname() for i in model.states()]
    a.set_xticks([i + 0.5 for i in xrange(0, n)])
    a.set_xticklabels(names)
    from matplotlib.transforms import Affine2D
    r = Affine2D.identity()
    a.set_yticks([i + 0.5 for i in xrange(0, n)])
    rnames = list(names)
    rnames.reverse()
    a.set_yticklabels(rnames)
    for tick in a.xaxis.iter_ticks():
        tick[0].label2On = True
        tick[0].label1On = False
        tick[0].label2.set_rotation('vertical')
    # Add axes labels
    a.annotate('Affecting variable -->',
               xy=(0, -0.05),
               ha='left',
               va='center',
               xycoords='axes fraction',
               textcoords='offset points')
    # Adjust subplot margins
    return a
Ejemplo n.º 27
0
    def highlight_artist(self, val, artist=None):
        from ifigure.matplotlib_mod.art3d_gl import Poly3DCollectionGL
        from ifigure.matplotlib_mod.art3d_gl import Line3DCollectionGL
        figure = self.get_figpage()._artists[0]
        ax = self.get_figaxes()
        if artist is None:
            alist = self._artists
        else:
            alist = artist

        if val == True:
            if self._parent is None: return
            container = self.get_container()
            if container is None: return

            if isinstance(alist[0], Poly3DCollectionGL):
                hl = alist[0].add_hl_mask()
                for item in hl:
                    alist[0].figobj_hl.append(item)
            else:
                de = self.get_data_extent()
                x = (de[0], de[1], de[1], de[0], de[0])
                y = (de[2], de[2], de[3], de[3], de[2])

                facecolor = 'k'
                if isinstance(alist[0], Poly3DCollectionGL):
                    hl = alist[0].make_hl_artist(container)
                    facecolor = 'none'
                    self._hit_path = None
                elif isinstance(alist[0], Line3DCollectionGL):
                    hl = alist[0].make_hl_artist(container)
                    facecolor = 'none'
                    self._hit_path = None
                else:
                    hl = container.plot(x,
                                        y,
                                        marker='s',
                                        color='k',
                                        linestyle='None',
                                        markerfacecolor='None',
                                        markeredgewidth=0.5,
                                        scalex=False,
                                        scaley=False)
                for item in hl:
                    alist[0].figobj_hl.append(item)

                if self._hit_path is not None:
                    v = self._hit_path.vertices
                    hl = container.plot(v[:, 0],
                                        v[:, 1],
                                        marker='s',
                                        color='k',
                                        linestyle='None',
                                        markerfacecolor='None',
                                        markeredgewidth=0.5,
                                        scalex=False,
                                        scaley=False)
                    for item in hl:
                        alist[0].figobj_hl.append(item)

                hlp = Rectangle((de[0], de[2]),
                                de[1] - de[0],
                                de[3] - de[2],
                                alpha=0.3,
                                facecolor=facecolor,
                                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)
                alist[0].figobj_hl.append(hlp)
        else:
            for a in alist:
                if len(a.figobj_hl) == 0: continue
                for hl in a.figobj_hl[:-1]:
                    hl.remove()
                if isinstance(alist[0], Poly3DCollectionGL):
                    a.figobj_hl[-1].remove()
                else:
                    figure.patches.remove(a.figobj_hl[-1])
                a.figobj_hl = []