Esempio n. 1
0
def test_polar_coord_annotations():
    # You can also use polar notation on a catesian axes.  Here the
    # native coordinate system ('data') is cartesian, so you need to
    # specify the xycoords and textcoords as 'polar' if you want to
    # use (theta, radius)
    from matplotlib.patches import Ellipse
    el = Ellipse((0,0), 10, 20, facecolor='r', alpha=0.5)

    fig = plt.figure()
    ax = fig.add_subplot( 111, aspect='equal' )

    ax.add_artist( el )
    el.set_clip_box( ax.bbox )

    ax.annotate('the top',
                xy=(np.pi/2., 10.),      # theta, radius
                xytext=(np.pi/3, 20.),   # theta, radius
                xycoords='polar',
                textcoords='polar',
                arrowprops=dict(facecolor='black', shrink=0.05),
                horizontalalignment='left',
                verticalalignment='baseline',
                clip_on=True, # clip to the axes bounding box
                )

    ax.set_xlim( -20, 20 )
    ax.set_ylim( -20, 20 )
def plot(data, mus=None, sigmas=None, colors='black', figname='fig.png'):
    # Create figure
    fig = plt.figure()

    # Plot data
    x = data[:, 0]
    y = data[:, 1]
    plt.scatter(x, y, 24, c=colors)

    # Plot cluster centers
    if mus is not None:
        x = [float(m[0]) for m in mus]
        y = [float(m[1]) for m in mus]
        plt.scatter(x, y, 99, c='red')

    # Plot ellipses for each cluster
    if sigmas is not None:
        for sig_ix in range(K):
            ax = fig.gca()
            cov = np.array(sigmas[sig_ix])
            lam, v = np.linalg.eig(cov)
            lam = np.sqrt(lam)
            ell = Ellipse(xy=(x[sig_ix], y[sig_ix]),
                          width=lam[0]*4, height=lam[1]*4,
                          angle=np.rad2deg(np.arccos(v[0, 0])),
                          color='blue')
            ell.set_facecolor('none')
            ax.add_artist(ell)

    # Save figure
    fig.savefig(figname)
Esempio n. 3
0
def graficaGrilla(dataGrilla,name,framesNumber,colour,xPixels,yPixels):	
	from matplotlib.patches import Ellipse
	from pylab import figure, show, savefig

	fig = figure()
	ax = fig.add_subplot(111, aspect='equal')
	# Each row of dataGrilla contains 
	# N == "framesNumbers" , signal
	# A radius of the RF ellipse
	# B radius of the RF ellipse
	# Angle of the RF ellipse
	# X coordinate of the RF ellipse
	# Y coordinate of the RF ellipse

	ax = fig.add_subplot(111, aspect='equal')
	for unit in range(dataGrilla.shape[0]):
		eWidth = dataGrilla[unit][framesNumber-1+1]
		eHeight = dataGrilla[unit][framesNumber-1+2]
		eAngle = dataGrilla[unit][framesNumber-1+3]
		eXY = [dataGrilla[unit][framesNumber-1+4],  dataGrilla[unit][framesNumber-1+5]]
		e = Ellipse(xy=eXY, width=eWidth, height=eHeight, angle=eAngle)
		ax.add_artist(e)
		e.set_alpha(0.2)
		e.set_facecolor(colour)
	
	ax.set_xlim(0, xPixels)
	ax.set_ylim(0, yPixels)
	savefig(name, dpi=None, bbox_inches='tight')
	return 0
Esempio n. 4
0
def motorplot_group_scatter(fig, ax, data, hz, title, markersz = 2, ellipseht=0.2, ylim=[]):
  for d in data:
    x = d.get('i')
    y = d.get('hz')
    label = d.get('label')
    ax.scatter(x, y, marker='o', s=markersz, label=label)

  xi = ax.get_xlim()[0]
  xf = ax.get_xlim()[1]
  e = Ellipse(((xi + xf)/2,hz),xf-xi, ellipseht)
  e.set_alpha(0.2)
  ax.add_artist(e)
  ax.set_title(title)
  ax.set_xlabel('Sample')
  ax.set_ylabel('Frequency (Hz)')

  box = ax.get_position()
  ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
  plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize='large', markerscale=2)

  ax.title.set_fontsize(16)
  ax.xaxis.label.set_fontsize(16)
  for item in ax.get_xticklabels():
    item.set_fontsize(12)
  ax.yaxis.label.set_fontsize(16)
  for item in ax.get_yticklabels():
    item.set_fontsize(12)
  #ax.yaxis.get_major_formatter().set_powerlimits((0, 1))
  if ylim:
    ax.set_ylim(ylim)
Esempio n. 5
0
    def error_ellipse(self, i, j, nstd=1, space_factor=5.0, clr="b", alpha=0.5, lw=1.5):
        """
        return the plot of the error ellipse from the covariance matrix
        use ideas from error_ellipse.m from
        http://www.mathworks.com/matlabcentral/fileexchange/4705-error-ellipse
        ( the version used here was taken from an earlier version, it looks to have been updated there to a new version.)

        * (i,j) specify the ith and jth parameters to be used and
        * nstd specifies the number of standard deviations to plot, the default is 1 sigma.
        * space_factor specifies the number that divides the width/height, the result of which is then added as extra space to the figure
        """

        def eigsorted(cov):
            vals, vecs = np.linalg.eigh(cov)
            order = vals.argsort()[::1]
            return vals[order], vecs[:, order]

        self.marginalize(param_list=[i, j])
        vals, vecs = eigsorted(self.marginal_covariance_matrix)
        theta = np.degrees(np.arctan2(*vecs[:, 0][::-1]))
        # print theta
        width, height = 2 * nstd * np.sqrt(vals)
        xypos = [self.parameter_values[i], self.parameter_values[j]]
        ellip = Ellipse(xy=xypos, width=width, height=height, angle=theta, color=clr, alpha=alpha)
        # ellip.set_facecolor("white")
        ellip.set_linewidth(lw)
        ellip_vertices = ellip.get_verts()
        xl = [ellip_vertices[k][0] for k in range(len(ellip_vertices))]
        yl = [ellip_vertices[k][1] for k in range(len(ellip_vertices))]
        dx = (max(xl) - min(xl)) / space_factor
        dy = (max(yl) - min(yl)) / space_factor
        xyaxes = [min(xl) - dx, max(xl) + dx, min(yl) - dy, max(yl) + dy]
        return ellip, xyaxes
Esempio n. 6
0
def show_minimum_bounding_ellipsoids(Xr, with_sampled = False):
    clustellip = Clustered_Sampler(active_samples = Xr,likelihood_constraint=0.0, enlargement= 1.0,no=1)
    ellipsoids = clustellip.ellipsoid_set
    X0 = [i[0] for i in Xr]
    Y0 = [i[1] for i in Xr] 
    plt.figure()
    ax = plt.gca()
    points = []
    #print len(ellipsoids)
    for i in range(len(ellipsoids)):
        if ellipsoids[i]!=None:
            a, b = np.linalg.eig(ellipsoids[i].covariance_matrix)
            c = np.dot(b, np.diag(np.sqrt(a)))
            width = np.sqrt(np.sum(c[:,1]**2)) * 2.
            height = np.sqrt(np.sum(c[:,0]**2)) * 2.
            angle = math.atan(c[1,1] / c[0,1]) * 180./math.pi
            points = ellipsoids[i].sample(n_points = 50)
            ellipse = Ellipse(ellipsoids[i].centroid, width, height, angle)
            ellipse.set_facecolor('None')
            ax.add_patch(ellipse)
    X = [i[0] for i in points]
    Y = [i[1] for i in points]
    if with_sampled == True:
        plt.plot(X, Y, 'bo')
    plt.plot(X0, Y0, 'ro')
    plt.show()
def plot_data(data0, label0, title, subtitle, *args):
    
    colors = iter(cm.rainbow(np.linspace(0,1,5)))
    plt.clf()
    fig = plt.figure()
    ax = plt.gca()
    if (len(args) == 2):
        means, covmats = args
    elif (len(args) == 4):
        means, covmats, traindata, trainlabel = args
        trainlabel = trainlabel.reshape(trainlabel.size)
    for i in range(1,6):
        cl = next(colors)
        plt.scatter(data0[(label0==i).reshape((label0==i).size),0],
        data0[(label0==i).reshape((label0==i).size),1],color=cl)
        # Draw ellipse with 1 standard deviation
        if (len(args) >= 2):
            # Compute eigen vectors and value for covmat to plot an ellipse
            lambda_, v = np.linalg.eig(covmats[i-1])
            lambda_ = np.sqrt(lambda_)
            ell = Ellipse(xy=(means[0,i-1], means[1,i-1]),
                        width=lambda_[0]*2, height=lambda_[1]*2,
                        angle=np.rad2deg(np.arccos(v[0, 0])))
            ell.set_facecolor('none')
            ax.add_artist(ell)
            #Add mean points
            plt.scatter(means[0,i-1], means[1,i-1],c='black',s=30);
            if (len(args) == 4):
                plt.scatter(traindata[trainlabel==i,0],
                traindata[trainlabel==i,1],color=cl,
                edgecolor='black')
    fig.suptitle(title)
    ax.set_title(subtitle,fontsize='10')
    fig.show()
    return
Esempio n. 8
0
File: odak.py Progetto: kunguz/odak
 def PlotLens(self,CenterXY, thickness, LensHeight, rotation, alpha=0.5):
     # Definition to plot a lens.
     lens = Ellipse(xy=CenterXY, width=thickness, height=LensHeight, angle=-rotation)
     self.ax.add_artist(lens)
     lens.set_clip_box(self.ax.bbox)
     lens.set_alpha(alpha)
     return True
def visualizer(data, x, y, lengths):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    fig.suptitle("Clustered Results")
    colors = plt.get_cmap("gist_rainbow")
    norm = col.Normalize(vmin = 0, vmax = len(lengths))
    color_map = cm.ScalarMappable(cmap = colors, norm = norm)
    index = 0
    for i in range(len(lengths)):
        plt.scatter(data[index:index + lengths[i], x], data[index:index + lengths[i], y], c = color_map.to_rgba(i))
        if lengths[i] != 1:
            cov = numpy.cov(data[index:index + lengths[i], x], data[index:index + lengths[i], y], ddof = 0)
        else:
            cov = numpy.asarray([[0, 0], [0,0]])
        values, vectors = numpy.linalg.eig(cov)
        angle = numpy.arctan((vectors[0,1] - vectors[1,1])/(vectors[0,0] - vectors[1,0]))
        ellipse = Ellipse(xy = (numpy.mean(data[index:index + lengths[i], x]), numpy.mean(data[index:index + lengths[i], y])), width = 2 * 2 * numpy.sqrt(values[0]),
                          height = 2 * 2 * numpy.sqrt(values[1]), angle = numpy.rad2deg(angle))
        ellipse.set_edgecolor(color_map.to_rgba(i))
        ellipse.set_facecolor("none")
        ax.add_artist(ellipse)
        plt.scatter(numpy.mean(data[index:index + lengths[i], x]), numpy.mean(data[index:index + lengths[i], y]), c = color_map.to_rgba(i), marker = 'x')
        index += lengths[i]
    plt.show()
    plt.close()
Esempio n. 10
0
    def plot_error_ellipse_xy(cls, figure, x, y, abom, style): 
        """
        plots standard error ellipse
        x, y : position of center of ellipse
        abom : a, b, om parameters of ellipse

        method do not handle axes orientation (self.figure.axesXY)
        """

        from matplotlib.patches import Ellipse
        from math import pi

        a, b, om = abom

        #print "swapXY:", figure.is_swap_xy()
        if figure.is_swap_xy():
            y, x = x, y
            om = pi/2 - om
            #om = om - pi/2

        ell = Ellipse((x, y), 2*a, 2*b, om*180.0/pi) #?
                      #transform=self.axes.transData + self.ellTrans)

        figure.set_style(style, ell)
        
        ell.set_clip_box(figure.gca().bbox) # cut edges outside axes box?
        figure.gca().add_artist(ell)
Esempio n. 11
0
class ErrEllipse(object):
    """
    A class for creating and drawing an ellipse in matplotlib.
    """
    def __init__(self, x_cen, y_cen, a, b, pa, color='b'):
        """
        :param x_cen: x coordinate at center of the ellipse
        :param y_cen: y coordinate at center of the ellipse
        :param a: size of semi-major axes of the ellipse
        :param b: size of semi-minor axes of the ellipse
        :param pa: position angle of a to x  (90 ==> a is same orientation as x)
        """

        self.center = (x_cen, y_cen)
        self.a = max(a, 10)
        self.b = max(b, 10)
        self.pa = pa

        angle = self.pa - 90

        self.artist = Ellipse(self.center, self.a, self.b, angle=angle,
                              linewidth=3, edgecolor=color, facecolor='#E47833',
                              alpha=0.1)

    def add_to_axes(self, axes):
        self.artist.set_clip_box(axes.bbox)
        axes.add_patch(self.artist)
Esempio n. 12
0
def motorplot_scatter(fig, ax, session, hz, title, markersz = 2, ylim=[], color='r'):
  x = session.get('i')
  y = session.get('hz')
  label = session.get('label')
  #title = 'Actuator Frequency - ' + label 
  ax.scatter(x, y, marker='o', s=markersz, label=label, color=color)
  xi = ax.get_xlim()[0]
  xf = ax.get_xlim()[1]
  e = Ellipse(((xi + xf)/2,hz),xf-xi, 0.1)
  e.set_alpha(0.2)
  ax.add_artist(e)
  ax.set_title(title)
  ax.set_xlabel('Sample')
  ax.set_ylabel('Frequency (Hz)')

  ax.title.set_fontsize(16)
  ax.xaxis.label.set_fontsize(16)
  for item in ax.get_xticklabels():
    item.set_fontsize(12)
  ax.yaxis.label.set_fontsize(16)
  for item in ax.get_yticklabels():
    item.set_fontsize(12)
  #ax.yaxis.get_major_formatter().set_powerlimits((0, 1))
  if ylim:
    ax.set_ylim(ylim)
Esempio n. 13
0
def photogeneration(loc):
    arl = 0.10
    sep = 0.05
    arprop = dict(mutation_scale=10,
                  lw=1, arrowstyle="-|>", 
                  zorder=20)
    x, y, z = loc
    
    #electron
    electron, = ax.plot3D([x-sep/2], [y], [z],
                          c='c', marker='$-$', markersize=7, ls='none')
    v = ((x-sep/2,x-sep/2), (y,y), (z+0.02, z+arl))
    ar = Arrow3D(*v, color='c', **arprop)
    ax.add_artist(ar)
    
    #hole
    hole, = ax.plot3D([x+sep/2], [y], [z],
              c='r', marker='$+$', markersize=7, ls='none')
    v = ((x+sep/2,x+sep/2), (y,y), (z-0.02, z-arl))
    ar = Arrow3D(*v, color='r', **arprop)
    ax.add_artist(ar)
    
    #photon
    draw_photon(ax, (0,0,1), location=(x,y,z-0.35), length=0.3, amplitude=0.02)
    
    #encircle
    ell = Ellipse((x,y), 2.5*sep, 2.5*sep, ls=':', ec='y', fc='none', lw=1)
    art3d.pathpatch_2d_to_3d(ell, z, 'z')
    ell._path2d = ell._path
    ax.add_patch(ell)
    
    return electron, hole
Esempio n. 14
0
 def plot_galaxies(self, ax, gals=None):
     if gals == None:
         gals = self.galaxies
     for gal in gals:
         e = Ellipse((gal.x, gal.y), gal.a(), gal.b(), angle=gal.theta, linewidth=2, fill=True)
         ax.add_artist(e)
         e.set_clip_box(ax.bbox)
Esempio n. 15
0
def plotCovariance(center, matrix, color):
    eigvalue, eigvector = lng.eig(matrix)
    theta = atan2(eigvector[0][1], eigvector[0][0])
    ellipse = Ellipse([center[0], center[1]], 2*pow(eigvalue[0], 0.5), 2*pow(eigvalue[1], 0.5), center[2])
    ellipse.set_facecolor(color)
    fig = plt.gcf()
    fig.gca().add_artist(ellipse)
Esempio n. 16
0
   def testPolarCoordAnnotations( self ):
      """Polar Coordinate Annotations"""

      # You can also use polar notation on a catesian axes.  Here the
      # native coordinate system ('data') is cartesian, so you need to
      # specify the xycoords and textcoords as 'polar' if you want to
      # use (theta, radius)

      el = Ellipse((0,0), 10, 20, facecolor='r', alpha=0.5)

      fname = self.outFile( "polar_coords.png" )

      fig = figure()
      ax = fig.add_subplot( 111, aspect='equal' )

      ax.add_artist( el )
      el.set_clip_box( ax.bbox )

      ax.annotate('the top',
                   xy=(npy.pi/2., 10.),      # theta, radius
                   xytext=(npy.pi/3, 20.),   # theta, radius
                   xycoords='polar',
                   textcoords='polar',
                   arrowprops=dict(facecolor='black', shrink=0.05),
                   horizontalalignment='left',
                   verticalalignment='bottom',
                   clip_on=True, # clip to the axes bounding box
      )

      ax.set_xlim( -20, 20 )
      ax.set_ylim( -20, 20 )
      fig.savefig( fname )
      self.checkImage( fname )
Esempio n. 17
0
    def calculate_ellipse(center_x, center_y, covariance_matrix, n_std_dev=3):
        values, vectors = np.linalg.eigh(covariance_matrix)
        order = values.argsort()[::-1]
        values = values[order]
        vectors = vectors[:, order]

        theta = np.degrees(np.arctan2(*vectors[:, 0][::-1]))

        # make all angles positive
        if theta < 0:
            theta += 360

        # Width and height are "full" widths, not radius
        width, height = 2 * n_std_dev * np.sqrt(values)

        ellipse = Ellipse(
            xy=[center_x, center_y],
            width=width,
            height=height,
            angle=theta
        )

        ellipse.set_alpha(0.3)
        ellipse.set_facecolor((1, 0, 0))

        return ellipse
Esempio n. 18
0
def plot_ellipse(x, y, ax, color):
	(xy, width, height, angle) = get_ellipse(x, y)
	e = Ellipse(xy, width, height, angle)
	ax.add_artist(e)
	#e.set_clip_box(ax.bbox)
	e.set_alpha(0.2)
	e.set_facecolor(color)
Esempio n. 19
0
def drawDef(dfeat,dy,dx,mindef=0.001,distr="father"):
    """
        auxiliary funtion to draw recursive levels of deformation
    """
    from matplotlib.patches import Ellipse
    pylab.ioff()
    if distr=="father":
        py=[0,0,2,2];px=[0,2,0,2]
    if distr=="child":
        py=[0,1,1,2];px=[1,2,0,1]
    ordy=[0,0,1,1];ordx=[0,1,0,1]
    x1=-0.5+dx;x2=2.5+dx
    y1=-0.5+dy;y2=2.5+dy
    if distr=="father":       
        pylab.fill([x1,x1,x2,x2,x1],[y1,y2,y2,y1,y1],"r", alpha=0.15, edgecolor="b",lw=1)    
    for l in range(len(py)):
        aux=dfeat[ordy[l],ordx[l],:].clip(-1,-mindef)
        wh=numpy.exp(-mindef/aux[0])/numpy.exp(1);hh=numpy.exp(-mindef/aux[1])/numpy.exp(1)
        e=Ellipse(xy=[(px[l]+dx),(py[l]+dy)], width=wh, height=hh, alpha=0.35)
        x1=-0.75+dx+px[l];x2=0.75+dx+px[l]
        y1=-0.76+dy+py[l];y2=0.75+dy+py[l]
        col=numpy.array([wh*hh]*3).clip(0,1)
        if distr=="father":
            col[0]=0       
        e.set_facecolor(col)
        pylab.gca().add_artist(e)
        if distr=="father":       
            pylab.fill([x1,x1,x2,x2,x1],[y1,y2,y2,y1,y1],"b", alpha=0.15, edgecolor="b",lw=1)            
Esempio n. 20
0
def plotCovEllipse(cov, pos, nstd=2, ax=None, with_line=False, **kwargs):
    """
    Plots an `nstd` sigma error ellipse based on the specified covariance
    matrix (`cov`). Additional keyword arguments are passed on to the
    ellipse patch artist.
    Parameters
    ----------
        cov : The 2x2 covariance matrix to base the ellipse on
        pos : The location of the center of the ellipse. Expects a 2-element
            sequence of [x0, y0].
        nstd : The radius of the ellipse in numbers of standard deviations.
            Defaults to 2 standard deviations.
        ax : The axis that the ellipse will be plotted on. Defaults to the
            current axis.
        Additional keyword arguments are pass on to the ellipse patch.
    Returns
    -------
        A matplotlib ellipse artist
    """

    def eigsorted(cov):
        vals, vecs = np.linalg.eigh(cov)
        order = vals.argsort()[::-1]
        return vals[order], vecs[:, order]

    if ax is None:
        ax = plt.gca()

    # largest eigenvalue is first
    vals, vecs = eigsorted(cov)
    theta = np.degrees(np.arctan2(*vecs[:, 0][::-1]))

    # Width and height are "full" widths, not radius
    width, height = 2 * nstd * np.sqrt(vals)
    ellip = Ellipse(xy=pos, width=width, height=height, angle=theta, **kwargs)

    if 'alpha' not in kwargs.keys():
        ellip.set_alpha(0.3)
    if 'color' not in kwargs.keys():# and 'c' not in kwargs.keys():
        ellip.set_facecolor('red')

    ax.add_patch(ellip)

    # THEN just f***ing plot an invisible line across the ellipse.
    if with_line:
        # brute forcing axes limits so they contain ellipse patch
        # maybe a cleaner way of doing this, but I couldn't work it out
        x_extent = 0.5*(abs(width*np.cos(np.radians(theta))) +
                        abs(height*np.sin(np.radians(theta))))
        y_extent = 0.5*(abs(width*np.sin(np.radians(theta))) +
                        abs(height*np.cos(np.radians(theta))))

        lx = pos[0] - x_extent
        ux = pos[0] + x_extent
        ly = pos[1] - y_extent
        uy = pos[1] + y_extent
        ax.plot((lx, ux), (ly, uy), alpha=0.)

    return ellip
Esempio n. 21
0
def grad(im,Ix,Iy,prozor=5):

    #koordinate oko kojih ce se gledati gradijent
    imshow(im)
    koord = ginput(1)
    x = round(koord[0][0])
    y = round(koord[0][1])
    
    #uzmi gradijente Ix i Iy unutar tog prozora
    IxF = (Ix[x-prozor:x+prozor+1,y-prozor:y+prozor+1]).flatten()
    IyF = (Iy[x-prozor:x+prozor+1,y-prozor:y+prozor+1]).flatten()

    #neka kvazi matematika...
    width = abs(max(IxF)) + abs(min(IxF))
    height = abs(max(IyF)) + abs(min(IyF))
    xS = (max(IxF) + min(IxF))/2
    yS = (max(IyF) + min(IyF))/2

    """x_segment = width/15.0
    y_segment = width/15.0
    broj_pojava = zeros((15,15),dtype='int')

    #procjeni gdje je najgusce
    for i in range(15):
        for j in range(15):
            for k in IxF:
                for m in IyF:
                    if IxF[k] >= i*x_segment and IxF[k] <= (i+1)*x_segment:
                        if IyF[m] >= j*y_segment and IyF[m] <= (j+1)*y_segment:
                            broj_pojava[i][j] += 1

    x_pom,y_pom = unravel_index(broj_pojava.argmax(), broj_pojava.shape)

    x = (x_pom*x_segment + (x_pom+1)*x_segment)/2
    y = (y_pom*y_segment + (y_pom+1)*y_segment)/2

    angle = arctan(y*1.0/x*1.0)*180/pi"""
            
    
    
    mod = sqrt(IxF**2 + IyF**2)
    pom = argmax(mod)
    angle = arctan(IyF[pom]*1.0/IxF[pom]*1.0)*180/pi
    if width < max(mod):
        width = max(mod)
    
    ells = Ellipse((xS,yS),width,height,angle)
    ells.set_alpha(0.3)


    
    fig = figure()
    ax = fig.add_subplot(111,aspect='equal')
    ax.add_artist(ells)
    ax.plot(IxF,IyF,'mo') #crtaj histogram
    gray()
    grid('on')
    show()
    return 
Esempio n. 22
0
 def create_artists(self, legend, orig_handle,
                    xdescent, ydescent, width, height, fontsize, trans):
     center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
     p = Ellipse(xy=center, width=height + xdescent,
                 height=height + ydescent, fill=False)
     self.update_prop(p, orig_handle, legend)
     p.set_transform(trans)
     return [p]
def draw_ellipse(a, m, S):
    v, w = np.linalg.eigh(S)
    u = w[0] / np.linalg.norm(w[0])
    angle = (180.0 / np.pi) * np.arctan(u[1] / u[0])
    e = Ellipse(m, 2.0 * np.sqrt(v[0]), 2.0 * np.sqrt(v[1]),
                180.0 + angle, color = 'k')
    a.add_artist(e)
    e.set_clip_box(ax.bbox)
    e.set_alpha(0.5)
Esempio n. 24
0
def plot_ellipse(w,h,b):
    fig = plt.figure(0)
    fig.clf()
    ax = fig.add_subplot(111, aspect='equal')
    e = Ellipse((0.,0.),w,h)
    e.set_facecolor((0.,0.,b))
    ax.add_artist(e)
    ax.set_xlim(-1., 1.)
    ax.set_ylim(-1., 1.)
Esempio n. 25
0
 def plot(self, ax, color):
     """
     Return an ellipse object for plotting, add to ax, with color
     """
     e = Ellipse(xy = array([self.pos.x, self.pos.y]), width = self.width, height = self.length, angle = self.lengthAngle/pi*180)
     ax.add_artist(e)
     e.set_clip_box(ax.bbox)
     e.set_facecolor(color)
     return e
Esempio n. 26
0
def plot_ellipse(pos, angle, w1, w2, edge_color, face_color='w',
                 alpha=1.):
    orient = math.degrees(angle)
    e = Ellipse(xy=pos, width=w1, height=w2, angle=orient,
                facecolor=face_color, edgecolor=edge_color)
    e.set_alpha(alpha)
    ax = pp.gca()
    ax.add_patch(e)
    return e
Esempio n. 27
0
 def __init__(self, x, y, dx, dy, border_tol=0.2, resize=True, plotview=None, **opts):
     shape = Ellipse((float(x),float(y)), dx, dy, **opts)
     if 'linewidth' not in opts:
         shape.set_linewidth(1.0)
     if 'facecolor' not in opts:
         shape.set_facecolor('r')
     super(NXellipse, self).__init__(shape, border_tol, resize, plotview)
     self.shape.set_label('Ellipse')
     self.ellipse = self.shape
Esempio n. 28
0
def ellipse(xy=None, x=None, y=None, **kwargs):
	if xy is None:
		if x is None or y is None:
			raise 'ellipse: need x and y'
		xy = array([x,y])
	c = Ellipse(xy=xy, **kwargs)
	a=gca()
	c.set_clip_box(a.bbox)
	a.add_artist(c)
	return c
Esempio n. 29
0
def confidence_ellipse(x, y, ax, n_std=3.0, facecolor='none', **kwargs):
    """
    Create a plot of the covariance confidence ellipse of `x` and `y`

    Parameters
    ----------
    x, y : array_like, shape (n, )
        Input data.

    ax : matplotlib.axes.Axes
        The axes object to draw the ellipse into.

    n_std : float
        The number of standard deviations to determine the ellipse's radiuses.

    Returns
    -------
    matplotlib.patches.Ellipse

    Other parameters
    ----------------
    kwargs : `~matplotlib.patches.Patch` properties
    """
    if x.size != y.size:
        raise ValueError("x and y must be the same size")

    cov = np.cov(x, y)
    pearson = cov[0, 1]/np.sqrt(cov[0, 0] * cov[1, 1])
    # Using a special case to obtain the eigenvalues of this
    # two-dimensionl dataset.
    ell_radius_x = np.sqrt(1 + pearson)
    ell_radius_y = np.sqrt(1 - pearson)
    ellipse = Ellipse((0, 0),
        width=ell_radius_x * 2,
        height=ell_radius_y * 2,
        facecolor=facecolor,
        **kwargs)

    # Calculating the stdandard deviation of x from
    # the squareroot of the variance and multiplying
    # with the given number of standard deviations.
    scale_x = np.sqrt(cov[0, 0]) * n_std
    mean_x = np.mean(x)

    # calculating the stdandard deviation of y ...
    scale_y = np.sqrt(cov[1, 1]) * n_std
    mean_y = np.mean(y)

    transf = transforms.Affine2D() \
        .rotate_deg(45) \
        .scale(scale_x, scale_y) \
        .translate(mean_x, mean_y)

    ellipse.set_transform(transf + ax.transData)
    return ax.add_patch(ellipse)
Esempio n. 30
0
def pathplot_startpoint(fig, ax, x, dims=(0,1), sgns=(1,1), fill='r', edge='k'):
  x = subsample_endpts(x)
  d = 0.084       # wb diameter
  r = d/2.0       # wb radius
  alpha = 0.25
  lw = 4
  e = Ellipse((sgns[0]*x[0,dims[0]], sgns[1]*x[0,dims[1]]),d, d, color=fill, zorder=100)
  e.set_alpha(alpha)
  ax.add_artist(e)
  c = Circle((sgns[0]*x[0,dims[0]], sgns[1]*x[0,dims[1]]),r, ec=edge, fc='none', lw = lw, zorder=100)
  ax.add_artist(c)
Esempio n. 31
0
Draw many ellipses. Here individual ellipses are drawn. Compare this
to the :doc:`Ellipse collection example
</gallery/shapes_and_collections/ellipse_collection>`.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse

# Fixing random state for reproducibility
np.random.seed(19680801)

NUM = 250

ells = [
    Ellipse(xy=np.random.rand(2) * 10,
            width=np.random.rand(),
            height=np.random.rand(),
            angle=np.random.rand() * 360) for i in range(NUM)
]

fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
for e in ells:
    ax.add_artist(e)
    e.set_clip_box(ax.bbox)
    e.set_alpha(np.random.rand())
    e.set_facecolor(np.random.rand(3))

ax.set_xlim(0, 10)
ax.set_ylim(0, 10)

plt.show()
Esempio n. 32
0
def plotPhotometry(imgsources,
                   refsources,
                   matches,
                   prefix,
                   band=None,
                   zp=None,
                   delta=False,
                   referrs=None,
                   refstargal=None,
                   title=None,
                   saveplot=True,
                   format='png'):
    print('%i ref sources' % len(refsources))
    print('%i image sources' % len(imgsources))
    print('%i matches' % len(matches))

    # In the "matches" list:
    #    m.first  is catalog
    #    m.second is image

    # In this function, the "m" prefix stands for "matched",
    # "u" stands for "unmatched".

    # *sigh*, turn these into Python lists, so we have the "index" function.
    refsources = [s for s in refsources]
    imgsources = [s for s in imgsources]

    # Now we build numpy int arrays for indexing into the "refsources" and
    # "imgsources" arrays.
    MR = []
    MI = []
    for m in matches:
        try:
            i = refsources.index(m.first)
        except ValueError:
            print('Match list reference source ID', m.first.getSourceId(),
                  'was not in the list of reference stars')
            continue
        try:
            j = imgsources.index(m.second)
        except ValueError:
            print('Match list source ID', m.second.getSourceId(),
                  'was not in the list of image sources')
            continue
        MR.append(i)
        MI.append(j)
    MR = np.array(MR)
    MI = np.array(MI)

    # Build numpy boolean arrays for indexing the unmatched stars.
    UR = np.ones(len(refsources), bool)
    UR[MR] = False
    UI = np.ones(len(imgsources), bool)
    UI[MI] = False

    def flux2mag(f):
        return -2.5 * np.log10(f)

    refmag = np.array([flux2mag(s.getPsfFlux()) for s in refsources])
    imgflux = np.array([s.getPsfFlux() for s in imgsources])
    imgfluxerr = np.array([s.getPsfFluxErr() for s in imgsources])

    # Cut to fluxes that aren't silly and get mags of matched sources.
    okflux = (imgflux[MI] > 1)
    MI = MI[okflux]
    MR = MR[okflux]

    mimgflux = imgflux[MI]
    mimgmag = flux2mag(mimgflux)
    mimgmagerr = abs(2.5 / np.log(10.) * imgfluxerr[MI] / mimgflux)
    mrefmag = refmag[MR]

    # Get mags of unmatched sources.
    uimgflux = imgflux[UI]
    okflux = (uimgflux > 1)
    uimgmag = flux2mag(uimgflux[okflux])
    urefmag = refmag[UR]

    if False:
        unmatched = [imgsources[i] for i in np.flatnonzero(uimg)]
        uflux = np.array([s.getPsfFlux() for s in unmatched])
        I = np.argsort(-uflux)
        print('Unmatched image sources, by psf flux:')
        print('# FLUX, X, Y, RA, DEC')
        for i in I:
            u = unmatched[i]
            print(u.getPsfFlux(), u.getXAstrom(), u.getYAstrom(), u.getRa(),
                  u.getDec())

        print('Matched image sources, by psf flux:')
        print('# FLUX, X, Y, RA, DEC')
        for i in mimgi:
            m = imgsources[i]
            print(m.getPsfFlux(), m.getXAstrom(), m.getYAstrom(), m.getRa(),
                  m.getDec())

    # Legend entries:
    pp = []
    pl = []

    plt.clf()
    imag = np.append(mimgmag, uimgmag)

    mrefmagerr = None
    if referrs is not None:
        referrs = np.array(referrs)
        mrefmagerr = referrs[MR]

    if refstargal:
        assert (len(refstargal) == len(refsources))
        refstargal = np.array(refstargal).astype(bool)
        ptsets = [(np.logical_not(refstargal[MR]), 'g', 'Matched galaxies',
                   10), (refstargal[MR], 'b', 'Matched stars', 12)]

    else:
        ptsets = [(np.ones_like(mrefmag).astype(bool), 'b', 'Matched sources',
                   10)]

    for I, c, leg, zo in ptsets:
        if delta:
            dm = mimgmag[I] - mrefmag[I] + zp
            xi = mrefmag[I]
            yi = dm
            dx = mrefmagerr
            dy = mimgmagerr
        else:
            xi = mimgmag[I]
            yi = mrefmag[I]
            dx = mimgmagerr
            dy = mrefmagerr

        p1 = plt.plot(xi, yi, '.', color=c, mfc=c, mec=c, alpha=0.5, zorder=zo)
        if dx is None or dy is None:
            # errorbars
            xerr, yerr = None, None
            if dx is not None:
                xerr = dx[I]
            if dy is not None:
                yerr = dy[I]
            plt.errorbar(xi,
                         yi,
                         xerr=xerr,
                         yerr=yerr,
                         ecolor=c,
                         fmt=None,
                         zorder=zo)
        else:
            # get the current axis
            ca = plt.gca()
            # add error ellipses
            for j, i in enumerate(np.flatnonzero(I)):
                a = Ellipse(xy=np.array([xi[j], yi[j]]),
                            width=dx[i] / 2.,
                            height=dy[i] / 2.,
                            alpha=0.5,
                            fill=True,
                            ec=c,
                            fc=c,
                            zorder=zo)
                ca.add_artist(a)
        pp.append(p1)
        pl.append(leg)

    if delta:
        m = max(abs(dm))
        plt.axis([np.floor(min(refmag)) - 0.5, np.ceil(max(refmag)), -m, m])
    else:
        plt.axis([
            np.floor(min(imag)) - 0.5,
            np.ceil(max(imag)),
            np.floor(min(refmag)) - 0.5,
            np.ceil(max(refmag))
        ])
    ax = plt.axis()

    if not delta:
        # Red tick marks show unmatched img sources
        dy = (ax[3] - ax[2]) * 0.05
        y1 = np.ones_like(uimgmag) * ax[3]
        p2 = plt.plot(np.vstack((uimgmag, uimgmag)),
                      np.vstack((y1, y1 - dy)),
                      'r-',
                      alpha=0.5)
        p2 = p2[0]
        # Blue tick marks show matched img sources
        y1 = np.ones_like(mimgmag) * ax[3]
        p3 = plt.plot(np.vstack((mimgmag, mimgmag)),
                      np.vstack((y1 - (0.25 * dy), y1 - (1.25 * dy))),
                      'b-',
                      alpha=0.5)
        p3 = p3[0]
        # Red ticks for unmatched ref sources
        dx = (ax[1] - ax[0]) * 0.05
        x1 = np.ones_like(urefmag) * ax[1]
        p4 = plt.plot(np.vstack((x1, x1 - dx)),
                      np.vstack((urefmag, urefmag)),
                      'r-',
                      alpha=0.5)
        p4 = p4[0]
        # Blue ticks for matched ref sources
        x1 = np.ones_like(mrefmag) * ax[1]
        p5 = plt.plot(np.vstack((x1 - (0.25 * dx), x1 - (1.25 * dx))),
                      np.vstack((mrefmag, mrefmag)),
                      'b-',
                      alpha=0.5)
        p5 = p5[0]

    if zp is not None:
        if delta:
            pzp = plt.axhline(0, linestyle='--', color='b')
        else:
            X = np.array([ax[0], ax[1]])
            pzp = plt.plot(X, X + zp, 'b--')
        pp.append(pzp)
        pl.append('Zeropoint')

    # reverse axis directions.
    if delta:
        plt.axis([ax[1], ax[0], ax[2], ax[3]])
    else:
        plt.axis([ax[1], ax[0], ax[3], ax[2]])

    if band is not None:
        reflabel = 'Reference catalog: %s band (mag)' % band
    else:
        reflabel = 'Reference catalog mag'

    if delta:
        plt.xlabel(reflabel)
        plt.ylabel('Instrumental - Reference (mag)')
        fn = prefix + '-dphotom.' + format

        if zp is not None:
            # Make the plot area smaller to fit the twin axis
            pos = plt.gca().get_position()
            ll = pos.min
            sz = pos.size
            plt.gca().set_position(pos=[ll[0], ll[1], sz[0], sz[1] - 0.05])
            # Put the title up top (otherwise it follows the axis)
            if title is not None:
                plt.figtext(0.5,
                            0.96,
                            title,
                            ha='center',
                            va='top',
                            fontsize='large')
                title = None

            ax2 = plt.twiny()

            # Red tick marks show unmatched img sources
            if zp is not None:
                dy = (ax[3] - ax[2]) * 0.05
                y1 = np.ones_like(uimgmag) * ax[3]
                p2 = plt.plot(np.vstack((uimgmag, uimgmag)) + zp,
                              np.vstack((y1, y1 - dy)),
                              'r-',
                              alpha=0.5)
                p2 = p2[0]
                # Blue tick marks show matched img sources
                y1 = np.ones_like(mimgmag) * ax[3]
                p3 = plt.plot(np.vstack((mimgmag, mimgmag)) + zp,
                              np.vstack((y1 - (0.25 * dy), y1 - (1.25 * dy))),
                              'b-',
                              alpha=0.5)
                p3 = p3[0]
            # Red ticks for unmatched ref sources
            y1 = np.ones_like(urefmag) * ax[2]
            p4 = plt.plot(np.vstack((urefmag, urefmag)),
                          np.vstack((y1, y1 + dy)),
                          'r-',
                          alpha=0.5)
            p4 = p4[0]
            # Blue ticks for matched ref sources
            y1 = np.ones_like(mrefmag) * ax[2]
            p5 = plt.plot(np.vstack((mrefmag, mrefmag)),
                          np.vstack((y1 + (0.25 * dy), y1 + (1.25 * dy))),
                          'b-',
                          alpha=0.5)
            p5 = p5[0]

            plt.xlim(ax[1] - zp, ax[0] - zp)
            plt.xlabel('Instrumental mag')

        legloc = 'lower right'

    else:
        plt.ylabel(reflabel)
        plt.xlabel('Image instrumental mag')
        fn = prefix + '-photom.' + format
        legloc = 'center right'

    if title is not None:
        plt.title(title)

    pp += [p3, p2]
    pl += ['Matched sources', 'Unmatched sources']
    plt.figlegend(pp,
                  pl,
                  legloc,
                  numpoints=1,
                  prop=FontProperties(size='small'))

    P1 = _output(fn, format, saveplot)

    if delta:
        plt.ylim(-0.5, 0.5)
        fn = prefix + '-dphotom2.' + format
        P2 = _output(fn, format, saveplot)
        if not saveplot:
            P1.update(P2)

    return P1
Esempio n. 33
0
def venn4(data, set_labels=None, show_names=True, ax=None, **kwds):
    from collections import Iterable
    alignment = {
        'horizontalalignment': 'center',
        'verticalalignment': 'baseline'
    }

    if (set_labels is None) or (len(set_labels) != 4):
        set_labels = ("set 1", "set 2", "set 3", "set 4")

    if ax is None:

        # set figure size
        if 'figsize' in kwds and len(kwds['figsize']) == 2:
            # if 'figsize' is in kwds, and it is a list or tuple with length of 2
            figsize = kwds['figsize']
        else:  # default figure size
            figsize = (10, 10)

        fig = plt.figure(figsize=figsize)  # set figure size
        ax = fig.add_subplot(111)

    # set colors for different Circles or ellipses
    if 'colors' in kwds and isinstance(kwds['colors'],
                                       Iterable) and len(kwds['colors']) >= 4:
        colors = kwds['colors']
    else:
        colors = ['r', 'g', 'b', 'c']

    # draw ellipse, the coordinates are hard coded in the rest of the function

    patches = []
    width, height = 170, 110  # width and height of the ellipses
    patches.append(
        Ellipse((170, 170), width, height, -45, color=colors[0], alpha=0.5))
    patches.append(
        Ellipse((200, 200), width, height, -45, color=colors[1], alpha=0.5))
    patches.append(
        Ellipse((200, 200), width, height, -135, color=colors[2], alpha=0.5))
    patches.append(
        Ellipse((230, 170), width, height, -135, color=colors[3], alpha=0.5))
    for e in patches:
        ax.add_patch(e)
    ax.set_xlim(80, 320)
    ax.set_ylim(80, 320)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_aspect("equal")

    ### draw text
    # 1
    ax.text(120, 200, data['1000'], **alignment)
    ax.text(280, 200, data['0100'], **alignment)
    ax.text(155, 250, data['0010'], **alignment)
    ax.text(245, 250, data['0001'], **alignment)
    # 2
    ax.text(200, 115, data['1100'], **alignment)
    ax.text(140, 225, data['1010'], **alignment)
    ax.text(145, 155, data['1001'], **alignment)
    ax.text(255, 155, data['0110'], **alignment)
    ax.text(260, 225, data['0101'], **alignment)
    ax.text(200, 240, data['0011'], **alignment)
    # 3
    ax.text(235, 205, data['0111'], **alignment)
    ax.text(165, 205, data['1011'], **alignment)
    ax.text(225, 135, data['1101'], **alignment)
    ax.text(175, 135, data['1110'], **alignment)
    # 4
    ax.text(200, 175, data['1111'], **alignment)
    # names of different groups
    if show_names:
        ax.text(110, 110, set_labels[0], **alignment)
        ax.text(290, 110, set_labels[1], **alignment)
        ax.text(130, 275, set_labels[2], **alignment)
        ax.text(270, 275, set_labels[3], **alignment)

    return ax
Esempio n. 34
0
            med_RMS = 0
        print('%10s  gap%i  %.1f  %.1f  %.1f  %.3f' % \
              (targets[i], ir, RMS_gap, med_RMS, disk.disk[targets[i]]['RMS'],
               med_RMS / disk.disk[targets[i]]['RMS']))

    # mark Rout
    xb, yb = rout * np.cos(tt) * np.cos(inclr), rout * np.sin(tt)
    ax.plot(xb * np.cos(PAr) + yb * np.sin(PAr),
            -xb * np.sin(PAr) + yb * np.cos(PAr),
            '--',
            color='gray',
            lw=0.5,
            alpha=0.5)

    # clean beams
    beam = Ellipse((xs_lims[0] + 0.1 * np.diff(xs_lims),
                    ys_lims[0] + 0.1 * np.diff(ys_lims)), bmaj, bmin, 90 - bPA)
    beam.set_facecolor('k')
    ax.add_artist(beam)

    # limits and labeling
    ax.text(xs_lims[0] + 0.05 * np.diff(xs_lims),
            ys_lims[1] - 0.09 * np.diff(ys_lims),
            disk.disk[targets[i]]['label'],
            color='k')
    ax.text(xs_lims[1] - 0.03 * np.diff(xs_lims),
            ys_lims[0] + 0.05 * np.diff(ys_lims),
            str(np.int(np.round(disk.disk[targets[i]]['RMS']))),
            color='dimgrey',
            ha='right',
            va='center')
    ax.set_xlim(xs_lims)
Esempio n. 35
0
import numpy as np

if 1:
    fig = figure(1, figsize=(8, 5))
    fig.clf()

    # bx = fig.add_subplot(111, autoscale_on=False, xlim=(-3,3), ylim=(-2,2))
    # bx.plot([3, 3, -3, -3],[-3,3,-3,3])

    ax = fig.add_subplot(111, autoscale_on=False, xlim=(-4, 4), ylim=(-3, 3))
    ax.plot([3, 3, -3, -3, 3], [-2, 2, 2, -2, -2], 'r')

    els = [[-1, 2], [3, 0], [-1, -2]]
    r = 0.25
    for el in els:
        e = Ellipse((el[0], el[1]), r, r)
        e.set_color('g')
        r *= 1.5
        ax.add_patch(e)
    # TODO implement the radius properly

    bx = fig.add_subplot(111, autoscale_on=False, xlim=(-4, 4), ylim=(-3, 3))
    bx.scatter([.1, .1], [.2, .4])
    bx.scatter([.2, .2], [.2, .4])
    """
    ax.annotate('$->$', xy=(2., -1),  xycoords='data',
                xytext=(-150, -140), textcoords='offset points',
                bbox=dict(boxstyle="round", fc="0.8"),
                arrowprops=dict(arrowstyle="->",
                                patchB=el,
                                connectionstyle="angle,angleA=90,angleB=0,rad=10"),
top_center = 1/2
left_center = 1/2
right_center = 1/2
for i in range (0,dim2):
	for j in range (0,dim1):
		xlist[i*dim1 +j] = j
		ylist[i*dim1 +j] = i
scatterpoint = ax2.scatter(xlist,ylist, marker="s",s=900) 
ax2.set_aspect('equal')
# angle , = ax2.plot((dim1/2-1/2,dim1/2-1/2+5*np.cos(pi/4)),(dim2/2-1/2 ,dim2/2-1/2+5*np.cos(pi/4)))
vert_spine, = ax2.plot((bottom_center + dim1, top_center + dim1),(0, dim2-1))
hor_spine, = ax2.plot((0, dim1-1),(left_center + dim2, right_center + dim2))



forcePlot = Ellipse(xy=[4,5], width=10, height=4, angle=pi/4)
ax2.add_artist(forcePlot)
       
peakcounter = 0
state = 0

while(1):
	count = count + 1;
	timenow = time.time()
	if (timenow > lasttime):
		hz = 1/(timenow - lasttime)

	lasttime = timenow
	# print(str(hz) + " Hz")

	while(ser.read() != b':'):
# Regression
fit = np.polyfit(x1, x2, 1) # careful: it's phi_n, ..., phi_1, phi_0
fit_fn = np.poly1d(fit)
# fit_fn is now a function which takes in x and returns an estimate for y

# Principal components
lam2, v = np.linalg.eig(cov)
lam = np.sqrt(lam2)



# Better do a standard regression plot
d_lam = 3
ax = plt.subplot(111, aspect='equal')
ax.scatter(x1, x2, alpha=0.1)
ell = Ellipse(xy=avg, width=2*lam[0], height=2*lam[1], 
          angle=np.rad2deg(np.arccos(v[0, 0])), facecolor='none')
ax.add_artist(ell)
ax.plot(x1, fit_fn(x1), '--k', alpha=0.5)
ax.plot(avg[0]+d_lam*np.array([0, v[0,0]]), avg[1]+d_lam*np.array([0, v[1,0]]), 'y', alpha=1) # yeah, this was just an SVD I assume not PCA so may not be ordered
ax.plot(avg[0]-d_lam*np.array([0, v[0,0]]), avg[1]-d_lam*np.array([0, v[1,0]]), 'y', alpha=1)
ax.plot(avg[0]+d_lam*np.array([0, v[0,1]]), avg[1]+d_lam*np.array([0, v[1,1]]), 'r', alpha=1)
ax.plot(avg[0]-d_lam*np.array([0, v[0,1]]), avg[1]-d_lam*np.array([0, v[1,1]]), 'r', alpha=1)
plt.axvline(x1.mean(), color='k', linestyle='--', alpha=0.1)
plt.axhline(x2.mean(), color='k', linestyle='--', alpha=0.1)
plt.title('beta = {:1.2f}'.format(fit[0]))
plt.xlabel(x1.name)
plt.ylabel(x2.name)



# Note: regression line quite different from principal components!
Esempio n. 38
0
def main(images,
         regions,
         colors,
         labels,
         shrdsfile=None,
         fluxlimit=0.,
         wisefile=None,
         sigma=0.,
         levels=[5., 10., 20., 50., 100.]):
    """
    Plot some regions on top of some images with specified colors,
    and create PDF.

    Inputs:
      images = list of fits image names to plot
      regions = list of region filenames to plot
      colors = what colors to plot each region
      labels = label for regions
      shrdsfile = if not None, path to SHRDS candidates data file
                 This will plot the SHRDS candidate regions on top
      fluxlimit = only plot WISE regions brighter than this peak
                  continuum flux density (mJy/beam)
      wisefile = if not None, path to WISE positions data file
                 This will plot the WISE regions on top
      sigma = if > 0., will plot colormap with contours at
              levels * sigma
      levels = list of contour levels

    Returns:
      Nothing
    """
    levels = np.array(levels)
    outimages = []
    for image in images:
        #
        # Open fits file, generate WCS
        #
        hdu = fits.open(image)[0]
        wcs = WCS(hdu.header)
        #
        # Generate figure
        #
        plt.ioff()
        fig = plt.figure()
        wcs_celest = wcs.sub(['celestial'])
        ax = plt.subplot(projection=wcs_celest)
        ax.set_title(image.replace('.fits', ''))
        # image
        cax = ax.imshow(hdu.data[0, 0],
                        origin='lower',
                        interpolation='none',
                        cmap='viridis')
        # contours
        if sigma > 0.:
            con = ax.contour(hdu.data[0, 0],
                             origin='lower',
                             levels=levels * sigma,
                             colors='k',
                             linewidths=0.2)
        xlen, ylen = hdu.data[0, 0].shape
        ax.coords[0].set_major_formatter('hh:mm:ss')
        ax.set_xlabel('RA (J2000)')
        ax.set_ylabel('Declination (J2000)')
        #
        # Adjust limits
        #
        ax.set_xlim(0.1 * xlen, 0.9 * xlen)
        ax.set_ylim(0.1 * ylen, 0.9 * ylen)
        #
        # Plot colorbar
        #
        cbar = fig.colorbar(cax, fraction=0.046, pad=0.04)
        cbar.set_label('Flux Density (Jy/beam)')
        #
        # Plot beam, if it is defined
        #
        pixsize = hdu.header['CDELT2']  # deg
        if 'BMAJ' in hdu.header.keys():
            beam_maj = hdu.header['BMAJ'] / pixsize  # pix
            beam_min = hdu.header['BMIN'] / pixsize  # pix
            beam_pa = hdu.header['BPA']
            ellipse = Ellipse((1. / 8. * xlen, 1. / 8. * ylen),
                              beam_min,
                              beam_maj,
                              angle=beam_pa,
                              fill=True,
                              zorder=10,
                              hatch='///',
                              edgecolor='black',
                              facecolor='white')
            ax.add_patch(ellipse)
        #
        # Plot regions
        #
        for reg, col, lab in zip(regions, colors, labels):
            if not os.path.exists(reg):
                continue
            # read second line in region file
            with open(reg, 'r') as f:
                f.readline()
                data = f.readline()
                # handle point region
                if 'ellipse' in data:
                    splt = data.split(' ')
                    RA = splt[1].replace('[[', '').replace(',', '')
                    RA_h, RA_m, RA_s = RA.split(':')
                    RA = '{0}h{1}m{2}s'.format(RA_h, RA_m, RA_s)
                    dec = splt[2].replace('],', '')
                    dec_d, dec_m, dec_s, dec_ss = dec.split('.')
                    dec = '{0}d{1}m{2}.{3}s'.format(dec_d, dec_m, dec_s,
                                                    dec_ss)
                    coord = SkyCoord(RA, dec)
                    ax.plot(coord.ra.value,
                            coord.dec.value,
                            '+',
                            color=col,
                            markersize=10,
                            transform=ax.get_transform('world'),
                            label=lab)
                # handle point region
                elif 'poly' in data:
                    splt = data.split('[[')[1]
                    splt = splt.split(']]')[0]
                    parts = splt.split(' ')
                    RAs = []
                    decs = []
                    for ind in range(0, len(parts), 2):
                        RA = parts[ind].replace('[', '').replace(',', '')
                        RA_h, RA_m, RA_s = RA.split(':')
                        RA = '{0}h{1}m{2}s'.format(RA_h, RA_m, RA_s)
                        dec = parts[ind + 1].replace('],', '')
                        dec_d, dec_m, dec_s, dec_ss = dec.split('.')
                        dec = '{0}d{1}m{2}.{3}s'.format(
                            dec_d, dec_m, dec_s, dec_ss)
                        coord = SkyCoord(RA, dec)
                        RAs.append(coord.ra.value)
                        decs.append(coord.dec.value)
                    RAs.append(RAs[0])
                    decs.append(decs[0])
                    ax.plot(RAs,
                            decs,
                            marker=None,
                            linestyle='solid',
                            color=col,
                            transform=ax.get_transform('world'),
                            label=lab,
                            zorder=110)
        #
        # Add regions legend
        #
        if len(regions) > 0:
            region_legend = plt.legend(loc='upper right', fontsize=10)
            ax.add_artist(region_legend)
        #
        # Plot SHRDS candidate regions
        #
        if shrdsfile is not None:
            shrdsdata = np.genfromtxt(shrdsfile,
                                      dtype=None,
                                      delimiter=',',
                                      encoding='UTF-8',
                                      usecols=(0, 1, 4, 5, 6, 7),
                                      skip_header=1,
                                      names=('name', 'GName', 'RA', 'Dec',
                                             'diameter', 'flux'))
            RA = np.zeros(len(shrdsdata))
            Dec = np.zeros(len(shrdsdata))
            for i, dat in enumerate(shrdsdata):
                parts = [float(part) for part in dat['RA'].split(':')]
                RA[i] = 360. / 24. * (parts[0] + parts[1] / 60. +
                                      parts[2] / 3600.)
                parts = [float(part) for part in dat['Dec'].split(':')]
                Dec[i] = np.abs(parts[0]) + parts[1] / 60. + parts[2] / 3600.
                if '-' in dat['Dec']:
                    Dec[i] = -1. * Dec[i]
            # limit only to regions with centers within image
            corners = wcs_celest.calc_footprint()
            min_RA = np.min(corners[:, 0])
            max_RA = np.max(corners[:, 0])
            RA_range = max_RA - min_RA
            #min_RA += RA_range
            #max_RA -= RA_range
            min_Dec = np.min(corners[:, 1])
            max_Dec = np.max(corners[:, 1])
            Dec_range = max_Dec - min_Dec
            #min_Dec += Dec_range
            #max_Dec -= Dec_range
            good = (min_RA < RA) & (RA < max_RA) & (min_Dec < Dec) & (
                Dec < max_Dec) & (shrdsdata['flux'] > fluxlimit)
            # plot them
            shrdsdata = shrdsdata[good]
            RA = RA[good]
            Dec = Dec[good]
            for R, D, dat in zip(RA, Dec, shrdsdata):
                xpos, ypos = wcs_celest.wcs_world2pix(R, D, 1)
                size = dat['diameter'] / 3600. / pixsize
                ell = Ellipse((xpos, ypos),
                              size,
                              size,
                              color='m',
                              fill=False,
                              linestyle='dashed',
                              zorder=105)
                ax.add_patch(ell)
                ax.text(R,
                        D,
                        dat['GName'],
                        transform=ax.get_transform('world'),
                        fontsize=10,
                        zorder=105)
        #
        # Plot WISE regions
        #
        if wisefile is not None:
            wisedata = np.genfromtxt(wisefile,
                                     dtype=None,
                                     names=True,
                                     encoding='UTF-8')
            # limit only to regions with centers within image
            corners = wcs_celest.calc_footprint()
            min_RA = np.min(corners[:, 0])
            max_RA = np.max(corners[:, 0])
            RA_range = max_RA - min_RA
            #min_RA += RA_range
            #max_RA -= RA_range
            min_Dec = np.min(corners[:, 1])
            max_Dec = np.max(corners[:, 1])
            Dec_range = max_Dec - min_Dec
            #min_Dec += Dec_range
            #max_Dec -= Dec_range
            good = (min_RA < wisedata['RA']) & (wisedata['RA'] < max_RA) & (
                min_Dec < wisedata['Dec']) & (wisedata['Dec'] < max_Dec)
            # plot them
            wisedata = wisedata[good]
            for dat in wisedata:
                xpos, ypos = wcs_celest.wcs_world2pix(dat['RA'], dat['Dec'], 1)
                size = dat['Size'] * 2. / 3600. / pixsize
                ell = Ellipse((xpos, ypos),
                              size,
                              size,
                              color='y',
                              fill=False,
                              linestyle='dashed',
                              zorder=100)
                ax.add_patch(ell)
                ax.text(dat['RA'],
                        dat['Dec'],
                        dat['GName'],
                        transform=ax.get_transform('world'),
                        fontsize=10,
                        zorder=100)
        #
        # Add WISE+SHRDS legend
        #
        if shrdsfile is not None or wisefile is not None:
            patches = []
            if shrdsfile is not None:
                ell = Ellipse((0, 0),
                              0.1,
                              0.1,
                              color='m',
                              fill=False,
                              linestyle='dashed',
                              label='SHRDS Candidates')
                patches.append(ell)
            if wisefile is not None:
                ell = Ellipse((0, 0),
                              0.1,
                              0.1,
                              color='y',
                              fill=False,
                              linestyle='dashed',
                              label='WISE Catalog')
                patches.append(ell)
            wise_legend = plt.legend(handles=patches,
                                     loc='lower right',
                                     fontsize=10,
                                     handler_map={Ellipse: HandlerEllipse()})
            ax.add_artist(wise_legend)
        #
        # Re-scale to fit, then save
        #
        fig.savefig(image.replace('.fits', '.reg.pdf'), bbox_inches='tight')
        plt.close(fig)
        plt.ion()
        outimages.append(image.replace('.fits', '.reg.pdf'))
Esempio n. 39
0
        PHI_1 -= pi

    while PHI_2 >= pi:
        PHI_2 -= pi

    # get the roots
    #
    r = roots[Id]
    length = len(r) - 1

    pylab.axes()

    cir = Ellipse(xy=(H1, K1),
                  width=2 * A1,
                  height=2 * B1,
                  angle=PHI_1 * 180 / pi,
                  alpha=.2,
                  fc='r',
                  lw=3)
    plot(H1, K1, "or", ms=ms)
    plot(H2, K2, "ob", ms=ms)
    pylab.gca().add_patch(cir)

    #plot roots
    if length:
        R = array([float(i) for i in r[1:]])
        rx_TR = (R[0::2]) * cos(-PHI_1) + (R[1::2]) * sin(-PHI_1) + H1
        ry_TR = -(R[0::2]) * sin(-PHI_1) + (R[1::2]) * cos(-PHI_1) + K1
        plot(rx_TR, ry_TR, "og", ms=ms, lw=2)

    cir = Ellipse(xy=(H2, K2),
Esempio n. 40
0
        else:
            dfile = 'data/deep_'+targets[i]+'_'+dmr[j]+'.JvMcorr.fits'
        hdu = fits.open(dfile)
        img = np.squeeze(hdu[0].data)    

        # set location in figure
        ax = fig.add_subplot(gs[i,j])

        # plot the image (in brightness temperature units)
        Tb = (1e-23 * img / barea) * c_**2 / (2 * k_ * freq**2)
        im = ax.imshow(Tb, origin='lower', cmap=cmap, extent=im_bounds,
                       norm=norm, aspect='equal')

        # clean beams
        beam = Ellipse((dRA_lims[0] + 0.1*np.diff(dRA_lims),
                        dDEC_lims[0] + 0.1*np.diff(dDEC_lims)), 
                       bmaj, bmin, 90-bPA)
        beam.set_facecolor('w')
        ax.add_artist(beam)

        # limits and labeling
        if (j == 0):
            ax.text(dRA_lims[0] + 0.03*np.diff(dRA_lims), 
                    dDEC_lims[1] - 0.10*np.diff(dDEC_lims), 
                    disk.disk[targets[i]]['label'], color='w', fontsize=6)
        ax.set_xlim(dRA_lims)
        ax.set_ylim(dDEC_lims)
        ax.set_yticks([-1, 0.0, 1])
        if (i == 3) and (j == 0):
            ax.set_xlabel('RA offset  ($^{\prime\prime}$)', labelpad=2.5)
            ax.set_ylabel('DEC offset  ($^{\prime\prime}$)', labelpad=2)
Esempio n. 41
0
def pl_2_param_dens(_2_params, gs, min_max_p2, varIdxs, params_trace):
    '''
    Parameter vs parameters density map.
    '''
    plot_dict = {
        'metal-age': [0, 2, 2, 4, 0, 1],
        'metal-ext': [0, 2, 4, 6, 0, 2],
        'metal-dist': [0, 2, 6, 8, 0, 3],
        'metal-mass': [0, 2, 8, 10, 0, 4],
        'metal-binar': [0, 2, 10, 12, 0, 5],
        'age-ext': [2, 4, 4, 6, 1, 2],
        'age-dist': [2, 4, 6, 8, 1, 3],
        'age-mass': [2, 4, 8, 10, 1, 4],
        'age-binar': [2, 4, 10, 12, 1, 5],
        'ext-dist': [4, 6, 6, 8, 2, 3],
        'ext-mass': [4, 6, 8, 10, 2, 4],
        'ext-binar': [4, 6, 10, 12, 2, 5],
        'dist-mass': [6, 8, 8, 10, 3, 4],
        'dist-binar': [6, 8, 10, 12, 3, 5],
        'mass-binar': [8, 10, 10, 12, 4, 5]
    }

    labels = [
        '$z$', '$log(age)$', '$E_{(B-V)}$', '$(m-M)_o$', '$M\,(M_{{\odot}})$',
        '$b_{frac}$'
    ]

    gs_x1, gs_x2, gs_y1, gs_y2, mx, my = plot_dict[_2_params]
    x_label, y_label = labels[mx], labels[my]

    ax = plt.subplot(gs[gs_y1:gs_y2, gs_x1:gs_x2])

    # To specify the number of ticks on both or any single axes
    ax.locator_params(nbins=5)
    if gs_x1 == 0:
        plt.ylabel(y_label, fontsize=11)
        plt.yticks(rotation=45)
    else:
        ax.tick_params(labelleft=False)
    if gs_y2 == 12:
        plt.xlabel(x_label, fontsize=11)
        plt.xticks(rotation=45)
    else:
        ax.tick_params(labelbottom=False)
    plt.minorticks_on()

    if mx in varIdxs and my in varIdxs:
        mx_model, my_model = varIdxs.index(mx), varIdxs.index(my)

        ax.set_title(r"$\rho={:.2f}$".format(
            np.corrcoef([params_trace[mx_model],
                         params_trace[my_model]])[0][1]),
                     fontsize=11)

        hist2d(ax, params_trace[mx_model], params_trace[my_model])

        mean_pos, width, height, theta = SigmaEllipse(
            np.array([params_trace[mx_model], params_trace[my_model]]).T)
        # Plot 95% confidence ellipse.
        plt.scatter(mean_pos[0],
                    mean_pos[1],
                    marker='x',
                    c='b',
                    s=30,
                    linewidth=2,
                    zorder=4)
        ellipse = Ellipse(xy=mean_pos,
                          width=width,
                          height=height,
                          angle=theta,
                          edgecolor='r',
                          fc='None',
                          lw=.7,
                          zorder=4)
        ax.add_patch(ellipse)

    xp_min, xp_max, yp_min, yp_max = min_max_p2
    ax.set_xlim([xp_min, xp_max])
    ax.set_ylim([yp_min, yp_max])

    # Grid won't respect 'zorder':
    # https://github.com/matplotlib/matplotlib/issues/5045
    # So we plot the grid behind everything else manually.
    xlocs, xlabels = plt.xticks()
    ylocs, ylabels = plt.yticks()
    for xt in xlocs:
        plt.axvline(x=xt, linestyle='-', color='w', zorder=-4)
    for yt in ylocs:
        plt.axhline(y=yt, linestyle='-', color='w', zorder=-4)
Esempio n. 42
0
    def loadImage(self):
        bashCommand = "rm test.PNG"
        import subprocess
        process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
        output, error = process.communicate()
        print output

        # first of all, the base transformation of the data points is needed
        base = plt.gca().transData
        rot = transforms.Affine2D().rotate_deg(270)

        filename = askopenfilename()
        img = rz.resizeSignature(filename)

        # Image filtering
        imgSmooted = GaussS.gaussianBlur(1, 0.5, img)
        imgFiltered = bN.filter(imgSmooted)

        # Calculate the ones in the matrix.
        blackPoints = bN.calculateBlackPoints(imgFiltered)

        # Calculate the center of mass
        centerMass = bN.centroid(blackPoints)
        self.CenterMass.setText(str(centerMass[1]))
        self.CenterMass_2.setText(str(centerMass[0]))

        # Calculate the eccentricity
        eccentricity = bN.calculateEccentricity(blackPoints)
        self.Eccentricity.setText(str(round(eccentricity,4)))

        # Calculate the representative points of a signature
        densePoints = bN.calculateDensePoints(blackPoints)
        listY = [y[0] for y in blackPoints]
        listX = [x[1] for x in blackPoints]
        plt.plot(listY, listX, "ro", transform=rot + base)

        # Print Center of mass
        plt.plot(centerMass[0], centerMass[1], "^", transform=rot + base)

        # Print dense points
        densePoints = densePoints.T
        plt.plot(densePoints[0], densePoints[1], "g+", transform=rot + base)

        kurtosis = bN.calculateKurtosis(blackPoints)
        self.kurtosis.setText(str(round(kurtosis[1], 4 )))
        self.kurtosis_2.setText(str(round(kurtosis[0], 4)))

        # Print skew detection
        testSkew = bN.skewDetection(imgFiltered)
        self.Skew.setText(str(round(testSkew)))

        # Calculate gradient in a grid 4x4 - Choosen just 2x2 important grid in the middle
        matrixGradient = bN.calculateGradient(blackPoints, imgFiltered.shape)
        self.Gradient.setRowCount(len(matrixGradient))
        self.Gradient.setColumnCount(len(matrixGradient[0]))
        for i, row in enumerate(matrixGradient):
            for j, val in enumerate(row):
                self.Gradient.setItem(i, j, QtGui.QTableWidgetItem(str(val)))

        self.Gradient.resizeColumnsToContents()
        self.Gradient.resizeRowsToContents()


        # Calculate pressure in a grid 4x4
        matrixPresure = np.around(bN.calculatePressure(imgSmooted), decimals=2)
        self.Presure.setRowCount(len(matrixPresure))
        self.Presure.setColumnCount(len(matrixPresure[0]))
        for i, row in enumerate(matrixPresure):
            for j, val in enumerate(row):
                self.Presure.setItem(i, j, QtGui.QTableWidgetItem(str(val)))

        self.Presure.resizeColumnsToContents()
        self.Presure.resizeRowsToContents()

        plt.axis('off')

        # Plot Ellipse
        subplot = plt.subplot()
        b, a = drawEllipse(blackPoints)
        ell = Ellipse((centerMass[1], centerMass[0] * -1), b + 10, a + 10, edgecolor='black', facecolor='none',
                      linewidth=5)
        subplot.add_patch(ell)

        # plt.plot([y positions of the points], [x positions of the points])
        # plt.plot([testSkewLeft[1], testSkewRight[1]], [testSkewLeft[0], testSkewRight[0]], 'k')
        # plt.plot([testSkewLeft[1], testSkewLeft[1]], [testSkewLeft[0], testSkewRight[0]], 'k')
        # Save Scanned Signature
        plt.savefig("test.PNG", dpi=700)
        plt.close()

        ############################################
        # Signature image
        ############################################
        logoPic1 = QPixmap(filename)
        self.signature.setPixmap(logoPic1.scaled(291,255,Qt.KeepAspectRatio))
        self.signature.show()

        ############################################
        # Signature Feature
        ############################################

        search_pixmap = QtGui.QPixmap()
        search_pixmap.load('test.PNG')
        self.featureSignature.setPixmap(search_pixmap.scaled(291, 255, Qt.KeepAspectRatio))
        self.featureSignature.show()



        ########################
        # Save test image
        ##########################
        vectorFeature = []
        vectorFeature.append(round(centerMass[0], 4))
        vectorFeature.append(round(centerMass[1], 4))
        vectorFeature.append(round(eccentricity, 4))
        vectorFeature.append(round(kurtosis[0], 4))
        vectorFeature.append(round(kurtosis[1], 4))
        vectorFeature.append(round(matrixGradient[0][0][0], 4))
        vectorFeature.append(round(matrixGradient[0][0][1], 4))
        vectorFeature.append(round(matrixGradient[0][1][0], 4))
        vectorFeature.append(round(matrixGradient[0][1][1], 4))
        vectorFeature.append(round(matrixGradient[0][2][0], 4))
        vectorFeature.append(round(matrixGradient[0][2][1], 4))
        vectorFeature.append(round(matrixGradient[0][3][0], 4))
        vectorFeature.append(round(matrixGradient[0][3][1], 4))
        vectorFeature.append(round(matrixGradient[1][0][0], 4))
        vectorFeature.append(round(matrixGradient[1][0][1], 4))
        vectorFeature.append(round(matrixGradient[1][1][0], 4))
        vectorFeature.append(round(matrixGradient[1][1][1], 4))
        vectorFeature.append(round(matrixGradient[1][2][0], 4))
        vectorFeature.append(round(matrixGradient[1][2][1], 4))
        vectorFeature.append(round(matrixGradient[1][3][0], 4))
        vectorFeature.append(round(matrixGradient[1][3][1], 4))
        vectorFeature.append(round(matrixPresure[0][0], 4))
        vectorFeature.append(round(matrixPresure[0][1], 4))
        vectorFeature.append(round(matrixPresure[0][2], 4))
        vectorFeature.append(round(matrixPresure[0][3], 4))
        vectorFeature.append(round(matrixPresure[1][0], 4))
        vectorFeature.append(round(matrixPresure[1][1], 4))
        vectorFeature.append(round(matrixPresure[1][2], 4))
        vectorFeature.append(round(matrixPresure[1][3], 4))
        vectorFeature.append(round(matrixPresure[2][0], 4))
        vectorFeature.append(round(matrixPresure[2][1], 4))
        vectorFeature.append(round(matrixPresure[2][2], 4))
        vectorFeature.append(round(matrixPresure[2][3], 4))
        vectorFeature.append(round(matrixPresure[3][0], 4))
        vectorFeature.append(round(matrixPresure[3][1], 4))
        vectorFeature.append(round( matrixPresure[3][2], 4))
        vectorFeature.append(round(matrixPresure[3][3], 4))

        label = 0
        if len(filename.split('/')[len(filename.split('/'))-1]) < 11:
            label = int(filename.split('/')[len(filename.split('/'))-2])
        # print label

        matrixData = []
        vectorTarget = []
        with open('../LearningInformation/learningBayesianMulticlassGenuine.csv') as f:
            readerGenuine = csv.reader(f)

            readerGenuine.next()
            for i in readerGenuine:
                matrixData.append(map(float, i[:len(i) - 1]))
                # matrixData.append(map(float, i[2:5] + i[25:len(i) - 1]))
                vectorTarget.append(int(i[len(i) - 1]))

        with open('../LearningInformation/learningBayesianMulticlassForgeries.csv') as f:
            readerForgeriestmp = csv.reader(f)
            readerForgeriestmp.next()
            for i in readerForgeriestmp:
                matrixData.append(map(float, i[:len(i) - 1]))
                # matrixData.append(map(float, i[2:5] + i[25:len(i) - 1]))
                vectorTarget.append(int(i[len(i) - 1]))

        matrixData = np.array(matrixData)
        vectorTarget = np.array(vectorTarget)

        asdsada = TemplateClassifier().fit(matrixData, vectorTarget)
        y_predict_X = asdsada.predict(vectorFeature)[0]

        self.realLabelText = label
        self.predicted = y_predict_X
Esempio n. 43
0
    def get_graph(self):
        """
        @brief generate the graph of the contacts
        @param      self The object
        @return The graph.
        @todo add a label to the sets
        """

        fig_glob, ax_glob = plt.subplots()
        ax_glob.set_title("Global COP Analysis")

        if not self.contacts:
            plt.axis([-0.1, 0.1, -0.1, 0.1])
            #plt.axis([-2, 2, -2, 2])
        else:
            colors = get_cmap(len(self.contacts) + 1)
            plt.axis('equal')
            for i, contact in enumerate(self.contacts):
                cop = contact.cop_
                if len(cop) > 0:
                    #ax_glob.plot(cop[:, 0], cop[:, 1], 'o', color=colors(i), label="{}-{}".format(i + 1, labels[i + 1]))
                    ax_glob.plot(cop[:, 0],
                                 cop[:, 1],
                                 '.',
                                 color=colors(i),
                                 label="{}".format(contact.name_))

                    [cop_mean, sigma, angle, major_axis,
                     minor_axis] = contact.get_ellipse()

                    ellipse = Ellipse(cop_mean,
                                      width=major_axis,
                                      height=minor_axis,
                                      angle=angle)
                    ellipse.set_color(colors(i))
                    ellipse.set_alpha(0.6)
                    ellipse.set_clip_box(ax_glob.bbox)
                    ax_glob.add_artist(ellipse)
                else:
                    self.log_warn("No points for {}".format(i + 1))
        #if self.contacts:
        #    ax_glob.legend()

        # import matplotlib.patches as mpatches
        # texts = ["Exp {}".format(i + 1) for i in range(5)]
        # patches = [ mpatches.Patch(color=colors[i], label="{:s}".format(labels[relevant_slices[i][0]]) ) for i in range(len(relevant_slices)) ]
        # plt.legend(handles=patches, ncol=2 )

        ax_glob.set_xlabel("x[mm]")
        ax_glob.set_ylabel("y[mm]")
        ax_glob.grid()

        if self.contacts:
            #ax_glob.legend(loc='upper center', bbox_to_anchor=(0.5, 1.0), ncol=3, fancybox=True, shadow=True)
            # to put the legend on the right
            # Shrink current axis by 20%
            box = ax_glob.get_position()
            ax_glob.set_position([box.x0, box.y0, box.width * 0.8, box.height])

            # Put a legend to the right of the current axis
            ax_glob.legend(loc='center left', bbox_to_anchor=(1, 0.5))

        return fig_glob, ax_glob
Esempio n. 44
0
def rand_compl(compl_type, ra, dec, mjd, chunk, outfig=True):

    output_path = 'output/' + chunk + '/' + mjd

    if compl_type == 'tiling':
        tmp = 'Tcompleteness'
    elif compl_type == 'redshift':
        tmp = 'Zcompleteness'
    else:
        sys.exit(
            'Error: The completeness type in rand.py must be either "tiling" or "redshift".'
        )

    if chunk == 'eboss21':
        outroot = output_path + '/ELG_SGC.eboss21.' + tmp
        completeness_file = output_path + '/ELG_SGC.eboss21.' + tmp + '.asc'
        footprint_ra = np.array([-43.0, 0.0, 0.0, -43.0, -43.0])
        footprint_dec = np.array([-2.0, -2.0, 2.0, 2.0, -2.0])
        xlim = [-46, 3]
        ylim = [-3, 3]

    elif chunk == 'eboss22':
        outroot = output_path + '/ELG_SGC.eboss22.' + tmp
        completeness_file = output_path + '/ELG_SGC.eboss22.' + tmp + '.asc'
        footprint_ra = np.array([0.0, 45.0, 45.0, 0.0, 0.0])
        footprint_dec = np.array([-5.0, -5.0, 5.0, 5.0, -5.0])
        xlim = [-3, 48]
        ylim = [-6, 6]

    elif chunk == 'eboss23':
        outroot = output_path + '/ELG_NGC.eboss23.' + tmp
        completeness_file = output_path + '/ELG_NGC.eboss23.' + tmp + '.asc'
        footprint_ra = np.array(
            [126, 126, 142.5, 142.5, 157, 157, 136.5, 136.5, 126])
        footprint_dec = np.array([16, 29, 29, 27, 27, 13.8, 13.8, 16, 16])
        xlim = [125, 158]
        ylim = [13, 30]

    # reading the completeness
    completeness = np.zeros(0)
    tilecomb_uniq = np.zeros(0, dtype='str')
    with open(completeness_file) as f:
        for line in f:
            if (line[0] != '#'):
                completeness = np.append(completeness, float(line.split()[0]))
                tilecomb_uniq = np.append(tilecomb_uniq, line.split()[1])

    # reading the tiles
    tile = np.zeros(0, dtype='str')
    tilera = np.zeros(0)
    tiledec = np.zeros(0)

    tmp = read_tiles('data/tiles-' + chunk + '.par')
    tile = np.append(tile, tmp[0])
    tilera = np.append(tilera, tmp[1])
    tiledec = np.append(tiledec, tmp[2])
    ntile = len(tilera)

    # number of spectroscopic objects
    nspecobj = len(ra)
    objSkyCoord = SkyCoord(ra=ra * u.deg, dec=dec * u.deg, frame='fk5')
    tile_rad = 1.49  # tile radius in degrees

    # listing the tiles in which each object lies
    spectile = np.array(['' for x in np.arange(nspecobj)], dtype=object)
    for i in xrange(ntile):
        tileSkyCoord = SkyCoord(ra=tilera[i] * u.deg,
                                dec=tiledec[i] * u.deg,
                                frame='fk5')
        tmpspec = (objSkyCoord.separation(tileSkyCoord).deg <= tile_rad)
        spectile[tmpspec] += tile[i] + '-'

    # loop on unique combinations of tiles
    speccompl = np.zeros(nspecobj)
    for i in xrange(len(tilecomb_uniq)):
        tmpspec = (spectile == tilecomb_uniq[i])
        speccompl[tmpspec] = completeness[i]

    if outfig:
        # building ellipses
        ells = [
            Ellipse(xy=np.array([x, y]),
                    width=3.0 / np.cos(y / 180. * np.pi),
                    height=3.0,
                    angle=0) for x, y in zip(tilera, tiledec)
        ]

        if chunk in ['eboss21', 'eboss22']:
            fig = plt.figure(figsize=(20, 8.8))
        elif chunk == 'eboss23':
            fig = plt.figure(figsize=(16, 8))

        ax = fig.add_subplot(111)

        # eBOSS/ELG footprint
        ax.plot(footprint_ra, footprint_dec, c='k', zorder=10, linewidth=2)
        if compl_type == 'redshift':
            clim = [50., 100. * max(speccompl)]
        else:
            clim = [100. * min(speccompl), 100. * max(speccompl)]
        SC   = ax.scatter(ra,dec,s=2,c=100.*speccompl,edgecolor='none',\
                vmin=clim[0],vmax=clim[1],cmap=matplotlib.cm.rainbow)
        for e in ells:
            e.set_color('k')
            e.set_facecolor('none')
            e.set_linewidth(1)
            e.set_alpha(0.3)
            e.set_clip_box(ax.bbox)
            ax.add_artist(e)
        # colorbar
        cbar = plt.colorbar(SC, pad=0.01)
        if compl_type == 'tiling':
            cbar.set_label(r'Tiling completeness [\%]', size=16)
        elif compl_type == 'redshift':
            cbar.set_label(r'Redshift completeness [\%]', size=16)
        cbar.set_clim(clim)
        # plot stuff
        ax.grid(True, linestyle='-', alpha=0.3)
        ax.set_xlabel(r'R.A. [deg.]', size=16)
        ax.set_ylabel(r'DEC. [deg.]', size=16)
        ax.set_xlim(xlim)
        ax.set_ylim(ylim)
        plt.tight_layout()
        plt.savefig(outroot + '.png', bbox_inches='tight', format='png')

    return speccompl
def main():
    p = argparse.ArgumentParser(
        description="Plot map with Mercator projection")
    p.add_argument("fitsfile", nargs="?", help="Input HEALPix FITS file")
    p.add_argument("-a",
                   "--abthresh",
                   dest="athresh",
                   default=None,
                   type=float,
                   help="Apply an absolute (lower/upper) threshold to the map")
    p.add_argument("-c",
                   "--coords",
                   dest="coords",
                   default="C",
                   help="C=equatorial (default), G=galactic")
    p.add_argument("-C",
                   "--column",
                   dest="col",
                   default=0,
                   type=int,
                   help="FITS column in which healpix map resides")
    p.add_argument("-D",
                   "--coldiff",
                   dest="coldif",
                   default=-1,
                   type=int,
                   help="FITS column in which healpix map to be subtracted "
                   "(if any) resides")
    p.add_argument(
        "--mjd",
        default=None,
        type=float,
        help=
        "MJD of the map. Will be plotted in J2000. Supersedes info in header")
    p.add_argument("-l",
                   "--threshold",
                   dest="thresh",
                   type=float,
                   default=None,
                   help="Apply a lower threshold to the plot.")
    p.add_argument(
        "--norm-sqdeg",
        dest="sqdeg",
        action="store_true",
        default=False,
        help="Normalize values to square degree, according to nSides"
        " (makes sense only certain dinds of maps)")
    p.add_argument("--milagro",
                   action="store_true",
                   dest="milagro",
                   default=False,
                   help="Use Milagro color scale")
    p.add_argument(
        "--contours",
        dest="contours",
        type=float,
        nargs='*',
        default=None,
        help="plot contours. If --contourmap is provided, it will be"
        " used instead of plotted map. If no contours are"
        " provided, it will plot confidence intervals"
        " (1, 2, 3 sigma CI). Else, absolute sigmas are used,"
        " e.g. --contours 1 2 3 4 [sigma] --contours")
    p.add_argument("--contourscolor",
                   dest="contourscolor",
                   nargs='*',
                   default=None,
                   help="Draw options for contours")
    p.add_argument("--contoursstyle",
                   dest="contoursstyle",
                   default=None,
                   help="Draw options for contours")
    p.add_argument("--contourswidth",
                   dest="contourswidth",
                   default=None,
                   help="Draw options for contours")
    p.add_argument("--gamma",
                   action="store_true",
                   dest="gamma",
                   default=False,
                   help="Use GeV/TeV gamma-ray color scale")
    p.add_argument("-L",
                   "--label",
                   dest="label",
                   default=None,
                   help="Color bar label")
    p.add_argument("--cross",
                   dest="cross",
                   action="store_true",
                   help="Plot a cross at the center of the plot")
    p.add_argument("--moon",
                   action="store_true",
                   default=False,
                   dest="isMoon",
                   help="is in moon centered coordinates")
    p.add_argument("-m",
                   "--min",
                   dest="min",
                   type=float,
                   default=None,
                   help="Plot minimum value")
    p.add_argument("-M",
                   "--max",
                   dest="max",
                   type=float,
                   default=None,
                   help="Plot maximum value")
    p.add_argument("-n",
                   "--ncolors",
                   dest="ncolors",
                   type=int,
                   default=256,
                   help="Number of contours to use in the colormap")
    p.add_argument("--nocolorbar",
                   dest="colorbar",
                   action="store_false",
                   default=True,
                   help="Do not draw color bar.")
    p.add_argument("--nofill",
                   dest="nofill",
                   action="store_true",
                   help="Do not draw fill plot with colors. "
                   "Useful for contours.")
    p.add_argument("-o",
                   "--output",
                   dest="output",
                   default=None,
                   help="Output file name (optional)")
    p.add_argument("-s",
                   "--scale",
                   dest="scale",
                   type=float,
                   default=1.,
                   help="scale up or down values in map")
    p.add_argument("--sun",
                   action="store_true",
                   default=False,
                   dest="isSun",
                   help="is in Sun centered coordinates")
    p.add_argument("--dpar",
                   dest="dpar",
                   type=float,
                   default=1.,
                   help="Interval in degrees between parallels")
    p.add_argument("--dmer",
                   dest="dmer",
                   type=float,
                   default=1.,
                   help="Interval in degrees between meridians.")
    p.add_argument("--nogrid",
                   action="store_true",
                   default=False,
                   dest="nogrid",
                   help="Do not plot gridlines.")
    p.add_argument("--interpolation", dest="interpolation", \
                   default=False, action='store_true',
                   help="Uses bilinear interpolation in data map.")
    p.add_argument("--xsize",
                   dest="xsize",
                   type=int,
                   default=1000,
                   help="Number of X pixels, Y will be scaled acordingly.")
    p.add_argument("-t",
                   "--ticks",
                   dest="ticks",
                   nargs="+",
                   type=float,
                   help="List of ticks for color bar, space-separated")
    p.add_argument("-T", "--title", dest="title", help="title of map")
    p.add_argument("--squareaspect", dest="squareaspect", \
                   action='store_true',
                   help="Better Mercator X/Y ratio.")
    p.add_argument("--preliminary",
                   action="store_true",
                   dest="preliminary",
                   help="Add a watermark indicating the plot as preliminary")
    p.add_argument(
        "--onlystats",
        action="store_true",
        default=False,
        help=
        "Exits after returning min, max and value at center. If map is called 'flux', it will give the error if there is a map called 'flux_error'"
    )

    # Mutually exclusive option to specify plot xy range OR center + WxH
    argRange = p.add_mutually_exclusive_group(required=False)
    argRange.add_argument("--xyrange",
                          dest="xyrange",
                          type=float,
                          nargs=4,
                          help="Xmin Xmax Ymin Ymax plot range [degree]")
    argRange.add_argument(
        "--origin",
        dest="origin",
        type=float,
        nargs=4,
        help="Central (x,y) coords + width + height [degree]")

    # Plot P-Value instead of sigma, expects location and scale of
    # a right-skewed Gumble distribution
    p.add_argument("--gumbel",
                   dest="gumbel",
                   type=float,
                   nargs=2,
                   help="Plot P-Value instead of significance. "
                   "Arguments: location and scale of right-skewed "
                   "Gumble distribution.")

    # Download/plotting options for Fermi catalog sources
    p.add_argument(
        "--download-fermi",
        dest="dfermi",
        default=None,
        help="Download Fermi FITS data from NASA and exit. Enter version number"
    )
    p.add_argument("--fermicat",
                   dest="fermicat",
                   default=None,
                   help="Fermi xFGL catalog FITS file name")
    p.add_argument("--fermicat-labels",
                   dest="fermicatLabels",
                   action="store_true",
                   default=False,
                   help="Draw Fermi sources with labels.")

    # plotting options for Fermi Healpix file
    p.add_argument("--contourmap",
                   dest="contourmap",
                   default=None,
                   help="Healpix map from which to grab contours.")
    p.add_argument(
        "--contourmapcoord",
        dest="contourmapcoord",
        default="G",
        help=
        "Coordinate system of contourmap. C=equatorial, G=galactic (default)")

    # Download/plotting options for TeVCat sources
    p.add_argument("--download-tevcat",
                   dest="dtevcat",
                   action="store_true",
                   default=False,
                   help="Download data from tevcat.uchicago.edu and exit")
    p.add_argument("--tevcat",
                   dest="tevcat",
                   default=None,
                   help="Draw TeVCat sources using TeVCat ASCII file")
    p.add_argument("--tevcat-labels",
                   dest="tevcatLabels",
                   action="store_true",
                   default=False,
                   help="Draw TeVCat sources with labels.")
    p.add_argument("--cat-labels-angle",
                   dest="catLabelsAngle",
                   default=90,
                   help="Oriantation of catalog labels.")
    p.add_argument("--cat-labels-size",
                   dest="catLabelsSize",
                   default=8,
                   help="Size of catalog labels.")

    # Highlight hotspots listed in an ASCII file
    p.add_argument("--hotspots",
                   dest="hotspots",
                   default=None,
                   help="Hotspot coordinates in an ASCII file")
    p.add_argument("--hotspot-labels",
                   dest="hotspotLabels",
                   action="store_true",
                   default=False,
                   help="Draw hotspots sources with labels.")
    # Plot 2D Gaussian fit result listed in an ASCII file from fitMap.py
    p.add_argument("--gaussfit",
                   dest="gaussfit",
                   default=None,
                   help="2D-Gaussian fit result in an ASCII file")

    args = p.parse_args()

    #Sanity checks
    if (args.mjd is not None) and (not canPrecess):
        print "Missing necessary packages to make precession"
        raise SystemExit

    if args.nofill:
        # If we don't fill with colors, we don't plot the colorbar either
        args.colorbar = False

    # Download TeVCat
    if args.dtevcat:
        if haveTeVCat:
            print("Fetching data from tevcat.uchicago.edu.")
            tevcat = TeVCat.TeVCat()
            return None
        else:
            print("Sorry, AERIE TeVCat python module is not available.")
            raise SystemExit

    # Downlaod Fermi catalog
    if args.dfermi:
        if haveFermi:
            print "Fetching 2FGL catalog, version %s" % args.dfermi
            FGLCatalog.fetch_catalog(args.dfermi)
            return None
        else:
            print "Sorry, AERIE Fermi python module is not available."
            raise SystemExit

    # Start normal processing
    if args.fitsfile == None:
        print("Please specify an FITS file to plot.")
        raise SystemExit

    # Fill 2D array
    xmin = -180.
    xmax = 180.
    ymax = 90
    ymin = -90

    if (args.xyrange):
        xmin, xmax, ymin, ymax = args.xyrange
        xC = (xmin + xmax) / 2.
        yC = (ymin + ymax) / 2.
    elif (args.origin):
        xC, yC, w, h = args.origin
        xmin = xC - 0.5 * w
        xmax = xC + 0.5 * w
        ymin = yC - 0.5 * h
        ymax = yC + 0.5 * h
    else:
        print(
            "Using default zoom window. "
            "To customize the zoom window you must specify either "
            "(xyrange) or (origin and width and height).")

    if args.isMoon or args.isSun:
        xmin += 180.
        xmax += 180.

    # Move to range expected by healpy
    while xmin < -180:
        xmin += 360
    while xmin > 180:
        xmin -= 360
    while xmax < -180:
        xmax += 360
    while xmax > 180:
        xmax -= 360

    if xmax < xmin:
        tmax = xmax
        tmin = xmin
        xmin = tmax
        xmax = tmin

    cxmin = xmin
    cxmax = xmax
    frot = 0.
    if xmax > 90. and xmin < -90.:
        frot = 180.
        cxmin = xmax - 180.
        cxmax = xmin + 180.

    if args.origin:
        while xC > 180:
            xC -= 360

    # Read in the skymap and mask out empty pixels
    skymap, skymapHeader = hp.read_map(args.fitsfile, args.col, h=True)
    # remove naughty values
    skymap[np.isnan(skymap)] = hp.UNSEEN
    skymap *= args.scale
    nside1 = hp.get_nside(skymap)
    npix = hp.nside2npix(nside1)

    if args.coldif > -1:
        skymap2 = hp.read_map(args.fitsfile, args.coldif)
        skymap -= skymap2

    if (args.gumbel):
        assert haveGumbel
        gumbel_location, gumbel_scale = args.gumbel
        gumbel = gumbel_r(loc=gumbel_location, scale=gumbel_scale)
        skymap = gumbel.logsf(skymap) / log(10)

        def inf_suppressor(x):
            return x if np.isfinite(x) else 0.

        inf_suppressor = np.vectorize(inf_suppressor)
        skymap = inf_suppressor(skymap)

    # Normalize value to square degree
    if args.sqdeg:
        pixsizestr = 4 * np.pi / (12 * nside1**2)
        str2sqdeg = (180 / np.pi)**2
        pixsizesqdeg = pixsizestr * str2sqdeg
        skymap /= pixsizesqdeg

    # I did not find header handler, thats all I came up with...
    toFind = 'TTYPE' + str(args.col + 1)
    #print type(skymapHeader), type(skymapHeader[0]), skymapHeader, toFind, dict(skymapHeader)[toFind]
    skymapName = dict(skymapHeader)[toFind]

    #Check if it is flux
    isFlux = False
    hasFluxError = False
    if skymapName == 'flux':
        isFlux = True

        keyname = dict((v, n) for n, v in skymapHeader).get("flux_error")

        if keyname is not None:
            if keyname.find('TTYPE') == 0 and len(keyname) == 6:
                hasFluxError = True
                fluxerrmap = hp.read_map(args.fitsfile, int(keyname[5]) - 1)

        if not hasFluxError:
            print "Map called 'flux_error' not present, will not print errors"

    # Find FOV
    pxls = np.arange(skymap.size)
    nZeroPix = pxls[(skymap != 0)]
    pxTh, pxPh = hp.pix2ang(nside1, pxls)

    # Mask outside FOV
    values = np.ma.masked_where((pxTh > pxTh[nZeroPix].max())
                                | (pxTh < pxTh[nZeroPix].min())
                                | (skymap == hp.UNSEEN)
                                | (skymap == 1e20), skymap)

    # Plot the skymap as an image, setting up the color palette on the way
    mpl.rc("font", size=14, family="serif")
    faspect = abs(cxmax - cxmin) / abs(ymax - ymin)
    fysize = 4
    # Set up the figure frame and coordinate rotation angle
    coords = ["C", "C"]
    gratcoord = "C"
    if args.coords == "G":
        coords = ["C", "G"]
        gratcoord = "G"

    if args.mjd is not None:
        rotMap = precess.mjd2J2000ang(mjd=args.mjd, coord=coords, rot=frot)
        rotVertex = precess.mjd2J2000ang(mjd=args.mjd, coord=coords)
    else:
        mjd = False
        if havePyfits:
            hdulist = pf.open(args.fitsfile)
            header = hdulist[0].header
            if 'EPOCH' in header:
                epoch = header['EPOCH']
                if epoch == 'J2000':
                    pass
                elif epoch == 'current':
                    if 'STARTMJD' in header and 'STOPMJD' in header:
                        startmjd = header['STARTMJD']
                        stopmjd = header['STOPMJD']
                        if (startmjd > 0
                                and stopmjd > 0) or startmjd > stopmjd:
                            mjd = (stopmjd + startmjd) / 2
                        else:
                            print "STARTMJD/STOPMJD are not well-definned, will not attempt to precess!"
                    else:
                        print "STARTMJD or STOPMJD not present in header, will not attempt to precess!"
                else:
                    print "Currently EPOCH can be J2000 or current. Will not attempt to precess"
            else:
                print "Key EPOCH not in header, will not attempt to precess!"

        else:
            print "Pyfits not available -> Can't check map epoch -> Will not attempt to precess!"

        if mjd:
            print "Current epoch detected in header, will precess from MJD%g to J2000" % mjd
            rotMap = precess.mjd2J2000ang(mjd=mjd, coord=coords, rot=frot)
            rotVertex = precess.mjd2J2000ang(mjd=mjd, coord=coords)
        else:
            rotMap = frot
            rotVertex = 0

    # Get extrema
    angverts = [[xmin,ymin],[xmax,ymin],\
                [xmax,ymax],[xmin,ymax]]
    vertlist = []
    cRot = hp.Rotator(coord=coords, rot=rotVertex)
    for x, y in angverts:
        ctht, cph = np.deg2rad((y, x))
        ctht = 0.5 * np.pi - ctht
        if cph < 0:
            cph = 2. * np.pi + cph
        vertlist.append(cRot.I(hp.ang2vec(ctht, cph)))

    # Get pixels in image
    imgpix = hp.query_polygon(nside1, vertlist, inclusive=True)

    seenpix = imgpix[values[imgpix] > hp.UNSEEN]

    #Get stats
    precRot = hp.Rotator(coord=coords, rot=rotVertex)

    pixMin, pixMax = seenpix[[
        np.argmin(values[seenpix]),
        np.argmax(values[seenpix])
    ]]
    dMin, dMax = values[[pixMin, pixMax]]
    [[thMin, thMax],
     [phMin, phMax]] = np.rad2deg(precRot(hp.pix2ang(nside1,
                                                     [pixMin, pixMax])))

    if args.coords == 'C':
        while phMin < 0:
            phMin += 360

        while phMax < 0:
            phMax += 360

    th0, ph0 = precRot.I((90. - yC) * degree, xC * degree)
    pix0 = hp.ang2pix(nside1, th0, ph0)

    if isFlux:
        if hasFluxError:
            fluxerrMin, fluxerrMax, fluxerr0 = fluxerrmap[[
                pixMin, pixMax, pix0
            ]]
        else:
            fluxerrMin, fluxerrMax, fluxerr0 = [0, 0, 0]

        print "Flux units: TeV^-1 cm^-2 s^-1"
        print "Coord units: deg"
        print "Min:                 %11.2e +/- %11.2e (%6.2f, %5.2f)" % (
            dMin, fluxerrMin, phMin, 90 - thMin)
        print "Max:                 %11.2e +/- %11.2e (%6.2f, %5.2f)" % (
            dMax, fluxerrMax, phMax, 90 - thMax)
        print "Map value at origin: %11.2e +/- %11.2e" % (skymap[pix0],
                                                          fluxerr0)

    else:
        print("Min:                 %5.2f (%6.2f, %5.2f)" %
              (dMin, phMin, 90 - thMin))
        print("Max:                 %5.2f (%6.2f, %5.2f)" %
              (dMax, phMax, 90 - thMax))
        print("Map value at origin: %5.2f" % skymap[pix0])

    if args.onlystats:
        return 0

    figsize = (fysize * faspect + 2, fysize + 2.75)
    fig = plt.figure(num=1, figsize=figsize)

    # Set  min/max value of map
    if args.min is not None:
        dMin = args.min
        values[(skymap < dMin) & (values > hp.UNSEEN)] = dMin
    if args.max is not None:
        dMax = args.max
        values[(skymap > dMax) & (values > hp.UNSEEN)] = dMax

    textcolor, colormap = MapPalette.setupDefaultColormap(args.ncolors)

    # Use the Fermi/HESS/VERITAS purply-red-yellow color map
    if args.gamma:
        textcolor, colormap = MapPalette.setupGammaColormap(args.ncolors)

    # Use the Milagro color map
    if args.milagro:
        dMin = -5
        dMax = 15
        dMin = args.min if args.min != None else -5
        dMax = args.max if args.max != None else 15
        thresh = args.thresh if args.thresh != None else 2.
        textcolor, colormap = \
            MapPalette.setupMilagroColormap(dMin, dMax, thresh, args.ncolors)
        print("Milagro", dMin, dMax, thresh)
    # Use a thresholded grayscale map with colors for extreme values
    else:
        if args.thresh != None:
            textcolor, colormap = \
                MapPalette.setupThresholdColormap(dMin, dMax, args.thresh,
                                                args.ncolors)
        elif args.athresh != None:
            textcolor, colormap = \
                MapPalette.setupAbsThresholdColormap(dMin, dMax, args.athresh,
                                                    args.ncolors)

    if args.interpolation:
        cRot = hp.Rotator(rot=rotMap, coord=coords)
        phi = np.linspace(np.deg2rad(xmax), np.deg2rad(xmin), args.xsize)
        if xmin < 0 and xmax > 0 and (xmax - xmin) > 180.:
            phi = np.linspace(
                np.deg2rad(xmin) + 2. * np.pi, np.deg2rad(xmax), args.xsize)
            phi[(phi > 2. * np.pi)] -= 2. * np.pi
        theta = 0.5 * np.pi - np.linspace(np.deg2rad(ymin), np.deg2rad(ymax),
                                          args.xsize / faspect)
        Phi, Theta = np.meshgrid(phi, theta)
        rTheta,rPhi = cRot.I(Theta.reshape(phi.size*theta.size),\
                           Phi.reshape(phi.size*theta.size))
        rotimg = hp.get_interp_val(values, rTheta.reshape(Phi.shape),\
                                           rPhi.reshape(Theta.shape))
    else:
        tfig = plt.figure(num=2, figsize=figsize)
        rotimg = hp.cartview(values, fig=2,coord=coords,title="",\
                            cmap=colormap, cbar=False,\
                            lonra=[cxmin,cxmax],latra=[ymin,ymax],rot=rotMap,
                            notext=True, xsize=args.xsize,
                            return_projected_map=True)
        plt.close(tfig)

    ax = fig.add_subplot(111)
    ax.set_aspect(1.)

    # if plotting contours
    if args.contours != None:
        if args.contourmap:
            contourmap = args.contourmap
            contourmapcoord = args.contourmapcoord
        else:
            contourmap = args.fitsfile
            contourmapcoord = 'C'

        contourSkyMap, contourSkyMapHeader = hp.read_map(contourmap, h=True)
        fnside1 = hp.get_nside(contourSkyMap)
        ftoFind = 'TTYPE' + str(1)
        contourSkyMapName = dict(contourSkyMapHeader)[ftoFind]
        fvalues = np.ma.masked_where(contourSkyMap == 0, contourSkyMap)
        if args.interpolation:
            cRot = hp.Rotator(rot=rotMap, coord=[contourmapcoord, coords[-1]])
            phi = np.linspace(np.deg2rad(xmax), np.deg2rad(xmin), args.xsize)
            if xmin < 0 and xmax > 0 and (xmax - xmin) > 180.:
                phi = np.linspace(
                    np.deg2rad(xmin) + 2. * np.pi, np.deg2rad(xmax),
                    args.xsize)
                phi[(phi > 2. * np.pi)] -= 2. * np.pi
            theta = 0.5 * np.pi - np.linspace(
                np.deg2rad(ymin), np.deg2rad(ymax), args.xsize / faspect)
            Phi, Theta = np.meshgrid(phi, theta)
            rTheta,rPhi = cRot.I(Theta.reshape(phi.size*theta.size),\
                                Phi.reshape(phi.size*theta.size))
            frotimg = hp.get_interp_val(fvalues,rTheta.reshape(Phi.shape),\
                                        rPhi.reshape(Theta.shape))
        else:
            tfig = plt.figure(num=3, figsize=figsize)
            frotimg = hp.cartview(fvalues,
                                  fig=3,
                                  coord=[contourmapcoord, coords[-1]],
                                  title="",
                                  cmap=colormap,
                                  cbar=False,
                                  lonra=[xmin, xmax],
                                  latra=[ymin, ymax],
                                  rot=rotMap,
                                  notext=True,
                                  xsize=1000,
                                  min=dMin,
                                  max=dMax,
                                  return_projected_map=True)
            plt.close(tfig)

        if args.contours == []:
            rMaxSig2 = (fvalues[imgpix].max())**2
            if rMaxSig2 < 11.83:
                print "No spot detected with at least 95% confidence contour"
                contours = [-float("inf")]
            else:
                contours = [
                    sqrt(rMaxSig2 - 2.30),
                    sqrt(rMaxSig2 - 6.18),
                    sqrt(rMaxSig2 - 11.83)
                ]
        else:
            contours = args.contours

        ccolor = args.contourscolor or 'g'
        cstyle = args.contoursstyle or '-'
        cwidth = args.contourswidth or 2.
        print 'Contours style: ', ccolor, cstyle, cwidth

        contp = ax.contour(frotimg,
                           levels=contours,
                           colors=ccolor,
                           linestyles=cstyle,
                           linewidths=cwidth,
                           origin='upper',
                           extent=[cxmax, cxmin, ymax, ymin])

    rotimg[(rotimg > dMax)] = dMax
    rotimg[(rotimg < dMin)] = dMin
    if not args.nofill:
        imgp = ax.imshow(rotimg,extent=[cxmax, cxmin, ymax, ymin],\
                         vmin=dMin,vmax=dMax,cmap=colormap)

        imgp.get_cmap().set_under('w', alpha=0.)
        imgp.get_cmap().set_over('w', alpha=0.)

    # Draw grid lines
    xts = np.arange(np.floor(xmin), np.ceil(xmax + args.dmer), args.dmer)[1:-1]
    xtlbs = [
        '%g' % (xt + 360) if args.coords == 'C' and xt < 0 else '%g' % xt
        for xt in xts
    ]
    if xmin < 0. and xmax > 0. and (xmax - xmin) > 180.:
        xts = np.arange(np.floor(cxmin), np.ceil(cxmax + args.dmer),
                        args.dmer)[1:-1]
        xtlbs = []
        for xt in xts:
            cval = xt - 180.
            if xt < 0:
                cval = 180. + xt
            if cval == -180:
                cval = 180
            if args.isMoon or args.isSun:
                cval -= 180.
                if cval < -180.:
                    cval += 360.
            elif args.coords == 'C' and cval < 0:
                cval += 360

            xtlbs.append('%g' % (cval))
    yts = np.arange(np.floor(ymin), np.ceil(ymax + args.dpar), args.dpar)[1:-1]

    if args.nogrid == False:
        ax.grid(color=textcolor)
        ax.xaxis.set_ticks(xts)
        ax.xaxis.set_ticklabels(xtlbs)
        ax.yaxis.set_ticks(yts)

    if args.preliminary:
        plt.text((xmin + xmax) / 2.,
                 ymin + 0.85 * (ymax - ymin),
                 "PRELIMINARY",
                 color=textcolor,
                 alpha=0.8,
                 fontdict={
                     "family": "sans-serif",
                     "weight": "bold",
                     "size": 28
                 },
                 horizontalalignment='center')

    # If TeVCat data are available, plot them
    if args.tevcat or args.tevcatLabels:
        if haveTeVCat:
            try:
                if args.tevcat:
                    tevcat = TeVCat.TeVCat(args.tevcat)
                elif args.tevcatLabels:
                    tevcat = TeVCat.TeVCat(args.tevcatLabels)
            except IOError as e:
                print(e)
                print("Downloading data from tevcat.uchicago.edu")
                tevcat = TeVCat.TeVCat()
            except:
                print("Why caught here?")
                print("Downloading data from tevcat.uchicago.edu")
                tevcat = TeVCat.TeVCat()

            cRot = hp.Rotator(coord=["C", coords[-1]])
            tnside = 512
            fpix = np.zeros(hp.nside2npix(tnside))
            for cId in (1, 2):
                catalog = tevcat.GetCatalog(cId)
                ra = catalog.GetRA()
                dec = catalog.GetDec()
                assoc = catalog.GetCanonicalName()
                cut = (assoc != 'Crab Pulsar')
                ra = ra[cut]
                dec = dec[cut]
                assoc = assoc[cut]
                cpix = hp.ang2pix(tnside, np.pi * 0.5 - dec, ra)
                slpx = []
                for sx, px in enumerate(cpix):
                    fpix[px] += 1
                    if fpix[px] != 1:
                        print("%s is a duplicate" % (assoc[sx]))
                        slpx.append(sx)

                ra = np.delete(ra, slpx)
                dec = np.delete(dec, slpx)
                assoc = np.delete(assoc, slpx)
                y, x = cRot(np.pi * 0.5 - dec, ra)
                x = np.rad2deg(x) + frot
                x[(x > 180.)] -= 360.
                y = 90. - np.rad2deg(y)
                cut = (x > xmin) & (x < xmax) & (y > ymin) & (y < ymax)
                x = x[cut]
                y = y[cut]
                assoc = assoc[cut]
                ax.scatter(x,
                           y,
                           color=textcolor,
                           facecolors="none",
                           marker="s")

                if args.tevcatLabels:
                    for r, d, s in zip(x, y, assoc):
                        print(r, d, s)
                        ax.text(r,
                                d,
                                s + '   .',
                                color=textcolor,
                                rotation=args.catLabelsAngle,
                                fontdict={
                                    'family': 'sans-serif',
                                    'size': args.catLabelsSize,
                                    'weight': 'bold'
                                })
        else:
            print("Sorry, TeVCat could not be loaded.")

    # If Fermi data are available, plot them
    if args.fermicat:
        if haveFermi:
            fcat = None
            try:
                fcat = FGLCatalog.FGLCatalog(args.fermicat)
                aflag = fcat.GetAnalysisFlags()
                acut = (aflag == 0)  # cut analysis errors

                flux = fcat.GetFlux1000()  # 1-100 GeV flux
                dflx = fcat.GetFlux1000Error()  # flux uncertainty
                fcut = dflx / flux < 0.5  # cut poorly measured srcs

                cuts = np.logical_and(acut, fcut)
                print('Using FGL')
            except:
                try:
                    fcat = FHLCatalog.FHLCatalog(args.fermicat)
                    cuts = (fcat.GetFlux() > 0.)  # Dummy cut
                    print('Using FHL')
                except:
                    print('Fermi catalog could not be loaded!')
        if fcat != None:
            # Don't show TeV associations if plotting from TeVCat
            if args.tevcat or args.tevcatLabels:
                tcfg = fcat.GetTeVCatFlag()
                tcut = (tcfg == "N") | (tcfg == "C")
                cuts = np.logical_and(cuts, tcut)
            ra = fcat.GetRA()[cuts]
            dec = fcat.GetDec()[cuts]
            assoc = fcat.GetSourceName()[cuts]
            catnms = fcat.GetCatalogName()[cuts]
            for i in xrange(len(assoc)):
                if assoc[i] == '':
                    assoc[i] = catnms[i]

            cRot = hp.Rotator(coord=["C", coords[-1]])
            y, x = cRot(np.pi * 0.5 - dec, ra)
            x = np.rad2deg(x) + frot
            x[(x > 180.)] -= 360.
            y = 90. - np.rad2deg(y)
            cut = (x > xmin) & (x < xmax) & (y > ymin) & (y < ymax)
            x = x[cut]
            y = y[cut]
            assoc = assoc[cut]
            ax.scatter(x, y, color=textcolor, facecolors="none", marker="o")

            if args.fermicatLabels:
                for r, d, s in zip(x, y, assoc):
                    ax.text(r,
                            d,
                            s,
                            color=textcolor,
                            rotation=args.catLabelsAngle,
                            fontdict={
                                'family': 'sans-serif',
                                'size': args.catLabelsSize,
                                'weight': 'bold'
                            })
        else:
            print("Sorry, the Fermi xFGL catalog could not be loaded.")

    # If a hotspot list is given, plot it
    if args.hotspots:
        fhot = open(args.hotspots, "r")
        ra = []
        dec = []
        assoc = []
        for line in fhot:
            if line.startswith("#"):
                continue
            larr = line.strip().split()
            ra.append(float(larr[1]))
            dec.append(float(larr[2]))
            assoc.append(larr[4])

        ra = np.deg2rad(ra)
        dec = np.deg2rad(dec)
        assoc = np.array(assoc)
        cRot = hp.Rotator(coord=["C", coords[-1]])
        y, x = cRot(np.pi * 0.5 - dec, ra)
        x = np.rad2deg(x) + frot
        x[(x > 180.)] -= 360.
        y = 90. - np.rad2deg(y)
        cut = (x > xmin) & (x < xmax) & (y > ymin) & (y < ymax)
        x = x[cut]
        y = y[cut]
        assoc = assoc[cut]
        ax.scatter(x, y, color=textcolor, facecolors="none", marker="o")
        if args.hotspotLabels:
            for r, d, s in zip(x, y, assoc):
                print(r, d, s)
                ax.text(r,
                        d,
                        s + '   .',
                        color=textcolor,
                        rotation=90,
                        fontdict={
                            'family': 'sans-serif',
                            'size': 8,
                            'weight': 'bold'
                        })

    # If a gaussian fit file is given, plot it
    if args.gaussfit:
        gfit = open(args.gaussfit, "r")
        gfit.next()
        gfit.next()
        ra, raErr = [float(i) for i in gfit.next().strip().split()]
        dec, decErr = [float(i) for i in gfit.next().strip().split()]
        raW, raWErr = [float(i) for i in gfit.next().strip().split()]
        decW, decWErr = [float(i) for i in gfit.next().strip().split()]
        gfit.close()

        mrot = -180. if args.isMoon or args.isSun else 0.

        cRot = hp.Rotator(coord=["C", coords[-1]])
        y, x = cRot(np.pi * 0.5 - np.deg2rad(dec), np.deg2rad(ra + mrot))
        x = np.rad2deg(x) + frot
        x = x - 360. if x > 180. else x
        y = 90. - np.rad2deg(y)
        ellip0 = Ellipse((x, y),
                         width=2 * raW,
                         height=2 * decW,
                         edgecolor='black',
                         facecolor='None')
        ax.add_patch(ellip0)
        ax.scatter(x, y, s=20, color='black', facecolors="black", marker="o")

        print(x, y, xmin, xmax, ymin, ymax)
        ax.text(
            x - 1,
            y + 1,
            "%s=%.02f$\pm$%.02f\n$\Delta\delta$=%.02f$\pm$%.02f\n%s=%.02f$\pm$%.02f\n$\sigma_\delta$=%.02f$\pm$%.02f"
            % (r"$\Delta\alpha$", ra, raErr, dec, decErr, r"$\sigma_\alpha$",
               raW, raWErr, decW, decWErr),
            color=textcolor,
            rotation=0,
            fontdict={"size": 12})

    # Set up the color bar
    # Setup color tick marks
    if args.colorbar:
        cticks = args.ticks
        if args.ticks == None:
            if (dMax - dMin) > 3:
                clrmin = np.floor(dMin)
                clrmax = np.ceil(dMax)
                ctspc = np.round((clrmax - clrmin) / 10.)
                if ctspc == 0.:
                    ctspc = 1.
                if clrmin < 0 and clrmax > 0:
                    cticks = -np.arange(0, -clrmin, ctspc)
                    cticks = np.sort(
                        np.unique(
                            np.append(cticks, np.arange(0, clrmax, ctspc))))
                else:
                    cticks = np.arange(clrmin, clrmax + ctspc, ctspc)
            else:
                cticks = None

        cb = fig.colorbar(
            imgp,
            orientation="horizontal",
            shrink=0.85,
            fraction=0.1,
            #aspect=25,
            pad=0.1,
            ax=ax,
            ticks=cticks)

    if args.label:
        skymapName = args.label
    else:
        if re.match("significance", skymapName):
            skymapName = r"significance [$\sigma$]"
    if args.gumbel:
        skymapName = "log10(P-Value)"

    if args.colorbar:
        cb.set_label(skymapName)

    xlabel = r"$\alpha$ [$^\circ$]"
    ylabel = r"$\delta$ [$^\circ$]"

    # Set up the color bar and tick axis
    if args.coords == "G":
        xlabel = r"$l$ [$^\circ$]"
        ylabel = r"$b$ [$^\circ$]"
    if args.isMoon or args.isSun:
        xlabel = r"$\Delta\alpha$"
        ylabel = r"$\Delta\delta$"

    # X axis label
    ax.set_xlabel(xlabel, color='k')
    # Y axis label
    ax.set_ylabel(ylabel, color='k')

    # Title
    if args.title != None:
        ax.set_title(args.title.replace("\\n", "\n"), color='k')

    if args.cross:
        # Indicate the center of the plot with a thick black cross
        ax.scatter(xC,
                   yC,
                   s=20**2,
                   marker="+",
                   facecolor="#000000",
                   color="#000000")

    ax.set_ylim(ymin, ymax)
    ax.set_xlim(cxmax, cxmin)
    if args.squareaspect:
        plt.axes().set_aspect(1. / cos((ymax + ymin) / 2 * pi / 180))

    # Either output the image to a file and quit or plot it in a window
    if args.output:
        if not args.nofill:
            fig.savefig(args.output, dpi=300)
        else:
            fig.savefig(args.output, dpi=300, transparent=True)
    else:
        plt.show()

    from scipy.optimize import leastsq
    fitfunc = lambda p, x: p[0] * np.exp(-0.5 * ((x - p[1]) / p[2])**2) + p[3]
    errfunc = lambda p, x, y: (y - fitfunc(p, x))
    n, bins, patches = plt.hist(values[seenpix],
                                bins=int(np.sqrt(len(seenpix))),
                                label="Data")
    init = [1.0, 0.5, 0.5, 0.5]
    print(len(n), len(bins))
    out = leastsq(errfunc, init, args=(bins[:-1], n))
    c = out[0]
    print(c)
    plt.plot(bins[:-1], fitfunc(c, bins[:-1]), '--', label="Calculated")
    c[1] = 0.
    c[2] = 1.
    plt.plot(bins[:-1], fitfunc(c, bins[:-1]), '--', label="Expected")
    plt.xlabel("$\sqrt{TS}$")
    plt.legend()
    plt.savefig("TS_distribution.pdf")
    plt.savefig("TS_distribution.png")
    plt.savefig("TS_distribution.eps")
    plt.show()
Esempio n. 46
0
xmin, xmax = r[0, 0, 0, 0] * 100, r[-1, 0, 0, 0] * 100
ymin, ymax = r[0, 0, 0, 1] * 100, r[0, -1, 0, 1] * 100
fig = plt.figure(figsize=(10, 10))
ax = fig.gca()
plt.imshow(np.abs(P[0][:, :, np.int(np.floor(N / 2))].T),
           extent=[xmin, xmax, ymin, ymax],
           cmap=plt.cm.get_cmap('viridis'),
           interpolation='spline16')
# plt.imshow(np.abs(Mr[:, :, np.int(np.floor(N/2))].T),
#            extent=[xmin, xmax, ymin, ymax],
#            cmap=plt.cm.get_cmap('viridis'))#, interpolation='spline16')
plt.xlabel(r'$x$ (cm)')
plt.ylabel(r'$y$ (cm)')
ellipse = Ellipse((focus[0] * 100, focus[1] * 100),
                  2 * radius[0] * 100,
                  2 * radius[1] * 100,
                  linewidth=1,
                  fill=False,
                  zorder=2)
ax.add_patch(ellipse)
cbar = plt.colorbar()
cbar.ax.set_ylabel('Pressure (MPa)')
fig.savefig('results/H101_scatter.png')
plt.close()

# from matplotlib.patches import Ellipse
# fig = plt.figure()
# ax = fig.add_subplot(211, aspect='auto')
# # ax.fill(x, y, alpha=0.2, facecolor='yellow',
# #         edgecolor='yellow', linewidth=1, zorder=1)

# e1 = Ellipse((-0.5, -0.5), 0.2, .1,
    ax2.set_xlabel(r'Relative strength of inhibition $g$')
    ax2.set_ylabel(r'Relative strength of external drive $\eta$')

    ax3.set_xlabel('Generation')
    ax3.set_ylabel('Fitness')

    # raster plot
    ax1.plot(espikes['times'], espikes['senders'], ls='', marker='.')

    # search distributions and individuals
    for mu, sigma in zip(optimization_result['mu_history'],
                         optimization_result['sigma_history']):
        ellipse = Ellipse(xy=mu,
                          width=2 * sigma[0],
                          height=2 * sigma[1],
                          alpha=0.5,
                          fc='k')
        ellipse.set_clip_box(ax2.bbox)
        ax2.add_artist(ellipse)
    ax2.plot(optimization_result['mu_history'][:, 0],
             optimization_result['mu_history'][:, 1],
             marker='.',
             color='k',
             alpha=0.5)
    for generation in optimization_result['pop_history']:
        ax2.scatter(generation[:, 0], generation[:, 1])

    # fitness over generations
    ax3.errorbar(np.arange(len(optimization_result['fitness_history'])),
                 np.mean(optimization_result['fitness_history'], axis=1),
Esempio n. 48
0
ax1 = fig.add_subplot(131)
ax1.bar(range(1, 5), range(1, 5), color='red', edgecolor='black', hatch="/")
ax1.bar(range(1, 5), [6] * 4,
        bottom=range(1, 5),
        color='blue',
        edgecolor='black',
        hatch='//')
ax1.set_xticks([1.5, 2.5, 3.5, 4.5])

ax2 = fig.add_subplot(132)
bars = ax2.bar(range(1,5), range(1,5), color='yellow', ecolor='black') + \
    ax2.bar(range(1, 5), [6] * 4, bottom=range(1,5), color='green', ecolor='black')
ax2.set_xticks([1.5, 2.5, 3.5, 4.5])

patterns = ('-', '+', 'x', '\\', '*', 'o', 'O', '.')
for bar, pattern in zip(bars, patterns):
    bar.set_hatch(pattern)

ax3 = fig.add_subplot(133)
ax3.fill([1, 3, 3, 1], [1, 1, 2, 2], fill=False, hatch='\\')
ax3.add_patch(Ellipse((4, 1.5), 4, 0.5, fill=False, hatch='*'))
ax3.add_patch(
    Polygon([[0, 0], [4, 1.1], [6, 2.5], [2, 1.4]],
            closed=True,
            fill=False,
            hatch='/'))
ax3.set_xlim((0, 6))
ax3.set_ylim((0, 2.5))

plt.show()
Esempio n. 49
0
    def redraw(self):
        if self.YcomboBox.currentText() == self.XcomboBox.currentText():
            QtWidgets.QMessageBox.critical(
                self, 'Error', "You have to choose different parameters!",
                QtWidgets.QMessageBox.Ok)
            return ()
        res = FIT.getres()
        Mod = FIT.getmodel()
        p = FIT.getp()
        jac = FIT.getjac()
        fig = Figure()
        ax = fig.add_subplot(111)
        vcol = ['red'] * len(res)
        ind = range(1, len(res) + 1)
        ix = self.XcomboBox.currentIndex()
        iy = self.YcomboBox.currentIndex()
        if self.ellradioButton.isChecked():

            def eigsorted(cov):
                vals, vecs = np.linalg.eigh(cov)
                order = vals.argsort()[::-1]
                return vals[order], vecs[:, order]

            pos = (p[ix], p[iy])
            s2 = res.var()
            cov = np.linalg.inv(np.dot(jac.T, jac)) * s2
            cov = cov[np.ix_([ix, iy], [ix, iy])]
            vals, vecs = eigsorted(cov)
            theta = np.degrees(np.arctan2(*vecs[:, 0][::-1]))
            width, height = 2 * np.sqrt(vals)
            ellip = Ellipse(xy=pos,
                            width=width,
                            height=height,
                            angle=theta,
                            fill=False)
            ax.add_artist(ellip)
            ax.set_xlim([
                p[ix] - 4 * np.sqrt(cov[0, 0]), p[ix] + 4 * np.sqrt(cov[0, 0])
            ])
            ax.set_ylim([
                p[iy] - 4 * np.sqrt(cov[1, 1]), p[iy] + 4 * np.sqrt(cov[1, 1])
            ])
            ax.scatter(p[ix], p[iy], color='red', marker='o')
            ax.set_xlabel(self.XcomboBox.currentText())
            ax.set_ylabel(self.YcomboBox.currentText())
        elif self.resradioButton.isChecked():
            if self.CcheckBox.isChecked():
                vcol = DS.getCr()
            ax.hist(res, bins=10, orientation=u'horizontal', fc=(0, 0, 1, 0.5))
            ax.scatter(ind, res, color=vcol, marker='o')
            ax.set_ylabel('Residuals')
            ax.set_xlabel('Object Index')
            if self.VcheckBox.isChecked():
                for txt in enumerate(DS.getLr()):
                    ax.annotate(txt, (ind, res))
        elif self.surradioButton.isChecked():

            def fun(p1, p2):
                pi = p
                pi[ix] = p1
                pi[iy] = p2
                return sum((model(pi, x) - y)**2) / 2

            def model(p, x):
                if Mod == 0:
                    return p[0] * x**3 + p[1] * x**2 + p[2] * x + p[3]
                elif Mod == 1:
                    return p[0] * x**2 + p[1] * x + p[2]
                elif Mod == 2:
                    return p[0] * x + p[1]
                elif Mod == 3:
                    return p[0] * np.exp(p[1] * x)
                elif Mod == 4:
                    return p[0] * np.exp(p[1] / (p[2] + x))
                elif Mod == 5:
                    return p[0] * np.exp(-p[1] / x)
                elif Mod == 6:
                    return p[0] * np.log(p[1] * x)
                elif Mod == 7:
                    return p[0] * x**(p[1])
                elif Mod == 8:
                    return p[0] / (1 + p[1] * x)
                elif Mod == 9:
                    return p[0] / (1 + p[1] * x**2)
                elif Mod == 10:
                    return p[0] / (1 + np.exp(-p[1] * x))
                elif Mod == 11:
                    return p[0] * (x**2 + p[1] * x) / (x**2 + p[2] * x + p[3])

            fig = plt.figure()
            ax = fig.add_subplot(111)
            npts = 60
            s2 = res.var()
            x = FIT.getx()
            y = FIT.gety()
            cov = np.linalg.inv(np.dot(jac.T, jac)) * s2
            cov = cov[np.ix_([ix, iy], [ix, iy])]
            pcx = p[ix]
            pcy = p[iy]
            pxi = np.linspace(pcx - 4 * np.sqrt(cov[0, 0]),
                              pcx + 4 * np.sqrt(cov[0, 0]), npts)
            pyi = np.linspace(pcy - 4 * np.sqrt(cov[1, 1]),
                              pcy + 4 * np.sqrt(cov[1, 1]), npts)
            px = [pcx]
            py = [pcy]
            pz = [fun(pcx, pcy)]
            for i in range(npts):
                for j in range(npts):
                    px.append(pxi[i])
                    py.append(pyi[j])
                    pz.append(fun(pxi[i], pyi[j]))
            px = np.array(px)
            py = np.array(py)
            pz = np.array(pz)
            pzi = plt.mlab.griddata(px, py, pz, pxi, pyi, interp='linear')
            plt.contour(pxi, pyi, pzi, 15, linewidths=0.5, colors='k')
            plt.contourf(pxi, pyi, pzi, 15, cmap=plt.cm.rainbow)
            plt.colorbar()
            ax.scatter(pcx, pcy, color='red', marker='o')
            ax.set_xlabel(self.XcomboBox.currentText())
            ax.set_ylabel(self.YcomboBox.currentText())
            ax.set_xlim([px.min(), px.max()])
            ax.set_ylim([py.min(), py.max()])
        if self.XcheckBox.isChecked():
            if self.XlineEdit.text():
                ax.set_xlabel(self.XlineEdit.text())
        else:
            ax.set_xlabel('')
        if self.YcheckBox.isChecked():
            if self.YlineEdit.text():
                ax.set_ylabel(self.YlineEdit.text())
        else:
            ax.set_ylabel('')
        if self.XGcheckBox.isChecked():
            ax.xaxis.grid(True)
        if self.YGcheckBox.isChecked():
            ax.yaxis.grid(True)
        if self.TlineEdit.text():
            ax.set_title(self.TlineEdit.text())
        if not self.XMcheckBox.isChecked():
            ax.tick_params(axis='x',
                           which='both',
                           bottom='off',
                           top='off',
                           labelbottom='off')
        if not self.YMcheckBox.isChecked():
            ax.tick_params(axis='y',
                           which='both',
                           left='off',
                           right='off',
                           labelleft='off')
        self.rmmpl()
        self.addmpl(fig)
Esempio n. 50
0
def plot(means,
         sigmas,
         values,
         shape=None,
         axes=None,
         flip_y=None,
         alpha_global=1.0):
    """
    :param means:
    :param sigmas:
    :param values:
    :param shape:
    :param axes:
    :param flip_y: If not None, interpreted as the max y value. y values in the scatterplot are
            flipped so that the max is equal to zero and vice versa.
    :return:
    """

    b, n, d = means.size()

    means = means.data[0, :, :].cpu().numpy()
    sigmas = sigmas.data[0, :].cpu().numpy()
    values = nn.functional.tanh(values).data[0, :].cpu().numpy()

    if flip_y is not None:
        means[:, 0] = flip_y - means[:, 0]

    norm = mpl.colors.Normalize(vmin=-1.0, vmax=1.0)
    cmap = mpl.cm.RdYlBu
    map = mpl.cm.ScalarMappable(norm=norm, cmap=cmap)

    if axes is None:
        axes = plt.gca()

    colors = []
    for i in range(n):
        color = map.to_rgba(values[i])

        alpha = min(0.8, max(0.05, (
            (sigmas[i, 0] * sigmas[i, 0]) + 1.0)**-2)) * alpha_global
        axes.add_patch(
            Ellipse((means[i, 1], means[i, 0]),
                    width=sigmas[i, 1],
                    height=sigmas[i, 0],
                    color=color,
                    alpha=alpha,
                    linewidth=0))
        colors.append(color)

    axes.scatter(means[:, 1],
                 means[:, 0],
                 s=5,
                 c=colors,
                 zorder=100,
                 linewidth=0,
                 edgecolor='k',
                 alpha=alpha_global)

    if shape is not None:

        m = max(shape)
        step = 1 if m < 100 else m // 25

        # gray points for the integer index tuples
        x, y = np.mgrid[0:shape[0]:step, 0:shape[1]:step]
        axes.scatter(x.ravel(),
                     y.ravel(),
                     c='k',
                     s=5,
                     marker='D',
                     zorder=-100,
                     linewidth=0,
                     alpha=0.1 * alpha_global)

    axes.spines['right'].set_visible(False)
    axes.spines['top'].set_visible(False)
    axes.spines['bottom'].set_visible(False)
    axes.spines['left'].set_visible(False)
Esempio n. 51
0
    config = ConfigParser.SafeConfigParser()
    config.optionxform = str
    config.read(dataFile)

    param1, param2 = config.get('confEllipse', 'params').split(',')
    confLevel = config.getint('confEllipse', 'confLevel')
    angle = config.getfloat('confEllipse', 'angle')
    xcenter = config.getfloat('confEllipse', 'xcenter')
    ycenter = config.getfloat('confEllipse', 'ycenter')
    width = config.getfloat('confEllipse', 'width')
    height = config.getfloat('confEllipse', 'height')

    e = Ellipse((xcenter, ycenter),
                width,
                height,
                angle=angle,
                color=colors.next(),
                fill=False,
                label=dataLabel)
    ax.add_patch(e)
    ax.plot(xcenter, ycenter, 'r*')

    ax.set_xlabel(labels[param1], fontsize=fontsize)
    ax.set_ylabel(labels[param2], fontsize=fontsize)

# Hard coded again
ax.set_xlim([0.1185, 0.1210])
ax.set_ylim([-1.15, -0.85])

ax.set_title('Joint constraint (' + CL[confLevel] + ' CL) on ' +
             labels[param1] + ' and ' + labels[param2],
Esempio n. 52
0
Iscat = hdulist[0].data
hdr = hdulist[0].header
nx, ny = hdr['NAXIS1'], hdr['NAXIS2']
cellsize = 12.26 * 1e-3  # in arcseconds (based on IRDIS plate scale)
RA, DEC = np.meshgrid(cellsize*(np.arange(nx)-0.5*nx+0.5), \
                      cellsize*(np.arange(ny)-0.5*ny+0.5))
ext = (np.max(RA), np.min(RA), np.min(DEC), np.max(DEC))
norm = ImageNormalize(vmin=0, vmax=85, stretch=LinearStretch())
im = ax0.imshow(Iscat,
                origin='lower',
                cmap='afmhot',
                extent=ext,
                aspect='equal',
                norm=norm)
beam = Ellipse(
    (xlims[0] + 0.08 * np.diff(xlims), xlims[1] - 0.06 * np.diff(xlims)),
    0.037, 0.037, 0.)
beam.set_facecolor('w')
ax0.add_artist(beam)

# scale bar
barAU = 10.
xbarr = xlims[1] - 0.09 * np.diff(xlims)
xbarl = xbarr + barAU / 165.3
ybar = xlims[1] - 0.09 * np.diff(xlims)
ax0.plot([xbarr, xbarl], [ybar, ybar], '-w', lw=1)

xlims = [0.7, -0.7]
ylims = [-0.7, 0.7]
ax1 = fig.add_subplot(gs[0, 1])
ax1.set_xlim(xlims)
Esempio n. 53
0
def Fat_Vis(Fat, Fatp):
    #    if __name__ == "__main__":
    from matplotlib.patches import Ellipse
    el = Ellipse((0, 0), 10, 20, facecolor='r', alpha=0.5)
    ###==============Less charaterization==============####
    pos1 = 10
    pos2 = 20
    wd = [[pos1, pos1], [pos2, pos2]]
    plt.fill_between([2, 5], wd[0], wd[1], color=alizarin[7])
    plt.fill_between([6, 13], wd[0], wd[1], color=emerald[8])
    plt.fill_between([14, 17], wd[0], wd[1], color=green_sea[7])
    plt.fill_between([18, 24], wd[0], wd[1], color=turquoise[6])
    plt.fill_between([25, 35], wd[0], wd[1], color=orange[5])
    plt.fill_between([36, 60], wd[0], wd[1], color=pomegranate[8])

    sz = 12
    up = wd[0][0] + 11
    down = wd[0][0] - 2
    plt.annotate("2", xy=([2, down]), size=sz, weight='bold')
    plt.annotate("6", xy=([6, down]), size=sz, weight='bold')
    plt.annotate("14", xy=([14, down]), size=sz, weight='bold')
    plt.annotate("18", xy=([18, down]), size=sz, weight='bold')
    plt.annotate("25", xy=([25, down]), size=sz, weight='bold')
    plt.annotate("35", xy=([35, down]), size=sz, weight='bold')
    plt.annotate("50", xy=([50, down]), size=sz, weight='bold')

    plt.annotate('Current Body Fat: {}%'.format(Fat),
                 xy=(Fat, up + 2),
                 xycoords='data',
                 xytext=(-100, up + 20),
                 textcoords='offset points',
                 size=18,
                 va="center",
                 bbox=dict(boxstyle="round", fc=(0.7, 0.9, 1), ec="none"),
                 arrowprops=dict(arrowstyle="wedge,tail_width=1.",
                                 fc=(0.7, 0.9, 1),
                                 ec="none",
                                 patchA=None,
                                 patchB=el,
                                 relpos=(0.2, 0.5)))
    plt.annotate('After one year: {}%'.format(Fatp),
                 xy=(Fatp, down),
                 xycoords='data',
                 xytext=(-50, down - 80),
                 textcoords='offset points',
                 size=18,
                 va="bottom",
                 ha='left',
                 bbox=dict(boxstyle="round", fc=(0.9, 0.9, 0.9), ec="none"),
                 arrowprops=dict(arrowstyle="wedge,tail_width=1.",
                                 fc=(0.9, 0.9, 0.9),
                                 ec="none",
                                 patchA=None,
                                 patchB=el,
                                 relpos=(0.2, 0.5)))
    plt.plot(Fat, 21, 'v', color=(0.7, 0.9, 1), markersize=15, alpha=0.4)
    plt.plot(Fatp, 9, '^k', markersize=15, alpha=0.3)

    sz = 10.5
    plt.annotate("Essential",
                 xy=([3, 17.5]),
                 rotation=90,
                 color='w',
                 size=sz,
                 weight='bold')
    plt.annotate("Athlete",
                 xy=([9, 17]),
                 rotation=90,
                 color='w',
                 size=sz,
                 weight='bold')
    plt.annotate("Fitness",
                 xy=([15, 17]),
                 rotation=90,
                 color='w',
                 size=sz,
                 weight='bold')
    plt.annotate("Average",
                 xy=([21, 17]),
                 rotation=90,
                 color='w',
                 size=sz,
                 weight='bold')
    plt.annotate("Overweight",
                 xy=([29, 17.5]),
                 rotation=90,
                 color='w',
                 size=sz,
                 weight='bold')
    plt.annotate("Obese",
                 xy=([43, 15]),
                 rotation=90,
                 color='w',
                 size=sz,
                 weight='bold')

    plt.xlim([0, 60])
    plt.ylim([0, 35])
    plt.axis('off')

    plt.savefig("Body_Fat_Vis.jpeg", dpi=400, bbox_inches='tight')
    plt.show()
Esempio n. 54
0
ar = 3
#se definen las coordenadas de la Antena B
bx = d
by = 0
#se define la cobertura Antena B
br = 3
#se definen las coordenadas de la Antena C
cx = i
cy = j
#se define la cobertura de la Antena c
cr = 3
#grafica
fig = plt.figure()
a = fig.add_subplot(111, aspect='equal')
#################antena1#####################
e1 = Ellipse(xy=(ax, ay), width=ar*2, height=ar*2, angle=0)
e1.set_clip_box(a.bbox)
e1.set_color('green')
e1.set_alpha(0.1)
a.add_patch(e1)
a.annotate("Antena A",
               xy=(ax, ay), xycoords='data',
               xytext=(ax-6, ay+6), textcoords='data',
               arrowprops=dict(arrowstyle="->",
                               connectionstyle="arc3"), 
               )
a.plot(ax,ay, "g^", mew=2, ms=12)
a.add_artist(e1)
#####################antena2####################
e2 = Ellipse(xy=(bx, by), width=br*2, height=br*2, angle=0)
e2.set_clip_box(a.bbox)
Esempio n. 55
0
    def render(self, ctx):
        """
        Render the node.

        :param ctx:
            The :class:`_rendering_context` object.

        """
        # Get the axes and default plotting parameters from the rendering
        # context.
        ax = ctx.ax()

        # Resolve the plotting parameters.
        p = dict(self.plot_params)
        p["lw"] = _pop_multiple(p, ctx.line_width, "lw", "linewidth")

        p["ec"] = p["edgecolor"] = _pop_multiple(p, ctx.node_ec,
                                                 "ec", "edgecolor")

        p["fc"] = _pop_multiple(p, "none", "fc", "facecolor")
        fc = p["fc"]

        p["alpha"] = p.get("alpha", 1)

        # And the label parameters.
        if self.label_params is None:
            l = dict(ctx.label_params)
        else:
            l = dict(self.label_params)

        l["va"] = _pop_multiple(l, "center", "va", "verticalalignment")
        l["ha"] = _pop_multiple(l, "center", "ha", "horizontalalignment")

        # Deal with ``fixed`` nodes.
        scale = self.scale
        if self.fixed:
            # MAGIC: These magic numbers should depend on the grid/node units.
            self.offset[1] += 6

            l["va"] = "baseline"
            l.pop("verticalalignment", None)
            l.pop("ma", None)

            if p["fc"] == "none":
                p["fc"] = "k"

        diameter = ctx.node_unit * scale
        if self.aspect is not None:
            aspect = self.aspect
        else:
            aspect = ctx.aspect

        self.artistTree = Tree()
        # Set up an observed node. Note the fc INSANITY.
        if self.observed:
            # Update the plotting parameters depending on the style of
            # observed node.
            h = float(diameter)
            w = aspect * float(diameter)
            if ctx.observed_style == "shaded":
                p["fc"] = "0.7"
            elif ctx.observed_style == "outer":
                h = diameter + 0.1 * diameter
                w = aspect * diameter + 0.1 * diameter
            elif ctx.observed_style == "inner":
                h = diameter - 0.1 * diameter
                w = aspect * diameter - 0.1 * diameter
                p["fc"] = fc

            # Draw the background ellipse.
            bg = Ellipse(xy=ctx.convert(self.x, self.y),
                         width=w, height=h, **p)
            ax.add_artist(bg)
            self.artistTree.add_branch(bg)

            # Reset the face color.
            p["fc"] = fc

        # Draw the foreground ellipse.
        if ctx.observed_style == "inner" and not self.fixed:
            p["fc"] = "none"
        self.artistTree.root = Ellipse(xy=ctx.convert(self.x, self.y),
                     width=diameter * aspect, height=diameter, **p)
        ax.add_artist(self.artistTree.root)

        # Reset the face color.
        p["fc"] = fc

        # Annotate the node.
        an = ax.annotate(self.content, ctx.convert(self.x, self.y),
                    xycoords="data",
                    xytext=self.offset, textcoords="offset points",
                    **l)
        self.artistTree.add_branch(an)

        return self.artistTree
            axs[i, j].axis('off')
        else : 
            submat = np.ix_([j, i+1], [j, i+1])
            C1ii = np.linalg.inv(C3i[submat])
            C2ii = np.linalg.inv(C4i[submat])
#            C1ii = fish3[submat]
#            C2ii = fish2[submat]
            a = C1ii[0, 0]#
            b = 2*C1ii[0, 1]#A[1]
            c = C1ii[1, 1]#A[2]
            aux = np.sqrt((a-c)**2+b**2)
            aux2 = b**2-4*a*c
            ang = np.arctan((c-a-aux)/b)*180/np.pi
            w = -1/aux2*np.sqrt(-2*aux2*(a+c+aux))
            h = -1/aux2*np.sqrt(-2*aux2*(a+c-aux))
            ell1 = Ellipse((indx_c[j], indx_c[i+1]), w*1.52, h*1.52, ang, color = 'r', lw = 2., fill = False, linestyle = '--')
            ell2 = Ellipse((indx_c[j], indx_c[i+1]), w*2.48, h*2.48, ang, color = 'r', lw = 2., fill = False, linestyle = '--')
            a = C2ii[0, 0]#
            b = 2*C2ii[0, 1]#A[1]
            c = C2ii[1, 1]#A[2]
            aux = np.sqrt((a-c)**2+b**2)
            aux2 = b**2-4*a*c
            ang = np.arctan((c-a-aux)/b)*180/np.pi
            w = -1/aux2*np.sqrt(-2*aux2*(a+c+aux))
            h = -1/aux2*np.sqrt(-2*aux2*(a+c-aux))
            ell3 = Ellipse((indx_c[j], indx_c[i+1]), w*1.52, h*1.52, ang, alpha = 1)
            ell4 = Ellipse((indx_c[j], indx_c[i+1]), w*2.48, h*2.48, ang, alpha = 0.40) #linestyle = '--',                         
            axs[i, j].add_artist(ell3)
            axs[i, j].add_artist(ell4)
            axs[i, j].add_artist(ell1)
            axs[i, j].add_artist(ell2)
Esempio n. 57
0
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse

NUM = 250

ells = [
    Ellipse(xy=np.random.rand(2) * 10,
            width=np.random.rand(),
            height=np.random.rand(),
            angle=np.random.rand() * 360) for i in range(NUM)
]

fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
for e in ells:
    ax.add_artist(e)
    e.set_clip_box(ax.bbox)
    e.set_alpha(np.random.rand())
    e.set_facecolor(np.random.rand(3))

ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
plt.savefig("ellipse.png")
plt.show()
Esempio n. 58
0
    def __init__(self,
                 transform,
                 width,
                 height,
                 angle,
                 loc,
                 pad=0.1,
                 borderpad=0.1,
                 prop=None,
                 frameon=True,
                 **kwargs):
        """
        Draw an anchored ellipse of a given size.

        Parameters
        ----------
        transform : `matplotlib.transforms.Transform`
            The transformation object for the coordinate system in use, i.e.,
            :attr:`matplotlib.axes.Axes.transData`.

        width, height : int or float
            Width and height of the ellipse, given in coordinates of
            *transform*.

        angle : int or float
            Rotation of the ellipse, in degrees, anti-clockwise.

        loc : int
            Location of this size bar. Valid location codes are::

                'upper right'  : 1,
                'upper left'   : 2,
                'lower left'   : 3,
                'lower right'  : 4,
                'right'        : 5,
                'center left'  : 6,
                'center right' : 7,
                'lower center' : 8,
                'upper center' : 9,
                'center'       : 10

        pad : int or float, optional
            Padding around the ellipse, in fraction of the font size. Defaults
            to 0.1.

        borderpad : int or float, optional
            Border padding, in fraction of the font size. Defaults to 0.1.

        frameon : bool, optional
            If True, draw a box around the ellipse. Defaults to True.

        prop : `matplotlib.font_manager.FontProperties`, optional
            Font property used as a reference for paddings.

        **kwargs :
            Keyworded arguments to pass to
            :class:`matplotlib.offsetbox.AnchoredOffsetbox`.

        Attributes
        ----------
        ellipse : `matplotlib.patches.Ellipse`
            Ellipse patch drawn.
        """
        self._box = AuxTransformBox(transform)
        self.ellipse = Ellipse((0, 0), width, height, angle)
        self._box.add_artist(self.ellipse)

        AnchoredOffsetbox.__init__(self,
                                   loc,
                                   pad=pad,
                                   borderpad=borderpad,
                                   child=self._box,
                                   prop=prop,
                                   frameon=frameon,
                                   **kwargs)
Esempio n. 59
0
def plot_ellipses(m_res, l_res, w_res, al_res, m_prior, l_prior, w_prior, al_prior, m_meas, l_meas, w_meas, al_meas,
                  m_gt, l_gt, w_gt, al_gt, name, filename, est_color='red'):
    """
    Plot the estimated, prior, measured, and ground truth ellipses and save the plot
    :param m_res:       Center of estimated ellipse
    :param l_res:       Semi-axis length of estimated ellipse
    :param w_res:       Semi-axis width of estimated ellipse
    :param al_res:      Orientation of estimated ellipse
    :param m_prior:     Center of prior ellipse
    :param l_prior:     Semi-axis length of prior ellipse
    :param w_prior:     Semi-axis width of prior ellipse
    :param al_prior:    Orientation of prior ellipse
    :param m_meas:      Center of measured ellipse
    :param l_meas:      Semi-axis length of measured ellipse
    :param w_meas:      Semi-axis width of measured ellipse
    :param al_meas:     Orientation of measured ellipse
    :param m_gt:        Center of ground truth ellipse
    :param l_gt:        Semi-axis length of ground truth ellipse
    :param w_gt:        Semi-axis width of ground truth ellipse
    :param al_gt:       Orientation of ground truth ellipse
    :param name:        Name of the approach
    :param filename:    Name of the file the plot is to be saved in
    :param est_color:   Color for plotting the estimated ellipse
    """
    fig, ax = plt.subplots(1, 1)

    el_gt = Ellipse((m_gt[0], m_gt[1]), 2 * l_gt, 2 * w_gt, np.rad2deg(al_gt), fill=True, linewidth=2.0)
    el_gt.set_alpha(0.7)
    el_gt.set_fc('grey')
    el_gt.set_ec('grey')
    ax.add_artist(el_gt)

    ela_final = Ellipse((m_prior[0], m_prior[1]), 2 * l_prior, 2 * w_prior, np.rad2deg(al_prior), fill=False,
                        linewidth=2.0)
    ela_final.set_alpha(0.7)
    ela_final.set_ec('mediumpurple')
    ax.add_artist(ela_final)

    elb_final = Ellipse((m_meas[0], m_meas[1]), 2 * l_meas, 2 * w_meas, np.rad2deg(al_meas), fill=False, linewidth=2.0)
    elb_final.set_alpha(0.7)
    elb_final.set_ec('darkturquoise')
    ax.add_artist(elb_final)

    el_res = Ellipse((m_res[0], m_res[1]), 2 * l_res, 2 * w_res, np.rad2deg(al_res), fill=False, linewidth=2.0)
    el_res.set_alpha(0.9)
    el_res.set_ec(est_color)
    ax.add_artist(el_res)

    plt.axis([-10, 10, -10, 10])
    ax.set_aspect('equal')
    ax.set_title(name)
    plt.xlabel('x in m')
    plt.ylabel('y in m')
    plt.savefig(filename)
    plt.show()
Esempio n. 60
0
def plot_covariance_ellipse(mean,
                            cov=None,
                            variance=1.0,
                            std=None,
                            ellipse=None,
                            title=None,
                            axis_equal=True,
                            facecolor='none',
                            edgecolor='#004080',
                            alpha=1.0,
                            xlim=None,
                            ylim=None):
    """ plots the covariance ellipse where

    mean is a (x,y) tuple for the mean of the covariance (center of ellipse)

    cov is a 2x2 covariance matrix.

    variance is the normal sigma^2 that we want to plot. If list-like,
    ellipses for all ellipses will be ploted. E.g. [1,2] will plot the
    sigma^2 = 1 and sigma^2 = 2 ellipses.

    ellipse is a (angle,width,height) tuple containing the angle in radians,
    and width and height radii.

    You may provide either cov or ellipse, but not both.

    plt.show() is not called, allowing you to plot multiple things on the
    same figure.
    """

    assert cov is None or ellipse is None
    assert not (cov is None and ellipse is None)

    if cov is not None:
        ellipse = covariance_ellipse(cov)

    if axis_equal:
        plt.axis('equal')

    if title is not None:
        plt.title(title)

    compute_std = False
    if std is None:
        std = variance
        compute_std = True

    if np.isscalar(std):
        std = [std]

    if compute_std:
        std = np.sqrt(np.asarray(std))

    ax = plt.gca()

    angle = np.degrees(ellipse[0])
    width = ellipse[1] * 2.
    height = ellipse[2] * 2.

    for sd in std:
        e = Ellipse(xy=mean,
                    width=sd * width,
                    height=sd * height,
                    angle=angle,
                    facecolor=facecolor,
                    edgecolor=edgecolor,
                    alpha=alpha,
                    lw=2)
        ax.add_patch(e)
    plt.scatter(mean[0], mean[1], marker='+')  # mark the center
    if xlim is not None:
        ax.set_xlim(xlim)

    if ylim is not None:
        ax.set_ylim(ylim)