Exemplo n.º 1
0
def test_radar_view():
	lats=linspace(-13.0, -11.5, 40)
	lons=linspace(130., 132., 40)
	ber_loc=[-12.4, 130.85] #location of Berrimah radar
	gp_loc=[-12.2492,  131.0444]#location of CPOL at Gunn Point
	h=2.5*1000.0
	t0=systime()
	i_a, j_a, k_a=propigation.unit_vector_grid(lats, lons, h, gp_loc)
	print "unit_vector_compute took ", systime()-t0, " seconds"
	fw=0.1#degrees
	m_bump=5.0
	#b1=simul_winds.speed_bump(lats, lons, [-12.0, 131.0], fw)*m_bump
	#b2=-1.0*simul_winds.speed_bump(lats, lons, [-12.0, 131.1], fw)*m_bump
	u,v=simul_winds.unif_wind(lats, lons, 5.0, 75.0)
	up,vp=array(simul_winds.vortex(lats, lons,  [-12.5, 131.1], fw))*m_bump
	#up=u+(b1-b2)
	#vp=v-(b1-b2)
	w=v*0.0
	v_r=i_a*(up+u)+j_a*(vp+v)+k_a*w
	f=figure()
	mapobj=pres.generate_darwin_plot()
	pres.contour_vr(mapobj,lats, lons, v_r)
	savefig(os.getenv('HOME')+'/bom_mds/output/test_radar_view_gp.png')
	close(f)
	f=figure()
	mapobj=pres.generate_darwin_plot()
	pres.quiver_contour_winds(mapobj, lats, lons, (up+u),(vp+v))
	savefig(os.getenv('HOME')+'/bom_mds/output/test_pert2.png')
	close(f)
Exemplo n.º 2
0
def test():
	figure(figsize=(6,12))
	t = linspace(0, 1, 1001)
	y = sin(2*pi*t*6) + sin(2*pi*t*10) + sin(2*pi*t*13)
	subplot(311)
	plot(t, y, 'b-')
	xlabel("TIME (sec)")
	ylabel("SIGNAL MAGNITUDE")
	# compute FFT and plot the magnitude spectrum
	F = fft(y)
	N = len(t)             # number of samples
	dt = 0.001             # inter-sample time difference
	w = fftfreq(N, dt)     # gives us a list of frequencies for the FFT
	ipos = where(w>0)
	freqs = w[ipos]        # only look at positive frequencies
	mags = abs(F[ipos])    # magnitude spectrum
	subplot(312)
	plot(freqs, mags, 'b-')
	ylabel("POWER")
	subplot(313)
	plot(freqs, mags, 'b-')
	xlim([0, 50])          # replot but zoom in on freqs 0-50 Hz
	ylabel("POWER")
	xlabel("FREQUENCY (Hz)")
	savefig("signal_3freqs.jpg", dpi=150)
Exemplo n.º 3
0
def show_dct_fig():
    figure(figsize=(12,7))
    for u in range(8):
        subplot(2, 4, u+1)
        ylim((-1, 1))
        title(str(u))
        plot(arange(0,8,0.1), dct0[u, :])
        plot(dct[u, :],'ro')
Exemplo n.º 4
0
def test_gracon():
	#setup
	noise_level=0.0#m/s
	nx=40
	ny=40
	fw=0.1
	m_bump=10.00
	t0=systime()
	lats=linspace(-13.5, -12.0, 40)
	lons=linspace(130.5, 131.5, 40)
	ber_loc=[-12.4, 130.85] #location of Berrimah radar
	gp_loc=[-12.2492,  131.0444]#location of CPOL at Gunn Point
	h=2.5*1000.0
	print 'calculating berimah UV', systime()-t0
	i_ber, j_ber, k_ber=propigation.unit_vector_grid(lats, lons, h, ber_loc)
	print 'calculating gp UV', systime()-t0
	i_gp, j_gp, k_gp=propigation.unit_vector_grid(lats, lons, h, gp_loc)
	#make winds
	u,v=simul_winds.unif_wind(lats, lons, 10.0, 75.0)
	up,vp=array(simul_winds.vortex(lats, lons,  [-12.5, 131.1], fw))*m_bump
	#make V_r measurements
	vr_ber=i_ber*(up+u)+j_ber*(vp+v) + (random.random([nx,ny])-0.5)*(noise_level*2.0)
	vr_gp=i_gp*(up+u)+j_gp*(vp+v)+ (random.random([nx,ny])-0.5)*(noise_level*2.0)
	#try to reconstruct the wind field
	igu, igv= simul_winds.unif_wind(lats, lons, 0.0, 90.0)
	gv_u=zeros(u.shape)
	gv_v=zeros(v.shape)
	f=0.0
	print igu.mean()
	
	angs=array(propigation.make_lobe_grid(ber_loc, gp_loc, lats,lons))
	wts=zeros(angs.shape, dtype=float)+1.0
	#for i in range(angs.shape[0]):
	#	for j in range(angs.shape[1]):
	#		if (angs[i,j] < 150.0) and (angs[i,j] > 30.0): wts[i,j]=1.0
	print 'Into fortran'
	gv_u,gv_v,f,u_array,v_array = gracon_vel2d.gracon_vel2d(gv_u,gv_v,f,igu,igv,i_ber,j_ber,i_gp,j_gp,vr_ber,vr_gp,wts, nx=nx,ny=ny)
	print u_array.mean()
	print f
	bnds=[0.,20.]
	f=figure()
	mapobj=pres.generate_darwin_plot()
	pres.quiver_contour_winds(mapobj, lats, lons, (up+u),(vp+v), bounds=bnds)
	savefig(os.getenv('HOME')+'/bom_mds/output/orig_winds_clean.png')
	close(f)
	f=figure()
	mapobj=pres.generate_darwin_plot()
	pres.quiver_contour_winds(mapobj, lats, lons, (wts*u_array +0.001),(wts*v_array +0.001), bounds=bnds)
	savefig(os.getenv('HOME')+'/bom_mds/output/recon_winds_clean.png')
	close(f)
	f=figure()
	mapobj=pres.generate_darwin_plot()
	pres.quiver_contour_winds(mapobj, lats, lons, (wts*u_array - (up+u)),(wts*v_array -(vp+v)))
	savefig(os.getenv('HOME')+'/bom_mds/output/errors_clean.png')
	close(f)
Exemplo n.º 5
0
def generate_plot(array, vmin, vmax, figNumber=1):
    plt.figure(figNumber)
    plt.subplot(2,3,i)
    print i
    plt.imshow(array, vmin = vmin, vmax= vmax, interpolation = None) 
    plt.xlabel('Sample')
    plt.ylabel('Line')
    plt.title(row[0])
    cb = plt.colorbar(orientation='hor', spacing='prop',ticks = [vmin,vmax],format = '%.2f')
    cb.set_label('Reflectance / cos({0:.2f})'.format(incAnglerad*180.0/math.pi))
    plt.grid(True)
Exemplo n.º 6
0
	def plot_f_score(self, disag_filename):
		plt.figure()
		from nilmtk.metrics import f1_score
		disag = DataSet(disag_filename)
		disag_elec = disag.buildings[building].elec
		f1 = f1_score(disag_elec, test_elec)
		f1.index = disag_elec.get_labels(f1.index)
		f1.plot(kind='barh')
		plt.ylabel('appliance');
		plt.xlabel('f-score');
		plt.title(type(self.model).__name__);
Exemplo n.º 7
0
def plotSolutions(x,states=None): #Default func values is trivial

    plt.figure(figsize=(11,8.5))

    #get the exact values
    f = open('exact_results.txt', 'r')
    x_e = []
    u_e = []
    p_e = []
    rho_e = []
    e_e = []
    for line in f:
        if len(line.split())==1:
            t = line.split()
        else:
            data = line.split()
            x_e.append(float(data[0]))
            u_e.append(float(data[1]))
            p_e.append(float(data[2]))
            rho_e.append(float(data[4]))
            e_e.append(float(data[3]))


    if states==None:
        raise ValueError("Need to pass in states")
    else:
        u = []
        p = []
        rho = []
        e = []
        for i in states:
            u.append(i.u)
            p.append(i.p)
            rho.append(i.rho)
            e.append(i.e)

    #get edge values
    x_cent = [0.5*(x[i]+x[i+1]) for i in range(len(x)-1)]
    
    if u != None:
        plot2D(x_cent,u,"$u$",x_ex=x_e,y_ex=u_e)
    
    if rho != None:
        plot2D(x_cent,rho,r"$\rho$",x_ex=x_e,y_ex=rho_e) 

    if p != None:
        plot2D(x_cent,p,r"$p$",x_ex=x_e,y_ex=p_e)

    if e != None:
        plot2D(x_cent,e,r"$e$",x_ex=x_e,y_ex=e_e)

    plt.show(block=False) #show all plots generated to this point
    raw_input("Press anything to continue...")
    plot2D.fig_num=0
Exemplo n.º 8
0
 def plot(self, output):
     plt.figure(figsize=output.fsize, dpi=output.dpi)
     for ii in range(0, len(self.v)):
         imsize = [self.t[0], self.t[-1], self.x[ii][-1], self.x[ii][0]]
         lim = amax(absolute(self.v[ii])) / output.scale_sat
         plt.imshow(self.v[ii], extent=imsize, vmin=-lim, vmax=lim, cmap=cm.gray, origin='upper', aspect='auto')
         plt.title("%s-Velocity for Trace #%i" % (self.comp.upper(), ii))
         plt.xlabel('Time (s)')
         plt.ylabel('Offset (km)')
         #plt.colorbar()
         plt.savefig("Trace_%i_v%s.pdf" % (ii, self.comp))
         plt.clf()
Exemplo n.º 9
0
def compress_kmeans(im, k=4):
    height, width, depth = im.shape

    data = im.reshape((height * width, depth))
    labels, centers = kmeans(data, k, 1e-2)
    rep = closest(data, centers)
    data_compressed = centers[rep]

    im_compressed = data_compressed.reshape((height, width, depth))
    plt.figure()
    plt.imshow(im_compressed)
    plt.show()
Exemplo n.º 10
0
def plotCentroidFitDiagnostic(img, hdr, ccdMod, ccdOut, res, prfObj):
    """Some diagnostic plots showing the performance of fitPrfCentroid()

    Inputs:
    -------------
    img
        (np 2d array) Image of star to be fit. Image is in the
        format img[row, col]. img should not contain Nans

    hdr
        (Fits header object) header associated with the TPF file the
        image was drawn from

    ccdMod, ccdOut
        (int) CCD module and output of image. Needed to
        create the correct PRF model

    prfObj
        An object of the class prf.KeplerPrf()


    Returns:
    -------------
    **None**

    Output:
    ----------
    A three panel subplot is created
    """
    mp.figure(1)
    mp.clf()
    mp.subplot(131)
    plotTpf.plotCadence(img, hdr)
    mp.colorbar()
    mp.title("Input Image")

    mp.subplot(132)
    c,r = res.x[0], res.x[1]
    bbox = getBoundingBoxForImage(img, hdr)
    model = prfObj.getPrfForBbox(ccdMod, ccdOut, c, r, bbox)
    model *= res.x[2]
    plotTpf.plotCadence(model, hdr)
    mp.colorbar()
    mp.title("Best fit model")

    mp.subplot(133)
    diff = img-model
    plotTpf.plotCadence(diff, hdr)
    mp.colorbar()
    mp.title("Residuals")

    print "Performance %.3f" %(np.max(np.abs(diff))/np.max(img))
def plot_confusion_matrix(cm, labels, title='Confusion matrix', cmap=plt.cm.Blues, save=False):
    plt.figure()
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(labels))
    plt.xticks(tick_marks, labels, rotation=45)
    plt.yticks(tick_marks, labels)
    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.show()
    if save:
        plt.savefig(save)
def get_trajectories_for_DF(DF):
    GetXYS=ct.get_xys(DF)
    xys_s=ct.get_xys_s(GetXYS['xys'],GetXYS['Nmin'])
    plt.figure(figsize=(5, 5),frameon=False)
    for m in list(range(9)):
        plt.plot()
        plt.subplot(3,3,m+1)
        xys_s_x_n=xys_s[m]['X']-min(xys_s[m]['X'])
        xys_s_y_n=xys_s[m]['Y']-min(xys_s[m]['Y'])
        plt.plot(xys_s_x_n,xys_s_y_n)
        plt.axis('off')
        axes = plt.gca()
        axes.set_ylim([0,125])
        axes.set_xlim([0,125])
Exemplo n.º 13
0
def plotRetinaSpikes(retina=None, label=""):
    
    assert retina is not None, "Network is not initialised! Visualising failed."
    import matplotlib.pyplot as plt
    from matplotlib import animation
    
    print "Visualising {0} Spikes...".format(label) 

    spikes = [x.getSpikes() for x in retina]
#     print spikes
    
    sortedSpikes = sortSpikes(spikes)
#     print sortedSpikes
    
    framesOfSpikes = generateFrames(sortedSpikes)
#     print framesOfSpikes
    
    x = range(0, dimensionRetinaX)
    y = range(0, dimensionRetinaY)
    from numpy import meshgrid
    rows, pixels = meshgrid(x,y)
    
    fig = plt.figure()
    
    initialData = createInitialisingData()
    
    imNet = plt.imshow(initialData, cmap='green', interpolation='none', origin='upper')
    
    plt.xticks(range(0, dimensionRetinaX)) 
    plt.yticks(range(0, dimensionRetinaY))
    args = (framesOfSpikes, imNet)
    anim = animation.FuncAnimation(fig, animate, fargs=args, frames=int(simulationTime)*10, interval=30)
          
    plt.show()
def get_trajectories_singleAxis_for_DF(DF):
    from random import randint
    sns.set_palette(sns.color_palette("Paired"))
    fig = plt.figure(figsize=(5, 5),frameon=False)
    ax=fig.add_subplot(1, 1, 1)
    ax.spines['left'].set_position('zero')
    ax.spines['right'].set_color('none')
    ax.spines['bottom'].set_position('zero')
    ax.spines['top'].set_color('none')
    #ax.spines['left'].set_smart_bounds(True)
    #ax.spines['bottom'].set_smart_bounds(True)
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')
    ax.set_ylim([-300,300])
    ax.set_xlim([-300,300])
    ticklab = ax.xaxis.get_ticklabels()[0]
    ax.xaxis.set_label_coords(300, -40,transform=ticklab.get_transform())
    ax.set_xlabel('x($\mu$m)',fontsize=14)
    ticklab = ax.yaxis.get_ticklabels()[0]
    ax.yaxis.set_label_coords(90, 280,transform=ticklab.get_transform())
    ax.set_ylabel('y($\mu$m)',rotation=0,fontsize=14)
    
    
    GetXYS=ct.get_xys(DF)
    xys_s=ct.get_xys_s(GetXYS['xys'],GetXYS['Nmin'])
    for n in list(range(12)):
        m=randint(0,len(xys_s))-1
        xys_s_x_n=xys_s[m]['X']-(xys_s[m]['X'][xys_s[m]['X'].index[0]])
        xys_s_y_n=xys_s[m]['Y']-(xys_s[m]['Y'][xys_s[m]['X'].index[0]])
        xys_s_x_n=[x*(100/(60.)) for x in xys_s_x_n]
        xys_s_y_n=[x*(100/(60.)) for x in xys_s_y_n]
        ax.plot(xys_s_x_n,xys_s_y_n)
    return fig
Exemplo n.º 15
0
def plot_images(header):
    ''' function to plot images from header.

    It plots images, return nothing
    Parameters
    ----------
        header : databroker header object
            header pulled out from central file system
    '''
    # prepare header
    if type(list(headers)[1]) == str:
        header_list = list()
        header_list.append(headers)
    else:
        header_list = headers

    for header in header_list:
        uid = header.start.uid
        img_field = _identify_image_field(header)
        imgs = np.array(get_images(header, img_field))
        print('Plotting your data now...')
        for i in range(imgs.shape[0]):
            img = imgs[i]
            plot_title = '_'.join(uid, str(i))
            # just display user uid and index of this image
            try:
                fig = plt.figure(plot_title)
                plt.imshow(img)
                plt.show()
            except:
                pass # allow matplotlib to crash without stopping other function
Exemplo n.º 16
0
def showScatterPlot(data, labels, idx1, idx2): 
    import matplotlib.pyplot as plt 
    fig = plt.figure() 
    ax = fig.add_subplot(111) 
    # X-axis data, Y-axis data, Size for each sample, Color for each sample 
    ax.scatter(data[:,idx1], data[:,idx2], 100.0*(1 + np.array(labels)), 100.0*(1 + np.array(labels))) 
    plt.show()
Exemplo n.º 17
0
def plotColorCodedNetworkSpikes(network):
    assert network is not None, "Network is not initialised! Visualising failed."
    import matplotlib as plt
    from NetworkBuilder import sameDisparityInd
    
    cellsOutSortedByDisp = []
    spikes = []
    for disp in range(0, maxDisparity+1):
        cellsOutSortedByDisp.append([network[x][2] for x in sameDisparityInd[disp]])
        spikes.append([x.getSpikes() for x in cellsOutSortedByDisp[disp]])
    
    sortedSpikes = sortSpikesByColor(spikes)
    print sortedSpikes
    framesOfSpikes = generateColoredFrames(sortedSpikes)
    print framesOfSpikes
    
    fig = plt.figure()
    
    initialData = createInitialisingDataColoredPlot()
    
    imNet = plt.imshow(initialData[0], c=initialData[1], cmap=plt.cm.coolwarm, interpolation='none', origin='upper')
    
    plt.xticks(range(0, dimensionRetinaX)) 
    plt.yticks(range(0, dimensionRetinaY))
    plt.title("Disparity Map {0}".format(disparity))
    args = (framesOfSpikes, imNet)
    anim = animation.FuncAnimation(fig, animate, fargs=args, frames=int(simulationTime)*10, interval=30)
          
    plt.show()
Exemplo n.º 18
0
def showScatterPlot(data, idx1, idx2): 
    import matplotlib.pyplot as plt 
    fig = plt.figure() 
    ax = fig.add_subplot(111) 
    
    # X-axis data, Y-axis data, Size for each sample, Color for each sample 
    ax.scatter(data[:,idx1], data[:,idx2]) 
    plt.show()
Exemplo n.º 19
0
def simple_reconstruction_3d_pytest(tim, lvl_str, use_guess):
	lvl=int(lvl_str)
	ber, gp=netcdf_utis.load_cube('/bm/gdata/scollis/cube_data/20060122_'+tim+'_ver_hr_big.nc')
	print gp['levs'][lvl]
	Re=6371.0*1000.0
	rad_at_radar=Re*sin(pi/2.0 -abs(gp['zero_loc'][0]*pi/180.0))#ax_radius(float(lat_cpol), units='degrees')
	lons=gp['zero_loc'][1]+360.0*gp['xar']/(rad_at_radar*2.0*pi)
	lats=gp['zero_loc'][0] + 360.0*gp['yar']/(Re*2.0*pi)	
	ber_loc=[-12.457, 130.925]
	gp_loc=	 [-12.2492,  131.0444]
	if use_guess=='none':
		igu=ones(ber['CZ'].shape, dtype=float)*0.0
		igv=ones(ber['CZ'].shape, dtype=float)*0.0
	else:
		ber_ig, gp_ig=netcdf_utis.load_cube(use_guess)
		print gp_ig.keys()
		igu=gp_ig['u_array']
		igv=gp_ig['v_array']
	mywts=ones(ber['CZ'].shape, dtype=float)
	angs=array(propigation.make_lobe_grid(ber_loc, gp_loc, lats,lons))
	wts_ang=zeros(gp['CZ'][:,:,0].shape, dtype=float)
	for i in range(angs.shape[0]):
			for j in range(angs.shape[1]):
				if (angs[i,j] < 150.0) and (angs[i,j] > 30.0): wts_ang[i,j]=1.0
	for lvl_num in range(len(gp['levs'])):
		#create a weighting grid
		mask_reflect=10.0#dBZ	
		mask=(gp['CZ'][:,:,lvl_num]/mask_reflect).round().clip(min=0., max=1.0) 
		mask_vel_ber=(ber['VR'][:,:,lvl_num]+100.).clip(min=0., max=1.)
		mywts[:,:,lvl_num]=mask*mask_vel_ber*wts_ang	
	f=0.0
	gv_u=zeros(ber['CZ'].shape, dtype=float)
	gv_v=zeros(ber['CZ'].shape, dtype=float)
	wts=mask*mask_vel_ber*wts_ang
	gu,gv,f= grad_conj_solver_plus_plus.meas_cost(gv_u, gv_v, f, igu, igv, ber['i_comp'], ber['j_comp'], gp['i_comp'], gp['j_comp'],  ber['VR'], gp['VR'], mywts)
	print "Mean U gradient", gu.mean(), "gv mean", gv.mean(), "F ", f
	for i in range(len(gp['levs'])):
		print "U,V ", (igu[:,:,i]).sum()/mywts[:,:,i].sum(), (igv[:,:,i]).sum()/mywts[:,:,i].sum()
		#gv_u,gv_v,cost = vel_2d_cost(gv_u,gv_v,cost,u_array,v_array,i_cmpt_r1,j_cmpt_r1,i_cmpt_r2,j_cmpt_r2,vr1,vr2,weights,nx=shape(gv_u,0),ny=shape(gv_u,1))
      		print gracon_vel2d.vel_2d_cost(gv_u[:,:,i]*0.0,gv_v[:,:,i]*0.0,0.0,igu[:,:,i],igv[:,:,i],ber['i_comp'][:,:,i], ber['j_comp'][:,:,i], gp['i_comp'][:,:,i], gp['j_comp'][:,:,i],  ber['VR'][:,:,i], gp['VR'][:,:,i],mywts[:,:,i])[2]
	gv_u,gv_v,f,u_array,v_array = grad_conj_solver_plus_plus.gracon_vel2d_3d( gv_u, gv_v, f, igu, igv, ber['i_comp'], ber['j_comp'], gp['i_comp'], gp['j_comp'], ber['VR'], gp['VR'], mywts)#, nx=nx, ny=ny, nz=nz)
	gp.update({'u_array': u_array, 'v_array':v_array})
	netcdf_utis.save_data_cube(ber, gp, '/bm/gdata/scollis/cube_data/20060122_'+tim+'_winds_ver1.nc', gp['zero_loc'])
	plotit=True
	if plotit:
		for lvl in range(len(gp['levs'])):
			print lvl
			f=figure()
			mapobj=pres.generate_darwin_plot(box=[130.8, 131.2, -12.4, -12.0])
			diff=gp['VR']-(u_array*gp['i_comp']+ v_array*gp['j_comp'])
			gp.update({'diff':diff})
			pres.reconstruction_plot(mapobj, lats, lons, gp, lvl, 'diff',u_array[:,:,lvl],v_array[:,:,lvl], angs, mywts[:,:,lvl])
			#pres.quiver_contour_winds(mapobj, lats, lons, (wts*u_array).clip(min=-50, max=50),(wts*v_array).clip(min=-50, max=50))
			t1='Gunn Point CAPPI (dBZ) and reconstructed winds (m/s) at %(lev)05dm \n 22/01/06 ' %{'lev':gp['levs'][lvl]}
			title(t1+tim) 
			ff=os.getenv('HOME')+'/bom_mds/output/recons_22012006/real_%(lev)05d_' %{'lev':gp['levs'][lvl]}
			savefig(ff+tim+'_2d_3d.png')
			close(f)	
Exemplo n.º 20
0
def plot_roc_curve(fpr, tpr, roc_auc, title='ROC curve'):
    plt.figure()
    lw = 2
    colors = cycle(['darkorange', 'blue', 'red', 'green', 'black', 'purple',
                   'yellow'])
    for i, color in zip(range(len(fpr), colors)):
        plt.plot(fpr[i], tpr[i], color=color, lw=lw,
                 label='ROC area {0:.4f}'.format(roc_auc[i]))
    # plt.plot(fpr, tpr, color='darkorange', lw=lw,
    #          label='ROC area under curve = {}'.format(roc_auc))
    plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.title(title)
    plt.xlabel('False positive rate')
    plt.ylabel('True positive rate')
    plt.legend(loc='lower right')
    plt.show()
Exemplo n.º 21
0
def draw_bar(savename):
    import matplotlib.pyplot as plt
    size = 3
    x = np.arange(size)
    a = [34.89, 33.87, 72.37]
    b = [551.72, 552.87, 698.34]
    xl = ['training time \n on MNIST', 'training time on \n Fashion-MNIST', 'training time \n on CIFAR-10']
    total_width, n = 0.54, 2
    width = total_width / n
    x = x - (total_width - width)
    plt.figure()
    plt.bar(x, a, width=width)
    plt.bar(x + width, b, width=width)
    plt.ylabel('time(s)')
    plt.xticks(x, xl,)
    plt.legend()
    plt.savefig('../eps/' + savename)
    plt.show()
Exemplo n.º 22
0
def sh2(data):
    dpi = 80.0
    xpixels, ypixels = data.shape[::-1]
    margin = 0.05
    figsize = (1 + margin) * ypixels / dpi, (1 + margin) * xpixels / dpi
    fig = plt.figure(figsize=figsize, dpi=dpi)
    ax = fig.add_axes([margin, margin, 1 - 2 * margin, 1 - 2 * margin])
    ax.imshow(data, interpolation='none')
    plt.show()
Exemplo n.º 23
0
def plot_df(
    df1, plot_title, x_axis, y_axis, plot, save
):  # function for plotting high-dimension and low-dimension eigenvalues
    y1 = df1[df1.columns[1]]
    x1 = df1[df1.columns[0]]
    plt.figure(figsize=(8, 8))
    plt.plot(x1, y1, color='red')
    plt.grid(color='black', linestyle='-',
             linewidth=0.1)  # parameters for plot grid
    plt.title(plot_title).set_position([0.5, 1.05])
    plt.xlabel(x_axis)
    plt.ylabel(y_axis)
    plt.legend(loc='best')  # creating legend and placing in at the top right
    if save == 'yes':
        plt.savefig(plot_title)
    if plot == 'yes':
        plt.show()
    plt.close()
Exemplo n.º 24
0
def plot_probability_distributions(pmfs, lcolors, tam=[15, 7]):
    fig = plt.figure(figsize=tam)
    ax = fig.add_subplot(111)

    for k, m in enumerate(pmfs, start=0):
        m.plot(ax, color=lcolors[k])

    handles0, labels0 = ax.get_legend_handles_labels()
    ax.legend(handles0, labels0)
Exemplo n.º 25
0
def test_uniform_winds():
	f=figure()
	lats=linspace(-13.0, -11.5, 20)
	lons=linspace(130., 132., 20)
	u,v=simul_winds.unif_wind(lats, lons, 10.0, 45.0)
	mapobj=pres.generate_darwin_plot()
	pres.quiver_winds(mapobj, lats, lons, u,v)
	savefig(os.getenv('HOME')+'/bom_mds/output/test_uniform.png')
	close(f)
Exemplo n.º 26
0
def plot(tf_confidence, num_groundtruthbox):
    """
    从上到下截取tf_confidence, 计算并画图
    :param tf_confidence: np.array, 存放所有检测框对应的tp或fp和置信度
    :param num_groundtruthbox: int, 标注框的总数
    """
    fp_list = []
    recall_list = []
    precision_list = []
    auc = 0
    mAP = 0
    for num in range(len(tf_confidence)):
        arr = tf_confidence[:(num + 1), 0]  # 截取, 注意要加1
        tp = np.sum(arr)
        fp = np.sum(arr == 0)
        recall = tp / num_groundtruthbox
        precision = tp / (tp + fp)
        auc = auc + recall
        mAP = mAP + precision

        fp_list.append(fp)
        recall_list.append(recall)
        precision_list.append(precision)

    auc = auc / len(fp_list)
    mAP = mAP * max(recall_list) / len(recall_list)

    plt.figure()
    plt.title('ROC')
    plt.xlabel('False Positives')
    plt.ylabel('True Positive rate')
    plt.ylim(0, 1)
    plt.plot(fp_list, recall_list, label='AUC: ' + str(auc))
    plt.legend()

    plt.figure()
    plt.title('Precision-Recall')
    plt.xlabel('Recall')
    plt.ylabel('Precision')
    plt.axis([0, 1, 0, 1])
    plt.plot(recall_list, precision_list, label='mAP: ' + str(mAP))
    plt.legend()

    plt.show()
Exemplo n.º 27
0
def log_transform(data, columns, plot=True, figsize=(12, 6)):
    '''
    Nomralizes the dataset to be as close to the gaussian distribution.

    Parameter:
    -----------------------------------------
    data: DataFrame, Series.

        Data to Log transform.

    columns: List, Series

        Columns to be transformed to normality using log transformation
    
    plot: bool, default True

        Plots a before and after log transformation plot
    
    Returns:

        Log-transformed dataframe
    '''

    if data is None:
        raise ValueError(
            "data: Expecting a DataFrame/ numpy2d array, got 'None'")

    if columns is None:
        raise ValueError(
            "columns: Expecting at least a column in the list of columns but got 'None'"
        )

    df = data.copy()
    for col in columns:
        df[col] = np.log1p(df[col])

    if plot:
        for col in columns:
            _ = plt.figure(figsize=figsize)
            plt.subplot(1, 2, 1)
            sns.distplot(data[col],
                         color="m",
                         label="Skewness : %.2f" % (df[col].skew()))
            plt.title('Distribution of ' + col + " before Log transformation")
            plt.legend(loc='best')

            plt.subplot(1, 2, 2)
            sns.distplot(df[col],
                         color="m",
                         label="Skewness : %.2f" % (df[col].skew()))
            plt.title('Distribution of ' + col + " after Log transformation")
            plt.legend(loc='best')
            plt.tight_layout(2)
            plt.show()

    return df
Exemplo n.º 28
0
            def plottrace(self, point):
                # 使用matplotlib之pyplot绘制船舶轨迹
                # point = 38
                def initial(ax):
                    ax.axis("equal")  #设置图像显示的时候XY轴比例
                    ax.set_xlabel('Horizontal Position')
                    ax.set_ylabel('Vertical Position')
                    ax.set_title('Vessel trajectory')
                    plt.grid(True)  #添加网格
                    return ax

                es_time = np.zeros([point])
                fig = plt.figure()
                ax = fig.add_subplot(1, 1, 1)
                ax = initial(ax)

                # test
                ax2 = fig.add_subplot(1, 1, 1)
                ax2 = initial(ax2)

                plt.ion()  #interactive mode on 动态绘制

                # IniObsX=0000
                # IniObsY=4000
                # IniObsAngle=135
                # IniObsSpeed=10*math.sqrt(2)   #米/秒
                # print('开始仿真')
                obsX = []
                obsX2 = []
                # obsY = [4000,]
                obsY = []
                obsY2 = []
                for t in range(point):
                    # t0 = time.time()
                    #障碍物船只轨迹
                    # obsX.append(IniObsX+IniObsSpeed*math.sin(IniObsAngle/180*math.pi)*t)
                    obsX.append(sim_res.SHIP1POS[t][0])
                    obsX2.append(sim_res.SHIP2POS[t][0])
                    # obsY.append(IniObsY+IniObsSpeed*math.cos(IniObsAngle/180*math.pi)*t)
                    obsY.append(sim_res.SHIP1POS[t][1])
                    obsY2.append(sim_res.SHIP2POS[t][1])
                    plt.cla()
                    ax = initial(ax)
                    ax.plot(obsX, obsY, '-g', marker='*')  #散点图

                    # test
                    ax2 = initial(ax2)
                    ax2.plot(obsX2, obsY2, '-r', marker='o')
                    risk_value_text = 'Risk value: ' + str(
                        sim_res.RISKVALUE[t])
                    plt.text(0, 7, risk_value_text)
                    plt.pause(0.5)
                    # es_time[t] = 1000*(time.time() - t0)
                plt.pause(0)
                # return es_time
                pass
Exemplo n.º 29
0
def save_image(image, filename):
    fig = plt.figure()
    fig.set_size_inches(image.shape)
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)
    ax.imshow(image, cmap='gray')

    if DEBUG_enable_write:
        plt.savefig(filename)
Exemplo n.º 30
0
 def plotNNFilter(units):
     filters = 3
     fig = plt.figure(1, figsize=(20, 20))
     n_columns = 6
     n_rows = math.ceil(filters / n_columns) + 1
     for i in range(filters):
         plt.subplot(n_rows, n_columns, i + 1)
         plt.title('Filter ' + str(i))
         plt.imshow(units[0, :, :, i], interpolation="nearest", cmap="gray")
     plt.savefig('/Users/raghav/Documents/Uni/oc-nn/models/representation_sigmoid_dog.png')
Exemplo n.º 31
0
def plot_roc(y_true: List[str], y_score: List[float]) -> None:
    """Plot a ROC curve for these results"""

    fpr, tpr, threshold = roc_curve(y_true, y_score, pos_label="target")
    fnr = 1 - tpr
    EER = fpr[np.nanargmin(np.absolute((fnr - fpr)))]
    print("EER: {}%".format(EER * 100))

    plt.figure()
    lw = 2
    plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve')
    plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver operating characteristic example')
    plt.legend(loc="lower right")
    plt.show()
Exemplo n.º 32
0
def drawTKY():
    """
    Function plots 10 most popular Venue Categories in Tokyo.
    """
    #Import dataset of New York from root directory
    TKY = pd.read_csv('dataset_TSMC2014_TKY.csv')

    TKY=TKY[["venueCategory","venueCategoryId"]]
    grouped2=TKY.groupby(["venueCategory"]).count()
    grouped2=grouped2.sort_values('venueCategoryId')
    grouped2=grouped2[237:247]
    
    #Plot bars of most popular venue categories
    plt.figure(figsize=(16,6))
    plt.style.use('fivethirtyeight')
    plt.bar(grouped2.index,grouped2["venueCategoryId"])
    plt.title("10 Most Popular Venue Categories \n Tokyo: 2012-2013",fontsize=14,color='black')
    plt.ylabel("Check-ins per Venue Category",fontsize=14)
    plt.show()
Exemplo n.º 33
0
def plot_results_multiple(predicted_data, true_data, prediction_len):
    fig = plt.figure(facecolor='white')
    ax = fig.add_subplot(111)
    ax.plot(true_data, label='True Data')
    # Pad the list of predictions to shift it in the graph to it's correct start
    for i, data in enumerate(predicted_data):
        padding = [None for p in range(i * prediction_len)]
        plt.plot(padding + data, label='Prediction')
        plt.legend()
    plt.show()
Exemplo n.º 34
0
def show3d(coords):
    global iterator, color
    fig = plt.figure(int(iterator))
    ax = fig.gca(projection='3d')
    ax.plot(coords[0], coords[1], coords[2], color="b")
    ax.plot([coords[0][-1]], [coords[1][-1]], [coords[2][-1]], 'ro')
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')
    iterator += 1
def plot_stats(training_stats,
               val_stats,
               x_label='Training Steps',
               stats='loss'):
    stats, x_label = stats.title(), x_label.title()
    legend_loc = 'upper right' if stats == 'loss' else 'lower right'
    training_steps = len(training_stats)
    test_steps = len(val_stats)

    plt.figure()
    plt.ylabel(stats)
    plt.xlabel(x_label)
    plt.plot(training_stats, label='Training ' + stats)
    plt.plot(np.linspace(0, training_steps, test_steps),
             val_stats,
             label='Validation ' + stats)
    plt.ylim([0, max(plt.ylim())])
    plt.legend(loc=legend_loc)
    plt.show()
Exemplo n.º 36
0
def drawNYC():
    """
    Function plots 10 most popular Venue Categories in New York.
    """
    #Import dataset of New York from root directory
    NYC = pd.read_csv('dataset_TSMC2014_NYC.csv')

    NYC=NYC[["venueCategory","venueCategoryId"]]
    grouped=NYC.groupby(["venueCategory"]).count()
    grouped=grouped.sort_values('venueCategoryId')
    grouped=grouped[241:251]
    
    #Plot bars of most popular venue categories
    plt.figure(figsize=(16,6))
    plt.style.use('fivethirtyeight')
    plt.bar(grouped.index,grouped["venueCategoryId"])
    plt.title("10 Most Popular Venue Categories \n New York: 2012-2013",fontsize=14,color='black')
    plt.ylabel("Check-ins per Venue Category",fontsize=14)
    plt.show()
Exemplo n.º 37
0
 def __save(self,n,plot,sfile):
     p.figure(figsize=sfile)
     p.xlabel(plot.xlabel)
     p.ylabel(plot.ylabel)
     p.xscale(plot.xscale)
     p.yscale(plot.yscale)
     p.grid()
     for curve in plot.curves: 
         if curve[1] == None: p.plot(curve[0],curve[2], label=curve[3])
         else: p.plot(curve[0],  curve[1], curve[2], label=curve[3])
     p.rc('legend', fontsize='small')
     p.legend(shadow=0, loc='best')
     p.axes().set_aspect(plot.aspect)
     if not plot.dir: plot.dir = './plots/'
     if not plot.name: plot.name = self.__global_name+'_%0*i'%(2,n)
     if not os.path.isdir(plot.dir): os.mkdir(plot.dir)
     if plot.pgf: p.savefig(plot.dir+plot.name+'.pgf')
     else: p.savefig(plot.dir+plot.name+'.pdf', bbox_inches='tight')
     p.close()
Exemplo n.º 38
0
    def __init__(self):
        super(CDataMingQtUi, self).__init__()
        self.setupUi(self)

        #CARgraphview 是一个QGraphicView的实例
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.graph_sence = CARscene()
        self.graph_sence.addWidget(self.canvas)
        self.CARgraphview.setScene(self.graph_sence)
 def plot_rewards(self):
     plt.figure(1)
     plt.clf()
     plt.title('Training...')
     plt.xlabel('Time')
     plt.ylabel('Reward')
     cumulative = []
     for i in range(len(self.rewards[self.n_training])):
         if i == 0:
             cumulative.append(self.rewards[self.n_training][i])
         else:
             cumulative.append(self.rewards[self.n_training][i] +
                               cumulative[-1])
     x = np.linspace(2.0,
                     len(self.rewards[self.n_training]),
                     num=len(self.rewards[self.n_training]))
     plt.plot(x, cumulative)
     plt.show()
     plt.pause(0.001)  # pause a bit so that plots are updated
Exemplo n.º 40
0
def sns_pair_plot_fb(target, var_list, file, redshift, fb):
	'''
	pair plot for fixed broadening parameter
	'''

	sns.set_style("white")
	sns.set_style("ticks")
	sns.set_context("talk")

	data = pd.read_pickle(file)
	
	plt.figure()

	data_f = {}

	for var in var_list:
		if var in ['NTOTH2', 'TEMP']:
			data_f[var] = data[var][0]
		if var == 'A_Z':
			data_f[var] = data[var][0]/100000.0 + redshift

	df = pd.DataFrame(data_f)

	g = sns.PairGrid(df) #, diag_kws=dict(color="blue", shade=True))
	g.map_upper(sns.kdeplot, cmap="bone_r",n_levels=10,shade=True,
		shade_lowest=False)
	g.map_lower(sns.kdeplot, cmap="bone_r",n_levels=10,shade=True,
		shade_lowest=False)
	g.map_diag(plt.hist) #, lw=2);
	
	#g.axes[0,0].set_ylim(redshift-0.0002,redshift+0.00005)
	g.axes[0,0].set_ylabel(r"$z$")
	g.axes[1,0].set_ylabel(r"$N(H_2)$")
	#g.axes[2,0].set_ylabel(r"$N(HI)$")
	g.axes[2,0].set_ylabel(r"$T$")

	#g.axes[3,0].set_xlim(redshift-0.0002,redshift+0.00005)
	g.axes[2,0].set_xlabel(r"$z$")
	g.axes[2,1].set_xlabel(r"$N(H_2)$")
	#g.axes[3,2].set_xlabel(r"$N(HI)$")
	g.axes[2,2].set_xlabel(r"$T$")

	g.savefig(target+"_b_"+str(fb)+"_H2_pairplot.pdf")
Exemplo n.º 41
0
def plotSolutions(x,
                  u=None,
                  rho=None,
                  p=None,
                  e=None):  #Default func values is trivial

    plt.figure(figsize=(11, 8.5))

    #get edge values
    x_edge = [0.5 * (x[i] + x[i + 1]) for i in range(len(x) - 1)]

    #get the exact values
    f = open('exact_results.txt', 'r')
    x_e = []
    u_e = []
    p_e = []
    rho_e = []
    e_e = []
    for line in f:
        if len(line.split()) == 1:
            t = line.split()
        else:
            data = line.split()
            x_e.append(float(data[0]))
            u_e.append(float(data[1]))
            p_e.append(float(data[2]))
            rho_e.append(float(data[4]))
            e_e.append(float(data[3]))

    if u != None:
        plot2D(x, u, x_e, u_e, "$u$")

    if rho != None:
        plot2D(x_edge, rho, x_e, rho_e, r"$\rho$")

    if p != None:
        plot2D(x_edge, p, x_e, p_e, r"$p$")

    if e != None:
        plot2D(x_edge, e, x_e, e_e, r"$e$")

    plt.show(block=False)  #show all plots generated to this point
    raw_input("Press anything to continue...")
Exemplo n.º 42
0
def sns_velo_pair_plot(target, line, file, nvoigts):

	sns.set_style("darkgrid")
	#sns.set_style("ticks")
	#sns.set_context("talk")

	for i in np.arange(1, nvoigts + 1, 1):

		data = pd.read_pickle(file)
		plt.figure()

		data_f = {}

		for key in data:
			if key.startswith(("v0", "N", "b")) and key.endswith(str(i)):
				data_f[key] = data[key][0]
			#if key in ["a", "a1", "a2"]:
			#	data_f[key] = data[key][0]
		
		df = pd.DataFrame(data_f)
		#g = sns.pairplot(df, diag_kind="kde")

		g = sns.PairGrid(df) #, diag_kws=dict(color="blue", shade=True))
		g.map_upper(sns.kdeplot, cmap="bone_r",n_levels=10,shade=True,
			shade_lowest=False)
		g.map_lower(sns.kdeplot, cmap="bone_r",n_levels=10,shade=True,
			shade_lowest=False)
		#g.map_diag(sns.kdeplot, lw=2);
		g.map_diag(plt.hist, alpha=0.8)

		plt.subplots_adjust(hspace=0.1, wspace=0.1)

		g.axes[0,0].set_ylabel(r"$\mathrm{log} N\, ({\rm cm}^{-2})$")
		g.axes[1,0].set_ylabel(r"$b\, {\rm (km/s)}$")
		g.axes[2,0].set_ylabel(r"$v_0\, {\rm (km/s)}$")

		g.axes[2,0].set_xlabel(r"$\mathrm{log} N\, ({\rm cm}^{-2})$")
		g.axes[2,1].set_xlabel(r"$b\, {\rm (km/s)}$")
		g.axes[2,2].set_xlabel(r"$v_0\, {\rm (km/s)}$")


		g.savefig(target+"_"+str(nvoigts)+"_"+str(i)+"_"+str(line)+"_"+"v.pdf")
Exemplo n.º 43
0
def print_for_test():
    f = h5py.File("lex-chocolate-1min.hdf5")
    ar = f.values()
    npar = np.array(ar)
    x1 = np.linspace(0, len(npar[0]), num=len(npar[0]))

    wavFile = wave.open("lex-chocolate-1min.wav")
    (nchannels, sampwidth, framerate, nframes, comptype, compname) = wavFile.getparams()
    frames = wavFile.readframes(-1)
    data = np.fromstring(frames, "Int16")
    x2 = np.linspace(0, len(data), num=len(data))

    f1 = plt.figure(1)
    plt.plot(x1*160, npar[0]*max(data), x2, data);
    f1.show()

    xA = np.linspace(0, len(A), num=len(A))
    f2 = plt.figure(2)
    plt.plot(xA*160/16000, A*max(data), x2/16000, data);
    f2.show()
Exemplo n.º 44
0
def show_signature(img_path, fignum=1):
    print('Showing signature: '+img_path)
    img = plt.imread(join(imgdir, img_path))
    sig_img = sliding_window_signature(img)
    fig = plt.figure(fignum)
    ax1 = fig.add_subplot(1,2,1)
    ax2 = fig.add_subplot(1,2,2)
    ax1.imshow(img)
    ax2.imshow(sig_img)
    fig.show()
    fig.canvas.draw()
def print_save_all_mean_faces(x_class_mean,global_mean,show,save):
	rows = 4
	cols = 14
	index = 1
	font_size = 10
	plt.figure(figsize=(20,10))
	plt.subplot(rows,cols,index), plt.imshow(np.reshape(global_mean,(46,56)).T, cmap = 'gist_gray')
	title = str("Global Mean")
	plt.title(title, fontsize=font_size).set_position([0.5,0.95]), plt.xticks([]), plt.yticks([])
	index=index+1
	for i in range(0,x_class_mean.shape[1]):
		title = str("Class Mean "+str(i+1))
		plt.subplot(rows,cols,index), plt.imshow(np.reshape(x_class_mean[:,i],(46,56)).T, cmap = 'gist_gray')
		plt.title(title, fontsize=font_size).set_position([0.5,0.95]), plt.xticks([]), plt.yticks([])
		index = index+1
	if show == 'yes':
		plt.show()
	if save == 'yes':
		plt.savefig('Global and Class Mean')
	plt.close()
def plot_top_M_fisherfaces(eigenvec,M,Mpca,mode):
	if mode == 'None':
		return None
	cols = 10
	rows = M/cols
	index = 1
	font_size = 10
	plt.figure(figsize=(20,20))
	for i in range(0,M):
		plt.subplot(rows,cols,index),plt.imshow(np.reshape(eigenvec[:,i],(46,56)).T, cmap = 'gist_gray')
		face_title = str("M="+str(i+1))
		plt.title(face_title, fontsize=font_size).set_position([0.5,1.05]), plt.xticks([]), plt.yticks([])	# set_position([a,b]) adjust b for height
		index = index+1
	if mode == 'show':
		plt.show()
		plt.close()
	if mode == 'save':
		title = str("Top 50 Fisherfaces for Mpca="+str(Mpca))
		plt.savefig(title)
		plt.close()
Exemplo n.º 47
0
def sunSat_plot(saturday_mean, sunday_mean, df):
    plt.figure()

    # declaring values to be plotted
    xs = [1, 2]
    ys = [saturday_mean, sunday_mean]

    # setting range
    xrng = np.arange(len(xs))
    yrng = np.arange(0, max(ys)+50, 50)

    # making bar chart and alligning items properly
    plt.bar(xrng, ys, 0.45, align="center") 

    # labeling
    plt.xticks(xrng, ["Saturday", "Sunday"])
    plt.yticks(yrng)

    plt.grid(True)
    plt.show()
Exemplo n.º 48
0
def visual_importnance(X, forest):
    importances = forest.feature_importances_
    std = np.std([tree.feature_importances_ for tree in forest.estimators_],
                 axis=0)
    indices = np.argsort(importances)[::-1]

    # Print the feature ranking
    print("Feature ranking:")

    for f in range(X.shape[1]):
        print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))

    # Plot the feature importances of the forest
    plt.figure()
    plt.title("Feature importances")
    plt.bar(range(X.shape[1]), importances[indices],
            color="r", yerr=std[indices], align="center")
    plt.xticks(range(X.shape[1]), indices)
    plt.xlim([-1, X.shape[1]])
    plt.show()
Exemplo n.º 49
0
def show_signature(img_path, fignum=1):
    print('Showing signature: ' + img_path)
    img = plt.imread(join(imgdir, img_path))
    sig_img = sliding_window_signature(img)
    fig = plt.figure(fignum)
    ax1 = fig.add_subplot(1, 2, 1)
    ax2 = fig.add_subplot(1, 2, 2)
    ax1.imshow(img)
    ax2.imshow(sig_img)
    fig.show()
    fig.canvas.draw()
Exemplo n.º 50
0
def fit_background(q,I):
    
    ## Working on background calculation
    ## mkak 2016.09.28
    
    x = q
    y = I
    pfit = np.polyfit(x,y,4)
    yfit = np.polyval(pfit,x)
    #panel.plot(xrd_spectra[0], xrd_spectra[1]-yfit, label='no bkg')
    #panel.plot(xrd_spectra[0], yfit, color='blue', label='bkg')
    
    ### calculation works, but plotting here wipes previous plots - only shows last
    import matplotlib as plt
    plt.figure()
    plt.plot(x,y,label='raw data')
    plt.plot(x,yfit,label='background')
    plt.plot(x,y-yfit,label='background subtracted')
    plt.legend()
    plt.show()
Exemplo n.º 51
0
def show3d_kalman_vs_ema(coordsK, coordsEMA):
    global iterator, color
    fig = plt.figure(int(iterator))
    ax = fig.gca(projection='3d')
    ax.plot(coordsK[0], coordsK[1], coordsK[2], color="b")
    ax.plot(coordsEMA[0], coordsEMA[1], coordsEMA[2], color="r")
    ax.plot([coordsK[0][-1]], [coordsK[1][-1]], [coordsK[2][-1]], 'ro')
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')
    iterator += 1
Exemplo n.º 52
0
def plot_sample(x, title="", width=28, fName=None):
    fig = plt.figure()
    sample = x.reshape(width, width)
    # interploation can be 'nearest' to put grid at the center the pixels
    plt.imshow(sample, interpolation='None', cmap='gray')
    plt.title(title)
    plt.xticks([])
    plt.yticks([])
    if fName != None:
        savefig(fName, bbox_inches='tight')
    plt.show()
Exemplo n.º 53
0
def show_image(image, grayscale=True, ax=None, title=''):
    if ax is None:
        plt.figure()
    plt.axis('off')

    if len(image.shape) == 2 or grayscale == True:
        if len(image.shape) == 3:
            image = np.sum(np.abs(image), axis=2)

        vmax = np.percentile(image, 99)
        vmin = np.min(image)

        plt.imshow(image, cmap=plt.cm.gray, vmin=vmin, vmax=vmax)
        plt.title(title)
    else:
        image = image + 127.5
        image = image.astype('uint8')

        plt.imshow(image)
        plt.title(title)
Exemplo n.º 54
0
def plot_confusion_matrix(cm, classes,
    normalize=False, title='Confusion matrix',
    cmap=plt.cm.Blues, filename='viz\\confusion_matrix.png'):
  plt.figure()
  plt.imshow(cm, interpolation='nearest', cmap=cmap)
  plt.title(title)
  plt.colorbar()
  tick_marks = np.arange(len(classes))
  plt.xticks(tick_marks, classes, rotation=45)
  plt.yticks(tick_marks, classes)

  if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]

  thresh = cm.max() / 2.
  for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
      plt.text(j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black")

  plt.tight_layout()
  plt.ylabel('True label')
  plt.xlabel('Predicted label')
  plt.savefig(filename)
Exemplo n.º 55
0
def plotSolutions(x,u=None,rho=None,p=None,e=None): #Default func values is trivial


    plt.figure(figsize=(11,8.5))

    #get edge values
    x_edge = [0.5*(x[i]+x[i+1]) for i in range(len(x)-1)]

    #get the exact values
    f = open('exact_results.txt', 'r')
    x_e = []
    u_e = []
    p_e = []
    rho_e = []
    e_e = []
    for line in f:
        if len(line.split())==1:
            t = line.split()
        else:
            data = line.split()
            x_e.append(float(data[0]))
            u_e.append(float(data[1]))
            p_e.append(float(data[2]))
            rho_e.append(float(data[4]))
            e_e.append(float(data[3]))
    
    if u != None:
        plot2D(x,u,x_e,u_e,"$u$")
    
    if rho != None:
        plot2D(x_edge,rho,x_e,rho_e,r"$\rho$") 

    if p != None:
        plot2D(x_edge,p,x_e,p_e,r"$p$")

    if e != None:
        plot2D(x_edge,e,x_e,e_e,r"$e$")

    plt.show(block=False) #show all plots generated to this point
    raw_input("Press anything to continue...")
Exemplo n.º 56
0
def plotCompared(original,forecasts,labels,title):
	fig = plt.figure(figsize=[13,6])
	ax = fig.add_subplot(111)
	ax.plot(original,color='k',label="Original")
	for c in range(0,len(forecasted)):
		ax.plot(forecasted[c],label=labels[c])
	handles0, labels0 = ax.get_legend_handles_labels()
	ax.legend(handles0,labels0)
	ax.set_title(title)
	ax.set_ylabel('F(T)')
	ax.set_xlabel('T')
	ax.set_xlim([0,len(original)])
	ax.set_ylim([min(original),max(original)])
Exemplo n.º 57
0
def compareModelsPlot(original,models_fo,models_ho):
    fig = plt.figure(figsize=[13,6])
    fig.suptitle("Comparação de modelos ")
    ax0 = fig.add_axes([0, 0, 1, 1]) #left, bottom, width, height
    rows = []
    for model in models_fo:
        fts = model["model"]
        ax0.plot(model["forecasted"], label=model["name"])
    for model in models_ho:
        fts = model["model"]
        ax0.plot(model["forecasted"], label=model["name"])
    handles0, labels0 = ax0.get_legend_handles_labels()
    ax0.legend(handles0, labels0)
Exemplo n.º 58
0
def test_pert_winds():
	f=figure()
	lats=linspace(-13.0, -11.5, 20)
	lons=linspace(130., 132., 20)
	u,v=simul_winds.unif_wind(lats, lons, 5.0, 45.0)
	mapobj=pres.generate_darwin_plot()
	fw=0.2#degrees
	m_bump=15.0
	b1=simul_winds.speed_bump(lats, lons, [-12.0, 131.0], fw)*m_bump
	b2=-1.0*simul_winds.speed_bump(lats, lons, [-12.0, 131.2], fw)*m_bump
	pres.quiver_contour_winds(mapobj, lats, lons, u+(b1+b2),v-(b1+b2))
	savefig(os.getenv('HOME')+'/bom_mds/output/test_pert.png')
	close(f)
Exemplo n.º 59
0
def execute():
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    x = random.normal(5, .5, 1000)
    y = random.normal(3, 1, 1000)
    a = x*cos(pi/4) + y*sin(pi/4)
    b = -x*sin(pi/4) + y*cos(pi/4)
    plt.plot(a, b, '.')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.title('原数据集')
    data = zeros((1000, 2))
    data[:, 0] = a
    data[:, 1] = b
    x, y, evals, evecs = pca(data, 1)
    print(y)
    plt.figure()
    plt.plot(y[:, 0], y[:, 1], '.')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.title('重新构造数据')
    plt.show()