Esempio n. 1
0
class BatchLineCollection(object):
    def __init__(self, ax):
        self._ax = ax
        self._lc = None

    @property
    def artists(self):
        return [self._lc]

    def draw(self, x, y, **kwargs):
        segments = []
        for x_i, y_i in zip(x, y):
            xy_i = np.stack([x_i, y_i], axis=1)
            xy_i = xy_i.reshape(-1, 1, 2)
            segments_i = np.hstack([xy_i[:-1], xy_i[1:]])
            segments.append(segments_i)
        segments = np.concatenate(segments, axis=0)

        if self._lc is None:
            self._lc = PltLineCollection(segments)
            self._ax.add_collection(self._lc)
        else:
            self._lc.set_segments(segments)
        if 'color' in kwargs:
            self._lc.set_color(np.reshape(kwargs['color'],
                                          [len(segments), -1]))
        if 'linewidth' in kwargs:
            self._lc.set_linewidth(kwargs['linewidth'])
        self._lc.set_joinstyle('round')
        self._lc.set_capstyle('round')
Esempio n. 2
0
 def changeVecteur(self, ech=1.0, col=None):
     """ modifie les valeurs de vecteurs existants"""
     self.drawVecteur(False)
     if type(ech) == type((3, 4)):
         if len(ech) >= 1:
             ech = ech[0]
     # previous object
     obj = self.getObjFromType("vecteur")
     if obj == None:
         return
     # change coordinates
     dep, arr_old, ech_old = obj.getData()
     arr = dep + (arr_old - dep) * ech / ech_old
     # new object
     lc1 = LineCollection(zip(dep, arr))
     lc1.set_transform(self.transform)
     if col == None:
         col = wx.Color(0, 0, 255)
     a = col.Get()
     col = (a[0] / 255, a[1] / 255, a[2] / 255)
     lc1.set_color(col)
     obj = GraphicObject("vecteur", lc1, False, None)
     obj.setData([dep, arr, ech])
     self.addGraphicObject(obj)
     self.cnv.collections[0] = lc1
     self.redraw()
Esempio n. 3
0
def plot_line_colored(x, y, t, w=None, color=None, cmap=None):
    import numpy as np
    from matplotlib.collections import LineCollection

    # Create a set of line segments so that we can color them individually
    # This creates the points as a N x 1 x 2 array so that we can stack points
    # together easily to get the segments. The segments array for line collection
    # needs to be numlines x points per line x 2 (x and y)
    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)

    extra = {}
    if w is None: extra['linewidths'] = w

    # Create the line collection object, setting the colormapping parameters.
    # Have to set the actual values used for colormapping separately.
    lc = LineCollection(segments,
                        cmap=p.get_cmap(cmap),
                        **extra
                        #norm=p.Normalize(0, 10)
                        )
    lc.set_array(t)
    lc.set_linewidth(w)

    if color is not None:
        lc.set_color(color)

    p.gca().add_collection(lc)
Esempio n. 4
0
def add_china_map_2basemap(ax,name ="province", facecolor='none',
                           edgecolor='c', lw=2, encoding='utf-8', **kwargs):
    """
    Add china province boundary to basemap instance.
    :param mp: basemap instance.
    :param ax: matplotlib axes instance.
    :param name: map name.
    :param facecolor: fill color, default is none.
    :param edgecolor: edge color.
    :param lw: line width.
    :param kwargs: keywords passing to Polygon.
    :return: None.
    """

    # map name
    names = {'nation': "bou1_4p", 'province': "bou2_4p",
             'county': "BOUNT_poly", 'river': "hyd1_4p",
             'river_high': "hyd2_4p"}
        # get shape file and information
    shpfile = pkg_resources.resource_filename(
        'meteva', "resources/maps/" + names[name])
    shp1 = readshapefile(shpfile, default_encoding=encoding)
    lines = LineCollection(shp1,antialiaseds=(1,))
    lines.set_color(edgecolor)
    lines.set_linewidth(lw)
    lines.set_label('_nolabel_')
    ax.add_collection(lines)
Esempio n. 5
0
def plotcf(grid, phase, modulus, darken=None, axes=None, linestylep="solid", linewidthp=1, color="k", **kwargs):
    r"""Plot the modulus of a complex valued function
    :math:`f:\mathbb{R} \rightarrow \mathbb{C}`
    together with its phase in a color coded fashion.

    :param grid: The grid nodes of the real domain R
    :param phase: The phase of the complex domain result f(grid)
    :param modulus: The modulus of the complex domain result f(grid)
    :param darken: Whether to take into account the modulus of the data to darken colors.
    :param axes: The axes instance used for plotting.
    :param linestylep: The line style of the phase curve.
    :param linewidthp: The line width of the phase curve.
    :param color: The color of the phase curve.
    """
    # Color mapping
    rgb_colors = color_map(modulus, phase=phase, modulus=modulus, darken=darken)

    # Put all the vertical line into a collection
    segments = [array([[node, 0], [node, value]]) for node, value in zip(grid, modulus)]
    line_segments = LineCollection(segments)

    # Set some properties of the lines
    rgb_colors = line_segments.to_rgba(rgb_colors)
    line_segments.set_color(rgb_colors[0])
    line_segments.set_linestyle(linestylep)
    line_segments.set_linewidth(linewidthp)

    # Plot to the given axis instance or retrieve the current one
    if axes is None:
        axes = gca()

    # Plot the phase
    axes.add_collection(line_segments)
    # Plot the modulus
    axes.plot(grid, modulus, color=color, **kwargs)
Esempio n. 6
0
    def update_plot(self):
        if len(self.variables.plot_data.shape) < 3:
            self.pyplot_canvas.canvas.draw()
        elif self.variables.plot_data is not None:
            n_overplots = numpy.shape(self.variables.segments)[0]
            animation_index = int(self.control_panel.scale.get())

            for i in range(n_overplots):
                self.variables.segments[
                    i, :, 1] = self.variables.plot_data[:, i, animation_index]

            self.pyplot_canvas.axes.clear()

            self.pyplot_canvas.axes.set_xlim(self.variables.xmin,
                                             self.variables.xmax)
            line_segments = LineCollection(
                self.variables.segments,
                self.pyplot_utils.linewidths,
                linestyle=self.pyplot_utils.linestyle)
            line_segments.set_color(self.pyplot_utils.rgb_array_full_palette)
            if self.variables.set_y_margins_per_frame:
                plot_data = self.variables.segments[:, :, 1]
                y_range = plot_data.max() - plot_data.min()
                self.variables.ymin = plot_data.min(
                ) - y_range * self.variables.y_margin
                self.variables.ymax = plot_data.max(
                ) + y_range * self.variables.y_margin
            self.pyplot_canvas.axes.set_ylim(self.variables.ymin,
                                             self.variables.ymax)

            self.pyplot_canvas.axes.add_collection(line_segments)
            self.pyplot_canvas.canvas.draw()
        else:
            pass
Esempio n. 7
0
    def loadlines(self,
                  name,
                  curdir='beijingJson',
                  zorder=None,
                  linewidth=0.5,
                  color='k',
                  antialiased=1,
                  ax=None,
                  default_encoding='utf-8',
                  linestyle='-',
                  linesalpha=1):
        # get current axes instance (if none specified).
        filename = curdir + '/' + name + '.json'
        coords = json.load(codecs.open(filename, 'r', 'utf-8'))
        coords = self.projectcoords(coords)

        ax = ax or self._check_ax()
        # make LineCollections for each polygon.
        lines = LineCollection(coords, antialiaseds=(1, ))
        lines.set_color(color)
        lines.set_linewidth(linewidth)
        lines.set_linestyle(linestyle)
        lines.set_alpha(linesalpha)
        lines.set_label('_nolabel_')
        if zorder is not None:
            lines.set_zorder(zorder)
        ax.add_collection(lines)
        # set axes limits to fit map region.
        self.set_axes_limits(ax=ax)
        # clip boundaries to map limbs
        lines, c = self._cliplimb(ax, lines)
        self.__dict__[name] = coords
        return lines
Esempio n. 8
0
def segments(X, Y, color=(1, 0, 0, 0)):
    N = X.shape[0]
    z = np.zeros((N, 2, 2))
    z[:, 0, :] = X
    z[:, 1, :] = Y
    lc = LineCollection(z)
    lc.set_color(color)
    plt.gca().add_collection(lc)
Esempio n. 9
0
def segments(X,Y,color=(1,0,0,0)):
    N = X.shape[0]
    z = np.zeros((N,2,2));
    z[:,0,:] = X
    z[:,1,:] = Y
    lc = LineCollection(z)
    lc.set_color(color)
    plt.gca().add_collection(lc)
def draw_graph(xy, edges, edgecolor='b'):
    lcol = xy[edges]
    lc = LineCollection(xy[edges])
    lc.set_linewidth(0.1)
    lc.set_color(edgecolor)
    pl.gca().add_collection(lc)
    pl.xlim(xy[:, 0].min(), xy[:, 0].max())
    pl.ylim(xy[:, 1].min(), xy[:, 1].max())
Esempio n. 11
0
def get_landcoastlines(basemap, color="0.0", linewidth=1):
    landpolygons = np.where(np.array(basemap.coastpolygontypes) == 1)[0]
    landsegs = []
    for index in landpolygons:
        landsegs.append(basemap.coastsegs[index])
    landcoastlines = LineCollection(landsegs, antialiaseds=(1, ))
    landcoastlines.set_color(color)
    landcoastlines.set_linewidth(linewidth)
    return landcoastlines
Esempio n. 12
0
def plotgraph(xy, edges, edgecolor='b'):
    lcol = xy[edges]
    lc = LineCollection(xy[edges])
    lc.set_linewidth(0.1)
    lc.set_color(edgecolor)
    pl.gca().add_collection(lc)
    #pl.plot(xy[:,0], xy[:,1], 'ro')
    pl.xlim(xy[:, 0].min(), xy[:, 0].max())
    pl.ylim(xy[:, 1].min(), xy[:, 1].max())
    pl.show()
Esempio n. 13
0
def plotgraph(xy,edges,edgecolor='b'):
    lcol = xy[edges]
    lc = LineCollection(xy[edges])
    lc.set_linewidth(0.1)
    lc.set_color(edgecolor)
    pl.gca().add_collection(lc)
    #pl.plot(xy[:,0], xy[:,1], 'ro')
    pl.xlim(xy[:,0].min(), xy[:,0].max())
    pl.ylim(xy[:,1].min(), xy[:,1].max())
    pl.show()
Esempio n. 14
0
    def plot(self,
             show_minima=False,
             show_trees=False,
             linewidth=0.5,
             axes=None):
        """draw the disconnectivity graph using matplotlib
        
        don't forget to call calculate() first
        
        also, you must call pyplot.show() to actually see the plot
        """
        from matplotlib.collections import LineCollection
        import matplotlib.pyplot as plt

        self.line_segments, self.line_colours = self._get_line_segments(
            self.tree_graph, eoffset=self.eoffset)

        # get the axes object
        if axes is not None:
            ax = axes
        else:
            fig = plt.figure(figsize=(6, 7))
            fig.set_facecolor('white')
            ax = fig.add_subplot(111, adjustable='box')

        #set up how the figure should look
        ax.tick_params(axis='y', direction='out')
        ax.yaxis.tick_left()
        ax.spines['left'].set_color('black')
        ax.spines['left'].set_linewidth(0.5)
        ax.spines['top'].set_color('none')
        ax.spines['bottom'].set_color('none')
        ax.spines['right'].set_color('none')
        #        plt.box(on=True)

        #draw the minima as points
        if show_minima:
            xpos, energies = self.get_minima_layout()
            ax.plot(xpos, energies, 'o')

        # draw the line segments
        # use LineCollection because it's much faster than drawing the lines individually
        linecollection = LineCollection([[(x[0], y[0]), (x[1], y[1])]
                                         for x, y in self.line_segments])
        linecollection.set_linewidth(linewidth)
        linecollection.set_color(self.line_colours)
        ax.add_collection(linecollection)

        # scale the axes appropriately
        ax.relim()
        ax.autoscale_view(scalex=True, scaley=True, tight=None)
        ax.set_ylim(top=self.Emax)
        #remove xtics
        ax.set_xticks([])
Esempio n. 15
0
    def plot_profiles(
        self,
        field="topographic__elevation",
        xlabel="Distance Along Profile",
        ylabel="Plotted Quantity",
        title="Extracted Profiles",
        color=None,
    ):
        """Plot distance-upstream vs at at-node or size (nnodes,) quantity.

        Parameters
        ----------
        field : field name or nnode array
            Array of the at-node-field to plot against distance upstream.
            Default value is the at-node field 'topographic__elevation'.
        xlabel : str, optional
            X-axis label, default is "Distance Along Profile".
        ylabel : str, optional
            Y-axis label, default value is "Plotted Quantity".
        title : str, optional
            Plot title, default value is "Extracted Profiles".
        color : RGBA tuple or color string
            Color to use in order to plot all profiles the same color. Default
            is None, and the colors assigned to each profile are used.
        """
        quantity = return_array_at_node(self._grid, field)

        # create segments the way that line collection likes them.
        segments = []
        qmin = []
        qmax = []
        for idx, nodes in enumerate(self._nodes):
            segments.append(
                list(zip(self._distance_along_profile[idx], quantity[nodes])))
            qmin.append(min(quantity[nodes]))
            qmax.append(max(quantity[nodes]))

        # We need to set the plot limits.
        ax = plt.gca()
        ax.set_xlim(
            _recursive_min(self._distance_along_profile),
            _recursive_max(self._distance_along_profile),
        )
        ax.set_ylim(min(qmin), max(qmax))

        line_segments = LineCollection(segments)
        colors = color or self._colors
        line_segments.set_color(colors)
        ax.add_collection(line_segments)
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        ax.set_title(title)
Esempio n. 16
0
    def plot(self, show_vor_points=True):
        if show_vor_points:
            self.plot_vor_points()

        # plot the finite edges:
        # build up the list of lines:
        all_lines = self.nodes[self.edges]
        coll = LineCollection(all_lines)
        coll.set_color('m')
        ax = plt.gca()
        ax.add_collection(coll)

        plt.draw()
Esempio n. 17
0
def plot_2D_cells(cells, axes):
    verts = np.array([cell.cube_map for cell in cells if cell.dim == 0]) / 2
    edges = np.array([edge_vertices(cell) for cell in cells if cell.dim == 1])
    faces = np.array([face_vertices(cell) for cell in cells if cell.dim == 2])
    if verts.shape[0]:
        axes.scatter(verts[:, 1], verts[:, 0], marker='s')
    edges_coll = LineCollection(edges)
    edges_coll.set_color('green')
    edges_coll.set_linewidth(2)
    faces_coll = PolyCollection(faces, )
    faces_coll.set_color('pink')
    axes.add_collection(edges_coll)
    axes.add_collection(faces_coll)
Esempio n. 18
0
    def plot(self, show_minima=False, linewidth=0.5, axes=None):
        """draw the disconnectivity graph using matplotlib
        
        don't forget to call calculate() first
        
        also, you must call pyplot.show() to actually see the plot
        """
        import matplotlib as mpl
        from matplotlib.collections import LineCollection
        import matplotlib.pyplot as plt
        
        self.line_segments = self._get_line_segments(self.tree_graph, eoffset=self.eoffset)
        
        #set up how the figure should look
        if axes is not None:
            ax = axes
        else:
            fig = plt.figure(figsize=(6,7))
            fig.set_facecolor('white')
            ax = fig.add_subplot(111, adjustable='box')

        ax.tick_params(axis='y', direction='out')
        ax.yaxis.tick_left()
        ax.spines['left'].set_color('black')
        ax.spines['left'].set_linewidth(0.5)
        ax.spines['top'].set_color('none')
        ax.spines['bottom'].set_color('none')
        ax.spines['right'].set_color('none')
#        plt.box(on=True)
        
        #draw the minima as points
        if show_minima:      
            leaves = self.tree_graph.get_leaves()
            energies = [self._getEnergy(leaf.data["minimum"]) for leaf in leaves]
            xpos = [leaf.data["x"] for leaf in leaves]
        
            ax.plot(xpos, energies, 'o')
        
        # draw the line segments 
        # use LineCollection because it's much faster than drawing the lines individually 
        linecollection = LineCollection([ [(x[0],y[0]), (x[1],y[1])] for x,y in self.line_segments])
        linecollection.set_linewidth(linewidth)
        linecollection.set_color("k")
        ax.add_collection(linecollection)
        
        # scale the axes appropriately
        ax.relim()
        ax.autoscale_view(scalex=True, scaley=True, tight=None)

        #remove xtics            
        ax.set_xticks([])        
Esempio n. 19
0
def save_spl_curves(path: str, name: str, img: np.array, roi, spl, curves):
    """Takes a path string, a name, two arrays, a roi, and splines, and saves
    the plotted array with splines superimposed.

    Args:
        path (str): The path to save the image to.
        name (str): The filename.
        img (np.array): The image.
        vel (np.array): The velocity.
        roi: A roi instance.
        spl: Fitted spolines.

    Returns:
    """
    if not os.path.exists(path):
        os.makedirs(path)

    # Plot image.
    fig, ax = plt.subplots(figsize=(10, 5))
    plt.imshow(img, cmap=cm.gray)
    # ax.set_title('Splines and characteristics.')

    # Plot splines.
    for v in roi:
        # Plot roi.
        y = roi[v]['y']
        points = np.array([spl[v](y), y]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)

        lc = LineCollection(segments)
        lc.set_linewidth(2)
        lc.set_color('C3')
        plt.gca().add_collection(lc)

        # Plot characteristics.
        y = np.arange(y[0], y[-1] + 1, 1)
        c = curves[v]
        points = np.array([c, y]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)

        lc = LineCollection(segments)
        lc.set_linewidth(2)
        lc.set_color('C0')
        plt.gca().add_collection(lc)

    fig.tight_layout()
    fig.savefig(os.path.join(path, '{0}-splines-curves.png'.format(name)),
                dpi=dpi,
                bbox_inches='tight')
    plt.close(fig)
Esempio n. 20
0
def plot_cubical_2D_cell_complex(K):
    fig, axes = configure_2D_plot(K)
    verts = np.array([cell.cube_map for cell in K(0)]) / 2
    edges = np.array([edge_vertices(cell) for cell in K(1)])
    faces = np.array([face_vertices(cell) for cell in K(2)])
    axes.scatter(verts[:, 1], verts[:, 0], alpha=0.5)
    edges_coll = LineCollection(edges)
    edges_coll.set_color('green')
    edges_coll.set_alpha(0.5)
    faces_coll = PolyCollection(faces, )
    faces_coll.set_color('pink')
    axes.add_collection(edges_coll)
    axes.add_collection(faces_coll)
    return fig, axes
Esempio n. 21
0
def plotcf(grid,
           phase,
           modulus,
           darken=None,
           axes=None,
           linestylep="solid",
           linewidthp=1,
           color="k",
           **kwargs):
    r"""Plot the modulus of a complex valued function
    :math:`f:\mathbb{R} \rightarrow \mathbb{C}`
    together with its phase in a color coded fashion.

    :param grid: The grid nodes of the real domain R
    :param phase: The phase of the complex domain result f(grid)
    :param modulus: The modulus of the complex domain result f(grid)
    :param darken: Whether to take into account the modulus of the data to darken colors.
    :param axes: The axes instance used for plotting.
    :param linestylep: The line style of the phase curve.
    :param linewidthp: The line width of the phase curve.
    :param color: The color of the phase curve.
    """
    # Color mapping
    rgb_colors = color_map(modulus,
                           phase=phase,
                           modulus=modulus,
                           darken=darken)

    # Put all the vertical line into a collection
    segments = [
        array([[node, 0], [node, value]])
        for node, value in zip(grid, modulus)
    ]
    line_segments = LineCollection(segments)

    # Set some properties of the lines
    rgb_colors = line_segments.to_rgba(rgb_colors)
    line_segments.set_color(rgb_colors[0])
    line_segments.set_linestyle(linestylep)
    line_segments.set_linewidth(linewidthp)

    # Plot to the given axis instance or retrieve the current one
    if axes is None:
        axes = gca()

    # Plot the phase
    axes.add_collection(line_segments)
    # Plot the modulus
    axes.plot(grid, modulus, color=color, **kwargs)
Esempio n. 22
0
  def segments(self, points, color='black', **kwargs):
    'plot line'

    segments = numpy.concatenate([numpy.array([xy[:-1], xy[1:]]).swapaxes(0,1) for xy in points], axis=0)
    from matplotlib.collections import LineCollection
    lc = LineCollection(segments, **kwargs)
    ax = self.gca()
    ax.add_collection(lc)
    if isinstance(color, str):
      lc.set_color(color)
    else:
      array = numpy.concatenate([.5 * (v[:-1] + v[1:]) for v in color], axis=0)
      lc.set_array(array)
      self.sci(lc)
    return lc
Esempio n. 23
0
def generate_boundary_artist(vertices, color):
    if DIM == 2:
        artist = LineCollection(vertices)
        artist.set_color(color)
        artist.set_linewidth(2.5)
    elif DIM == 3:
        artist = Poly3DCollection(vertices, linewidths=1)
        # transparency alpha must be set BEFORE face/edge color
        artist.set_alpha(0.5)
        artist.set_facecolor(color)
        artist.set_edgecolor('k')
    else:
        raise ValueError(
            "%d dimensions needs special attention for plotting." % int(DIM))
    return artist
Esempio n. 24
0
def _add_plot(fig, ax, plot_data, color_data, pkeys, lw=1, cmap='_auto',
              alpha=1.0):
  colors = color_data.color
  if cmap == '_auto':
    cmap = None
    if color_data.is_categorical:
      colors = np.take(COLOR_CYCLE, colors, mode='wrap')

  if plot_data.scatter:
    data, = plot_data.trajs
    artist = ax.scatter(*data.T, marker='o', c=colors, edgecolor='none',
                        s=lw*20, cmap=cmap, alpha=alpha, picker=5)
  else:
    # trajectory plot
    if hasattr(colors, 'dtype') and np.issubdtype(colors.dtype, np.number):
      # delete lines with NaN colors
      mask = np.isfinite(colors)
      if mask.all():
        trajs = plot_data.trajs
      else:
        trajs = [t for i,t in enumerate(plot_data.trajs) if mask[i]]
        colors = colors[mask]
      artist = LineCollection(trajs, linewidths=lw, cmap=cmap)
      artist.set_array(colors)
    else:
      artist = LineCollection(plot_data.trajs, linewidths=lw, cmap=cmap)
      artist.set_color(colors)
    artist.set_alpha(alpha)
    artist.set_picker(True)
    artist.set_pickradius(5)
    ax.add_collection(artist, autolim=True)
    ax.autoscale_view()
    # Force ymin -> 0
    ax.set_ylim((0, ax.get_ylim()[1]))

  def on_pick(event):
    if event.artist is not artist:
      return
    label = pkeys[event.ind[0]]
    ax.set_title(label)
    fig.canvas.draw_idle()

  # XXX: hack, make this more official
  if hasattr(fig, '_superman_cb'):
    fig.canvas.mpl_disconnect(fig._superman_cb[0])
  cb_id = fig.canvas.mpl_connect('pick_event', on_pick)
  fig._superman_cb = (cb_id, on_pick)
  return artist
Esempio n. 25
0
    def plot_profiles_in_map_view(self,
                                  field="topographic__elevation",
                                  endpoints_only=False,
                                  color=None,
                                  **kwds):
        """Plot profile locations in map view.

        Parameters
        ----------
        field : field name or nnode array
            Array of the at-node-field to plot as the 2D map values.
            Default value is the at-node field 'topographic__elevation'.
        endpoints_only : boolean
            Boolean where False (default) indicates every node along the
            profile is plotted, or True indicating only segment endpoints are
            plotted.
        color : RGBA tuple or color string
            Color to use in order to plot all profiles the same color. Default
            is None, and the colors assigned to each profile are used.
        **kwds : dictionary
            Keyword arguments to pass to imshow_grid.
        """
        # make imshow_grid background
        imshow_grid(self._grid, field, **kwds)
        ax = plt.gca()

        # create segments the way that line collection likes them.
        segments = []
        for idx, nodes in enumerate(self._nodes):
            if endpoints_only:
                select_nodes = [nodes[0], nodes[-1]]
                segments.append(
                    list(
                        zip(
                            self._grid.x_of_node[select_nodes],
                            self._grid.y_of_node[select_nodes],
                        )))

            else:
                segments.append(
                    list(
                        zip(self._grid.x_of_node[nodes],
                            self._grid.y_of_node[nodes])))

        line_segments = LineCollection(segments)
        colors = color or self._colors
        line_segments.set_color(colors)
        ax.add_collection(line_segments)
Esempio n. 26
0
 def plot(self, plot, col):
   # Set the scale of the plot
   if self.log_x:
     plot.xscale('log')
   if self.log_y:
     plot.yscale('log')
   # Process the values
   values = []
   for x in self.get_x_data_gen().get_values():
     for y in self.get_y_data_gen().get_values():
       values.append(zip(x,y))
   lines = LineCollection(values)
   lines.set_color(col)
   lines.set_label(str(self.get_name()))
   # Plot the values
   plot.add_collection(lines)
Esempio n. 27
0
    def drawstates(self,ax,linewidth=0.5,color='k',antialiased=1):
        """
 Draw state boundaries in Americas.

 ax - current axis instance.
 linewidth - state boundary line width (default 0.5)
 color - state boundary line color (default black)
 antialiased - antialiasing switch for state boundaries (default True).
        """
        coastlines = LineCollection(self.statesegs,antialiaseds=(antialiased,))
        try:
            coastlines.set_color(color)
        except: # this was a typo that existed in matplotlib-0.71 and earlier
            coastlines.color(color)
        coastlines.set_linewidth(linewidth)
        ax.add_collection(coastlines)
Esempio n. 28
0
 def add_lines(self, levels, colors, linewidths):
     '''
     Draw lines on the colorbar.
     '''
     N = len(levels)
     y = self._locate(levels)
     x = nx.array([0.0, 1.0])
     X, Y = meshgrid(x, y)
     if self.orientation == 'vertical':
         xy = [zip(X[i], Y[i]) for i in range(N)]
     else:
         xy = [zip(Y[i], X[i]) for i in range(N)]
     col = LineCollection(xy, linewidths=linewidths)
     self.lines = col
     col.set_color(colors)
     self.ax.add_collection(col)
Esempio n. 29
0
def generate_boundary_artist(vertices, color):
    ndim = len(next(iter(vertices[0])))
    vertices = tuple(map(tuple, vertices))
    if ndim == 2:
        artist = LineCollection(vertices)
        artist.set_color(color)
        artist.set_linewidth(2.5)
    elif ndim == 3:
        artist = Poly3DCollection(vertices, linewidth=1)
        # transparency alpha must be set BEFORE face/edge color
        artist.set_alpha(0.5)
        artist.set_facecolor(color)
        artist.set_edgecolor('k')
    else:
        raise ValueError("{:d} dimensions needs special attention for plotting".format(ndim))
    return artist
Esempio n. 30
0
 def add_lines(self, levels, colors, linewidths):
     """
     Draw lines on the colorbar.
     """
     N = len(levels)
     y = self._locate(levels)
     x = nx.array([0.0, 1.0])
     X, Y = meshgrid(x, y)
     if self.orientation == "vertical":
         xy = [zip(X[i], Y[i]) for i in range(N)]
     else:
         xy = [zip(Y[i], X[i]) for i in range(N)]
     col = LineCollection(xy, linewidths=linewidths)
     self.lines = col
     col.set_color(colors)
     self.ax.add_collection(col)
Esempio n. 31
0
    def drawcountries(self,linewidth=0.5,color='k',antialiased=1):
        """
 Draw country boundaries.

 linewidth - country boundary line width (default 0.5)
 color - country boundary line color (default black)
 antialiased - antialiasing switch for country boundaries (default True).
        """
        # get current axes instance.
        ax = pylab.gca()
        coastlines = LineCollection(self.cntrysegs,antialiaseds=(antialiased,))
        try:
            coastlines.set_color(color)
        except: # this was a typo that existed in matplotlib-0.71 and earlier
            coastlines.color(color)
        coastlines.set_linewidth(linewidth)
        ax.add_collection(coastlines)
Esempio n. 32
0
    def drawstates(self, ax, linewidth=0.5, color='k', antialiased=1):
        """
 Draw state boundaries in Americas.

 ax - current axis instance.
 linewidth - state boundary line width (default 0.5)
 color - state boundary line color (default black)
 antialiased - antialiasing switch for state boundaries (default True).
        """
        coastlines = LineCollection(self.statesegs,
                                    antialiaseds=(antialiased, ))
        try:
            coastlines.set_color(color)
        except:  # this was a typo that existed in matplotlib-0.71 and earlier
            coastlines.color(color)
        coastlines.set_linewidth(linewidth)
        ax.add_collection(coastlines)
def plot_trajectory_ellipse(frame, varx="attr_VARX", vary="attr_VARY", covxy="attr_COVXY", opacity_factor=1):
    """
    Draw the trajectory and uncertainty ellipses around teach point.
    1) Scatter of points 
    2) Trajectory lines
    3) Ellipses 
    :param frame: Trajectory
    :param opacity_factor: all opacity values are multiplied by this. Useful when used to plot multiple Trajectories in
     an overlay plot.
    :return: axis
    """
    ellipses = []    
    segments = []
    start_point = None

    for i, pnt in frame.iterrows():  
        # The ellipse
        U, s, V = np.linalg.svd(np.array([[pnt[varx], pnt[covxy]], 
                                          [pnt[covxy], pnt[vary]]]), full_matrices=True)
        w, h = s**.5 
        theta = np.arctan(V[1][0]/V[0][0])   # == np.arccos(-V[0][0])              
        ellipse = {"xy":pnt[list(frame.geo_cols)].values, "width":w, "height":h, "angle":theta}
        ellipses.append(Ellipse(**ellipse))
        
        # The line segment
        x, y = pnt[list(frame.geo_cols)][:2]
        if start_point:           
            segments.append([start_point, (x, y)])
        start_point = (x, y)

    ax = plt.gca()
    ellipses = PatchCollection(ellipses)
    ellipses.set_facecolor('none')
    ellipses.set_color("green")
    ellipses.set_linewidth(2)
    ellipses.set_alpha(.4*opacity_factor)
    ax.add_collection(ellipses)

    frame.plot(kind="scatter", x=frame.geo_cols[0], y=frame.geo_cols[1], marker=".", ax=plt.gca(), alpha=opacity_factor)

    lines = LineCollection(segments)
    lines.set_color("gray")
    lines.set_linewidth(1)
    lines.set_alpha(.2*opacity_factor)
    ax.add_collection(lines)
    return ax
Esempio n. 34
0
    def drawcoastlines(self,linewidth=1.,color='k',antialiased=1):
        """
 Draw coastlines.

 linewidth - coastline width (default 1.)
 color - coastline color (default black)
 antialiased - antialiasing switch for coastlines (default True).
        """
        # get current axes instance.
        ax = pylab.gca()
        coastlines = LineCollection(self.coastsegs,antialiaseds=(antialiased,))
        try:
            coastlines.set_color(color)
        except: # this was a typo that existed in matplotlib-0.71 and earlier
            coastlines.color(color)
        coastlines.set_linewidth(linewidth)
        ax.add_collection(coastlines)
        # set axes limits to fit map region.
        self.set_axes_limits()
Esempio n. 35
0
	def plotExpectationContours(self, projection = [0,0], showDU=False, showMU=False, plot=None, alpha=1):
		if plot is None:
			plot = pl.figure().add_subplot(1,1,1)
		self.setLimits(xprojection=projection)
		self.labelAxes(plot)
		mpl.rcParams['lines.linewidth']=1
		
		minx = min(self.OD.indAttr())-projection[0]
		maxx = max(self.OD.indAttr())+projection[1]
		x = np.array([np.linspace(minx, maxx, self.xres)]).T
		y_pred = self.ED.getExpectationsAt(x,False)
		
		DUvals=np.zeros(len(x))
		MUvals=np.zeros(len(x))
		if showDU:
			DUvals = self.OD.distanceUncertainty(x)
		if showMU:
			MUvals = self.ED.misclassUncertainty(x)
		scaling = 1-np.minimum(np.ones(len(x)),DUvals+MUvals)
		maxLW = 3
		minLW = 0.25	
		for i,b in enumerate(self.OD.bins):
			alpha=1
			#alpha = 1-(abs(i-len(self.OD.bins)/2.0)/float(len(self.OD.bins)/2.0)) # Weight the colour of the contour to the distance from the median
			points = np.array([x[:,0], y_pred[b]]).T.reshape(-1, 1, 2) 
			segments = np.concatenate([points[:-1], points[1:]], axis=1)
			# create a (r,g,b,a) color description for each line segment 
			cmap = [] 
			for a in segments: 
				# the x-value for this segment is: 
				x0 = a.mean(0)[0]
				# so it has a scaling value of: 
				s0 = np.interp(x0,x[:,0],scaling) 
				cmap.append([1-s0,0,s0,alpha])
			# Create the line collection object, and set the color parameters. 
			distFromMedian = 2 * abs(b - 0.5)
			lw = (1 - distFromMedian) * (maxLW-minLW)+minLW
			#if b== 0.5:
			#	lw = 3
			lc = LineCollection(segments, linewidths=lw) 
			lc.set_color(cmap)
			plot.add_collection(lc)
		return plot
Esempio n. 36
0
def stemcf(grid, phase, modulus, darken=False, axes=None, linestylep="solid", linewidthp=2, color=None, markerp="o", **kwargs):
    r"""
    Stemplot the modulus of a complex valued function :math:`f:I \rightarrow C` together with its phase in a color coded fashion.

    :param grid: The grid nodes of the real domain R
    :param phase: The phase of the complex domain result f(grid)
    :param modulus: The modulus of the complex domain result f(grid)
    :param darken: Whether to take into account the modulus of the data to darken colors.
    :param axes: The axes instance used for plotting.
    :param linestylep: The line style of the phase curve.
    :param linewidthp: The line width of the phase curve.
    :param color: The color of the stemmed markers.
    :param markerp: The shape of the stemmed markers.

    .. note:: Additional keyword arguments are passe to the plot function.
    """
    # Color mapping
    rgb_colors = color_map(grid, phase=phase, modulus=modulus, darken=darken)

    # Put all the vertical line into a collection
    segments = [ array([[node,0], [node,value]]) for node, value in zip(grid, modulus) ]
    line_segments = LineCollection(segments)

    # Set some properties of the lines
    rgb_colors = line_segments.to_rgba(rgb_colors)
    line_segments.set_color(rgb_colors[0])
    line_segments.set_linestyle(linestylep)
    line_segments.set_linewidth(linewidthp)

    # Plot to the given axis instance or retrieve the current one
    if axes is None:
        axes = gca()

    # Plot the phase
    axes.add_collection(line_segments)
    # Plot the modulus
    if color is None:
        # Scatter has a problem with complex data type, make sure values are purely real
        axes.scatter(grid, real(modulus), c=rgb_colors[0], **kwargs)
    else:
        axes.plot(grid, modulus, linestyle="", marker=markerp, color=color, **kwargs)
    # Plot the ground line
    axes.plot(grid, zeros(grid.shape), linestyle=linestylep, color="k", **kwargs)
Esempio n. 37
0
    def drawcountries(self,linewidth=0.5,color='k',antialiased=1):
        """
 Draw country boundaries.

 linewidth - country boundary line width (default 0.5)
 color - country boundary line color (default black)
 antialiased - antialiasing switch for country boundaries (default True).
        """
        # get current axes instance.
        ax = pylab.gca()
        coastlines = LineCollection(self.cntrysegs,antialiaseds=(antialiased,))
        try:
            coastlines.set_color(color)
        except: # this was a typo that existed in matplotlib-0.71 and earlier
            coastlines.color(color)
        coastlines.set_linewidth(linewidth)
        ax.add_collection(coastlines)
        # set axes limits to fit map region.
        self.set_axes_limits()
Esempio n. 38
0
def plot_fracdos():
    K1=1.4
    K2=1.0
    nsite=100
    target_block=(0,0)
    dmu_mag=0.01
    fnames=['fracdos_W1%s_W2%s_U%s_N%s_dmu%s_%s.dat'%(K1,K2,0.,nsite,dmu,target_block) for dmu in [dmu_mag,-dmu_mag]]
    pls=[loadtxt(fname) for fname in fnames]
    pls=array(pls)-0.5
    nsite=pls.shape[-1]
    pls_left=pls[...,:nsite/2]
    pls_right=pls[...,nsite/2:]
    print 'occupation in left block -> %s, right block -> %s.'%(sum(pls_left,axis=(-1,-2)),sum(pls_right,axis=(-1,-2)))
    ion()
    fig=figure(figsize=(7,5))
    lw=2
    lc='r'
    axs=[]
    site_loc=append(arange(20),arange(25,45))
    sites=append(arange(20),arange(nsite-20,nsite))
    for n in xrange(len(pls)):
        pln=pls[n].sum(axis=0)
        ax=subplot(11+n+100*len(pls),sharex=axs[0] if n==1 else None)
        text(0.02,0.9,'(a)' if n==0 else '(b)',transform=ax.transAxes)
        color='k'
        lc=LineCollection([[(posi,0),(posi,pln[sitei].item())] for posi,sitei in zip(site_loc,sites)])
        lc.set_linewidth(lw)
        lc.set_color(color)
        #lc.set_linestyle('--' if s==1 else '-')
        ax.add_collection(lc)

        ax.autoscale()
        ax.margins(0.1)
        ylabel(r'$\rho-\bar{\rho}$',fontsize=LABELSIZE)
        ax.set_xticks(list(site_loc[:20:5])+[23]+list(site_loc[19::5]))
        ax.set_xticklabels(list(sites[:20:5]+1)+[r'$\bf{\ldots}$']+list(sites[19::5]))
        yticks([-0.5,-0.25,0,0.25,0.5])
    xlabel(r'$N$',fontsize=LABELSIZE)
    subplots_adjust(hspace=0.05)
    pdb.set_trace()
    savefig('fracdos.eps')
    savefig('fracdos.png')
Esempio n. 39
0
def create_linecollection():
    '''
    According to the LineCollection tutorial: "We need to set the plot limits, they will not autoscale"
    - The autoscale() method works!
        - It is NOT implicitly invoked
    - LineCollection objects don't have a __len__() nor are they iterable
    '''
    segments = [
        [(0, 0), (5, 5)],  # line_0 # 2 points
        [(1, 1.1), (6, 6)],  # line_1 # 2 points
        [(2, 2), (4, 0), (10, 1)]  # line_2: 3 points
    ]
    lc = LineCollection(segments)
    lc.set_color(('r', 'g', 'b'))
    fig, ax = plt.subplots()
    ax.add_collection(lc)
    ax.autoscale()
    #ax.set_xlim(0, 10)
    #ax.set_ylim(0, 10)
    plt.show()
Esempio n. 40
0
def stemcf(grid, phase, modulus, darken=None, axes=None, linestylep="solid", linewidthp=2, color=None, markerp="o", **kwargs):
    r"""Stemplot the modulus of a complex valued function :math:`f:I -> \mathbb{C}` together with its phase in a color coded fashion.
    Additional keyword arguments are passed to the plot function.

    :param grid: The grid nodes of the real domain grid :math:`\Gamma`
    :param phase: The phase of the complex domain result :math:`f(\Gamma)`
    :param modulus: The modulus of the complex domain result :math:`f(\Gamma)`
    :param darken: Whether to take into account the modulus of the data to darken colors.
    :param axes: The axes instance used for plotting.
    :param linestylep: The line style of the phase curve.
    :param linewidthp: The line width of the phase curve.
    :param color: The color of the stemmed markers.
    :param markerp: The shape of the stemmed markers.
    """
    # Color mapping
    rgb_colors = color_map(grid, phase=phase, modulus=modulus, darken=darken)

    # Put all the vertical line into a collection
    segments = [array([[node, 0], [node, value]]) for node, value in zip(grid, modulus)]
    line_segments = LineCollection(segments)

    # Set some properties of the lines
    rgb_colors = line_segments.to_rgba(rgb_colors)
    line_segments.set_color(rgb_colors[0])
    line_segments.set_linestyle(linestylep)
    line_segments.set_linewidth(linewidthp)

    # Plot to the given axis instance or retrieve the current one
    if axes is None:
        axes = gca()

    # Plot the phase
    axes.add_collection(line_segments)
    # Plot the modulus
    if color is None:
        # Scatter has a problem with complex data type, make sure values are purely real
        axes.scatter(grid, real(modulus), c=rgb_colors[0], **kwargs)
    else:
        axes.plot(grid, modulus, linestyle="", marker=markerp, color=color, **kwargs)
    # Plot the ground line
    axes.plot(grid, zeros(grid.shape), linestyle=linestylep, color="k", **kwargs)
def plot_sparse_trajectory(trajectory, r=50, opacity_factor=1, plot_text=True,
                           num_col="segment_sparcify_n", min_static=100):
    """
    Plots a sparsified trajectory as circles with the number of points they represent as a number inside.
    :param trajectory: Trajectory object
    :param r: the radius of circles
    :param num_col: where to find the number to put in the circles
    :param min_static: minimum count to change color of circle
    :param plot_text: put the text with num of points in the circle?
    :return: ax
    """
    ax = plt.gca()
    trajectory.plot(kind="scatter", x=trajectory.geo_cols[0], y=trajectory.geo_cols[1], marker=".",
                    ax=plt.gca(), alpha=0.0*opacity_factor)

    circles = []
    segments = []
    start_point = None

    for i, pnt in trajectory.iterrows():
        circles.append(Circle(pnt[list(trajectory.geo_cols)].values, radius=r))

        if plot_text:
            plt.text(*pnt[list(trajectory.geo_cols)], s=str(int(pnt[num_col])), fontsize=12)

        x, y = pnt[list(trajectory.geo_cols)][:2]
        if start_point:
            segments.append([start_point, (x, y)])
        start_point = (x, y)

    circles = PatchCollection(circles)
    circles.set_facecolor(['none' if cnt < min_static else 'red' for cnt in trajectory[num_col].values])
    circles.set_alpha(.5*opacity_factor)
    ax.add_collection(circles)

    lines = LineCollection(segments)
    lines.set_color("gray")
    lines.set_alpha(.2*opacity_factor)
    ax.add_collection(lines)

    return ax
Esempio n. 42
0
class LineCollection(object):
    def __init__(self, ax):
        self._ax = ax
        self._lc = None

    @property
    def artists(self):
        return [self._lc]

    def draw(self, x, y, **kwargs):
        xy = np.stack([x, y], axis=1)
        xy = xy.reshape(-1, 1, 2)
        segments = np.hstack([xy[:-1], xy[1:]])

        if self._lc is None:
            self._lc = PltLineCollection(segments)
            self._ax.add_collection(self._lc)
        else:
            self._lc.set_segments(segments)
        if 'color' in kwargs:
            self._lc.set_color(kwargs['color'])
Esempio n. 43
0
def show_mf_wave(**kwargs):
    K1=1.4
    K2=1.0
    U=0.0
    nsite=100
    dmu=0.01
    lw=2
    lc='r'
    mjfile='mf_W1%s_W2%s_U%s_N%s_dmu%s.npy'%(K1,K2,U,nsite,dmu)
    pls=load(mjfile)
    ampl=(pls[:2]*pls[:2].conj()).real
    nsite=pls.shape[1]

    ion()
    fig=figure(figsize=(7,4))
    for n in xrange(2):
        pln=ampl[n]
        ax=subplot(121+n)
        lc=LineCollection([[(i+1,0),(i+1,pln[i].item())] for i in xrange(nsite)])
        lc.set_linewidth(lw)
        lc.set_color('k')
        ax.add_collection(lc)

        ax.autoscale()
        ax.margins(0.1)
        if n==0:
            text(0.02,0.9,'(a)',transform=ax.transAxes,color='k')
            xlim(0,22)
            xticks(arange(1,22,5))
            ylabel(r'$|\phi_j|^2$',fontsize=LABELSIZE)
        else:
            text(0.02,0.9,'(b)',transform=ax.transAxes,color='k')
            xlim(79,101)
            yticks([])
        ylim(0,0.2)
        xlabel('$j$',fontsize=LABELSIZE)
    tight_layout(w_pad=0.5)
    pdb.set_trace()
    savefig('mf.eps')
    savefig('mf.png')
Esempio n. 44
0
 def changeVecteur(self, ech=1., col=None):
     """ modifie les valeurs de vecteurs existants"""
     self.drawVecteur(False)
     if type(ech) == type((3, 4)):
         if len(ech) >= 1: ech = ech[0]
     # previous object
     obj = self.getObjFromType('vecteur')
     if obj == None: return
     #change coordinates
     dep, arr_old, ech_old = obj.getData()
     arr = dep + (arr_old - dep) * ech / ech_old
     # new object
     lc1 = LineCollection(zip(dep, arr))
     lc1.set_transform(self.transform)
     if col == None: col = wx.Color(0, 0, 255)
     a = col.Get()
     col = (a[0] / 255, a[1] / 255, a[2] / 255)
     lc1.set_color(col)
     obj = GraphicObject('vecteur', lc1, False, None)
     obj.setData([dep, arr, ech])
     self.addGraphicObject(obj)
     self.cnv.collections[0] = lc1
     self.redraw()
Esempio n. 45
0
class SURFDemo(ImageProcessDemo):
    TITLE = "SURF Demo"
    DEFAULT_IMAGE = "lena.jpg"
    SETTINGS = ["m_perspective", "hessian_threshold", "n_octaves"]
    m_perspective = Array(np.float, (3, 3))
    m_perspective2 = Array(np.float, (3, 3))

    hessian_threshold = Int(2000)
    n_octaves = Int(2)

    poly = Instance(PolygonWidget)

    def control_panel(self):
        return VGroup(
            Item("m_perspective", label=u"变换矩阵", editor=ArrayEditor(format_str="%g")),
            Item("m_perspective2", label=u"变换矩阵", editor=ArrayEditor(format_str="%g")),
            Item("hessian_threshold", label=u"hessianThreshold"),
            Item("n_octaves", label=u"nOctaves")
        )

    def __init__(self, **kwargs):
        super(SURFDemo, self).__init__(**kwargs)
        self.poly = None
        self.init_points = None
        self.lines = LineCollection([], linewidths=1, alpha=0.6, color="red")
        self.axe.add_collection(self.lines)
        self.connect_dirty("poly.changed,hessian_threshold,n_octaves")

    def init_poly(self):
        if self.poly is None:
            return
        h, w, _ = self.img_color.shape
        self.init_points = np.array([(w, 0), (2*w, 0), (2*w, h), (w, h)], np.float32)
        self.poly.set_points(self.init_points)
        self.poly.update()

    def init_draw(self):
        style = {"marker": "o"}
        self.poly = PolygonWidget(axe=self.axe, points=np.zeros((3, 2)), style=style)
        self.init_poly()

    @on_trait_change("hessian_threshold, n_octaves")
    def calc_surf1(self):
        self.surf = cv2.SURF(self.hessian_threshold, self.n_octaves)
        self.key_points1, self.features1 = self.surf.detectAndCompute(self.img_gray, None)
        self.key_positions1 = np.array([kp.pt for kp in self.key_points1])

    def _img_changed(self):
        self.img_gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
        self.img_color = cv2.cvtColor(self.img_gray, cv2.COLOR_GRAY2RGB)
        self.img_show = np.concatenate([self.img_color, self.img_color], axis=1)
        self.size = self.img_color.shape[1], self.img_color.shape[0]
        self.calc_surf1()

        FLANN_INDEX_KDTREE = 1
        index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
        search_params = dict(checks=100)

        self.matcher = cv2.FlannBasedMatcher(index_params, search_params)

        self.init_poly()

    def settings_loaded(self):
        src = self.init_points.copy()
        w, h = self.size
        src[:, 0] -= w
        dst = cv2.perspectiveTransform(src[None, :, :], self.m_perspective)
        dst = dst.squeeze()
        dst[:, 0] += w
        self.poly.set_points(dst)
        self.poly.update()

    def draw(self):
        if self.poly is None:
            return
        w, h = self.size
        src = self.init_points.copy()
        dst = self.poly.points.copy().astype(np.float32)
        src[:, 0] -= w
        dst[:, 0] -= w
        m = cv2.getPerspectiveTransform(src, dst)
        self.m_perspective = m
        img2 = cv2.warpPerspective(self.img_gray, m, self.size, borderValue=[255]*4)
        self.img_show[:, w:, :] = img2[:, :, None]
        key_points2, features2 = self.surf.detectAndCompute(img2, None)

        key_positions2 = np.array([kp.pt for kp in key_points2])

        match_list = self.matcher.knnMatch(self.features1, features2, k=1)
        index1 = np.array([m[0].queryIdx for m in match_list])
        index2 = np.array([m[0].trainIdx for m in match_list])

        distances = np.array([m[0].distance for m in match_list])

        n = min(50, len(distances))
        best_index = np.argsort(distances)[:n]
        matched_positions1 = self.key_positions1[index1[best_index]]
        matched_positions2 = key_positions2[index2[best_index]]

        self.m_perspective2, mask = cv2.findHomography(matched_positions1, matched_positions2, cv2.RANSAC)

        lines = np.concatenate([matched_positions1, matched_positions2], axis=1)
        lines[:, 2] += w
        line_colors = COLORS[mask.ravel()]
        self.lines.set_segments(lines.reshape(-1, 2, 2))
        self.lines.set_color(line_colors)
        self.draw_image(self.img_show)
Esempio n. 46
0
class SpiroGraph(object):

    '''
    Spirograph drawer with matplotlib slider widgets to change parameters.
    Parameters of line are:

        R: The radius of the big circle
        r: The radius of the small circle which rolls along the inside of the
           bigger circle
        p: distance from centre of smaller circle to point in the circle where
           the pen hole is.
        tmax: the angle through which the smaller circle is rotated to draw the
              spirograph
        tstep: how often matplotlib plots a point
        a, b, c: parameters of the linewidth equation.
    '''

    # kwargs for each of the matplotlib sliders
    slider_kwargs = (
        {'label': 't_max', 'valmin': np.pi, 'valmax': 200 * np.pi,
         'valinit': tmax0, 'valfmt': PiString()},
        {'label': 't_step', 'valmin': 0.01,
         'valmax': 10, 'valinit': tstep0},
        {'label': 'R', 'valmin': 1, 'valmax': 200, 'valinit': R0},
        {'label': 'r', 'valmin': 1, 'valmax': 200, 'valinit': r0},
        {'label': 'p', 'valmin': 1, 'valmax': 200, 'valinit': p0},
        {'label': 'colour', 'valmin': 0, 'valmax': 1, 'valinit': 1},
        {'label': 'width_a', 'valmin': 0.5, 'valmax': 10, 'valinit': 1},
        {'label': 'width_b', 'valmin': 0, 'valmax': 10, 'valinit': 0},
        {'label': 'width_c', 'valmin': 0, 'valmax': 10, 'valinit': 0.5})

    rbutton_kwargs = (
        {'labels': ('black', 'white'), 'activecolor': 'white', 'active': 0},
        {'labels': ('solid', 'variable'), 'activecolor': 'white', 'active': 0})

    def __init__(self, colormap, figsize=(7, 10)):
        self.colormap_name = colormap
        self.variable_color = False
        # Use ScalarMappable to map full colormap to range 0 - 1
        self.colormap = ScalarMappable(cmap=colormap)
        self.colormap.set_clim(0, 1)

        # set up main axis onto which to draw spirograph
        self.figsize = figsize
        plt.rcParams['figure.figsize'] = figsize
        self.fig, self.mainax = plt.subplots()
        plt.subplots_adjust(bottom=0.3)
        title = self.mainax.set_title('Spirograph Drawer!',
                                      size=20,
                                      color='white')
        self.text = [title, ]
        # set up slider axes
        self.slider_axes = [plt.axes([0.25, x, 0.65, 0.015])
                            for x in np.arange(0.05, 0.275, 0.025)]
        # same again for radio buttons
        self.rbutton_axes = [plt.axes([0.025, x, 0.1, 0.15])
                             for x in np.arange(0.02, 0.302, 0.15)]
        # use log scale for tstep slider
        self.slider_axes[1].set_xscale('log')
        # turn off frame, ticks and tick labels for all axes
        for ax in chain(self.slider_axes, self.rbutton_axes, [self.mainax, ]):
            ax.axis('off')
        # use axes and kwargs to create list of sliders/rbuttons
        self.sliders = [Slider(ax, **kwargs)
                        for ax, kwargs in zip(self.slider_axes,
                                              self.slider_kwargs)]
        self.rbuttons = [RadioButtons(ax, **kwargs)
                         for ax, kwargs in zip(self.rbutton_axes,
                                               self.rbutton_kwargs)]
        self.update_figcolors()

        # set up initial line
        self.t = np.arange(0, tmax0, tstep0)
        x, y = spiro_linefunc(self.t, R0, r0, p0)
        self.linecollection = LineCollection(
            segments(x, y),
            linewidths=spiro_linewidths(self.t, a0, b0, c0),
            color=self.colormap.to_rgba(col0))
        self.mainax.add_collection(self.linecollection)

        # creates the plot and connects sliders to various update functions
        self.run()

    def update_figcolors(self, bgcolor='black'):
        '''
        function run by background color radiobutton. Sets all labels, text,
        and sliders to foreground color, all axes to background color
        '''
        fgcolor = 'white' if bgcolor == 'black' else 'black'
        self.fig.set_facecolor(bgcolor)
        self.mainax.set_axis_bgcolor(bgcolor)
        for ax in chain(self.slider_axes, self.rbutton_axes):
            ax.set_axis_bgcolor(bgcolor)

        # set fgcolor elements to black or white, mostly elements of sliders
        for item in chain(map(attrgetter('label'), self.sliders),
                          map(attrgetter('valtext'), self.sliders),
                          map(attrgetter('poly'), self.sliders),
                          self.text,
                          *map(attrgetter('labels'), self.rbuttons)):
            item.set_color(fgcolor)

        self.update_radiobutton_colors()
        plt.draw()

    def update_linewidths(self, *args):
        '''
        function run by a, b and c parameter sliders. Sets width of each line
        in linecollection according to sine function
        '''
        a, b, c = (s.val for s in self.sliders[6:])
        self.linecollection.set_linewidths(spiro_linewidths(self.t, a, b, c))
        plt.draw()

    def update_linecolors(self, *args):
        '''
        function run by color slider and indirectly by variable/solid color
        radiobutton. Updates colors of each line in linecollection using the
        set colormap.
        '''
        # get current color value (a value between 1 and 0)
        col_val = self.sliders[5].val
        if not self.variable_color:
            # if solid color, convert color value to rgb and set the color
            self.linecollection.set_color(self.colormap.to_rgba(col_val))
        else:
            # create values between 0 and 1 for each line segment
            colors = (self.t / max(self.t)) + col_val
            # use color value to roll colors
            colors[colors > 1] -= 1
            self.linecollection.set_color(
                [self.colormap.to_rgba(i) for i in colors])
        plt.draw()

    def update_lineverts(self, *args):
        '''
        function run by R, r, p, tmax and tstep sliders to update line vertices
        '''
        tmax, tstep, R, r, p = (s.val for s in self.sliders[:5])
        self.t = np.arange(0, tmax, tstep)
        x, y = spiro_linefunc(self.t, R, r, p)
        self.linecollection.set_verts(segments(x, y))
        # change axis limits to pad new line nicely
        self.mainax.set(xlim=(min(x) - 5, max(x) + 5),
                        ylim=(min(y) - 5, max(y) + 5))
        plt.draw()

    def update_linecolor_setting(self, val):
        '''
        function run by solid/variable colour slider, alters variable_color
        attribute then calls update_linecolors
        '''
        if val == 'variable':
            self.variable_color = True
        elif val == 'solid':
            self.variable_color = False
        # need to update radiobutton colors here.
        self.update_radiobutton_colors()
        self.update_linecolors()

    def update_radiobutton_colors(self):
        '''
        makes radiobutton colors correct even on a changing axis background
        '''
        bgcolor = self.rbuttons[0].value_selected
        fgcolor = 'white' if bgcolor == 'black' else 'black'
        for i, b in enumerate(self.rbuttons):
            # find out index of the active button
            active_idx = self.rbutton_kwargs[i]['labels'].index(
                b.value_selected)
            # set button colors accordingly
            b.circles[not active_idx].set_color(bgcolor)
            b.circles[active_idx].set_color(fgcolor)

    def run(self):
        '''
        set up slider functions
        '''
        verts_func = self.update_lineverts
        colors_func = self.update_linecolors
        widths_func = self.update_linewidths
        # create iterable of slider funcs to zip with sliders
        slider_update_funcs = chain(repeat(verts_func, 5),
                                    [colors_func, ],
                                    repeat(widths_func, 3))
        # set slider on_changed functions
        for s, f in zip(self.sliders, slider_update_funcs):
            s.on_changed(f)

        self.rbuttons[0].on_clicked(self.update_figcolors)
        self.rbuttons[1].on_clicked(self.update_linecolor_setting)
        plt.show()
Esempio n. 47
0
# a "waterfall" plot or a "stagger" plot.

nverts = 60
ncurves = 20
offs = (0.1, 0.0)

rs = np.random.RandomState([12345678])
yy = np.linspace(0, 2*np.pi, nverts)
ym = np.amax(yy)
xx = (0.2 + (ym-yy)/ym)**2 * np.cos(yy-0.4) * 0.5
segs = []
for i in range(ncurves):
    xxx = xx + 0.02*rs.randn(nverts)
    curve = list(zip(xxx, yy*100))
    segs.append(curve)

colors = [(1.0, 0.0, 0.0, 1.0), (0.0, 0.5, 0.0, 1.0), (0.0, 0.0, 1.0, 1.0), (0.0, 0.75, 0.75, 1.0),
          (0.75, 0.75, 0, 1.0), (0.75, 0, 0.75, 1.0), (0.0, 0.0, 0.0, 1.0)]

col = LineCollection(segs, linewidth=5, offsets=offs)

ax = plt.axes()
ax.add_collection(col, autolim=True)
col.set_color(colors)
ax.set_title('Successive data offsets')

fig = plt.gcf()

pyplot.show_bokeh(plt.gcf(), filename="mpl_lc_offsets.html")

plotting.session().dumpjson(file="mpl_lc_offsets.json")
Esempio n. 48
0
class ScatterLayerArtist(MatplotlibLayerArtist):

    _layer_state_cls = ScatterLayerState

    def __init__(self, axes, viewer_state, layer_state=None, layer=None):

        super(ScatterLayerArtist, self).__init__(axes, viewer_state,
                                                 layer_state=layer_state, layer=layer)

        # Watch for changes in the viewer state which would require the
        # layers to be redrawn
        self._viewer_state.add_global_callback(self._update_scatter)
        self.state.add_global_callback(self._update_scatter)

        # Scatter
        self.scatter_artist = self.axes.scatter([], [])
        self.plot_artist = self.axes.plot([], [], 'o', mec='none')[0]
        self.errorbar_artist = self.axes.errorbar([], [], fmt='none')
        self.vector_artist = None
        self.line_collection = LineCollection(np.zeros((0, 2, 2)))
        self.axes.add_collection(self.line_collection)

        # Scatter density
        self.density_auto_limits = DensityMapLimits()
        self.density_artist = ScatterDensityArtist(self.axes, [], [], color='white',
                                                   vmin=self.density_auto_limits.min,
                                                   vmax=self.density_auto_limits.max)
        self.axes.add_artist(self.density_artist)

        self.mpl_artists = [self.scatter_artist, self.plot_artist,
                            self.errorbar_artist, self.vector_artist,
                            self.line_collection, self.density_artist]
        self.errorbar_index = 2
        self.vector_index = 3

        self.reset_cache()

    def reset_cache(self):
        self._last_viewer_state = {}
        self._last_layer_state = {}

    @defer_draw
    def _update_data(self, changed):

        # Layer artist has been cleared already
        if len(self.mpl_artists) == 0:
            return

        try:
            x = self.layer[self._viewer_state.x_att].ravel()
        except (IncompatibleAttribute, IndexError):
            # The following includes a call to self.clear()
            self.disable_invalid_attributes(self._viewer_state.x_att)
            return
        else:
            self.enable()

        try:
            y = self.layer[self._viewer_state.y_att].ravel()
        except (IncompatibleAttribute, IndexError):
            # The following includes a call to self.clear()
            self.disable_invalid_attributes(self._viewer_state.y_att)
            return
        else:
            self.enable()

        if self.state.markers_visible:
            if self.state.density_map:
                self.density_artist.set_xy(x, y)
                self.plot_artist.set_data([], [])
                self.scatter_artist.set_offsets(np.zeros((0, 2)))
            else:
                if self.state.cmap_mode == 'Fixed' and self.state.size_mode == 'Fixed':
                    # In this case we use Matplotlib's plot function because it has much
                    # better performance than scatter.
                    self.plot_artist.set_data(x, y)
                    self.scatter_artist.set_offsets(np.zeros((0, 2)))
                    self.density_artist.set_xy([], [])
                else:
                    self.plot_artist.set_data([], [])
                    offsets = np.vstack((x, y)).transpose()
                    self.scatter_artist.set_offsets(offsets)
                    self.density_artist.set_xy([], [])
        else:
            self.plot_artist.set_data([], [])
            self.scatter_artist.set_offsets(np.zeros((0, 2)))
            self.density_artist.set_xy([], [])

        if self.state.line_visible:
            if self.state.cmap_mode == 'Fixed':
                points = np.array([x, y]).transpose()
                self.line_collection.set_segments([points])
            else:
                # In the case where we want to color the line, we need to over
                # sample the line by a factor of two so that we can assign the
                # correct colors to segments - if we didn't do this, then
                # segments on one side of a point would be a different color
                # from the other side. With oversampling, we can have half a
                # segment on either side of a point be the same color as a
                # point
                x_fine = np.zeros(len(x) * 2 - 1, dtype=float)
                y_fine = np.zeros(len(y) * 2 - 1, dtype=float)
                x_fine[::2] = x
                x_fine[1::2] = 0.5 * (x[1:] + x[:-1])
                y_fine[::2] = y
                y_fine[1::2] = 0.5 * (y[1:] + y[:-1])
                points = np.array([x_fine, y_fine]).transpose().reshape(-1, 1, 2)
                segments = np.concatenate([points[:-1], points[1:]], axis=1)
                self.line_collection.set_segments(segments)
        else:
            self.line_collection.set_segments(np.zeros((0, 2, 2)))

        for eartist in list(self.errorbar_artist[2]):
            if eartist is not None:
                try:
                    eartist.remove()
                except ValueError:
                    pass
                except AttributeError:  # Matplotlib < 1.5
                    pass

        if self.vector_artist is not None:
            self.vector_artist.remove()
            self.vector_artist = None

        if self.state.vector_visible:

            if self.state.vx_att is not None and self.state.vy_att is not None:

                vx = self.layer[self.state.vx_att].ravel()
                vy = self.layer[self.state.vy_att].ravel()

                if self.state.vector_mode == 'Polar':
                    ang = vx
                    length = vy
                    # assume ang is anti clockwise from the x axis
                    vx = length * np.cos(np.radians(ang))
                    vy = length * np.sin(np.radians(ang))

            else:
                vx = None
                vy = None

            if self.state.vector_arrowhead:
                hw = 3
                hl = 5
            else:
                hw = 1
                hl = 0

            v = np.hypot(vx, vy)
            vmax = np.nanmax(v)
            vx = vx / vmax
            vy = vy / vmax

            self.vector_artist = self.axes.quiver(x, y, vx, vy, units='width',
                                                  pivot=self.state.vector_origin,
                                                  headwidth=hw, headlength=hl,
                                                  scale_units='width',
                                                  scale=10 / self.state.vector_scaling)
            self.mpl_artists[self.vector_index] = self.vector_artist

        if self.state.xerr_visible or self.state.yerr_visible:

            if self.state.xerr_visible and self.state.xerr_att is not None:
                xerr = self.layer[self.state.xerr_att].ravel()
            else:
                xerr = None

            if self.state.yerr_visible and self.state.yerr_att is not None:
                yerr = self.layer[self.state.yerr_att].ravel()
            else:
                yerr = None

            self.errorbar_artist = self.axes.errorbar(x, y, fmt='none',
                                                      xerr=xerr, yerr=yerr)
            self.mpl_artists[self.errorbar_index] = self.errorbar_artist

    @defer_draw
    def _update_visual_attributes(self, changed, force=False):

        if not self.enabled:
            return

        if self.state.markers_visible:

            if self.state.density_map:

                if self.state.cmap_mode == 'Fixed':
                    if force or 'color' in changed or 'cmap_mode' in changed:
                        self.density_artist.set_color(self.state.color)
                        self.density_artist.set_c(None)
                        self.density_artist.set_clim(self.density_auto_limits.min,
                                                     self.density_auto_limits.max)
                elif force or any(prop in changed for prop in CMAP_PROPERTIES):
                    c = self.layer[self.state.cmap_att].ravel()
                    set_mpl_artist_cmap(self.density_artist, c, self.state)

                if force or 'stretch' in changed:
                    self.density_artist.set_norm(ImageNormalize(stretch=STRETCHES[self.state.stretch]()))

                if force or 'dpi' in changed:
                    self.density_artist.set_dpi(self._viewer_state.dpi)

                if force or 'density_contrast' in changed:
                    self.density_auto_limits.contrast = self.state.density_contrast
                    self.density_artist.stale = True

            else:

                if self.state.cmap_mode == 'Fixed' and self.state.size_mode == 'Fixed':

                    if force or 'color' in changed:
                        self.plot_artist.set_color(self.state.color)

                    if force or 'size' in changed or 'size_scaling' in changed:
                        self.plot_artist.set_markersize(self.state.size *
                                                        self.state.size_scaling)

                else:

                    # TEMPORARY: Matplotlib has a bug that causes set_alpha to
                    # change the colors back: https://github.com/matplotlib/matplotlib/issues/8953
                    if 'alpha' in changed:
                        force = True

                    if self.state.cmap_mode == 'Fixed':
                        if force or 'color' in changed or 'cmap_mode' in changed:
                            self.scatter_artist.set_facecolors(self.state.color)
                            self.scatter_artist.set_edgecolor('none')
                    elif force or any(prop in changed for prop in CMAP_PROPERTIES):
                        c = self.layer[self.state.cmap_att].ravel()
                        set_mpl_artist_cmap(self.scatter_artist, c, self.state)
                        self.scatter_artist.set_edgecolor('none')

                    if force or any(prop in changed for prop in MARKER_PROPERTIES):

                        if self.state.size_mode == 'Fixed':
                            s = self.state.size * self.state.size_scaling
                            s = broadcast_to(s, self.scatter_artist.get_sizes().shape)
                        else:
                            s = self.layer[self.state.size_att].ravel()
                            s = ((s - self.state.size_vmin) /
                                 (self.state.size_vmax - self.state.size_vmin)) * 30
                            s *= self.state.size_scaling

                        # Note, we need to square here because for scatter, s is actually
                        # proportional to the marker area, not radius.
                        self.scatter_artist.set_sizes(s ** 2)

        if self.state.line_visible:

            if self.state.cmap_mode == 'Fixed':
                if force or 'color' in changed or 'cmap_mode' in changed:
                    self.line_collection.set_array(None)
                    self.line_collection.set_color(self.state.color)
            elif force or any(prop in changed for prop in CMAP_PROPERTIES):
                # Higher up we oversampled the points in the line so that
                # half a segment on either side of each point has the right
                # color, so we need to also oversample the color here.
                c = self.layer[self.state.cmap_att].ravel()
                cnew = np.zeros((len(c) - 1) * 2)
                cnew[::2] = c[:-1]
                cnew[1::2] = c[1:]
                set_mpl_artist_cmap(self.line_collection, cnew, self.state)

            if force or 'linewidth' in changed:
                self.line_collection.set_linewidth(self.state.linewidth)

            if force or 'linestyle' in changed:
                self.line_collection.set_linestyle(self.state.linestyle)

        if self.state.vector_visible and self.vector_artist is not None:

            if self.state.cmap_mode == 'Fixed':
                if force or 'color' in changed or 'cmap_mode' in changed:
                    self.vector_artist.set_array(None)
                    self.vector_artist.set_color(self.state.color)
            elif force or any(prop in changed for prop in CMAP_PROPERTIES):
                c = self.layer[self.state.cmap_att].ravel()
                set_mpl_artist_cmap(self.vector_artist, c, self.state)

        if self.state.xerr_visible or self.state.yerr_visible:

            for eartist in list(self.errorbar_artist[2]):

                if eartist is None:
                    continue

                if self.state.cmap_mode == 'Fixed':
                    if force or 'color' in changed or 'cmap_mode' in changed:
                        eartist.set_color(self.state.color)
                elif force or any(prop in changed for prop in CMAP_PROPERTIES):
                    c = self.layer[self.state.cmap_att].ravel()
                    set_mpl_artist_cmap(eartist, c, self.state)

                if force or 'alpha' in changed:
                    eartist.set_alpha(self.state.alpha)

                if force or 'visible' in changed:
                    eartist.set_visible(self.state.visible)

                if force or 'zorder' in changed:
                    eartist.set_zorder(self.state.zorder)

        for artist in [self.scatter_artist, self.plot_artist,
                       self.vector_artist, self.line_collection,
                       self.density_artist]:

            if artist is None:
                continue

            if force or 'alpha' in changed:
                artist.set_alpha(self.state.alpha)

            if force or 'zorder' in changed:
                artist.set_zorder(self.state.zorder)

            if force or 'visible' in changed:
                artist.set_visible(self.state.visible)

        self.redraw()

    @defer_draw
    def _update_scatter(self, force=False, **kwargs):

        if (self._viewer_state.x_att is None or
            self._viewer_state.y_att is None or
                self.state.layer is None):
            return

        # Figure out which attributes are different from before. Ideally we shouldn't
        # need this but currently this method is called multiple times if an
        # attribute is changed due to x_att changing then hist_x_min, hist_x_max, etc.
        # If we can solve this so that _update_histogram is really only called once
        # then we could consider simplifying this. Until then, we manually keep track
        # of which properties have changed.

        changed = set()

        if not force:

            for key, value in self._viewer_state.as_dict().items():
                if value != self._last_viewer_state.get(key, None):
                    changed.add(key)

            for key, value in self.state.as_dict().items():
                if value != self._last_layer_state.get(key, None):
                    changed.add(key)

        self._last_viewer_state.update(self._viewer_state.as_dict())
        self._last_layer_state.update(self.state.as_dict())

        if force or len(changed & DATA_PROPERTIES) > 0:
            self._update_data(changed)
            force = True

        if force or len(changed & VISUAL_PROPERTIES) > 0:
            self._update_visual_attributes(changed, force=force)

    def get_layer_color(self):
        if self.state.cmap_mode == 'Fixed':
            return self.state.color
        else:
            return self.state.cmap

    @defer_draw
    def update(self):
        self._update_scatter(force=True)
        self.redraw()
Esempio n. 49
0
            ball_rad = float(tokens[1])

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

ax.invert_yaxis()
ax.axis('equal')

for obs in obstacles:
    ax.add_patch(plt.Polygon(obs, fc='#404040'))

ax.add_patch(plt.Circle(target_pos, target_rad, ec='None', fc='red'))

# Draw graph
edges = LineCollection(([dataset[v1][:2], dataset[v2][:2]] for v1, v2 in graph.get_edgelist()))
edges.set_color('Lavender')
edges.set_zorder(1)
ax.add_collection(edges)

# Draw points
params = {}
if args.clustering:
    # Open the vertex dendogram
    print 'Loading clustering...'
    membership = cPickle.load(open(args.clustering, 'rb'))
    params['c'] = membership
    params['cmap'] = plt.get_cmap('hsv')

    # Highlight boundary points
    boundary = [v.index for v in graph.vs
            if sum((membership[nid] != membership[v.index]
Esempio n. 50
0
def show_frac_charge(filename=None,bias=False,usevec=False,theta=0,dmu=0.01,target_block=(0,0),append=False,**kwargs):
    '''
    Show the fractional charge wave functions.
    '''
    model,expander=get_solving_system(evolutor_type='masked',periodic=False,**kwargs)
    if filename is None:
        filename='data/frac_W1%s_W2%s_U%s_N%s'%(kwargs.get('K1'),kwargs.get('K2'),kwargs.get('U'),kwargs.get('nsite'))
    if not bias:
        ket_even=MPS.load(filename+'-even.dat')
        ket_odd=MPS.load(filename+'-odd.dat')
        #ket_odd=ket_odd-(ket_even.tobra(labels=ket_even.labels)*ket_odd).item()*ket_even
        #combine to left-right edge states.
        if usevec:
            ket_odd,ket_even=ket_odd.state,ket_even.state
        #else:
            #ket_odd.recanonicalize(tol=1e-8)
        ket_left=ket_even#(ket_even+exp(1j*theta)*ket_odd)/sqrt(2.)
        ket_right=ket_odd#(ket_even-exp(1j*theta)*ket_odd)/sqrt(2.)
        if not usevec:
            ket_left.recanonicalize(tol=1e-8)   #we must recanonicalize it, for it is not canonical!!!
            ket_right.recanonicalize(tol=1e-8)
            print ket_left
            print ket_right
            pls=[dos4mps(spaceconfig=expander.spaceconfig,ket=ket) for ket in [ket_left,ket_right]]
        else:
            pls=[dos4vec(spaceconfig=model.hgen.spaceconfig,ket=ket) for ket in [ket_left,ket_right]]
    else:
        suffix='W1%s_W2%s_U%s_N%s_dmu%s_%s.dat'%(kwargs.get('K1'),kwargs.get('K2'),kwargs.get('U'),kwargs.get('nsite'),dmu,target_block)
        filename_mps='data/mps_'+suffix
        print filename_mps
        fname='data/fracdos_'+suffix
        #suffix2='W1%s_W2%s_U%s_N%s_dmu%s_%s.dat'%(kwargs.get('K1'),kwargs.get('K2'),kwargs.get('U'),kwargs.get('nsite'),dmu,(0,-1))
        #filename_mps2='data/mps_'+suffix2
        if append:
            pls=loadtxt(fname)[newaxis,:,:]
        else:
            ket_bias=MPS.load(filename_mps)
            #ket_bias=1./sqrt(2)*(MPS.load(filename_mps2)-1j*ket_bias)
            #ket_bias.compress()
            pls=[dos4mps(spaceconfig=expander.spaceconfig,ket=ket) for ket in [ket_bias]]
            savetxt(fname,pls[0].real)

    #pls=sum(pls,axis=1)
    pls=array(pls)-0.5
    nsite=pls.shape[-1]
    pls_left=pls[:,:,:nsite/2]
    pls_right=pls[:,:,nsite/2:]
    print 'occupation in left block -> %s, right block -> %s.'%(sum(pls_left,axis=(-1,-2)),sum(pls_right,axis=(-1,-2)))
    if ONSV: return pls
    ion()
    lw=2
    lc='r'
    for n in xrange(len(pls)):
        pln=pls[n]
        ax=subplot(101+n+10*len(pls))
        for s in xrange(2):
            color='b' if s==0 else 'r'
            lc=LineCollection([[(i,0),(i,pln[s,i].real.item())] for i in xrange(model.nsite)])
            lc.set_linewidth(lw)
            lc.set_color(color)
            lc.set_linestyle('--' if s==1 else '-')
            ax.add_collection(lc)

        ax.autoscale()
        ax.margins(0.1)
        xlabel('N')
        ylabel(r'$\rho-\bar{\rho}$')
    pdb.set_trace()
Esempio n. 51
0
def plot(bmap, X, k_fig, x_next, kappa):
    """ Auxillary plotting function
    
    Parameters
    ----------
    bma : EnrichedBayesianModelAveraging object to be plotted
    X  : The values that have been previously traversed
    mode : mode = "predict" if the GaussianProcessEI prediction is disired
         or mode = "EI" if the expected improvement is desired
    k_fig  : The suffix seed for saving the figure
    
    """
    import matplotlib.pyplot as plt
    from matplotlib.collections import LineCollection
    from matplotlib import colors as cl
    from matplotlib import gridspec

    # Get the bma
    bma = bmap.bma

    # Get number of models
    nModels = len(bma.quadratic_models)

    # Plot ranges
    x_min = -5.0
    x_max = 5.0
    y_min = -200
    y_max = 200

    colorcycle = ['r', 'b', 'g', 'm', 'y']

    # Plot for 1d
    num_points = 200
    # mini plot dx param
    dx = 0.5
    # miniplot num points
    mini_num_points = 50
    
    dpi = 300
    
    # Create x array to be plotted
    x_plot = np.linspace(x_min, x_max, num_points)
    x_grid = np.array([x_plot])

    # Get mean values at each of the grid points
    
    F = np.zeros(x_plot.shape)
    for i in range(len(x_plot)):
        F[i] = fun(np.array([x_plot[i]]))

    Z_rolled = bma.predict_with_unc(x_grid)
    model_weights, errors, N_eff, marginal_likelihoods = bma.estimate_model_weights(x_grid, return_likelihoods=True)
    Z = Z_rolled[0,:]

    # bma disagreement
    S = Z_rolled[1,:]
    # bma uncertainty
    U = Z_rolled[2,:]

    # Get full variance
    std = np.sqrt(np.square(S) + np.square(U))

    def plt_func(ax):
        # Plot function
        func_line = ax.plot(x_plot, F)
        # Set line properties 
        plt.setp(func_line, color="black", linewidth=2.0, alpha=0.5)

    def plt_data(ax, X):
        # Scatter of observations models (sampled models)
        for i in range(nModels):
            f = bma.quadratic_models[i].get_y()
            ax.scatter(X[0,i], f, s=100.0, c="black", alpha=0.5)

    def plt_acquisition(ax):
        # Get acquisition values:
        acq = bmao.calculate_discounted_mean(x_grid, kappa=kappa)
        
        acq_line = ax.plot(x_plot, acq)
        plt.setp(acq_line, color="red", linewidth = 2.0, linestyle='--')

        # Plot next point
        Z_next_rolled = bma.predict(np.array([x_next]))
        #ax.scatter(x_next,Z_next_rolled[0,:]+(y_max-y_min)/80., s=100.0, c="red",marker='v')

    def plt_mean(ax):
        # Plot prediction, and plot function
        pred_line = ax.plot(x_plot, Z)
        # Set line properties
        plt.setp(pred_line, color="blue", linewidth=2.0, alpha=0.5)


    def plt_confidence(ax):
        # Plot confidence bars for the two types of errors
        ax.fill_between(x_plot,Z-S,Z+S, facecolor='blue', interpolate=True, alpha=0.3)
        ax.fill_between(x_plot,Z-U,Z+U, facecolor='red', interpolate=True, alpha=0.3)
        # Full std bars
        upper_min = np.max(np.vstack([Z+S,Z+U]), axis=0)

        lower_min = np.min(np.vstack([Z-S,Z-U]), axis=0)
        ax.fill_between(x_plot,upper_min,Z+std, facecolor='black', interpolate=True, alpha=0.15)
        ax.fill_between(x_plot,Z-std,lower_min, facecolor='black', interpolate=True, alpha=0.15)

    def plt_minature(ax):
        # Plot minature cuvature plots for each model
        dx_mini_plot = np.linspace(-dx, dx, mini_num_points)
        dx_mini_grid = np.array([dx_mini_plot])

        # For the plotting, we will use the current colorcycle
        ax.set_color_cycle(colorcycle)

        for i in range(nModels):
            model_predictions = bma.model_predictions(x_grid)
            line = ax.plot(x_plot, model_predictions[i,:])

            # Set line properties for miniplot
            plt.setp(line, linewidth=3.0, alpha=0.5, linestyle='-',
                     dash_capstyle='round')

    ### Plot 1
    fig, ax = plt.subplots(dpi=dpi)

    plt_func(ax)
    plt_data(ax, X)
    plt_minature(ax)

    # Plot range
    plt.ylim([y_min, y_max])
    plt.xlim([x_min, x_max])
    plt.savefig("figures/"+str(k_fig)+"_func_obs_.png", dpi=dpi)

    ### Plot 2
    fig, ax = plt.subplots(dpi=dpi)

    plt_func(ax)
    plt_data(ax, X)
    plt_mean(ax)
    plt_confidence(ax)

    # Plot range
    plt.ylim([y_min, y_max])
    plt.xlim([x_min, x_max])
    plt.savefig("figures/"+str(k_fig)+"_bma_conf_.png", dpi=dpi)

    ### Plot 3
    fig, ax = plt.subplots(dpi=dpi)

    plt_func(ax)
    plt_data(ax, X)
    plt_mean(ax)
    plt_acquisition(ax)

    # Plot range
    plt.ylim([y_min, y_max])
    plt.xlim([x_min, x_max])
    plt.savefig("figures/"+str(k_fig)+"_bma_acq_.png", dpi=dpi)

    ### Informative Plot
    n_subplot = 5
    fig2 = plt.figure(figsize=(8, 8), dpi=dpi)
    gs = gridspec.GridSpec(n_subplot, 1, height_ratios=[3, 1, 1, 1, 1])
    
    # Create axis array
    ax = []
    for i in range(n_subplot):
        ax.append(plt.subplot(gs[i]))

    # Show the model priors
    log_model_priors = bma.estimate_log_model_priors(x_grid)
    ax[1]._get_lines.set_color_cycle(colorcycle)
    for i in range(nModels):
        p1_line = ax[1].plot(x_plot, np.exp(log_model_priors[i,:]))
        plt.setp(p1_line, linewidth=3.0, alpha=1.0, linestyle='-',
                 dash_capstyle='round')
    # Plot range
    ax[1].set_ylim([0, 1])
    ax[1].set_xlim([x_min, x_max])
    ax[1].set_ylabel('prior', fontsize=16)

    # Plot marginal likelihood proportionalities
    ax[2]._get_lines.set_color_cycle(colorcycle)
    for i in range(nModels):
        p2_line = ax[2].plot(x_plot, np.log(marginal_likelihoods[i,:]))
        plt.setp(p2_line, linewidth=3.0, alpha=1.0, linestyle='-',
                 dash_capstyle='round')

    #ax[2].set_ylim([0.00000001, 1])
    ax[2].set_ylim(-25,0)
    #ax[2].set_yscale('log')
    ax[2].set_xlim([x_min, x_max])
    ax[2].set_ylabel('ll', fontsize=16)
        
    # Show the model weights
    model_weights = bma.estimate_model_weights(x_grid)
    ax[3]._get_lines.set_color_cycle(colorcycle)
    for i in range(nModels):
        p3_line = ax[3].plot(x_plot, model_weights[i,:])
        plt.setp(p3_line, linewidth=3.0, alpha=1.0, linestyle='-',
                 dash_capstyle='round')
    # Plot range
    ax[3].set_ylim([0, 1])
    ax[3].set_xlim([x_min, x_max])
    ax[3].set_ylabel('posterior', fontsize=16)

    # Show the kernel weights
    kernel_weights = bma.calc_kernel_weights(x_grid)
    # N_eff
    N_eff = np.sum(kernel_weights, 0)
    #N_eff_line = ax[4].plot(x_plot, N_eff)
    #plt.setp(N_eff_line, linewidth = 3.0, alpha=1.0, linestyle='-',
    #         color='black')

    # Shade in the makeup of N_eff
    cumulant = N_eff*0.0

    for i in range(nModels):
        color = colorcycle[i]
        ax[4].fill_between(x_plot,cumulant,cumulant+kernel_weights[i,:], facecolor=color, interpolate=True, alpha=0.35)
        cumulant += kernel_weights[i,:]
    # Plot range
    ax[4].set_ylim([0, nModels])
    ax[4].set_xlim([x_min, x_max])
    ax[4].set_ylabel('N_eff', fontsize=16)


    ### Plot alpha weighted by posterior cuvature plots for each model
    model_predictions = bma.model_predictions(x_grid)

    # For the plotting, we will use the current colorcycle
    ax[0]._get_lines.set_color_cycle(colorcycle)
    color_cycle = ax[0]._get_lines.color_cycle

    for i in range(nModels):
        # Max alpha for the plots
        max_alpha = 0.7

        # Cited from http://matplotlib.1069221.n5.nabble.com/Varying-alpha-in-ListedColormap-not-working-td39950.html

        x = x_plot
        y = model_predictions[i,:]
        scaling = model_weights[i,:]

        points = np.array([x, y]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1],points[1:]], axis=1)

        # Values to scale by
        smin = 0
        smax = 1
        
        # Inline function to convert scaling value to alpha value in [0,1]
        alpha = lambda s0:(s0-smin)/(smax-smin)

        # Create a (rgba) color description for each line segment
        cmap = []

        # Get the next color in the colorcycle
        color = next(color_cycle)
        converter = cl.ColorConverter()
        # Get the rgb color tuple and convert it to a list
        color_rgba = list(converter.to_rgb(color))
        # Add placeholder alpha to get color_rgba
        color_rgba.append(0.0)

        for a in segments:
            # The x-value for the segment
            x0 = a.mean(0)[0]
            # With scaling value of
            s0 = np.interp(x0, x, scaling)
            # And alpha value of 
            a0 = alpha(s0)

            # Pop the previous alpha and add the current alpha
            color_rgba[3] = a0*max_alpha
            
            # Add the rgba entry to the colormap. Make sure to copy the list
            # Using list slicing.
            cmap.append(color_rgba[:])
        
        # Create the line collection objecft
        lc = LineCollection(segments)
        lc.set_color(cmap)

        # Set line properties. 
        # Dashed line
        lc.set_dashes('-')
        # line width 3.0
        lc.set_linewidth(3.0)
            
        ax[0].add_collection(lc)

        """
        # Normal plot
        #p0_line = ax[0].plot(x_plot, model_predictions[i,:])
        # Set line properties for miniplot
        #plt.setp(p0_line, linewidth=3.0, alpha=model_weights[i,:], linestyle='--',
        #         dash_capstyle='round')
        """

    # Now plot scatter of observations
    for i in range(nModels):
        f = bma.quadratic_models[i].get_y()
        ax[0].scatter(X[0,i],f,s=100.0, c="black", alpha=0.5)

    # Plot bma predictions
    pred_line = ax[0].plot(x_plot,Z)
    
    # Line properties
    plt.setp(pred_line, color="black", alpha=0.3, linewidth=3.0)

    # Set the plot range
    ax[0].set_xlim(x_min, x_max)
    ax[0].set_ylim(y_min, y_max)

    # set x axis
    ax[4].set_xlabel("x",fontsize=16)

    plt.savefig("figures/"+str(k_fig)+"_bma_model_breakdown.png", dpi=dpi)

    fig3, ax = plt.subplots(2, sharex=True)
    
    ax[0].plot(x_plot, N_eff)

    ### Plot of errors
    for i in range(nModels):
        p1_line = ax[1].plot(x_plot, errors[i,:]+10**-32)
        plt.setp(p1_line, linewidth=3.0, alpha=1.0, linestyle='-',
                 dash_capstyle='round')
        
    # Set log scale
    ax[1].set_yscale('log')
    plt.savefig("figures/"+str(k_fig)+"_bma_error_breakdown.png", dpi=dpi)
    
    
    ### Likelihood plots
    fig4, ax = plt.subplots(2, sharex=True)
    kernel_grid = np.logspace(-4.0, 1, num=50)

    # Get the likelihoods 
    unreg_loglikelihood = np.array([bma.loglikelihood(kernel_range, regularization=False, skew=False) for kernel_range in kernel_grid])
    reg_loglikelihood = np.array([bma.loglikelihood(kernel_range) for kernel_range in kernel_grid])

    # Plot the two terms
    ll0 = ax[0].plot(kernel_grid, unreg_loglikelihood)
    ax[0].set_xscale('log')
    ll1 = ax[1].plot(kernel_grid, reg_loglikelihood)
    ax[1].set_xscale('log')

    plt.setp(ll0, color="red", linewidth=3.0, alpha=0.5, linestyle='-',
             dash_capstyle='round')
    plt.setp(ll1, color="red", linewidth=3.0, alpha=0.5, linestyle='-',
             dash_capstyle='round')

    ax[1].set_xlabel("kernel range",fontsize=16)

    plt.savefig("figures/"+str(k_fig)+"_bma_loglikelihood.png", dpi=dpi)

    """
Esempio n. 52
0
class Anim:
    def __init__(
        self, eddy, intern=False, sleep_event=0.1, graphic_information=False, **kwargs
    ):
        self.eddy = eddy
        x_name, y_name = eddy.intern(intern)
        self.t, self.x, self.y = eddy.time, eddy[x_name], eddy[y_name]
        self.x_core, self.y_core, self.track = eddy["lon"], eddy["lat"], eddy["track"]
        self.graphic_informations = graphic_information
        self.pause = False
        self.period = self.eddy.period
        self.sleep_event = sleep_event
        self.mappables = list()
        self.field_color = None
        self.field_txt = None
        self.time_field = False
        self.setup(**kwargs)

    def setup(
        self,
        cmap="jet",
        lut=None,
        field_color="time",
        field_txt="track",
        range_color=(None, None),
        nb_step=25,
        figsize=(8, 6),
        **kwargs,
    ):
        self.field_color = self.eddy[field_color].astype("f4")
        self.field_txt = self.eddy[field_txt]
        rg = range_color
        if rg[0] is None and rg[1] is None and field_color == "time":
            self.time_field = True
        else:
            rg = (
                self.field_color.min() if rg[0] is None else rg[0],
                self.field_color.max() if rg[1] is None else rg[1],
            )
            self.field_color = (self.field_color - rg[0]) / (rg[1] - rg[0])

        self.colors = pyplot.get_cmap(cmap, lut=lut)
        self.nb_step = nb_step

        x_min, x_max = self.x_core.min() - 2, self.x_core.max() + 2
        d_x = x_max - x_min
        y_min, y_max = self.y_core.min() - 2, self.y_core.max() + 2
        d_y = y_max - y_min
        # plot
        self.fig = pyplot.figure(figsize=figsize, **kwargs)
        t0, t1 = self.period
        self.fig.suptitle(f"{t0} -> {t1}")
        self.ax = self.fig.add_axes((0.05, 0.05, 0.9, 0.9), projection="full_axes")
        self.ax.set_xlim(x_min, x_max), self.ax.set_ylim(y_min, y_max)
        self.ax.set_aspect("equal")
        self.ax.grid()
        # init mappable
        self.txt = self.ax.text(x_min + 0.05 * d_x, y_min + 0.05 * d_y, "", zorder=10)
        self.segs = list()
        self.t_segs = list()
        self.c_segs = list()
        self.contour = LineCollection([], zorder=1)
        self.ax.add_collection(self.contour)

        self.fig.canvas.draw()
        self.fig.canvas.mpl_connect("key_press_event", self.keyboard)
        self.fig.canvas.mpl_connect("resize_event", self.reset_bliting)

    def reset_bliting(self, event):
        self.contour.set_visible(False)
        self.txt.set_visible(False)
        for m in self.mappables:
            m.set_visible(False)
        self.fig.canvas.draw()
        self.bg_cache = self.fig.canvas.copy_from_bbox(self.ax.bbox)
        self.contour.set_visible(True)
        self.txt.set_visible(True)
        for m in self.mappables:
            m.set_visible(True)

    def show(self, infinity_loop=False):
        pyplot.show(block=False)
        # save background for future bliting
        self.fig.canvas.draw()
        self.bg_cache = self.fig.canvas.copy_from_bbox(self.ax.bbox)
        loop = True
        t0, t1 = self.period
        while loop:
            self.now = t0
            while True:
                dt = self.sleep_event
                if not self.pause:
                    d0 = datetime.now()
                    self.next()
                    dt_draw = (datetime.now() - d0).total_seconds()
                    dt = self.sleep_event - dt_draw
                    if dt < 0:
                        # self.sleep_event = dt_draw * 1.01
                        dt = 1e-10
                if dt == 0:
                    dt = 1e-10
                self.fig.canvas.start_event_loop(dt)
                if self.now > t1:
                    break
            if infinity_loop:
                self.fig.canvas.start_event_loop(0.5)
            else:
                loop = False

    def next(self):
        self.now += 1
        return self.draw_contour()

    def prev(self):
        self.now -= 1
        return self.draw_contour()

    def func_animation(self, frame):
        while self.mappables:
            self.mappables.pop().remove()
        self.now = frame
        self.update()
        artists = [self.contour, self.txt]
        artists.extend(self.mappables)
        return artists

    def update(self):
        m = self.t == self.now
        if m.sum():
            segs = list()
            t = list()
            c = list()
            for i in where(m)[0]:
                segs.append(create_vertice(self.x[i], self.y[i]))
                c.append(self.field_color[i])
                t.append(self.now)
            self.segs.append(segs)
            self.c_segs.append(c)
            self.t_segs.append(t)
        self.contour.set_paths(chain(*self.segs))
        if self.time_field:
            self.contour.set_color(
                self.colors(
                    [
                        (self.nb_step - self.now + i) / self.nb_step
                        for i in chain(*self.c_segs)
                    ]
                )
            )
        else:
            self.contour.set_color(self.colors(list(chain(*self.c_segs))))
        # linewidth will be link to time delay
        self.contour.set_lw(
            [
                (1 - (self.now - i) / self.nb_step) * 2.5 if i <= self.now else 0
                for i in chain(*self.t_segs)
            ]
        )
        # Update date txt and info
        txt = f"{(timedelta(int(self.now)) + datetime(1950,1,1)).strftime('%Y/%m/%d')}"
        if self.graphic_informations:
            txt += f"- {1/self.sleep_event:.0f} frame/s"
        self.txt.set_text(txt)
        # Update id txt
        for i in where(m)[0]:
            mappable = self.ax.text(
                self.x_core[i],
                self.y_core[i],
                self.field_txt[i],
                fontsize=12,
                fontweight="demibold",
            )
            self.mappables.append(mappable)
            self.ax.draw_artist(mappable)
        self.ax.draw_artist(self.contour)
        self.ax.draw_artist(self.txt)
        # Remove first segment to keep only T contour
        if len(self.segs) > self.nb_step:
            self.segs.pop(0)
            self.t_segs.pop(0)
            self.c_segs.pop(0)

    def draw_contour(self):
        # select contour for this time step
        while self.mappables:
            self.mappables.pop().remove()
        self.ax.figure.canvas.restore_region(self.bg_cache)
        self.update()
        # paint updated artist
        self.ax.figure.canvas.blit(self.ax.bbox)

    def keyboard(self, event):
        if event.key == "escape":
            exit()
        elif event.key == " ":
            self.pause = not self.pause
        elif event.key == "+":
            self.sleep_event *= 0.9
        elif event.key == "-":
            self.sleep_event *= 1.1
        elif event.key == "right" and self.pause:
            self.next()
        elif event.key == "left" and self.pause:
            # we remove 2 step to add 1 so we rewind of only one
            self.segs.pop(-1)
            self.segs.pop(-1)
            self.t_segs.pop(-1)
            self.t_segs.pop(-1)
            self.c_segs.pop(-1)
            self.c_segs.pop(-1)
            self.prev()
Esempio n. 53
0
  def mesh( self, points, colors=None, edgecolors='k', edgewidth=None, triangulate='delaunay', setxylim=True, **kwargs ):
    'plot elemtwise mesh'

    assert isinstance( points, numpy.ndarray ) and points.dtype == float
    if colors is not  None:
      assert isinstance( colors, numpy.ndarray ) and colors.dtype == float
      assert points.shape[:-1] == colors.shape

    if points.ndim == 3: # gridded data: nxpoints x nypoints x ndims

      assert points.shape[-1] == 2
      assert colors is not None
      data = colors.ravel()
      xy = points.reshape( -1, 2 ).T
      ind = numpy.arange( xy.shape[1] ).reshape( points.shape[:-1] )
      vert1 = numpy.array([ ind[:-1,:-1].ravel(), ind[1:,:-1].ravel(), ind[:-1,1:].ravel() ]).T
      vert2 = numpy.array([ ind[1:,1:].ravel(), ind[1:,:-1].ravel(), ind[:-1,1:].ravel() ]).T
      triangles = numpy.concatenate( [vert1,vert2], axis=0 )
      edges = None

    elif points.ndim == 2: # mesh: npoints x ndims

      ndims = points.shape[1]
      if ndims == 1:
        self.plot( points[:,0], colors )
        return
      else:
        assert ndims == 2, 'unsupported: ndims=%s' % ndims

      nans = numpy.isnan( points ).all( axis=1 )
      split, = numpy.where( nans )
      if colors is not None:
        assert numpy.isnan( colors[split] ).all()
  
      P = []
      N = []
      C = []
      E = []
      npoints = 0
  
      for a, b in zip( numpy.concatenate([[0],split+1]), numpy.concatenate([split,[nans.size]]) ):
        np = b - a
        if np == 0:
          continue
        epoints = points[a:b]
        if colors is not None:
          ecolors = colors[a:b]
        if triangulate == 'delaunay':
          tri = spatial.Delaunay( epoints )
          vertices = tri.vertices
          e0 = [ edge[0] for edge in tri.convex_hull ]
          e1 = [ edge[1] for edge in tri.convex_hull ]
          last = e1.pop()
          hull = [ e0.pop(), last ]
          while e0:
            try:
              index = e0.index( last )
              last = e1[index]
            except ValueError:
              index = e1.index( last )
              last = e0[index]
            e0.pop( index )
            e1.pop( index )
            hull.append( last )
          assert hull[0] == hull[-1]
        elif triangulate == 'bezier':
          nquad = int( numpy.sqrt(np) + .5 )
          ntri = int( numpy.sqrt((2*np)+.25) )
          if nquad**2 == np:
            ind = numpy.arange(np).reshape(nquad,nquad)
            vert1 = numpy.array([ ind[:-1,:-1].ravel(), ind[1:,:-1].ravel(), ind[:-1,1:].ravel() ]).T
            vert2 = numpy.array([ ind[1:,1:].ravel(), ind[1:,:-1].ravel(), ind[:-1,1:].ravel() ]).T
            vertices = numpy.concatenate( [vert1,vert2], axis=0 )
            hull = numpy.concatenate([ ind[:,0], ind[-1,1:], ind[-2::-1,-1], ind[0,-2::-1] ])
          elif ntri * (ntri+1) == 2 * np:
            vert1 = [ ((2*ntri-i+1)*i)//2+numpy.array([j,j+1,j+ntri-i]) for i in range(ntri-1) for j in range(ntri-i-1) ]
            vert2 = [ ((2*ntri-i+1)*i)//2+numpy.array([j+1,j+ntri-i+1,j+ntri-i]) for i in range(ntri-1) for j in range(ntri-i-2) ]
            vertices = numpy.concatenate( [vert1,vert2], axis=0 )
            hull = numpy.concatenate([ numpy.arange(ntri), numpy.arange(ntri-1,0,-1).cumsum()+ntri-1, numpy.arange(ntri+1,2,-1).cumsum()[::-1]-ntri-1 ])
          else:
            raise Exception( 'cannot match points to a bezier scheme' )
        else:
          raise Exception( 'unknown triangulation method %r' % triangulate )
        P.append( epoints.T )
        N.append( vertices + npoints )
        if colors is not None:
          C.append( ecolors )
        E.append( epoints[hull] )
        npoints += np
  
      xy = numpy.concatenate( P, axis=1 )
      triangles = numpy.concatenate( N, axis=0 )
      if colors is not None:
        data = numpy.concatenate( C )
      edges = E

    else:

      raise Exception( 'invalid points shape %r' % ( points.shape, ) )
  
    TriMesh = self._trimesh_class()
    polycol = TriMesh( xy, triangles, rasterized=True, **kwargs )
    if colors is not None:
      polycol.set_array( data )

    if edges and edgecolors != 'none':
      from matplotlib.collections import LineCollection
      linecol = LineCollection( edges, linewidths=(edgewidth,) if edgewidth is not None else None )
      linecol.set_color( edgecolors )
      self.gca().add_collection( linecol )

    self.gca().add_collection( polycol )
    self.sci( polycol )
    
    if setxylim:
      xmin, ymin = numpy.min( xy, axis=1 )
      xmax, ymax = numpy.max( xy, axis=1 )
      self.xlim( xmin, xmax )
      self.ylim( ymin, ymax )
    
    if edgecolors != 'none':
      return polycol, linecol

    return polycol
Esempio n. 54
0
    def show_graph(self, fixed=False, show_ids=True):
        """draw the graph"""
        import pylab as pl
        if not hasattr(self, "graph"):
            self.make_graph()
        
        print "showing graph"
        # I need to clear the figure and make a new axes object because
        # I can't find any other way to remove old colorbars
        self.fig.clf()
        self.axes = self.fig.add_subplot(111)
        ax = self.axes
        ax.clear()
        graph = self.graph
        
        #get the layout of the nodes from networkx
        oldlayout = self.positions
        layout = nx.spring_layout(graph, pos=oldlayout)#, fixed=fixed)
        self.positions.update(layout)
        layout = self.positions
        
        # draw the edges as lines
        from matplotlib.collections import LineCollection
        linecollection = LineCollection([(layout[u], layout[v]) for u, v in graph.edges()
                 if u not in self.boundary_nodes and v not in self.boundary_nodes])
        linecollection.set_color('k')
        ax.add_collection(linecollection)

        if self.boundary_nodes:
            # draw the edges connecting the boundary nodes as thin lines
            from matplotlib.collections import LineCollection
            linecollection = LineCollection([(layout[u], layout[v]) for u, v in graph.edges()
                     if u in self.boundary_nodes or v in self.boundary_nodes])
            linecollection.set_color('k')
            linecollection.set_linewidth(0.2)
            ax.add_collection(linecollection)

        markersize = 8**2
        
        # draw the interior nodes
        interior_nodes = set(graph.nodes()) - self.boundary_nodes
        layoutlist = filter(lambda nxy: nxy[0] in interior_nodes, layout.items())
        xypos = np.array([xy for n, xy in layoutlist])
        if self._minima_color_value is None:
            #color the nodes by energy
            color_values = [m.energy for m, xy in layoutlist]
        else:
            color_values = [self._minima_color_value(m) for m, xy in layoutlist]
        #plot the nodes
        self._minima_points = ax.scatter(xypos[:,0], xypos[:,1], picker=5, 
                            s=markersize, c=color_values, cmap=pl.cm.autumn)
        self._mimima_layout_list = layoutlist
#        if not hasattr(self, "colorbar"):
        self.colorbar = self.fig.colorbar(self._minima_points)
        
        self._boundary_points = None
        self._boundary_list = []
        if self.boundary_nodes:
            # draw the boundary nodes as empty circles with thin lines
            boundary_layout_list = filter(lambda nxy: nxy[0] in self.boundary_nodes, layout.items())
            xypos = np.array([xy for n, xy in boundary_layout_list])
            #plot the nodes
            import matplotlib as mpl
#            marker = mpl.markers.MarkerStyle("o", fillstyle="none")
#            marker.set_fillstyle("none")
            self._boundary_points = ax.scatter(xypos[:,0], xypos[:,1], picker=5, 
                                s=markersize, marker="o", facecolors="none", linewidths=.5)
            self._boundary_layout_list = boundary_layout_list

        
        #scale the axes so the points are not cutoff
        xmax = max((x for x,y in layout.itervalues() ))
        xmin = min((x for x,y in layout.itervalues() ))
        ymax = max((y for x,y in layout.itervalues() ))
        ymin = min((y for x,y in layout.itervalues() ))
        dx = (xmax - xmin)*.1
        dy = (ymax - ymin)*.1
        ax.set_xlim([xmin-dx, xmax+dx])
        ax.set_ylim([ymin-dy, ymax+dy])
        import matplotlib.pyplot as plt
#        self.fig.relim()
#        self.fig.tight_layout()
#        plt.tight_layout()
#        self.fig.set_tight_layout(True)
        
        
#        def on_pick(event):
#            ind = event.ind[0]
#            if event.artist == points:
#                min1 = layoutlist[ind][0]
#            elif event.artist == boundary_points:
#                min1 = boundary_layout_list[ind][0]
#            else:
#                return True
#            print "you clicked on minimum with id", min1._id, "and energy", min1.energy
#            self._on_minima_picked(min1)

        
        if self._mpl_cid is not None:
            self.canvas.mpl_disconnect(self._mpl_cid)
            self._mpl_cid = None
        self._mpl_cid = self.fig.canvas.mpl_connect('pick_event', self._on_mpl_pick_event)

        
        self.canvas.draw()
        self.app.processEvents()
Esempio n. 55
0
    def plot(self, time, beam=None, maxground=2000, maxalt=500,
        iscat=True, gscat=True, title=False, weighted=False, cmap='hot_r', 
        fig=None, rect=111, ax=None, aax=None, zorder=4):
        """Plot scatter on ground/altitude profile
        
        Parameters
        ----------
        time : datetime.datetime
            time of profile
        beam : Optional[ ]
            beam number
        maxground : Optional[int]
            maximum ground range [km]
        maxalt : Optional[int]
            highest altitude limit [km]
        iscat : Optional[bool]
            show ionospheric scatter
        gscat : Optional[bool]
            show ground scatter
        title : Optional[bool]
            Show default title
        weighted : Optional[bool]
            plot ionospheric scatter relative strength (based on background density and range)
        cmap : Optional[str]
            colormap used for weighted ionospheric scatter
        fig : Optional[pylab.figure]
            object (default to gcf)
        rect : Optional[int]
            subplot spcification
        ax : Optional[ ]
            Existing main axes
        aax : Optional[ ]
            Existing auxialary axes
        zorder : Optional[int]


        Returns
        -------
        ax : matplotlib.axes
            object containing formatting
        aax : matplotlib.axes
            object containing data
        cbax : matplotlib.axes
            object containing colorbar

        Example
        -------
            # Show ionospheric scatter
            import datetime as dt
            from models import raydarn
            sTime = dt.datetime(2012, 11, 18, 5)
            rto = raydarn.RtRun(sTime, rCode='bks', beam=12)
            rto.readRays() # read rays into memory
            ax, aax, cbax = rto.rays.plot(sTime, title=True)
            rto.readScatter() # read scatter into memory
            rto.scatter.plot(sTime, ax=ax, aax=aax)
            ax.grid()

        written by Sebastien, 2013-04

        """
        from davitpy.utils import plotUtils
        from matplotlib.collections import LineCollection
        import matplotlib.pyplot as plt
        import numpy as np

        # Set up axes
        if not ax and not aax:
            ax, aax = plotUtils.curvedEarthAxes(fig=fig, rect=rect, 
                maxground=maxground, maxalt=maxalt)
        else:
            ax = ax
            aax = aax
            if hasattr(ax, 'beam'):
                beam = ax.beam

        # make sure that the required time and beam are present
        assert (time in self.isc.keys() or time in self.gsc.keys()), logging.error('Unkown time %s' % time)
        if beam:
            assert (beam in self.isc[time].keys()), logging.error('Unkown beam %s' % beam)
        else:
            beam = self.isc[time].keys()[0]

        if gscat and time in self.gsc.keys():
            for ir, (el, rays) in enumerate( sorted(self.gsc[time][beam].items()) ):
                if len(rays['r']) == 0: continue
                _ = aax.scatter(rays['th'], ax.Re*np.ones(rays['th'].shape), 
                    color='0', zorder=zorder)

        if iscat and time in self.isc.keys():
            if weighted:
                wmin = np.min( [ r['w'].min() for r in self.isc[time][beam].values() if r['nstp'] > 0] )
                wmax = np.max( [ r['w'].max() for r in self.isc[time][beam].values() if r['nstp'] > 0] )

            for ir, (el, rays) in enumerate( sorted(self.isc[time][beam].items()) ):
                if rays['nstp'] == 0: continue
                t = rays['th']
                r = rays['r']*1e-3
                spts = np.array([t, r]).T.reshape(-1, 1, 2)
                h = rays['h']*1e-3
                rel = np.radians( rays['rel'] )
                r = np.sqrt( r**2 + h**2 + 2*r*h*np.sin( rel ) )
                t = t + np.arcsin( h/r * np.cos( rel ) )
                epts = np.array([t, r]).T.reshape(-1, 1, 2)
                segments = np.concatenate([spts, epts], axis=1)
                lcol = LineCollection( segments, zorder=zorder )
                if weighted:
                    _ = lcol.set_cmap( cmap )
                    _ = lcol.set_norm( plt.Normalize(0, 1) )
                    _ = lcol.set_array( ( rays['w'] - wmin ) / wmax )
                else:
                    _ = lcol.set_color('0')
                _ = aax.add_collection( lcol )

            # Plot title with date ut time and local time
            if title:
                stitle = _getTitle(time, beam, self.header, None)
                ax.set_title( stitle )

            # If weighted, plot ionospheric scatter with colormap
            if weighted:
                # Add a colorbar
                cbax = plotUtils.addColorbar(lcol, ax)
                _ = cbax.set_ylabel("Ionospheric Scatter")
            else: cbax = None

        ax.beam = beam
        return ax, aax, cbax
#offs = (0.1, 0.0)
#
#from numpy import amax, cos, random, pi
#rs = random.RandomState([12345678])
#
#yy = linspace(0, 2*pi, nverts)
#ym = amax(yy)
#xx = (0.2 + (ym-yy)/ym)**2 * cos(yy-0.4) * 0.5
#segs = []
#for i in range(ncurves):
#    xxx = xx + 0.02*rs.randn(nverts)
#    curve = list(zip(xxx, yy*100))
#    segs.append(curve)
#    if i<2:
#        print segs

segs = []
segs.append(list(zip(freq, Magvec[:, 1])))
segs.append(list(zip(freqb, Magvecb[:, 1])))

col = LineCollection(segs)  #, offsets=offs)
ax4.add_collection(col, autolim=True)
col.set_color(colors)
ax4.autoscale_view()
ax4.set_title('Successive data offsets')
ax4.set_xlabel('Zonal velocity component (m/s)')
#ax4.set_ylabel('Depth (m)')
# Reverse the y-axis so depth increases downward
#ax4.set_ylim(ax4.get_ylim()[::-1])

plt.show()
def plot(bma, X, k_fig):
    """ Auxillary plotting function
    
    Parameters
    ----------
    bma : bayesianModelAveraging object to be plotted
    X  : The values that have been previously traversed
    mode : mode = "predict" if the GaussianProcessEI prediction is disired
         or mode = "EI" if the expected improvement is desired
    k_fig  : The suffix seed for saving the figure
    
    """
    import matplotlib.pyplot as plt
    from matplotlib.collections import LineCollection
    from matplotlib import colors as cl
    from matplotlib import gridspec

    # Get number of models
    nModels = len(bma.quadratic_models)

    # Plot ranges
    x_min = -3.0
    x_max = 3.0
    y_min = -100
    y_max = 100

    # Plot for 1d
    num_points = 100
    # mini plot dx param
    dx = 0.5
    # miniplot num points
    mini_num_points = 50

    # Create x array to be plotted
    x_plot = np.linspace(x_min, x_max, num_points)
    x_grid = np.array([x_plot])

    # Get mean values at each of the grid points
    Z = np.zeros(x_plot.shape)
    S = np.zeros(x_plot.shape)
    
    F = np.zeros(x_plot.shape)
    for i in range(len(x_plot)):
        F[i] = fun(np.array([x_plot[i]]))

    Z_rolled = bma.predict_with_unc(x_grid)
    Z = Z_rolled[0,:]
    # bma disagreement
    S = Z_rolled[1,:]
    # bma uncertainty
    U = Z_rolled[2,:]

    ### Plot 1
    fig, ax = plt.subplots()

    # Plot prediction, and plot function
    pred_line = ax.plot(x_plot,Z)
    func_line = ax.plot(x_plot,F)
    
    # Set line properties
    plt.setp(pred_line, color="blue", linewidth=2.0)
    plt.setp(func_line, color="black", linewidth=2.0)

    # Scatter of observations
    for i in range(nModels):
        f = bma.quadratic_models[i][0]
        ax.scatter(X[0,i],f,s=100.0, c="black", alpha=0.5)

    # Plot disagreement bars
    ax.fill_between(x_plot,Z-S,Z+S, facecolor='blue', interpolate=True, alpha=0.3)
    ax.fill_between(x_plot,Z-U,Z+U, facecolor='red', interpolate=True, alpha=0.3)

    # Plot minature cuvature plots for each model
    dx_mini_plot = np.linspace(-dx, dx, mini_num_points)
    dx_mini_grid = np.array([dx_mini_plot])
    for i in range(nModels):
        model_predictions = bma.model_predictions(dx_mini_grid+X[0,i])
        line = ax.plot(dx_mini_plot+X[0,i], model_predictions[i,:])
        # Set line properties for miniplot
        plt.setp(line, color="green", linewidth=3.0, alpha=0.5, linestyle='--',
                 dash_capstyle='round')
    
    # Plot range
    plt.ylim([y_min, y_max])
    plt.xlim([x_min, x_max])
    plt.savefig("figures/"+str(k_fig)+"_bma_vs_func_.png")

    ### Plot 2
    n_subplot = 4
    fig2 = plt.figure(figsize=(8, 8))
    gs = gridspec.GridSpec(4, 1, height_ratios=[3, 1, 1, 1])
    
    # Create axis array
    ax = []
    for i in range(n_subplot):
        ax.append(plt.subplot(gs[i]))
    #fig, ax = plt.subplots(4, sharex=True)

    # Show the model priors
    model_priors = bma.estimate_model_priors(x_grid)
    for i in range(nModels):
        p1_line = ax[1].plot(x_plot, model_priors[i,:])
        plt.setp(p1_line, linewidth=3.0, alpha=1.0, linestyle='-',
                 dash_capstyle='round')
    # Plot range
    ax[1].set_ylim([0, 1])
    ax[1].set_xlim([x_min, x_max])
        
    # Show the model weights
    model_weights = bma.estimate_model_weights(x_grid)
    for i in range(nModels):
        p2_line = ax[2].plot(x_plot, model_weights[i,:])
        plt.setp(p2_line, linewidth=3.0, alpha=1.0, linestyle='-',
                 dash_capstyle='round')
    # Plot range
    ax[2].set_ylim([0, 1])
    ax[2].set_xlim([x_min, x_max])

    # Show the kernel values 
    kernel_weights = bma.calc_relevance_weights(x_grid)
    for i in range(nModels):
        p3_line = ax[3].plot(x_plot, kernel_weights[i,:])
        plt.setp(p3_line, linewidth=3.0, alpha=1.0, linestyle='-',
                 dash_capstyle='round')

    ### Plot alpha weighted by posterior cuvature plots for each model
    model_predictions = bma.model_predictions(x_grid)

    # For the plotting, we will use the current colorcycle
    color_cycle = ax[0]._get_lines.color_cycle

    for i in range(nModels):
        # Max alpha for the plots
        max_alpha = 0.7

        # Cited from http://matplotlib.1069221.n5.nabble.com/Varying-alpha-in-ListedColormap-not-working-td39950.html

        x = x_plot
        y = model_predictions[i,:]
        scaling = model_weights[i,:]

        points = np.array([x, y]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1],points[1:]], axis=1)

        # Values to scale by
        smin = 0
        smax = 1
        
        # Inline function to convert scaling value to alpha value in [0,1]
        alpha = lambda s0:(s0-smin)/(smax-smin)

        # Create a (rgba) color description for each line segment
        cmap = []

        # Get the next color in the colorcycle
        color = next(color_cycle)
        converter = cl.ColorConverter()
        # Get the rgb color tuple and convert it to a list
        color_rgba = list(converter.to_rgb(color))
        # Add placeholder alpha to get color_rgba
        color_rgba.append(0.0)

        for a in segments:
            # The x-value for the segment
            x0 = a.mean(0)[0]
            # With scaling value of
            s0 = np.interp(x0, x, scaling)
            # And alpha value of 
            a0 = alpha(s0)

            # Pop the previous alpha and add the current alpha
            color_rgba[3] = a0*max_alpha
            
            # Add the rgba entry to the colormap. Make sure to copy the list
            # Using list slicing.
            cmap.append(color_rgba[:])
        
        # Create the line collection objecft
        lc = LineCollection(segments)
        lc.set_color(cmap)

        # Set line properties. 
        # Dashed line
        lc.set_dashes('--')
        # line width 3.0
        lc.set_linewidth(3.0)
            
        ax[0].add_collection(lc)

        """
        # Normal plot
        #p0_line = ax[0].plot(x_plot, model_predictions[i,:])
        # Set line properties for miniplot
        #plt.setp(p0_line, linewidth=3.0, alpha=model_weights[i,:], linestyle='--',
        #         dash_capstyle='round')
        """

    # Now plot scatter of observations
    for i in range(nModels):
        f = bma.quadratic_models[i][0]
        ax[0].scatter(X[0,i],f,s=100.0, c="black", alpha=0.5)

    # Plot bma predictions
    pred_line = ax[0].plot(x_plot,Z)
    
    # Line properties
    plt.setp(pred_line, color="black", alpha=0.3, linewidth=3.0)

    # Set the plot range
    ax[0].set_xlim(x_min, x_max)
    ax[0].set_ylim(y_min, y_max)

    plt.savefig("figures/"+str(k_fig)+"_bma_model_breakdown.png")

    fig3, ax = plt.subplots(2, sharex=True)
    model_weights, errors, N_eff = bma.estimate_model_weights(x_grid, return_errors=True)
    
    ax[0].plot(x_plot, N_eff)

    ### Plot of errors
    for i in range(nModels):
        p1_line = ax[1].plot(x_plot, errors[i,:])
        plt.setp(p1_line, linewidth=3.0, alpha=1.0, linestyle='-',
                 dash_capstyle='round')
        
    # Set log scale
    ax[1].set_yscale('log')
    plt.savefig("figures/"+str(k_fig)+"_bma_error_breakdown.png")
Esempio n. 58
0
    def plot(self, show_minima=False, show_trees=False, linewidth=0.5, axes=None,
             title=None):
        """draw the disconnectivity graph using matplotlib
        
        don't forget to call calculate() first
        
        also, you must call pyplot.show() to actually see the plot
        """
        from matplotlib.collections import LineCollection
        import matplotlib.pyplot as plt

        self.line_segments, self.line_colours = self._get_line_segments(self.tree_graph, eoffset=self.eoffset)

        # get the axes object        
        if axes is not None:
            ax = axes
        else:
            try:
                ax = self.axes
            except AttributeError:
                fig = plt.figure(figsize=(6, 7))
                fig.set_facecolor('white')
                ax = fig.add_subplot(111, adjustable='box')

        # set up how the figure should look
        ax.tick_params(axis='y', direction='out')
        ax.yaxis.tick_left()
        # make the borders a bit prettier
        ax.spines['left'].set_color('black')
        ax.spines['left'].set_linewidth(0.5)
        ax.spines['top'].set_color('none')
        ax.spines['bottom'].set_color('none')
        ax.spines['right'].set_color('none')
        #        plt.box(on=True)

        if title is not None:
            ax.set_title(title)

        # draw the minima as points
        if show_minima:
            xpos, minima = self.get_minima_layout()
            energies = [m.energy for m in minima]
            ax.plot(xpos, energies, 'o')

        # draw the line segments 
        # use LineCollection because it's much faster than drawing the lines individually 
        linecollection = LineCollection([[(x[0], y[0]), (x[1], y[1])] for x, y in self.line_segments])
        linecollection.set_linewidth(linewidth)
        linecollection.set_color(self.line_colours)
        ax.add_collection(linecollection)


        # scale the axes appropriately
        # note: do not call ax.relim().  As of matplotlib version 1.3
        # ax.relim() does not take Collections into account so it does
        # not compute the limits correctly.  ax.autoscale_view() seems to work just fine
        ax.autoscale_view(scalex=True, scaley=True, tight=False)
        ax.set_ybound(upper=self.Emax)
        xmin, xmax = ax.get_xlim()
        ax.set_xlim(xmin - 0.5, xmax + 0.5)

        # remove xtics
        # note: the xticks are removed after ax.autoscale_view() is called.
        # If it is the other way around the lines are too close the image border          
        ax.set_xticks([])
        self.axes = ax
Esempio n. 59
0
def plot_linestring_collection(ax, geoms, colors_or_values, plot_values,
                               vmin=None, vmax=None, cmap=None,
                               linewidth=1.0, **kwargs):
    """
    Plots a collection of LineString and MultiLineString geometries to `ax`

    Parameters
    ----------

    ax : matplotlib.axes.Axes
        where shapes will be plotted

    geoms : a sequence of `N` LineStrings and/or MultiLineStrings (can be mixed)

    colors_or_values : a sequence of `N` values or RGBA tuples
        It should have 1:1 correspondence with the geometries (not their components).

    plot_values : bool
        If True, `colors_or_values` is interpreted as a list of values, and will
        be mapped to colors using vmin/vmax/cmap (which become required).
        Otherwise `colors_or_values` is interpreted as a list of colors.

    Returns
    -------

    collection : matplotlib.collections.Collection that was plotted
    """

    from matplotlib.collections import LineCollection

    components, component_colors_or_values = _flatten_multi_geoms(
        geoms, colors_or_values)

    # LineCollection does not accept some kwargs.
    if 'markersize' in kwargs:
        del kwargs['markersize']
    segments = [np.array(linestring)[:, :2] for linestring in components]
    collection = LineCollection(segments,
                                linewidth=linewidth, **kwargs)

    if plot_values:
        collection.set_array(np.array(component_colors_or_values))
        collection.set_cmap(cmap)
        collection.set_clim(vmin, vmax)
    else:
        # set_color magically sets the correct combination of facecolor and
        # edgecolor, based on collection type.
        collection.set_color(component_colors_or_values)

        # If the user set facecolor and/or edgecolor explicitly, the previous
        # call to set_color might have overridden it (remember, the 'color' may
        # have come from plot_series, not from the user). The user should be
        # able to override matplotlib's default behavior, by setting them again
        # after set_color.
        if 'facecolor' in kwargs:
            collection.set_facecolor(kwargs['facecolor'])

        if 'edgecolor' in kwargs:
            collection.set_edgecolor(kwargs['edgecolor'])

    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    return collection