Exemple #1
0
    def add_circular_objects(self,
                             diameters,
                             positions,
                             collision,
                             pause_time=0.1):

        circ_colors = self.generate_color_array(collision)
        self.circles = EllipseCollection(widths=diameters,
                                         heights=diameters,
                                         angles=np.zeros_like(diameters),
                                         units='xy',
                                         offsets=positions,
                                         transOffset=self.ax.transData,
                                         edgecolor='k',
                                         facecolor=circ_colors)

        self.ax.add_collection(self.circles)

        #add text label
        text_labels = [None] * len(collision)
        for i in range(len(collision)):
            text_labels[i] = plt.text(positions[i, 0],
                                      positions[i, 1],
                                      str(i),
                                      color='k')
        self.circle_labels = text_labels
class Animator(object):
    def __init__(self, positions, diameter):
        self.count = positions.shape[0]

        plt.ion()
        fig = plt.figure(figsize=(10, 10))
        ax = fig.gca()
        self.ax = ax

        diameters = np.ones(self.count) * diameter
        colors = [randcolor() for _ in range(self.count)]
        self.circles = EllipseCollection(widths=diameters,
                                         heights=diameters,
                                         angles=np.zeros_like(diameters),
                                         units='xy',
                                         offsets=positions,
                                         transOffset=ax.transData,
                                         edgecolor='face',
                                         facecolor=colors)
        ax.add_collection(self.circles)

        ax.axis([0, 1, 0, 1])
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        ax.set_axis_bgcolor('black')
        plt.draw()

    def update(self, positions):
        self.circles.set_offsets(positions)
        plt.draw()
class Animator(object):
    def __init__(self, positions, diameter):
        self.count = positions.shape[0]

        plt.ion()
        fig = plt.figure(figsize=(10, 10))
        ax = fig.gca()
        self.ax = ax

        diameters = np.ones(self.count) * diameter
        colors = [randcolor() for _ in range(self.count)]
        self.circles = EllipseCollection(widths=diameters,
                                         heights=diameters,
                                         angles=np.zeros_like(diameters),
                                         units='xy',
                                         offsets=positions,
                                         transOffset=ax.transData,
                                         edgecolor='face', facecolor=colors)
        ax.add_collection(self.circles)

        ax.axis([0, 1, 0, 1])
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        ax.set_axis_bgcolor('black')
        plt.draw()
        plt.pause(0.1)
        #plt.show()
        #plt.savefig('foo.png')

    def update(self, positions):
        self.circles.set_offsets(positions)
        plt.draw()
        #plt.show()
        plt.pause(0.1)
def plot_2d(T):
    T = np.reshape(T,(n,n,2,2))
    x = np.arange(n)
    y = np.arange(n)
    Y, X = np.meshgrid(x, y)
    
    XY = np.hstack((X.ravel()[:, np.newaxis], Y.ravel()[:, np.newaxis]))
    
    ww = T[:,:,0,0]/2.0
    hh = T[:,:,1,1]/2.0
    aa = T[:,:,0,1]#/1.7
    
    
    fig, ax = plt.subplots()
    
    ec = EllipseCollection(ww, hh,aa*360, units='x', offsets=XY,
                           transOffset=ax.transData)
                           
    #ec.set_array((X + Y).ravel())
    ax.add_collection(ec)
    ax.autoscale_view()
    ax.set_xlabel('X')
    ax.set_ylabel('y')
    ec.set_facecolor('green')
    plt.xlim([-1,n])
    plt.ylim([-1,n])
    #cbar.set_label('X+Y')
    plt.show()
    plt.savefig('field.png')
    np.save('tensor',T)
Exemple #5
0
def scaled_scatter_plot(ax, X, Y, color, radius, filled=True):
    """ Regular scatter plots require the size of markers to be given in
pixels, not relative to the data.  This does relative-sized markers.  Taken
from
https://stackoverflow.com/questions/33094509/correct-sizing-of-markers-in-scatter-plot-to-a-radius-r-in-matplotlib.
"""
    offsets = list(zip(X, Y))
    size = 2 * radius
    if filled:
        ax.add_collection(
            EllipseCollection(widths=size,
                              heights=size,
                              angles=0,
                              units='xy',
                              facecolors=color,
                              offsets=offsets,
                              transOffset=ax.transData))
    else:
        ax.add_collection(
            EllipseCollection(widths=size,
                              heights=size,
                              angles=0,
                              units='xy',
                              edgecolors='k',
                              offsets=offsets,
                              transOffset=ax.transData))
Exemple #6
0
def plot_2d(T):
    T = np.reshape(T, (n, n, 2, 2))
    x = np.arange(n)
    y = np.arange(n)
    Y, X = np.meshgrid(x, y)

    XY = np.hstack((X.ravel()[:, np.newaxis], Y.ravel()[:, np.newaxis]))

    ww = T[:, :, 0, 0] / 2.0
    hh = T[:, :, 1, 1] / 2.0
    aa = T[:, :, 0, 1]  #/1.7

    fig, ax = plt.subplots()

    ec = EllipseCollection(ww,
                           hh,
                           aa * 360,
                           units='x',
                           offsets=XY,
                           transOffset=ax.transData)

    #ec.set_array((X + Y).ravel())
    ax.add_collection(ec)
    ax.autoscale_view()
    ax.set_xlabel('X')
    ax.set_ylabel('y')
    ec.set_facecolor('green')
    plt.xlim([-1, n])
    plt.ylim([-1, n])
    #cbar.set_label('X+Y')
    plt.show()
    plt.savefig('field.png')
    np.save('tensor', T)
Exemple #7
0
def draw_ellipses(w, mu, C, nsigmas=2, color='lightgray', axis=None):
    """Draw a collection of ellipses.
    Uses the low-level EllipseCollection to efficiently draw a large number
    of ellipses. Useful to visualize the results of a GMM fit via
    GMM_pairplot() defined below.
    Parameters
    ----------
    w : array
        1D array of K relative weights for each ellipse. Must sum to one.
        Ellipses with smaller weights are rended with greater transparency.
    mu : array
        Array of shape (K, 2) giving the 2-dimensional centroids of
        each ellipse.
    C : array
        Array of shape (K, 2, 2) giving the 2 x 2 covariance matrix for
        each ellipse.
    axis : matplotlib axis or None
        Plot axis where the ellipse collection should be drawn. Uses the
        current default axis when None.
    """
    # Calculate the ellipse angles and bounding boxes using SVD.
    U, s, _ = np.linalg.svd(C)
    angles = np.degrees(np.arctan2(U[:, 1, 0], U[:, 0, 0]))
    widths, heights = 2 * nsigmas * np.sqrt(s.T)
    # Data limits must already be defined for axis.transData to be valid.
    axis = axis or plt.gca()
    axis.add_collection(EllipseCollection(
        widths, heights, angles, units='xy', offsets=mu, linewidths=4,
        transOffset=axis.transData, facecolors='none', edgecolors='k'))
    axis.add_collection(EllipseCollection(
        widths, heights, angles, units='xy', offsets=mu, linewidths=2.5,
        transOffset=axis.transData, facecolors='none', edgecolors='w'))
Exemple #8
0
def draw_ellipses(w, mu, C, nsigmas=2, color='red', outline=None, filled=True, axis=None):
    """Draw a collection of ellipses.

    Uses the low-level EllipseCollection to efficiently draw a large number
    of ellipses. Useful to visualize the results of a GMM fit via
    GMM_pairplot() defined below.

    Parameters
    ----------
    w : array
        1D array of K relative weights for each ellipse. Must sum to one.
        Ellipses with smaller weights are rendered with greater transparency
        when filled is True.
    mu : array
        Array of shape (K, 2) giving the 2-dimensional centroids of
        each ellipse.
    C : array
        Array of shape (K, 2, 2) giving the 2 x 2 covariance matrix for
        each ellipse.
    nsigmas : float
        Number of sigmas to use for scaling ellipse area to a confidence level.
    color : matplotlib color spec
        Color to use for the ellipse edge (and fill when filled is True).
    outline : None or matplotlib color spec
        Color to use to outline the ellipse edge, or no outline when None.
    filled : bool
        Fill ellipses with color when True, adjusting transparency to
        indicate relative weights.
    axis : matplotlib axis or None
        Plot axis where the ellipse collection should be drawn. Uses the
        current default axis when None.
    """
    # Calculate the ellipse angles and bounding boxes using SVD.
    U, s, _ = np.linalg.svd(C)
    angles = np.degrees(np.arctan2(U[:, 1, 0], U[:, 0, 0]))
    widths, heights = 2 * nsigmas * np.sqrt(s.T)
    # Initialize colors.
    color = colorConverter.to_rgba(color)
    if filled:
        # Use transparency to indicate relative weights.
        ec = np.tile([color], (len(w), 1))
        ec[:, -1] *= w
        fc = np.tile([color], (len(w), 1))
        fc[:, -1] *= w ** 2
    # Data limits must already be defined for axis.transData to be valid.
    axis = axis or plt.gca()
    if outline is not None:
        axis.add_collection(EllipseCollection(
            widths, heights, angles, units='xy', offsets=mu, linewidths=4,
            transOffset=axis.transData, facecolors='none', edgecolors=outline))
    if filled:
        axis.add_collection(EllipseCollection(
            widths, heights, angles, units='xy', offsets=mu, linewidths=2,
            transOffset=axis.transData, facecolors=fc, edgecolors=ec))
    else:
        axis.add_collection(EllipseCollection(
            widths, heights, angles, units='xy', offsets=mu, linewidths=2.5,
            transOffset=axis.transData, facecolors='none', edgecolors=color))
Exemple #9
0
    def plotEllipse(self,barotropic=False,k=0,con='M2',scale=1e4,subsample=4,\
            xlims=None,ylims=None,cbarpos=[0.15, 0.15, 0.03, 0.3],**kwargs):
        """
        Plots tidal ellipses on a map
        """
        from matplotlib.collections import EllipseCollection
        
        plt.ioff()
        fig = plt.gcf()
        ax = fig.gca()
        
        iicon = findCon(con,self.frqnames)
        
        if self.clim==None:
            self.clim=[]
            self.clim.append(np.min(self.Amp))
            self.clim.append(np.max(self.Amp))
        if xlims==None or ylims==None:
            xlims=self.xlims 
            ylims=self.ylims

        ell = self.getEllipse(barotropic=barotropic,k=k,con=con)
            
        # Create the ellipse collection
        indices = range(0,self.Nc,subsample)
        widths = [ell[0][ii]*scale for ii in indices]
        heights = [ell[1][ii]*scale for ii in indices]
        angles = [ell[2][ii]*180.0/np.pi for ii in indices]
        #angles = [ell[2][ii] for ii in indices]
        offsets = [(self.xv[ii],self.yv[ii]) for ii in indices]

        
        collection = EllipseCollection(widths,heights,angles,units='xy',\
            offsets=offsets, transOffset=ax.transData,**kwargs)
        
        z=ell[0][indices]
        collection.set_array(np.array(z))
        collection.set_clim(vmin=self.clim[0],vmax=self.clim[1])
        collection.set_edgecolors(collection.to_rgba(np.array(z))) 
        
        ax.set_aspect('equal')
        ax.set_xlim(xlims)
        ax.set_ylim(ylims)

        titlestr='%s - Semi-major Ellipse Amplitude'%(self.frqnames[iicon])
        plt.title(titlestr)
        
        ax.add_collection(collection)
        # Add a decent looking colorbar
        if not cbarpos==None:
            cbaxes = fig.add_axes(cbarpos) 
            cb = fig.colorbar(collection,cax = cbaxes,orientation='vertical')  
            cb.ax.set_title('[m s$^{-1}$]')
    
        plt.sca(ax)
        
        #axcb = fig.colorbar(collection)
        
        return collection
Exemple #10
0
    def plot_as_data(self):
        """
        plot the as data
        """
        if not self.gui.datamanager.hasAS():
            return
        for i in range(len(self.gui.datamanager.datasets['AS'])):
            data = self.gui.datamanager.datasets['AS'][i].getData()
            if data is not None:
                if self.asdata_lines[i] is None:

                    self.asdata_lines[i], = self.as_ax.plot(
                        data[:, 1],
                        data[:, 2],
                        '.',
                        c=cst.ASCOLORS[i % len(cst.ASCOLORS)],
                        ls='',
                        label='Relative position')
                else:
                    self.asdata_lines[i].set_xdata(data[:, 1])
                    self.asdata_lines[i].set_ydata(data[:, 2])
                if self.as_ellipses[i] is not None:
                    self.as_ellipses[i].remove()
                self.as_ellipses[i] = EllipseCollection(
                    2 * data[:, 5],
                    2 * data[:, 6],
                    data[:, 7] - 90,
                    offsets=np.column_stack((data[:, 1], data[:, 2])),
                    transOffset=self.as_ax.transData,
                    units='x',
                    edgecolors=cst.ASCOLORS[i % len(cst.ASCOLORS)],
                    facecolors=(0, 0, 0, 0))
                self.as_ax.add_collection(self.as_ellipses[i])
Exemple #11
0
    def draw_confidence_ellipse(self, u, cov, ax, **kwargs):
        key = (ax, kwargs.pop('key', self.keyfor(u, cov)))
        fc = kwargs.pop('fc', 'none')
        ec = kwargs.pop('ec', 'k')
        zorder = kwargs.pop('zorder', 1)

        chisquare_val = kwargs.pop(
            'scale', 5.991)  # 95% confidence area based on chi2(2dof, 0.05)

        # http://www.visiondummy.com/2014/04/draw-error-ellipse-representing-covariance-matrix/
        # https://people.richland.edu/james/lecture/m170/tbl-chi.html

        if key in self.items:
            self.items[key].remove()

        u = np.asarray(u)
        cov = np.asarray(cov).reshape(-1, 2, 2)
        widths, heights, angles = self._compute_ellipse_parameters(
            cov, chisquare_val)

        e = EllipseCollection(widths,
                              heights,
                              np.degrees(angles),
                              units='y',
                              offsets=u.reshape(2, -1),
                              transOffset=ax.transData,
                              facecolors=fc,
                              edgecolors=ec,
                              zorder=zorder,
                              alpha=0.5)
        ax.add_collection(e)

        self.items[key] = e

        return e,
Exemple #12
0
    def save_plot(self, export_path):
        agent_positions = [agent.position for agent in self.agents]
        agent_size = [2 * agent.size for agent in self.agents]
        agent_type_colors = [
            self.agent_type_color(agent.type) for agent in self.agents
        ]
        agent_status_colors = [
            self.agent_status_color(agent.state) for agent in self.agents
        ]

        fig, ax = plt.subplots()
        ax.grid(True)
        ax.axis(xmin=-25,
                xmax=self.box[0] + 25,
                ymin=-25,
                ymax=self.box[1] + 25)
        ax.set_aspect(1)

        points = EllipseCollection(widths=agent_size,
                                   heights=agent_size,
                                   angles=0,
                                   units='xy',
                                   linewidths=2,
                                   transOffset=ax.transData,
                                   alpha=0.3,
                                   facecolors=agent_type_colors,
                                   edgecolors=agent_status_colors,
                                   offsets=agent_positions)

        ax.add_collection(points)

        fig.savefig(export_path, dpi=300)
        plt.close()
Exemple #13
0
def plot(filename, sim, i):
    fig = plt.figure(i, clear=True, figsize=(10, 10))
    xy = sim.get_position()
    u = sim.get_orientation()
    sigma_s = sim.get_sigma_s()
    k = sim.get_k()
    n = sim.size()

    ww = np.ones(n)*sigma_s*k
    hh = np.ones(n)*sigma_s
    aa = np.arctan2(u[:, 1], u[:, 0])*360/(2*3.14)

    ax = fig.subplots()
    ec = EllipseCollection(ww, hh, aa, units='x', offsets=xy, transOffset=ax.transData)
    ax.add_collection(ec)
    ax.autoscale_view()
    ax.quiver(xy[:, 0], xy[:, 1], u[:, 0], u[:, 1])
    ax.set_xlabel('X')
    ax.set_ylabel('y')
    ax.set_xlim(-2, 2)
    ax.set_ylim(-2, 2)
    ax.set_title('job %d' % i)
    fig.savefig(filename+'.png')
    plt.close(fig)

    data = np.concatenate([xy, u], axis=1)
    np.savetxt(filename+'.csv', data, header='x y ux uy')
Exemple #14
0
def plot_multi(filename, sims):
    fig, axs = plt.subplots(1, len(sims), clear=True, figsize=(12, 4))
    for i, sim in enumerate(sims):
        xy = sim.get_position()
        u = sim.get_orientation()
        sigma_s = sim.get_sigma_s()
        k = sim.get_k()
        n = sim.size()

        ww = np.ones(n)*sigma_s*k
        hh = np.ones(n)*sigma_s
        aa = np.arctan2(u[:, 1], u[:, 0])*360/(2*3.14)

        ax = axs[i]
        ec = EllipseCollection(ww, hh, aa, units='x', offsets=xy, transOffset=ax.transData)
        ax.add_collection(ec)
        ax.autoscale_view()
        ax.quiver(xy[:, 0], xy[:, 1], u[:, 0], u[:, 1])
        ax.set_xlabel('X')
        ax.set_ylabel('y')
        ax.set_xlim(-2, 2)
        ax.set_ylim(-2, 2)

    axs[0].set_title('weak support\npotential well scaling = %d' % params[0].potential_well_scaling)
    axs[1].set_title('medium support\npotential well scaling = %d' % params[1].potential_well_scaling)
    axs[2].set_title('strong support\npotential well scaling = %d' % params[2].potential_well_scaling)
    fig.savefig(filename)
def plot_corr_ellipses(data, ax=None, **kwargs):

    M = np.array(data)
    if not M.ndim == 2:
        raise ValueError('data must be a 2D array')
    if ax is None:
        fig, ax = plt.subplots(1, 1, subplot_kw={'aspect':'equal'})
        ax.set_xlim(-0.5, M.shape[1] - 0.5)
        ax.set_ylim(-0.5, M.shape[0] - 0.5)

    # xy locations of each ellipse center
    xy = np.indices(M.shape)[::-1].reshape(2, -1).T

    # set the relative sizes of the major/minor axes according to the strength of
    # the positive/negative correlation
    w = np.ones_like(M).ravel()
    h = 1 - np.abs(M).ravel()
    a = 45 * np.sign(M).ravel()

    ec = EllipseCollection(widths=w, heights=h, angles=a, units='x', offsets=xy,
                           transOffset=ax.transData, array=M.ravel(), **kwargs)
    ax.add_collection(ec)

    # if data is a DataFrame, use the row/column names as tick labels
    if isinstance(data, pd.DataFrame):
        ax.set_xticks(np.arange(M.shape[1]))
        ax.set_xticklabels(data.columns, rotation=90)
        ax.set_yticks(np.arange(M.shape[0]))
        ax.set_yticklabels(data.index)

    return ec
    def plot_spiral(self, axis, true, data, obsv, pred, rng):
        """Plots a single spiral on provided axis."""
        axis.cla()
        # Plot 95% confidence ellipses
        ec = EllipseCollection(1.96 * rng[0],
                               1.96 * rng[1], (0, ),
                               units='x',
                               facecolors=('c', ),
                               alpha=0.25,
                               offsets=np.column_stack(pred),
                               transOffset=axis.transData)
        axis.add_collection(ec)

        # Plot ground truth
        axis.plot(true[0], true[1], 'b-', linewidth=1.5)

        # Plot observations (blue = both, pink = x-only, yellow = y-only)
        if (np.isnan(obsv[0]) != np.isnan(obsv[1])).any():
            axis.plot(obsv[0], data[1], '<', markersize=2, color='#fe46a5')
            axis.plot(data[0], obsv[1], 'v', markersize=2, color='#fec615')
        axis.plot(obsv[0], obsv[1], 'bo', markersize=3)

        # Plot predictions
        axis.plot(pred[0], pred[1], '-', linewidth=1.5, color='#04d8b2')

        # Set limits
        axis.set_xlim(-4, 4)
        axis.set_ylim(-4, 4)
Exemple #17
0
def plot_corr_ellipses(data, ax=None, **kwargs):

    M = np.array(data)
    if not M.ndim == 2:
        raise ValueError('data must be a 2D array')
    if ax is None:
        fig, ax = plt.subplots(1, 1, subplot_kw={'aspect': 'equal'})
        ax.set_xlim(-0.5, M.shape[1] - 0.5)
        ax.set_ylim(-0.5, M.shape[0] - 0.5)

    # xy locations of each ellipse center
    xy = np.indices(M.shape)[::-1].reshape(2, -1).T
    x, y = zip(*xy)
    x = np.array(x, dtype=np.int8)
    y = np.array(y, dtype=np.int8)
    ind = x <= y

    # set the relative sizes of the major/minor axes according to the strength of
    # the positive/negative correlation
    w = np.ones_like(M).ravel()
    h = 1 - np.abs(M).ravel()
    w *= 0.85
    h *= 0.85
    a = 45 * np.sign(M).ravel()
    w = w[ind]
    h = h[ind]
    a = a[ind]
    xymat = xy[ind]
    Mfull = M.ravel()
    Mhalf = Mfull[ind]

    linewidths = np.repeat(1 + np.abs(Mhalf), len(h))
    edgecolors = cm.binary(np.abs(Mhalf))

    ec = EllipseCollection(widths=w,
                           heights=h,
                           angles=a,
                           units='x',
                           offsets=xymat,
                           linewidths=linewidths,
                           edgecolors=edgecolors,
                           transOffset=ax.transData,
                           array=Mhalf,
                           **kwargs)
    ax.add_collection(ec)
    for xt, yt, val in zip(x[~ind], y[~ind], Mfull[~ind]):
        strval = '{:+.2f}'.format(val).replace('0.', '.')
        ax.text(xt, yt, strval, ha='center', va='baseline', fontsize='small')

    # if data is a DataFrame, use the row/column names as tick labels
    if isinstance(data, pd.DataFrame):
        ax.set_xticks(np.arange(M.shape[1]))
        ax.set_xticklabels(data.columns, rotation=30)
        ax.set_yticks(np.arange(M.shape[0]))
        ax.set_yticklabels(data.index, rotation=30)
    ax.set_xlim(x.min() - 0.5, x.max() + 0.5)
    ax.set_ylim(x.min() - 0.5, x.max() + 0.5)
    ax.set_aspect('equal')
    return ec
    def update(self, positions):

        #update number of balls

        self.circles.set_offsets(positions)
        colors = [(1.0, 0.0, 0.0) for _ in range(self.circ_count)]
        self.circles.set_facecolors(colors)

        #redefine circles
        diameter = 2
        diameters = np.ones(self.circ_count + 100) * diameter
        circ_colors = [(0.0, 0.0, 1.0) for _ in range(self.circ_count)]

        #add circles
        self.circles.remove()
        self.circles = EllipseCollection(widths=diameters,
                                         heights=diameters,
                                         angles=np.zeros_like(diameters),
                                         units='xy',
                                         offsets=positions,
                                         transOffset=self.ax.transData,
                                         edgecolor='face',
                                         facecolor=circ_colors)
        self.ax.add_collection(self.circles)

        #label
        text_labels = [None] * positions.shape[0]
        for i in range(positions.shape[0]):
            text_labels[i] = plt.text(positions[i, 0],
                                      positions[i, 1],
                                      str(i),
                                      color='white')

        #remove polygon
        #self.polygons.remove()
        poly_color = np.random.uniform(0.0, 0.89, (3, )) + 0.1
        verts = [[(10, 1), (9, 0), (8, 2), (10, 2)], [(8, 8), (9, 9), (6, 7)]]
        self.polygons.set_verts(verts)

        plt.draw()
        plt.pause(0.1)

        #remove labels
        for i in range(positions.shape[0]):
            text_labels[i].remove()
Exemple #19
0
    def __init__(self, **kwargs):
        super(HoughDemo, self).__init__(**kwargs)
        self.connect_dirty("th2, show_canny, show_blur, rho, theta, hough_th,"
                           "min_radius, max_radius, blur_sigma,"
                           "minlen, maxgap, dp, mindist, param2, "
                           "linewidth, alpha, check_line, check_circle")
        self.lines = LineCollection([], linewidths=2, alpha=0.6)
        self.axe.add_collection(self.lines)

        self.circles = EllipseCollection([], [], [],
                                         units="xy",
                                         facecolors="none",
                                         edgecolors="red",
                                         linewidths=2,
                                         alpha=0.6,
                                         transOffset=self.axe.transData)

        self.axe.add_collection(self.circles)
Exemple #20
0
    def overlay_fibers(self,
                       ax,
                       diameter=None,
                       skies=None,
                       return_figure=True,
                       **kwargs):
        """ Overlay the individual fibers within an IFU on a plot.

        Parameters:
            ax (Axis):
                The matplotlib axis object
            diameter (float):
                The fiber diameter in arcsec. Default is 2".
            skies (bool):
                Set to True to additionally overlay the sky fibers. Default if False
            return_figure (bool):
                If True, returns the figure axis object.  Default is True
            kwargs:
                Any keyword arguments accepted by Matplotlib EllipseCollection
        """

        if self.wcs is None:
            raise MarvinError('No WCS found.  Cannot overlay fibers.')

        # check the diameter
        if diameter:
            assert isinstance(diameter,
                              (float, int)), 'diameter must be a number'
        diameter = (diameter or 2.0) / float(self.header['SCALE'])

        # get the fiber pixel coordinates
        fibers = self.bundle.fibers[:, [1, 2]]
        fiber_pix = self.wcs.wcs_world2pix(fibers, 1)

        # some matplotlib kwargs
        kwargs['edgecolor'] = kwargs.get('edgecolor', 'Orange')
        kwargs['facecolor'] = kwargs.get('facecolor', 'none')
        kwargs['linewidth'] = kwargs.get('linewidth', 0.4)

        ec = EllipseCollection(diameter,
                               diameter,
                               0.0,
                               units='xy',
                               offsets=fiber_pix,
                               transOffset=ax.transData,
                               **kwargs)
        ax.add_collection(ec)

        # overlay the sky fibers
        if skies:
            self.overlay_skies(ax,
                               diameter=diameter,
                               return_figure=return_figure,
                               **kwargs)

        if return_figure:
            return ax
Exemple #21
0
    def ellipse_plot(self, ax=None, **kwargs):
        """
        Make an ellipse plot of the correlation matrix. Return the figure instance. Code modified from
        https://stackoverflow.com/a/34558488/787267

        :param ax: If specified, will plot in this axes instance, otherwise will create a new figure instance
        :param kwargs: Key word arguments to be passed to matplotlib.collections.EllipseCollection. The default clim is
        [-1,1], use clim=None if the color scaling is to be set automatically
        :return: A matplotlotlib.pyplot.figure instance
        """

        M = self.matrix.values
        if ax is None:
            fig, ax = plt.subplots(1, 1, subplot_kw={'aspect': 'equal'})
            ax.set_xlim(-0.5, M.shape[1] - 0.5)
            ax.set_ylim(-0.5, M.shape[0] - 0.5)
            ax.margins(0.1)

        # xy locations of each ellipse center
        xy = np.indices(M.shape).reshape(2, -1).T

        # set the relative sizes of the major/minor axes according to the strength of
        # the positive/negative correlation
        w = np.ones_like(M).ravel()
        h = 1 - np.abs(M).ravel()
        # Fix diagonal entries to be straight lines
        h = [0.01 if e == 0 else e for e in h]
        a = 45 * np.sign(M).ravel()

        kwargs.setdefault('cmap', 'bwr_r')
        kwargs.setdefault('clim', [-1, 1])

        ec = EllipseCollection(widths=w,
                               heights=h,
                               angles=a,
                               units='x',
                               offsets=xy,
                               transOffset=ax.transData,
                               array=M.ravel(),
                               **kwargs)
        ax.add_collection(ec)

        for x, y in xy:
            ax.annotate("%.1f" % M[x, y], xy=(x, y), va='center', ha='center')

        cb = fig.colorbar(ec)
        cb.set_label('Correlation coefficient')

        ax.set_xticks(np.arange(self.matrix.shape[1]))
        ax.set_xticklabels(self.columns)
        ax.set_yticks(np.arange(self.matrix.shape[0]))
        ax.set_yticklabels(self.rows)

        ax.invert_yaxis()
        ax.xaxis.tick_top()
        return ec.figure
Exemple #22
0
def error_ellipse(x, y, xerr, yerr, alpha=0.2, **kw):
    """Like errorbar, but uses ellipses"""
    from matplotlib.collections import EllipseCollection
    ax = plt.gca()
    ec = EllipseCollection(xerr, yerr, 0, units='xy',
                           offsets=np.asarray([x, y]).T,
                           transOffset=ax.transData, alpha=alpha,
                           **kw)
    ax.add_collection(ec)
    return ec
Exemple #23
0
 def ellipse_collection(self,
                        x,
                        y,
                        widths,
                        heights,
                        angles,
                        cvalues=None,
                        **kwargs):
     import numpy as np
     from interactive_plotter.interactive_artist import EllipseCollection
     from matplotlib.collections import EllipseCollection as __EllipseCollection
     artist = __EllipseCollection([0] * x.size, [0] * x.size, [0] * x.size,
                                  offsets=np.zeros((x.size, 2)),
                                  transOffset=self.__axes.transData,
                                  **kwargs)
     self.__axes.add_collection(artist)
     interactive_artist = EllipseCollection(artist)
     interactive_artist.plot(x, y, widths, heights, angles, cvalues)
     self.__add_foreground_artist(interactive_artist)
     return interactive_artist
Exemple #24
0
def _plot_listeners(ls_xys, ax):
    if isinstance(ls_xys, (list,)):
        ls_xys = np.array(ls_xys)

    size = np.full(ls_xys.shape[0], 2 * DSRC_RANGE)
    wifi = EllipseCollection(widths=size, heights=size, angles=0, units='xy', offsets=ls_xys,
                             transOffset=ax.transData, color='white', edgecolor='black', linestyle='--', zorder=2)
    ax.add_collection(wifi)

    size = np.full(ls_xys.shape[0], 2 * WIFI_RANGE)
    dsrc = EllipseCollection(widths=size, heights=size, angles=0, units='xy', offsets=ls_xys,
                             transOffset=ax.transData, color='white', edgecolor='black', linestyle='-', zorder=2)
    ax.add_collection(dsrc)

    # make sure the points show up in the legend
    ax.scatter([], [], color='white', s=21, edgecolor='black', linestyle='--', label='DSRC coverage')
    ax.scatter([], [], color='white', s=7, edgecolor='black', linestyle='-', label='WiFi coverage')

    ax.axis('equal')

    return ax
Exemple #25
0
    def update(kk):
        ellipseNode = NodeList[kk]
        ellNodeShape = ellipseNode.means.shape
        xPlotValues = []
        yPlotValues = []
        xValues = []
        yValues = []
        widthValues = []
        heightValues = []
        angleValues = []
        # Prepare the trajectory x and y vectors and plot them
        for k in range(ellNodeShape[0]):
            xPlotValues.append(ellipseNode.means[k, 0, 0])
            yPlotValues.append(ellipseNode.means[k, 1, 0])
        # Plotting the risk bounded trajectories
        lx, = plt.plot(xPlotValues, yPlotValues, "#636D97", linewidth=2.0)
        # Plot only the last ellipse in the trajectory
        alfa = math.atan2(ellipseNode.means[-1, 1, 0], ellipseNode.means[-1, 0,
                                                                         0])
        elcovar = np.asarray(ellipseNode.covar[-1, :, :])
        elE, elV = LA.eig(elcovar[0:2, 0:2])
        xValues.append(ellipseNode.means[-1, 0, 0])
        yValues.append(ellipseNode.means[-1, 1, 0])
        widthValues.append(math.sqrt(elE[0]))
        heightValues.append(math.sqrt(elE[1]))
        angleValues.append(alfa * 360)

        # Plot the Safe Ellipses
        XY = np.column_stack((xValues, yValues))
        ec = EllipseCollection(widthValues,
                               heightValues,
                               angleValues,
                               units='x',
                               offsets=XY,
                               facecolors="#C59434",
                               transOffset=plt.axes().transData)
        ec.set_alpha(0.5)
        plt.axes().add_collection(ec)

        return lx, ec
Exemple #26
0
    def _update_ellipsoids(self, su, sv, rho):
        self.scale_units = 'xy'
        self.angles = 'xy'
        tips_x = self.X + self.U / self.scale
        tips_y = self.Y + self.V / self.scale
        tips = np.array([tips_x, tips_y]).transpose()
        a, b, angle = compute_abphi(su, sv, rho)
        width = 2.0 * a / self.scale
        height = 2.0 * b / self.scale
        if self.ellipsoids is not None:
            self.ellipsoids.remove()

        # do not draw ellipses which are too small
        too_small = 0.001
        length = np.sqrt((self.U / self.scale)**2 + (self.V / self.scale)**2)
        with warnings.catch_warnings():
            # do not print out zero division warning
            warnings.simplefilter("ignore")
            is_not_too_small = ((np.nan_to_num(width / length) > too_small) |
                                (np.nan_to_num(height / length) > too_small))

        width = width[is_not_too_small]
        height = height[is_not_too_small]
        angle = angle[is_not_too_small]
        tips = tips[is_not_too_small]

        # dont add ellipses if there are no ellipses to add
        if any(is_not_too_small):
            self.ellipsoids = EllipseCollection(width,
                                                height,
                                                angle,
                                                units=self.scale_units,
                                                offsets=tips,
                                                transOffset=self.ax.transData,
                                                **self.ellipse_kwargs)

            self.ax.add_collection(self.ellipsoids)

        else:
            self.ellipsoids = None
Exemple #27
0
def circular_border(ax):
    offsets = [width / 2, height / 2]
    color = 'k'
    size = width - 10
    ax.add_collection(
        EllipseCollection(widths=size,
                          heights=size,
                          angles=0,
                          units='xy',
                          facecolors='w',
                          edgecolors='k',
                          offsets=offsets,
                          transOffset=ax.transData))
Exemple #28
0
def plot_spd2(Is, filename=None):
    rc('axes', linewidth=0.5)
    rc('font', size=7, family='serif')
    rc('xtick', top=True, direction='in')
    rc('xtick.major', size=2.5, width=0.5)
    rc('ytick', right=True, direction='in')
    rc('ytick.major', size=2.5, width=0.5)
    fig = plt.figure(figsize=(len(Is) * 5, 5), dpi=100)

    for k, I in enumerate(Is):
        ax = fig.add_subplot(100 + len(Is) * 10 + (k + 1))

        imagedims = I.shape[:2]
        vals, vecs = np.linalg.eig(I)

        FA = np.sqrt(0.5 * (vals[..., 0]**2 + vals[..., 1]**2) -
                     vals[..., 0] * vals[..., 1])
        FA /= np.linalg.norm(Is[0], axis=(-2, -1))

        lvals = np.log(vals)
        GA = np.sqrt(0.5 * (lvals[..., 0]**2 + lvals[..., 1]**2) -
                     lvals[..., 0] * lvals[..., 1])
        GA /= 1 + GA

        angles = 180 + 180 * np.arctan2(vecs[..., 0, 0], vecs[..., 1,
                                                              0]) / np.pi
        vals /= 0.5 * vals.max()

        X, Y = np.meshgrid(np.arange(imagedims[0]), np.arange(imagedims[1]))
        XY = np.vstack((X.ravel(), Y.ravel())).T
        ec = EllipseCollection(vals[..., 0],
                               vals[..., 1],
                               angles,
                               units='x',
                               offsets=XY,
                               transOffset=ax.transData,
                               edgecolors=0.8 * cm.hsv(GA.ravel())[:, :-1],
                               facecolors=1.0 * cm.hsv(GA.ravel())[:, :-1],
                               linewidths=0.5)
        ax.add_collection(ec)
        ax.autoscale_view()
        ax.invert_yaxis()
        ax.axis("equal")

    if filename is None:
        plt.show()
    else:
        canvas = FigureCanvasAgg(fig)
        canvas.print_figure(filename)
        plt.close(fig)
    def __init__(self, positions, diameter):
        self.circ_count = positions.shape[0]

        plt.ion()
        fig = plt.figure(figsize=(10, 10))
        ax = fig.gca()
        self.ax = ax

        diameters = np.ones(self.circ_count) * diameter
        circ_colors = [(0.0, 0.0, 1.0) for _ in range(self.circ_count)]

        #add circles
        self.circles = EllipseCollection(widths=diameters,
                                         heights=diameters,
                                         angles=np.zeros_like(diameters),
                                         units='xy',
                                         offsets=positions,
                                         transOffset=ax.transData,
                                         edgecolor='face',
                                         facecolor=circ_colors)
        ax.add_collection(self.circles)

        #add polygons
        self.poly_count = 3
        verts = [[(0, 1), (1, 0), (2, 2)], [(6, 5), (3, 7), (7, 6)],
                 [(0, -1), (-1, 0), (4, 5)]]
        poly_colors = [(0.0, 0.0, 1.0) for _ in range(self.poly_count)]
        self.polygons = PolyCollection(verts, facecolors=poly_colors)

        ax.add_collection(self.polygons)

        ax.axis([-20, 20, -20, 20])
        ax.get_xaxis().set_visible(True)
        ax.get_yaxis().set_visible(True)
        #ax.set_axis_bgcolor('black')
        plt.draw()
        plt.pause(0.1)
def plot_corr_ellipses(data, ax=None, **kwargs):
    """For a given correlation matrix "data", plot the correlation matrix in terms
    of ellipses.

    parameters
    ----------
    data: Pandas dataframe containing the correlation of the data (df.corr())
    ax: axis (e.g. fig, ax = plt.subplots(1, 1))
    kwards: keywords arguments (cmap="Greens")

    https://stackoverflow.com/questions/34556180/
    how-can-i-plot-a-correlation-matrix-as-a-set-of-ellipses-similar-to-the-r-open

    """
    M = np.array(data)
    if not M.ndim == 2:
        raise ValueError('data must be a 2D array')
    if ax is None:
        fig, ax = plt.subplots(1, 1, subplot_kw={'aspect': 'equal'})
        ax.set_xlim(-0.5, M.shape[1] - 0.5)
        ax.set_ylim(-0.5, M.shape[0] - 0.5)

    # xy locations of each ellipse center
    xy = np.indices(M.shape)[::-1].reshape(2, -1).T

    # set the relative sizes of the major/minor axes according to the strength of
    # the positive/negative correlation
    w = np.ones_like(M).ravel()
    h = 1 - np.abs(M).ravel()
    a = 45 * np.sign(M).ravel()

    ec = EllipseCollection(widths=w,
                           heights=h,
                           angles=a,
                           units='x',
                           offsets=xy,
                           transOffset=ax.transData,
                           array=M.ravel(),
                           **kwargs)
    ax.add_collection(ec)

    # if data is a DataFrame, use the row/column names as tick labels
    if isinstance(data, pd.DataFrame):
        ax.set_xticks(np.arange(M.shape[1]))
        ax.set_xticklabels(data.columns, rotation=90)
        ax.set_yticks(np.arange(M.shape[0]))
        ax.set_yticklabels(data.index)

    return ec
 def DrawGraph(self, lastFlag, randNode=None):                
     """
     Updates the Plot with uncertainty ellipse and trajectory at each time step
     Input Parameters:
     lastFlag: Flag to denote if its the last iteration
     randNode: Node data representing the randomly sampled point        
     """            
     xValues      = []
     yValues      = []
     widthValues  = []
     heightValues = []
     angleValues  = []
     lineObjects  = []
     
     for ellipseNode in self.nodeList:
         if ellipseNode is not None and ellipseNode.parent is not None:                
             ellNodeShape = ellipseNode.means.shape  
             xPlotValues  = []
             yPlotValues  = []
             # Prepare the trajectory x and y vectors and plot them                
             for k in range(ellNodeShape[0]):                                    
                 xPlotValues.append(ellipseNode.means[k,0,0])
                 yPlotValues.append(ellipseNode.means[k,1,0]) 
             # Plotting the risk bounded trajectories
             lx, = plt.plot(xPlotValues, yPlotValues, "#636D97", linewidth=2.0)
             lineObjects.append(lx)  
             # Plot only the last ellipse in the trajectory                                             
             alfa     = math.atan2(ellipseNode.means[-1,1,0], ellipseNode.means[-1,0,0])
             elcovar  = np.asarray(ellipseNode.covar[-1,:,:])            
             elE, elV = LA.eig(elcovar[0:2,0:2])
             xValues.append(ellipseNode.means[-1,0,0])
             yValues.append(ellipseNode.means[-1,1,0])
             widthValues.append(math.sqrt(elE[0]))
             heightValues.append(math.sqrt(elE[1]))
             angleValues.append(alfa*360)                  
     
     # Plot the randomly sampled point
     rx, = plt.plot(randNode.means[-1,0,:], randNode.means[-1,1,:], "^k") 
                  
     # Plot the Safe Ellipses
     XY = np.column_stack((xValues, yValues))                                                 
     ec = EllipseCollection(widthValues, 
                            heightValues, 
                            angleValues, 
                            units='x', 
                            offsets=XY,
                            facecolors="#C59434",
                            transOffset=plt.axes().transData)        
     ec.set_alpha(0.5)
     plt.axes().add_collection(ec)
     plt.pause(0.0001)        
     if not lastFlag:            
         ec.remove() 
         rx.remove()
         for lx in lineObjects:
             lx.remove() 
Exemple #32
0
 def circle(self, x, y, dira, a, b, ax=None, **kwargs):
     """ Draw Ellipses with dira as primary axis, a, b as axis half length at x, y"""
     if ax is None: ax = self.default_axes
     dira = numpy.atleast_2d(dira)
     col = EllipseCollection(offsets=numpy.array([x, y]).T,
                             widths=a,
                             heights=b,
                             units='xy',
                             transOffset=ax.transData,
                             angles=numpy.arctan2(dira[:, 1], dira[:, 0]) /
                             numpy.pi * 180,
                             **kwargs)
     ax.add_collection(col)
     ax.autoscale_view()
     return col
Exemple #33
0
    def __init__(self, **kwargs):
        super(HoughDemo, self).__init__(**kwargs)
        self.connect_dirty("th2, show_canny, show_blur, rho, theta, hough_th,"
                            "min_radius, max_radius, blur_sigma,"
                           "minlen, maxgap, dp, mindist, param2, "
                           "linewidth, alpha, check_line, check_circle")
        self.lines = LineCollection([], linewidths=2, alpha=0.6)
        self.axe.add_collection(self.lines)

        self.circles = EllipseCollection(
            [], [], [],
            units="xy",
            facecolors="none",
            edgecolors="red",
            linewidths=2,
            alpha=0.6,
            transOffset=self.axe.transData)

        self.axe.add_collection(self.circles)
    def add_circular_objects(self,diameters,positions,collision,pause_time=0.1):
        
        circ_colors = self.generate_color_array(collision)
        self.circles = EllipseCollection(widths=diameters,
                                         heights=diameters,
                                         angles=np.zeros_like(diameters),
                                         units='xy',
                                         offsets=positions,
                                         transOffset=self.ax.transData,
                                         edgecolor='k', facecolor=circ_colors)


        self.ax.add_collection(self.circles)

        #add text label
        text_labels = [None] * len(collision)
        for i in range(len(collision)):
            text_labels[i]= plt.text(positions[i,0],positions[i,1],str(i),color = 'k')
        self.circle_labels = text_labels
Exemple #35
0
  def _update_ellipsoids(self,su,sv,rho):
    self.scale_units = 'xy'
    self.angles = 'xy'
    tips_x = self.X + self.U/self.scale
    tips_y = self.Y + self.V/self.scale
    tips = np.array([tips_x,tips_y]).transpose()
    a,b,angle = compute_abphi(su,sv,rho)
    width = 2.0*a/self.scale
    height = 2.0*b/self.scale
    if self.ellipsoids is not None: 
      self.ellipsoids.remove()

    # do not draw ellipses which are too small  
    too_small = 0.001
    length = np.sqrt((self.U/self.scale)**2 + (self.V/self.scale)**2)
    with warnings.catch_warnings():
      # do not print out zero division warning
      warnings.simplefilter("ignore")
      is_not_too_small = ((np.nan_to_num(width/length) > too_small) | 
                          (np.nan_to_num(height/length) > too_small))

    width = width[is_not_too_small]
    height = height[is_not_too_small]
    angle = angle[is_not_too_small]
    tips = tips[is_not_too_small]    
    
    # dont add ellipses if there are no ellipses to add
    if any(is_not_too_small):
      self.ellipsoids = EllipseCollection(width,height,angle,
                                          units=self.scale_units,
                                          offsets = tips,
                                          transOffset=self.ax.transData,
                                          **self.ellipse_kwargs)

      self.ax.add_collection(self.ellipsoids)

    else:
      self.ellipsoids = None      
    def __init__(self, positions, diameter):
        self.count = positions.shape[0]

        plt.ion()
        fig = plt.figure(figsize=(10, 10))
        ax = fig.gca()
        self.ax = ax

        diameters = np.ones(self.count) * diameter
        self.colors = np.array([randcolor() for _ in range(self.count)])
        self.circles = EllipseCollection(widths=diameters,
                                         heights=diameters,
                                         angles=np.zeros_like(diameters),
                                         units='xy',
                                         offsets=positions,
                                         transOffset=ax.transData,
                                         edgecolor='face', facecolor=self.colors)
        ax.add_collection(self.circles)

        ax.axis([0, 1, 0, 1])
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        ax.set_axis_bgcolor('black')
        plt.draw()
def graph(locator, parameters, method, samples):
    """

    :param locator: locator class
    :param parameters: list of output parameters to analyse
    :param method: 'morris' or 'sobol' methods
    :param samples: number of samples to calculate
    :return: .pdf file per output_parameter stored in locator.get_sensitivity_plots_file()

    """
    if method is 'sobol':
        result = ['ST', 'conf', 'S1']
    else:
        result = ['mu_star', 'sigma', 'mu_star_conf']

    for parameter in parameters:
        pdf = PdfPages(locator.get_sensitivity_plots_file(parameter))

        # read the mustar of morris analysis
        data_mu = pd.read_excel(locator.get_sensitivity_output(method, samples), (parameter + result[0]))
        data_sigma = pd.read_excel(locator.get_sensitivity_output(method, samples), (parameter + result[1]))
        var_names = data_mu.columns.values

        # normalize data to maximum value
        data_mu[var_names] = data_mu[var_names].div(data_mu[var_names].max(axis=1), axis=0)
        data_sigma[var_names] = data_sigma[var_names].div(data_sigma[var_names].max(axis=1), axis=0)
        # get x_names and y_names
        # columns
        x_names = data_mu.columns.tolist()
        # rows
        y_names = ['config '+str(i) for i in list(data_mu.index+1)]

        # get counter (integer to create the graph)
        x = range(len(x_names))
        y = range(len (y_names))

        X, Y = np.meshgrid(x,y)
        XY = np.hstack((X.ravel()[:, np.newaxis], Y.ravel()[:, np.newaxis]))
        ww = data_mu.values.tolist()
        hh = data_sigma.values.tolist()
        aa = X*0

        fig, ax = plt.subplots(dpi=150, figsize=(len(x_names)+2, len(y_names)+2)) #
        ec = EllipseCollection(ww, hh, aa, units='x', offsets=XY, transOffset=ax.transData, cmap='Blues')
        ec.set_array(np.array(ww).ravel())
        ec.set_alpha(0.8)
        ax.add_collection(ec)
        ax.autoscale_view()
        plt.xticks(np.arange(-1, max(x) + 1, 1.0))
        plt.yticks(np.arange(-1, max(y) + 1, 1.0))
        ax.set_xlabel('variables [-]')
        ax.set_ylabel('configurations [-]')
        ax.set_xticklabels([""]+x_names)
        ax.set_yticklabels([""]+y_names)
        cbar = plt.colorbar(ec)
        cbar.set_label(result[0])
        plt.title('GRAPH OF '+parameter+' PARAMETER', fontsize=14, fontstyle='italic', fontweight='bold')
        pdf.savefig()
        plt.close()
        plt.clf()
        pdf.close()
Exemple #38
0
class Quiver(_Quiver):
  def __init__(self,ax,*args,**kwargs):
    if 'sigma' in kwargs:
      scale_units = kwargs.get('scale_units','xy')
      kwargs['scale_units'] = scale_units
      if kwargs['scale_units'] != 'xy':
        raise ValueError('scale units must be "xy" when sigma is given')

      angles = kwargs.get('angles','xy')
      kwargs['angles'] = angles
      if kwargs['angles'] != 'xy':
        raise ValueError('angles must be "xy" when sigma is given')

    sigma = kwargs.pop('sigma',None)

    ellipse_kwargs = kwargs.pop('ellipse_kwargs',{})
    if 'offsets' in ellipse_kwargs:
      raise ValueError('cannot specify ellipse offsets')
    if 'units' in ellipse_kwargs:
      raise ValueError('cannot specify ellipse units')
    
    self.ellipse_kwargs = {'edgecolors':'k',
                           'facecolors':'none',
                           'linewidths':1.0}
    self.ellipse_kwargs.update(ellipse_kwargs)
    
    self.ellipsoids = None

    _Quiver.__init__(self,ax,*args,**kwargs)

    if sigma is not None:
      if self.scale is None:
        self.scale = _estimate_scale(self.X,self.Y,self.U,self.V)
        
      su,sv,rho = sigma[0],sigma[1],sigma[2]
      self._update_ellipsoids(su,sv,rho)


  def _update_ellipsoids(self,su,sv,rho):
    self.scale_units = 'xy'
    self.angles = 'xy'
    tips_x = self.X + self.U/self.scale
    tips_y = self.Y + self.V/self.scale
    tips = np.array([tips_x,tips_y]).transpose()
    a,b,angle = compute_abphi(su,sv,rho)
    width = 2.0*a/self.scale
    height = 2.0*b/self.scale
    if self.ellipsoids is not None: 
      self.ellipsoids.remove()

    # do not draw ellipses which are too small  
    too_small = 0.001
    length = np.sqrt((self.U/self.scale)**2 + (self.V/self.scale)**2)
    with warnings.catch_warnings():
      # do not print out zero division warning
      warnings.simplefilter("ignore")
      is_not_too_small = ((np.nan_to_num(width/length) > too_small) | 
                          (np.nan_to_num(height/length) > too_small))

    width = width[is_not_too_small]
    height = height[is_not_too_small]
    angle = angle[is_not_too_small]
    tips = tips[is_not_too_small]    
    
    # dont add ellipses if there are no ellipses to add
    if any(is_not_too_small):
      self.ellipsoids = EllipseCollection(width,height,angle,
                                          units=self.scale_units,
                                          offsets = tips,
                                          transOffset=self.ax.transData,
                                          **self.ellipse_kwargs)

      self.ax.add_collection(self.ellipsoids)

    else:
      self.ellipsoids = None      

  def set_UVC(self,u,v,C=None,sigma=None):
    if C is None:
      _Quiver.set_UVC(self,u,v)
    else:
      _Quiver.set_UVC(self,u,v,C)

    if sigma is not None:
      su,sv,rho = sigma[0],sigma[1],sigma[2]
      self._update_ellipsoids(su,sv,rho)
      
  def remove(self):  
    # remove the quiver and ellipsoid collection
    _Quiver.remove(self)    
    if self.ellipsoids is not None:
      self.ellipsoids.remove()
class Animator(object):
    def __init__(self, template_w, template_h):
        
        #set up figure
        plt.ion()
        fig = plt.figure(figsize = (10,10))
        ax = fig.gca()

        ax.axis([-template_w/2.0, template_w/2.0,-template_h/2.0,template_h/2.0]) 
        ax.get_xaxis().set_visible(True)
        ax.get_yaxis().set_visible(True)

        #draw template
        self.plot_template(template_w,template_h)

        #draw to screen
        plt.draw()
        plt.pause(0.1)

        #save axes to object
        self.ax = ax

    #plot template
    def plot_template(self,l = 20.0, w = 20.0):
        x_pos = [-l/2, l/2, l/2, -l/2, -l/2 ]
        y_pos = [-w/2, -w/2, w/2, w/2, -w/2]
        plt.plot(x_pos,y_pos,'k-',linewidth = 3.0)
        plt.xlabel('x')
        plt.ylabel('y')

    def generate_color_array(self,collision):
        #define colors (red = collision, blue = no collision)
        colors = [None] * len(collision)
        for i in range(len(collision)):
            if collision[i] == True:
                colors[i] = (1.0,0.0,0.0)
            else:
                colors[i] = (0.0,0.0,1.0)
        return colors


    #add circular objects
    def add_circular_objects(self,diameters,positions,collision):
        
        circ_colors = self.generate_color_array(collision)
        self.circles = EllipseCollection(widths=diameters,
                                         heights=diameters,
                                         angles=np.zeros_like(diameters),
                                         units='xy',
                                         offsets=positions,
                                         transOffset=self.ax.transData,
                                         edgecolor='k', facecolor=circ_colors)


        self.ax.add_collection(self.circles)

        #add text label
        text_labels = [None] * len(collision)
        for i in range(len(collision)):
            text_labels[i]= plt.text(positions[i,0],positions[i,1],str(i),color = 'w')
        self.circle_labels = text_labels

        #draw to screen
        plt.draw()
        plt.pause(0.1)

        #remove text labels
        #for i in range(len(collision)):
        #    text_labels[i].remove()

    #add polygon objects
    def add_polygon_objects(self,verts,collision):

        poly_colors = self.generate_color_array(collision)
        self.polygons = PolyCollection(verts, facecolors=poly_colors)

        self.ax.add_collection(self.polygons)

        #add text label
        num_circles = self.circles.get_offsets().shape[1]
        text_labels = [None] * len(collision)
        for i in range(len(collision)):
            temp = np.array(verts[i])
            x = np.mean(temp[:,0])
            y = np.mean(temp[:,1])
            text_labels[i]= plt.text(x,y,str(i+num_circles),color = 'w')

        self.polygon_labels = text_labels


        plt.draw()
        plt.pause(0.1)

        #remove text labels
        #for i in range(len(collision)):
        #    text_labels[i].remove()


    #remove circular objects:
    def remove_circles(self):
        self.circles.remove()
        for label in self.circle_labels:
            label.remove()

    #remove polygon objects:
    def remove_polygons(self):
        self.polygons.remove()
        for label in self.polygon_labels:
            label.remove()

    #update circular objects
    def update_circular_objects(self,positions,collision):
        
        #set circle colors
        circ_colors = self.generate_color_array(collision)
        self.circles.set_facecolors(circ_colors)

        #set circle positions
        self.circles.set_offsets(positions)

        #remove labels
        for label in self.circle_labels:
            label.remove()

        #add labels
        text_labels = [None] * len(collision)
        for i in range(len(collision)):
            text_labels[i]= plt.text(positions[i,0],positions[i,1],str(i),color = 'w')
        self.circle_labels = text_labels


        plt.draw()
        plt.pause(0.1)


    #update polygon objects
    def update_polygon_objects(self,positions,collision):

        #set polygon colors
        poly_colors = self.generate_color_array(collision)
        self.polygons.set_facecolors(poly_colors)

        #set polygon positions
        #print 'new verts positions=' , positions
        self.polygons.set_verts(positions)

        #remove labels
        for label in self.polygon_labels:
            label.remove()

        #add new labels
        num_circles = self.circles.get_offsets().shape[1]
        #print self.polygons.get_offsets()

        #assert(0)
        text_labels = [None] * len(collision)
        for i in range(len(collision)):
            temp = np.array(positions[i])
            x = np.mean(temp[:,0])
            y = np.mean(temp[:,1])
            text_labels[i]= plt.text(x,y,str(i+num_circles),color = 'w')

        self.polygon_labels = text_labels

        plt.draw()
        plt.pause(0.1)
homey = np.hstack((X.ravel()[:,np.newaxis], Y.ravel()[:,np.newaxis]))

ww = X/10.0
ww[:] = 1.0
hh = Y/15.0
hh[:] = 0.333
aa = X*9
#aa[:] = -50.0

fig, ax = plt.subplots()

myalpha = ww
myalpha[:] = 0.5
ec = EllipseCollection(
                        ww,
                        hh,
                        aa,
                        units='x',
                        alpha = 0.1, 
                        offsets=homey,
                        transOffset=ax.transData)
simon = (X+Y).ravel()
ec.set_array(simon)
ax.add_collection(ec)
ax.autoscale_view()
ax.set_xlabel('X')
ax.set_ylabel('y')
cbar = plt.colorbar(ec)
cbar.set_label('X+Y')
plt.show()
Exemple #41
0
class HoughDemo(ImageProcessDemo):
    TITLE = u"Hough Demo"
    DEFAULT_IMAGE = "stuff.jpg"
    SETTINGS = ["th2", "show_canny", "rho", "theta", "hough_th",
                "minlen", "maxgap", "dp", "mindist", "param2",
                "min_radius", "max_radius", "blur_sigma",
                "linewidth", "alpha", "check_line", "check_circle"]

    check_line = Bool(True)
    check_circle = Bool(True)

    #Gaussian blur parameters
    blur_sigma = Range(0.1, 5.0, 2.0)
    show_blur = Bool(False)

    # Canny parameters
    th2 = Range(0.0, 255.0, 200.0)
    show_canny = Bool(False)

    # HoughLine parameters
    rho = Range(1.0, 10.0, 1.0)
    theta = Range(0.1, 5.0, 1.0)
    hough_th = Range(1, 100, 40)
    minlen = Range(0, 100, 10)
    maxgap = Range(0, 20, 10)

    # HoughtCircle parameters

    dp = Range(1.0, 5.0, 1.9)
    mindist = Range(1.0, 100.0, 50.0)
    param2 = Range(5, 100, 50)
    min_radius = Range(5, 100, 20)
    max_radius = Range(10, 100, 70)

    # draw parameters
    linewidth = Range(1.0, 3.0, 1.0)
    alpha = Range(0.0, 1.0, 0.6)

    def control_panel(self):
        return VGroup(
            Group(
                Item("blur_sigma", label=u"标准方差"),
                Item("show_blur", label=u"显示结果"),
                label=u"高斯模糊参数"
            ),
            Group(
                Item("th2", label=u"阈值2"),
                Item("show_canny", label=u"显示结果"),
                label=u"边缘检测参数"
            ),
            Group(
                Item("rho", label=u"偏移分辨率(像素)"),
                Item("theta", label=u"角度分辨率(角度)"),
                Item("hough_th", label=u"阈值"),
                Item("minlen", label=u"最小长度"),
                Item("maxgap", label=u"最大空隙"),
                label=u"直线检测"
            ),
            Group(
                Item("dp", label=u"分辨率(像素)"),
                Item("mindist", label=u"圆心最小距离(像素)"),
                Item("param2", label=u"圆心检查阈值"),
                Item("min_radius", label=u"最小半径"),
                Item("max_radius", label=u"最大半径"),
                label=u"圆检测"
            ),
            Group(
                Item("linewidth", label=u"线宽"),
                Item("alpha", label=u"alpha"),
                HGroup(
                    Item("check_line", label=u"直线"),
                    Item("check_circle", label=u"圆"),
                ),
                label=u"绘图参数"
            )
        )

    def __init__(self, **kwargs):
        super(HoughDemo, self).__init__(**kwargs)
        self.connect_dirty("th2, show_canny, show_blur, rho, theta, hough_th,"
                            "min_radius, max_radius, blur_sigma,"
                           "minlen, maxgap, dp, mindist, param2, "
                           "linewidth, alpha, check_line, check_circle")
        self.lines = LineCollection([], linewidths=2, alpha=0.6)
        self.axe.add_collection(self.lines)

        self.circles = EllipseCollection(
            [], [], [],
            units="xy",
            facecolors="none",
            edgecolors="red",
            linewidths=2,
            alpha=0.6,
            transOffset=self.axe.transData)

        self.axe.add_collection(self.circles)

    def _img_changed(self):
        self.img_gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)

    def draw(self):
        img_smooth = cv2.GaussianBlur(self.img_gray, (0, 0), self.blur_sigma, self.blur_sigma)
        img_edge = cv2.Canny(img_smooth, self.th2 * 0.5, self.th2)

        if self.show_blur and self.show_canny:
            show_img = cv2.cvtColor(np.maximum(img_smooth, img_edge), cv2.COLOR_BAYER_BG2BGR)
        elif self.show_blur:
            show_img = cv2.cvtColor(img_smooth, cv2.COLOR_BAYER_BG2BGR)
        elif self.show_canny:
            show_img = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2BGR)
        else:
            show_img = self.img

        if self.check_line:
            theta = self.theta / 180.0 * np.pi
            lines = cv2.HoughLinesP(img_edge,
                                    self.rho, theta, self.hough_th,
                                    minLineLength=self.minlen,
                                    maxLineGap=self.maxgap)

            if lines is not None:
                lines = lines[0]
                lines.shape = -1, 2, 2
                self.lines.set_segments(lines)
                self.lines.set_visible(True)
            else:
                self.lines.set_visible(False)
        else:
            self.lines.set_visible(False)

        if self.check_circle:
            circles = cv2.HoughCircles(img_smooth, 3,
                                       self.dp, self.mindist,
                                       param1=self.th2,
                                       param2=self.param2,
                                       minRadius=self.min_radius,
                                       maxRadius=self.max_radius)

            if circles is not None:
                circles = circles[0]
                self.circles._heights = self.circles._widths = circles[:, 2]
                self.circles.set_offsets(circles[:, :2])
                self.circles._angles = np.zeros(len(circles))
                self.circles._transOffset = self.axe.transData
                self.circles.set_visible(True)
            else:
                self.circles.set_visible(False)
        else:
            self.circles.set_visible(False)

        self.lines.set_linewidths(self.linewidth)
        self.circles.set_linewidths(self.linewidth)
        self.lines.set_alpha(self.alpha)
        self.circles.set_alpha(self.alpha)

        self.draw_image(show_img)
from matplotlib.collections import EllipseCollection

x = np.arange(10)
y = np.arange(15)
X, Y = np.meshgrid(x, y)

XY = np.column_stack((X.ravel(), Y.ravel()))

ww = X / 10.0
hh = Y / 15.0
aa = X * 9


fig, ax = plt.subplots()

ec = EllipseCollection(ww, hh, aa, units='x', offsets=XY,
                       transOffset=ax.transData)
ec.set_array((X + Y).ravel())
ax.add_collection(ec)
ax.autoscale_view()
ax.set_xlabel('X')
ax.set_ylabel('y')
cbar = plt.colorbar(ec)
cbar.set_label('X+Y')
plt.show()

#############################################################################
#
# ------------
#
# References
# """"""""""
Exemple #43
0
x = samples[:,1]
y = samples[:,2]


fig, ax = plt.subplots()
ax.set_xlim(-0.5 * 15, 0.5 * 15)
ax.set_ylim(-0.5 * 15, 0.5 * 15)
ax.set_aspect('equal')

plt.ylabel('position~$y$')
plt.xlabel('position~$x$')


radius = 1.0

ellipse_pos = EllipseCollection(widths=radius, heights=radius, angles=0, units='xy', facecolors='r', offsets=[],
								transOffset=ax.transData)
ellipse_neg = EllipseCollection(widths=radius, heights=radius, angles=0, units='xy', facecolors='b', offsets=[],
								transOffset=ax.transData)
ax.add_collection(ellipse_pos)
ax.add_collection(ellipse_neg)

idx_pos = q > 0.0
idx_neg = np.logical_not(idx_pos)

ellipse_pos.set_offsets(np.column_stack((x[idx_pos], y[idx_pos])))
ellipse_neg.set_offsets(np.column_stack((x[idx_neg], y[idx_neg])))

#plt.scatter(x, y, s = area, c = ["r","b"])
plt.savefig('../figures/Kristall.pdf', bbox_inches='tight')