Exemple #1
0
def plotDensityMap(bins,binnedData,xscale='log',yscale='log',normaliseX=True,logScale=True):
    if logScale:
        l, b, r, t = 0.1, 0.12, 1.0, 0.970
    else:
        l, b, r, t = 0.1, 0.12, 1.05, 0.970
    axes_rect = [l,b,r-l,t-b]
    fig=p.figure()
    fig.subplots_adjust(left=0.01, bottom=.05, right=.985, top=.95, wspace=.005, hspace=.05)
    ax = fig.add_axes(axes_rect)
    ax.set_xscale(xscale)
    ax.set_yscale(yscale)
    X,Y=bins.edge_grids
    if normaliseX:
        ySum=p.sum(binnedData,1)
        ySum=p.ma.masked_array(ySum,ySum==0)
        Z=binnedData.transpose()/ySum
    else:
        Z=binnedData.transpose()

    if logScale:
        mappable=ax.pcolor(X,Y,p.ma.array(Z,mask=Z==0),cmap=p.get_cmap("jet"),norm=matplotlib.colors.LogNorm())
    else:
        mappable=ax.pcolor(X,Y,p.ma.array(Z,mask=Z==0),cmap=p.get_cmap("jet"))

    markersize=5.0
    linewidth=2.0

    fig.colorbar(mappable)

    #ax.set_ylim((T/2.0/bins2D.centers[0][-1],T/2.0*2))
    #ax.set_xlim(bins2D.centers[0][0]*day,bins2D.centers[0][-1]*day)
    return fig,ax
def visibility(vis,pol):
    """
    Helper function for plotMP. Defines the visibility/transparency of scatter
    symbols.

    @param vis: keyword among 'Visible', 'Invisible', and 'Transparent'.
    @type vis: string
    """

    if vis == "Visible":
        c = [pol]
        cmap = P.get_cmap('jet')
        v = True
        col = "0.0"
    elif vis == "Invisible": 
        c = [0.0]
        cmap = P.get_cmap('gist_yarg')
        v = False
        col = "1.0"
    elif vis == "Transparent": 
        c = [0.20]
        cmap = P.get_cmap('gist_yarg')
        v = True
        col = "0.80"
    else:
        c = None
        cmap = None
        v = None
        col = None
    
    return [c, cmap, v, col]
def show_matrix_with_names(matrix, vert_names, horiz_names, colormap='b_jet', overlay=None, force_range=False):

    def full_rename(namelist, subtypes):

        def rename(list, subtype, character):
            ret_list = []
            for bearer in list:
                modded = False
                for mod_decider in subtype:
                    if mod_decider in bearer:
                        modded = True
                        ret_list.append(bearer+' '+str(character))
                        break
                if not modded:
                    ret_list.append(bearer)
            return ret_list

        new_vert_names = namelist
        for idux, subtype in enumerate(subtypes, 1):
            new_vert_names = rename(new_vert_names, subtype, ''.join(['*']*idux))

        return new_vert_names

    if colormap == 'b_jet':
        prism_cmap = get_cmap('jet')
        prism_vals = prism_cmap(np.arange(0, 1, 0.01))
        prism_vals[99] = [0, 0, 0, 1]
        costum_cmap = colors.LinearSegmentedColormap.from_list('my_colormap', prism_vals)

    else:
        costum_cmap = get_cmap(colormap)

    if force_range:
        plt.imshow(matrix, interpolation='nearest', cmap=costum_cmap, vmin=force_range[0], vmax=force_range[1])
    else:
        plt.imshow(matrix, interpolation='nearest', cmap=costum_cmap)

    plt.colorbar()
    if overlay:
        print overlay[0]
        print overlay[1]
        overlay_y, overlay_x = np.nonzero(overlay[0])
        plt.scatter(overlay_x, overlay_y, c='k', marker='*', label=overlay[1])
        plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, mode="expand", borderaxespad=0.)
    plt.tick_params(axis='both', labelsize=10)

    if type(vert_names) == list:
        plt.yticks(range(0, len(vert_names)), vert_names, rotation='horizontal')
    if type(horiz_names) == list:
        plt.xticks(range(0, len(horiz_names)), horiz_names, rotation='vertical')
    if type(vert_names) == tuple:
        vert_names = full_rename(vert_names[0], vert_names[1:])
        plt.yticks(range(0, len(vert_names)), vert_names, rotation='horizontal')
    if type(horiz_names) == tuple:
        horiz_names = full_rename(horiz_names[0], horiz_names[1:])
        plt.xticks(range(0, len(horiz_names)), horiz_names, rotation='vertical')


    plt.subplots_adjust(left=0.2, bottom=0.2)
    plt.show()
    def __call__(self, inputs):
        from numpy import outer, arange, ones
        from pylab import figure, axis, imshow, title, show, subplot, text, clf, subplots_adjust
        maps = self.get_input('colormap')
        a=outer(arange(0,1,0.01),ones(10))

        if self.get_input('showall') is True:
            figure(figsize=(10,5))
            clf()
            l = len(tools.cmaps)
            subplots_adjust(top=0.9,bottom=0.05,left=0.01,right=0.99)
            for index, m in enumerate(tools.cmaps):
                #print index
                subplot(int(l/2)+l%2+1, 2, index+1)
                #print int(l/2)+l%2, 2, (index+1)/2+(index+1)%2+1
                axis("off")
                imshow(a.transpose(),aspect='auto',cmap=tools.get_cmap(m),origin="lower")
                #title(m,rotation=0,fontsize=10)
                text(0.5,0.5, m)
            show()
        elif self.get_input('show') is True:
            figure(figsize=(10,5))
            clf()
            axis("off")
            imshow(a.transpose(),aspect='auto',cmap=get_cmap(maps),origin="lower")
            title(maps,rotation=0,fontsize=10)
            show()
        from pylab import get_cmap
        res = get_cmap(maps)
        return res
Exemple #5
0
def plot_stats(X,Y,model,costs):
	#two plots, the decision fcn and points and the cost over time
	y_onehot = Trainer.class_to_onehot(Y)
	f,(p1,p2) = plot.subplots(1,2)
	p2.plot(range(len(costs)),costs)
	p2.set_title("Cost over time")
	
	#plot points/centroids/decision fcn
	cls_ct = y_onehot.shape[1]
	y_cls = Trainer.onehot_to_int(y_onehot)
	colors = get_cmap("RdYlGn")(np.linspace(0,1,cls_ct))
	
	#model_cents = model.c.get_value()
	#p1.scatter(model_cents[:,0], model_cents[:,1], c='black', s=81)
	for curclass,curcolor in zip(range(cls_ct),colors):
		inds = [i for i,yi in enumerate(y_cls) if yi==curclass]
		p1.scatter(X[inds,0], X[inds,1], c=curcolor)
		
	nx,ny = 200, 200
	x = np.linspace(X[:,0].min()-1,X[:,0].max()+1,nx)
	y = np.linspace(X[:,1].min()-1,X[:,1].max()+1,ny)
	xv,yv = np.meshgrid(x,y)
	
	Z = np.array([z for z in np.c_[xv.ravel(), yv.ravel()]])
	Zp = Trainer.onehot_to_int(np.array(model.probability(Z)))
	Zp = Zp.reshape(xv.shape)
	p1.imshow(Zp, interpolation='nearest', 
				extent=(xv.min(), xv.max(), yv.min(), yv.max()),
				origin = 'lower', cmap=get_cmap("Set1"))
	
	p1.set_title("Decision boundaries and centroids")
	f.tight_layout()
	plot.show()					
def compare(hdf5_in, hdf5_out, pdf_out, n_events):
    """Plots original and cropped img side by side."""
    _, original = load_dataset(hdf5_in)   # original dataset
    _, cropped = load_dataset(hdf5_out)  # cropped dataset

    # labels
    pid_ticks = [0, 1, 2, 3, 4, 5, 6, 7]
    pid_labels = ['nth', 'EM', 'mu', 'pi+', 'pi-', 'n', 'p', 'oth']

    with PdfPages(pdf_out) as pdf:
        for _ in range(n_events):
            # grab random event
            i = np.random.randint(0, cropped.shape[0])
            
            fig, axes = plt.subplots(1, 2)

            cmap = 'tab10'
            cbt = 'pid'

            fig.suptitle("Event: " + str(i))

            # plot pid image
            im = axes[0].imshow(original[i][0], cmap=pylab.get_cmap(cmap),
                                vmin=0, vmax=7)
            # plot pid image
            im = axes[1].imshow(cropped[i], cmap=pylab.get_cmap(cmap),
                                vmin=0, vmax=7)

            # just plot settings
            cbar = pylab.colorbar(im, fraction=0.04, ticks=pid_ticks)
            cbar.ax.set_yticklabels(pid_labels)
            cbar.set_label("pid", size=9)
            cbar.ax.tick_params(labelsize=6)

            pdf.savefig()
	def create_plot_2d_speeches(self, withLabels = True):
		if withLabels:
			font = { 'fontname':'Tahoma', 'fontsize':0.5, 'verticalalignment': 'top', 'horizontalalignment':'center' }
			labels= [ (i['who'], i['date']) for i in self.data ]
			pylab.subplots_adjust(bottom =0.1)
			pylab.scatter(self.speech_2d[:,0], self.speech_2d[:,1], marker = '.' ,cmap = pylab.get_cmap('Spectral'))
			for label, x, y in zip(labels, self.speech_2d[:, 0], self.speech_2d[:, 1]):
			    pylab.annotate(
			        label, 
			        xy = (x, y), xytext = None,
			        ha = 'right', va = 'bottom', **font)
			        #,textcoords = 'offset points',bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
			        #arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))

			pylab.title('U.S. Presidential Speeches(1790-2006)')
			pylab.xlabel('X')	
			pylab.ylabel('Y')

			pylab.savefig('plot_with_labels', bbox_inches ='tight', dpi = 1000, orientation = 'landscape', papertype = 'a0')
		else:
			pylab.subplots_adjust(bottom =0.1)
			pylab.scatter(self.speech_2d[:,0], self.speech_2d[:,1], marker = 'o' ,cmap = pylab.get_cmap('Spectral'))
			pylab.title('U.S. Presidential Speeches(1790-2006)')
			pylab.xlabel('X')	
			pylab.ylabel('Y')
			pylab.savefig('plot_without_labels', bbox_inches ='tight', dpi = 1000, orientation = 'landscape', papertype = 'a0')
		pylab.close()
Exemple #8
0
def run_main(options):
    try:
        inp = open(options.input_file,'rb')
        geo_input = pickle.load(inp)
        inp.close()
    except:
        print 'Problems in opening the %s. Check the file.' % options.input_file
        exit()

    width,height = map(int,options.size.split(','))
    mode_colormap = options.mode
    n_connections = options.n_connections

    #Create image
    im = Image.new('RGBA', (width, height), (0, 0, 0, 0))
    draw = ImageDraw.Draw(im)
    geo_final = {}

    #Remove the same start == end and repeated cities (start,end) == (end,start).
    for origem,destino in geo_input:
        if origem != destino:
            if not geo_final.has_key((origem,destino)):
                if not geo_final.has_key((destino,origem)):
                    geo_final.setdefault((origem,destino),0)
                    geo_final[(origem,destino)] += geo_input[(origem,destino)]
                else:
                    geo_final.setdefault((destino,origem),0)
                    geo_final[(destino,origem)] += geo_input[(origem,destino)]

    matrix_geo = {}
    #Find all valid cities and calculate the distances
    max_distance = -10000000
    for origem,destino in geo_final:
        if geo_final[(origem,destino)] > n_connections:
            x1,y1 = geo2pixel(origem[0],origem[1],width,height)
            x2,y2 = geo2pixel(destino[0],destino[1],width,height)
            distance = sqrt((y2-y1)**2 + (x2-x1)**2)*40000/360.0
            if distance > max_distance:  max_distance = distance
            matrix_geo[(x1,y1),(x2,y2)] = distance

    #Sort by distance.
    sorted_matrix = sorted(matrix_geo.items(),key= lambda x: x[1], reverse=True)

    cmap =  get_cmap('jet')  if mode_colormap == 'all' else get_cmap('jet')
    dist_bins = logspace(1,log(max_distance)/log(10),255)


    #Plot using the correct colormap
    for ((x1,y1),(x2,y2)),distance in sorted_matrix:
        for i in range(len(dist_bins)-1):
            if distance > dist_bins[i] and distance < dist_bins[i+1]:
                break
        p = rgb2hex(converter.to_rgb(cmap(255-i)))
        draw.line([(y1,x1),(y2,x2)], p )

    #Save the image.
    im.save(options.output_file)
Exemple #9
0
def flamePlot(mapZ, noNanZ, markRegions, flatten, colorCeil):
	print '\nPlotting flameview'

	ratios=[4,1,4]
	gs = gridspec.GridSpec(len(ratios), 1, height_ratios=ratios)
	plt.figure(figsize=(24,9))


	# Direct
	plt.subplot(gs[0])

	plt.imshow(mapZ, cmap=get_cmap(fColorMap), interpolation='nearest', aspect='auto')
	plt.clim(-colorCeil,colorCeil)

	plt.title('Overview')
	plt.xlabel('Probe number')
	plt.ylabel('Window Step')


	# Markers
	plt.subplot(gs[1])

	flatMarkers = [0]*len(markRegions[0])
	for i, val in enumerate(markRegions[0]):
		if abs(val) > flatten:
			flatMarkers[i] = val
	markRegions.append(flatMarkers)

	plt.imshow(markRegions, cmap=get_cmap(fColorMap), interpolation='nearest', aspect='auto')
	plt.clim(-colorCeil,colorCeil)

	plt.title('Maximum values')
	plt.xlabel('Probe number')
	plt.ylabel('Post|Pre')

	# Flattened
	for i in range(len(mapZ)):
		for j in range(len(noNanZ)):
			stouff=mapZ[i][j]
			if abs(stouff) < flatten:
				stouff = 0
			mapZ[i][j]=stouff

	plt.subplot(gs[2])
	plt.imshow(mapZ, cmap=get_cmap(fColorMap), interpolation='nearest', aspect='auto')
	plt.clim(-colorCeil,colorCeil)

	plt.title('Filtered at abs(z) > ' + str(flatten))
	plt.xlabel('Probe number')
	plt.ylabel('Window Step')

	plt.tight_layout()
	return plt
Exemple #10
0
 def _get__pl(self):
     '''return the LinearSegmentedColormap describing this CustomColormap'''
     if self.cmap=='file' and self.fname:
         colors = lut_manager.parse_lut_file(self.fname)
         if self.reverse:
             colors.reverse()
         return LinearSegmentedColormap.from_list('file',colors)
     elif self.cmap=='custom_heat':
         return gen_heatmap(t=self.threshold,reverse=self.reverse)
     elif self.reverse:
         return get_cmap(self.cmap+'_r')
     else:
         return get_cmap(self.cmap)
Exemple #11
0
def getColorMapPlotSettings(trackFile, colorPropertyName, settings):
	if 'colorSettings' in settings:
		colorSettings = settings['colorSettings']
		vmin = colorSettings['vmin']
		vmax = colorSettings['vmax']
		separation = colorSettings['separation']
		colormap = P.get_cmap(colorSettings['colorMap'])
	else:
		vmin = (trackFile.axisLimits[colorPropertyName])[0]
		vmax = (trackFile.axisLimits[colorPropertyName])[1]
		separation = 35
		colormap = P.get_cmap('jet')

	return vmin, vmax, separation, colormap
Exemple #12
0
def embed_dat_matrix_two_dimensions(low_dimension_data_matrix,
                                    y=None,
                                    labels=None,
                                    density_colormap='Blues',
                                    instance_colormap='YlOrRd'):
    from sklearn.preprocessing import scale
    low_dimension_data_matrix = scale(low_dimension_data_matrix)
    # make mesh
    x_min, x_max = low_dimension_data_matrix[:, 0].min(), low_dimension_data_matrix[:, 0].max()
    y_min, y_max = low_dimension_data_matrix[:, 1].min(), low_dimension_data_matrix[:, 1].max()
    step_num = 50
    h = min((x_max - x_min) / step_num, (y_max - y_min) / step_num)  # step size in the mesh
    b = h * 10  # border size
    x_min, x_max = low_dimension_data_matrix[:, 0].min() - b, low_dimension_data_matrix[:, 0].max() + b
    y_min, y_max = low_dimension_data_matrix[:, 1].min() - b, low_dimension_data_matrix[:, 1].max() + b
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

    # induce a one class model to estimate densities
    from sklearn.svm import OneClassSVM
    gamma = max(x_max - x_min, y_max - y_min)
    clf = OneClassSVM(gamma=gamma, nu=0.1)
    clf.fit(low_dimension_data_matrix)

    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, m_max] . [y_min, y_max].
    if hasattr(clf, "decision_function"):
        score_matrix = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
    else:
        score_matrix = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
    # Put the result into a color plot
    levels = np.linspace(min(score_matrix), max(score_matrix), 40)
    score_matrix = score_matrix.reshape(xx.shape)

    if y is None:
        y = 'white'

    plt.contourf(xx, yy, score_matrix, cmap=plt.get_cmap(density_colormap), alpha=0.9, levels=levels)
    plt.scatter(low_dimension_data_matrix[:, 0], low_dimension_data_matrix[:, 1],
                alpha=.5,
                s=70,
                edgecolors='gray',
                c=y,
                cmap=plt.get_cmap(instance_colormap))
    # labels
    if labels is not None:
        for id in range(low_dimension_data_matrix.shape[0]):
            label = labels[id]
            x = low_dimension_data_matrix[id, 0]
            y = low_dimension_data_matrix[id, 1]
            plt.annotate(label, xy=(x, y), xytext=(0, 0), textcoords='offset points')
Exemple #13
0
    def plot_vapor(self,imagename='vapor.png', title='',timestep=0):
	"""plot  qvapor
	Optional input:
	     --------
	     imagename = 'your file name.png', defaults to vapor.png'
	     title = 'your title' defaults to none
	     timestep = integer. If there are multiple time periods per file then
	     choose your timestep, defaults to 0'

	    Returns:
	    --------
		contour plot of qvapor
	
	"""

	pl.figure(2)
	pl.clf()
	try:
	    vapor_full=self.variable_dict['QVAPOR']
	except:
	    vapor_full=self.get_var('QVAPOR')

	qvapor=vapor_full[timestep,0,:,:].copy()


	custom_map=pl.get_cmap('jet',lut=22)
	try:
	    m=self.map_proj
	    x=self.map_x
	    y=self.map_y
	except:
	    self.bmap()
	    m=self.map_proj
	    x=self.map_x
	    y=self.map_y

	
	custom_map=pl.get_cmap('jet',lut=10)
	contour_levs=n.arange(0.012,0.025, 0.001)
	vapor_plot=m.contourf(x,y,qvapor[:,:],contour_levs,cmap=custom_map, title=title)#,cmap=custom_map)
	vapor_plot.set_clim((0.012,0.025))

	self.map_lines()

	pl.colorbar(orientation='horizontal')
	pl.title(title)

	pl.savefig(self.plot_directory+'/'+imagename)
Exemple #14
0
def color_iterator(grouping, cmap='jet', n=None):
    '''
    Given a Matplotlib colormap, iterate through the color range in equal-sized
    increments based on the size of the group.

    Parameters
    ----------
    grouping : iterable
        Values to return on each iteration
    cmap : string
        Matplotlib colormap to use
    n : int
        Size of the group.  If not provided, will attempt to estimate the size
        from the iterable.
    '''

    # Attempt to get the length of the iterator first.  If we can't get the
    # length, then  we need to convert the iterator into a list so we can get
    # the number of elements.
    if n is None:
        try:
            n = len(grouping)
        except:
            grouping = list(grouping)
            n = len(grouping)

    if isinstance(cmap, basestring):
        cmap = pylab.get_cmap(cmap)
    for i, g in enumerate(grouping):
        if n == 1:
            yield cmap(1), g
        else:
            yield cmap(i/(n-1)), g
Exemple #15
0
def makeimg(wav):
	global callpath
	global imgpath

	fs, frames = wavfile.read(os.path.join(callpath, wav))
	
	pylab.ion()

	# generate specgram
	pylab.figure(1)
	
	# generate specgram
	pylab.specgram(
		frames,
		NFFT=256, 
		Fs=22050, 
		detrend=pylab.detrend_none,
		window=numpy.hamming(256),
		noverlap=192,
		cmap=pylab.get_cmap('Greys'))
	
	x_width = len(frames)/fs
	
	pylab.ylim([0,11025])
	pylab.xlim([0,round(x_width,3)-0.006])
	
	img_path = os.path.join(imgpath, wav.replace(".wav",".png"))

	pylab.savefig(img_path)
	
	return img_path
def main():

    print "Importing data from: {0}".format(DIRPATH)
    # get the output file of interest from each of the experiment folders
    path_lists = natsort.natsorted([os.path.join(dp, f) \
                    for (dp, dn, fn) in os.walk(DIRPATH) \
                    for f in fn \
                    if re.search(r'(^l.*csv)', f)])

    print "Loading data ..."
    canopy_data = [import_spa_canopy(exp_paths, '30min') for exp_paths in path_lists]

    col1_map = get_cmap("rainbow")(np.linspace(0, 1, len(canopy_data)))

    plt.figure(figsize=(10, 8))
    mygrid = gridspec.GridSpec(5, 2, hspace=1)

    for (i, cdata) in enumerate(canopy_data):
        ax = plt.subplot(mygrid[i])
        gpp = cdata['Ag'].resample('D', how=lambda x: integrate.trapz(x, dx=1800)*1e-6*12)
        ax.plot(gpp, '-', lw=1.5, c=col1_map[i], label='layer {0}'.format(i+1))
        ax.set_title('layer {0}'.format(i+1))
    #plt.legend(loc='upper center', bbox_to_anchor=(1.0, 1),prop={'size':10})
    plt.show()

    print "Done"
    return None
def ST_xA(r,steps = 99):
	"""
	Makes a heat map for x over ST space for a given r using the full model.
	inputs
	======
	r : float
		Value of relatedness
	steps: int {99}
		Number of decrete points at which to sample S and T

	"""


	Ss = np.linspace(-1,2,steps)
	Ts = np.linspace(0,3,steps)
	dataFull = np.zeros( (steps,steps) )
	for i,S in enumerate(Ss):
		for j,T in enumerate(Ts):
			mod = ESS_class(r,S,T)
			state = mod.getESS()
			dataFull[i,j] = mod.xA(state,r)

	#pl.figure()
	cmap = pl.get_cmap('Reds')
	pl.imshow(dataFull, origin = [Ts[0], Ss[0]],\
			extent = [ Ts[0],Ts[-1],Ss[0],Ss[-1] ], vmin = 0,vmax = 1, cmap = cmap)
	pl.plot( [ Ts[0], Ts[-1] ],[ 0,0 ],color='black', linewidth = 2.5 )
	pl.plot( [ 1, 1 ],[ Ss[0],Ss[-1] ],'--',color='black',  linewidth = 2.5 )
	pl.plot( [ 0, 3 ],[ 2, -1 ],'--',color='black',  linewidth = 2.5 )
def ST_pi_pure(r,steps = 99):
	"""
	Makes a heat map over ST space for a given value of r, using the pure strategy model, plotting
	fitness.

	Inputs
	======
	r : float
		Value of relatedness
	steps : int {99}
		Number of points to sample S and T at.

	"""

	Ss = np.linspace(-1,2,steps)
	Ts = np.linspace(0,3,steps)
	dataFull = np.zeros( (steps,steps) )
	for i,S in enumerate(Ss):
		for j,T in enumerate(Ts):
			x = ESS_pure(r,S,T)
			dataFull[i,j] = fit_pure(x,r,S,T)/maximal_possible_fitness(S,T)

	#pl.figure()
	cmap = pl.get_cmap('Reds')
	pl.imshow(dataFull, origin = [Ts[0], Ss[0]], interpolation = 'nearest',\
			extent = [ Ts[0],Ts[-1],Ss[0],Ss[-1] ], cmap = cmap, vmin = 0, vmax = .5*(Ss[-1]+Ts[-1]))
	pl.plot( [ Ts[0], Ts[-1] ],[ 0,0 ],color='black', linewidth = 2.5 )
	pl.plot( [ 1, 1 ],[ Ss[0],Ss[-1] ],'--',color='black',  linewidth = 2.5 )
	pl.plot( [ 0, 3 ],[ 2, -1 ],'--',color='black',  linewidth = 2.5 )
Exemple #19
0
def plot_rels(data, labels=None, colors=None, outfile="rels", latent=None, alpha=0.5):
    ns, n = data.shape
    if labels is None:
        labels = map(str, range(n))
    ncol = 5
    nrow = int(np.ceil(float(n * (n - 1) / 2) / ncol))

    fig, axs = pylab.subplots(nrow, ncol)
    fig.set_size_inches(5 * ncol, 5 * nrow)
    pairs = list(combinations(range(n), 2))
    if colors is not None:
        colors = (colors - np.min(colors)) / (np.max(colors) - np.min(colors))

    for ax, pair in zip(axs.flat, pairs):
        ax.scatter(data[:, pair[0]], data[:, pair[1]], c=colors, cmap=pylab.get_cmap("jet"),
                       marker='.', alpha=alpha, edgecolors='none', vmin=0, vmax=1)

        ax.set_xlabel(shorten(labels[pair[0]]))
        ax.set_ylabel(shorten(labels[pair[1]]))

    for ax in axs.flat[axs.size - 1:len(pairs) - 1:-1]:
        ax.scatter(data[:, 0], data[:, 1], marker='.')

    pylab.rcParams['font.size'] = 12  #6
    pylab.draw()
    #fig.set_tight_layout(True)
    fig.tight_layout()
    for ax in axs.flat[axs.size - 1:len(pairs) - 1:-1]:
        ax.set_visible(False)
    filename = outfile + '.png'
    if not os.path.exists(os.path.dirname(filename)):
        os.makedirs(os.path.dirname(filename))
    fig.savefig(outfile + '.png')
    pylab.close('all')
    return True
Exemple #20
0
def draw_adjacency_graph(adjacency_matrix,
                         node_color=None,
                         size=10,
                         layout='graphviz',
                         prog='neato',
                         node_size=80,
                         colormap='autumn'):
    """draw_adjacency_graph."""
    graph = nx.from_scipy_sparse_matrix(adjacency_matrix)

    plt.figure(figsize=(size, size))
    plt.grid(False)
    plt.axis('off')

    if layout == 'graphviz':
        pos = nx.graphviz_layout(graph, prog=prog)
    else:
        pos = nx.spring_layout(graph)

    if len(node_color) == 0:
        node_color = 'gray'
    nx.draw_networkx_nodes(graph, pos,
                           node_color=node_color,
                           alpha=0.6,
                           node_size=node_size,
                           cmap=plt.get_cmap(colormap))
    nx.draw_networkx_edges(graph, pos, alpha=0.5)
    plt.show()
def ST_beta(r,steps = 99):
	"""
	Makes a heat map of beta over ST space, for a given value of r.
	Uses the full model.
	Steps : int {99}
		Number of steps to sample S and T at
	Returns
	=======
	None
	"""

	Ss = np.linspace(-1,3,steps)
	Ts = np.linspace(0,4,steps)
	dataFull = np.zeros( (steps,steps) )
	for i,S in enumerate(Ss):
		for j,T in enumerate(Ts):
			mod = ESS_class(r,S,T)
			state = mod.getESS()
			dataFull[i,j] = mod.beta(state,r)

	#pl.figure()
	cmap = pl.get_cmap('coolwarm')
	pl.imshow(dataFull, origin = [Ts[0], Ss[0]],\
			extent = [ Ts[0],Ts[-1],Ss[0],Ss[-1] ], vmin = -1,vmax = 1, cmap = cmap)
	pl.plot( [ Ts[0], Ts[-1] ],[ 0,0 ],color='black', linewidth = 2.5 )
	pl.plot( [ 1, 1 ],[ Ss[0],Ss[-1] ],'--',color='black',  linewidth = 2.5 )
	pl.plot( [ 0, 3 ],[ 2, -1 ],'--',color='black',  linewidth = 2.5 )
Exemple #22
0
def apply_cmap(img, cmap, min_value=None, max_value=None):
    """Applies the colormap to the image and returns the result.

    If min_value is None or max_value is None, the min and max values from img are used.
    :param img: image
    :param cmap: string that specifies the colormap
    :param min_value: min value of the colormap
    :param max_value: max value of the colormap
    :return: the image with the applied colormap
    """
    img = numpy.squeeze(img).astype(numpy.float32)
    if len(img.shape) != 2:
        raise Exception("The given image must be 2-dimensional.")

    # Check min and max values.
    if min_value is None:
        min_value = numpy.min(img)
    if max_value is None:
        max_value = numpy.max(img)

    # Convert img to fit into the values 0 to 255.
    img = ((img - min_value) * 255 / max_value).astype(numpy.uint8)

    # Apply the colormap.
    cmap = pylab.get_cmap(cmap)
    return cmap(img)
Exemple #23
0
    def _plot_annotation_on_ax(self, signal, ax, autoscale=False, colourmap="flag"):

        if autoscale:
            xstart = 0
            xdelta = signal.duration.total_seconds()
        else:

            xstart,ystart,xdelta,ydelta = ax.viewLim.bounds

        if xstart <0:
            start_time = timedelta()
        else:
            start_time = timedelta(seconds=xstart)

        stop_time = timedelta(seconds=xdelta) +  timedelta(seconds=xstart)
        sub_sig = signal[start_time:stop_time]
        xs =np.linspace(0, sub_sig.duration.total_seconds() ,sub_sig.size) + start_time.total_seconds()
        ys = sub_sig.values
        probs = sub_sig.probas

        ys = ys.reshape((1,ys.size))

        zoom_f = float(self.max_point_amplitude_plot)/ sub_sig.size

        ys = zoom(ys,[1, zoom_f], order=0)


        ax.imshow(ys, extent=[np.min(xs), np.max(xs), 1.5, -0.5], aspect="auto",
                  cmap=colourmap, vmin=0, vmax=255, origin='lower')


        ax.plot(xs,probs,"-", color="k", linewidth=3)
        ax.plot(xs,probs,"-", color="y", linewidth=1,alpha=0.5)


        jet = cm = pl.get_cmap(colourmap)
        cNorm  = colors.Normalize(vmin=0, vmax=255)
        scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)

        states = np.unique(ys)

        boxes = [pl.Rectangle((0, 0), 1, 1, fc=scalarMap.to_rgba(col)) for col in states]
        labels = [chr(s) for  s in states]
        pl.legend(boxes,labels, loc='lower right')

        n_labels = 8 #fixme magic number

        if len(xs) > n_labels:
            trimming = int(float(len(xs)) / float(n_labels))
            xs_trimmed = np.round(xs[::trimming])
        else:
            xs_trimmed = xs

        time_strings = [str(timedelta(seconds=s)) for s in xs_trimmed]


        ax.set_xticks(xs_trimmed)
        ax.set_xticklabels(time_strings, rotation=70)

        return
Exemple #24
0
def make_heatmap(data, col_labels, row_labels, make_grid=True,
                 grid_kwargs=None, colormap=None, **kwargs):

    if make_grid and (grid_kwargs is None):
        grid_kwargs = {'color': 'w', 'lw': 2}

    fig = plt.figure(**kwargs)
    plt.hold(True)
    if colormap is None:
        cmap = None
    elif type(colormap) == StringType:
        cmap = get_cmap(colormap)
    else:
        cmap = colormap

    plt.imshow(data, interpolation='nearest', cmap=cmap, aspect='auto')

    plt.yticks(range(len(row_labels)), row_labels)
    plt.xticks(range(len(col_labels)), col_labels, rotation=90)

    if grid_kwargs:
        xpos = np.arange(len(col_labels))+0.5
        ypos = np.arange(len(row_labels))+0.5
        add_grid(plt.gca(), xpos, ypos, **grid_kwargs)

    plt.hold(True)
    return fig
Exemple #25
0
def view(solution):
  """
  Plot a 2D projection of the original points and the discovered solution. Each
  original point is drawn as a square.  Each "center" associated with a point
  is drawn as a circle and has a line drawn between it and its corresponding
  point. Points/Centers/Lines with the same color are in the same cluster.
  """
  X        = solution.problem.X
  C        = solution.u
  labels   = solution.clusters
  maxlabel = np.max(labels).astype(float) + 1

  if X.shape[1] > 2:
    X, U = pca(X, n=2)
    C = C.dot(U)
  if X.shape[1] < 2:
    X = np.hstack([X, np.zeros(len(X))])
    U = np.hstack([U, np.zeros(len(X))])

  cmap = pl.get_cmap("Paired")

  # draw original points
  pl.scatter(X[:,0], X[:,1], c=labels/maxlabel, cmap=cmap, marker='s')

  # draw centers
  pl.scatter(C[:,0], C[:,1], c=labels/maxlabel, cmap=cmap, marker='o')

  # draw line between points, centers
  for i in range(len(X)):
    x = X[i]
    c = C[i]
    l = labels[i]
    s = np.vstack([x, c])
    pl.plot(s[:,0], s[:,1], color=cmap(l / maxlabel))
Exemple #26
0
def val2hex(v, scale=1.0):
    if not v:
        return "000044"
    j = pylab.get_cmap("jet")
    v = v / scale
    nums = [int(255 * i) for i in j(v)][:3]
    return ''.join(["00" if i == 0 else hex(i)[2:] for i in nums])
Exemple #27
0
def LevelColormap(levels, cmap=None):
    """Make a colormap based on an increasing sequence of levels"""
    
    # Start with an existing colormap
    if cmap == None:
        cmap = pl.get_cmap()

    # Spread the colours maximally
    nlev = len(levels)
    S = pl.arange(nlev, dtype='float')/(nlev-1)
    A = cmap(S)

    # Normalize the levels to interval [0,1]
    levels = pl.array(levels, dtype='float')
    L = (levels-levels[0])/(levels[-1]-levels[0])

    # Make the colour dictionary
    R = [(L[i], A[i,0], A[i,0]) for i in xrange(nlev)]
    G = [(L[i], A[i,1], A[i,1]) for i in xrange(nlev)]
    B = [(L[i], A[i,2], A[i,2]) for i in xrange(nlev)]
    cdict = dict(red=tuple(R),green=tuple(G),blue=tuple(B))

    # Use 
    return matplotlib.colors.LinearSegmentedColormap(
        '%s_levels' % cmap.name, cdict, 256)
def cluster_show(_3D_chan1, _3D_chan2, _3D_labels, n_clusters_, means, std, hulls):
    """

    :param _3D_chan1:
    :param _3D_chan2:
    :param _3D_labels:
    """
    red = (1.0, 0.0, 0.0)
    green = (0.0, 1.0, 0.1)

    mlab.pipeline.volume(mlab.pipeline.scalar_field(_3D_chan1), color=green)
    mlab.pipeline.volume(mlab.pipeline.scalar_field(_3D_chan2), color=red)
    mlab.show()

    cm = get_cmap('gist_rainbow')

    for i in range(0, n_clusters_):
        re_img = np.zeros(_3D_chan2.shape)
        re_img[_3D_labels == i] = _3D_chan2[_3D_labels == i]
        mlab.pipeline.volume(mlab.pipeline.scalar_field(re_img), color=tuple(cm(1.*i/n_clusters_)[:-1]))

    # mean_arr = np.zeros((n_clusters_, 3))
    # std_arr = np.zeros((n_clusters_))
    # for i in range(0, n_clusters_):
    #     mean_arr[i, :] = means[i]
    #     std_arr[i] = std[i]
    # x,y,z = mean_arr.T
    # mlab.points3d(x,y,z, std_arr)

    for hull in hulls:
        x,y,z = hull.points.T
        triangles = hull.simplices
        mlab.triangular_mesh(x, y, z, triangles, representation='wireframe', color=(0, 0, 0))

    mlab.show()
def calibration_summary(data, calname = "p_filt_value_tdc"):
    ds1 = data.first_good_dataset
    cal1 = ds1.calibration[calname]
    res = np.zeros((data.num_good_channels, len(cal1.elements)))
    plt.figure()
    cmap = plt.get_cmap()
    cmap = [cmap(i/float(len(cal1.elements))) for i in xrange(len(cal1.elements))]
    for j, feature in enumerate(cal1.elements):
        for k, ds in enumerate(data):
            #plt.subplot(np.ceil(np.sqrt(len(cal1.elements))), np.ceil(np.sqrt(len(cal1.elements))), j)
            res[k, j] = ds.calibration[calname].energy_resolutions[j]
        plt.hist(res[:,j], np.arange(0,40,1), histtype="step", label=str(feature+" %0.2f"%np.median(res[:,j])),color=cmap[j])
    plt.xlabel("energy resolution (eV)")
    plt.ylabel("num channels per bin")
    plt.legend()
    plt.grid("on")

    elements = [ds.calibration[calname].elements for ds in data]
    energy_resolution = [ds.calibration[calname].energy_resolutions for ds in data]

    energies = [mass.energy_calibration.STANDARD_FEATURES[name] for name in elements[0]]

    plt.figure()
    for j in xrange(len(elements)):
        plt.plot(energies, energy_resolution[j],'.')
    plt.plot(energies, np.median(res, axis=0),'s',markersize=10)
    plt.xlabel("energy (eV)")
    plt.ylabel("fwhm res from calibration (eV)")
    plt.ylim(0,20)
    plt.grid("on")
Exemple #30
0
    def _peek(self, lat, alt, data, latrange, dataname, vmin, vmax, axis_datetime=False, ymin=0, ymax=25, cmap=None):

        import niceplots

        import matplotlib.pyplot as plt
        from pylab import get_cmap

        print('Showing ' + dataname)
        print('Lat range : ', latrange)

        if cmap is None:
            cmap = get_cmap('gist_stern_r')

        plt.ioff()
        fig = plt.figure(figsize=(20, 6))
        ax = plt.gca()
        plt.pcolormesh(lat, alt, data.T, vmin=vmin, vmax=vmax, cmap=cmap)
        plt.xlim(latrange[0], latrange[1])
        plt.ylim(ymin, ymax)
        if axis_datetime:
            niceplots.axis_set_date_format(ax, format='%H:%M')
            fig.autofmt_xdate()
        else:
            plt.xlabel('Latitude')

        plt.colorbar().set_label(dataname)
        plt.ylabel('Altitude [km]')
        plt.title(dataname + ' - CALIOP ' + str(self.date))
Exemple #31
0
phi_km[0] = phit_km[-1]
S_km = np.zeros((len(phit_km) + 1, len(phit_km[0])), float)
S_km[1:] = St_km
S_km[0] = St_km[-1]
# S_km += 1
S_km /= 2

Nm = len(phi_km[0])
phi_km = np.tile(phi_km, (1, 2))
phi_km[:, Nm:] += 2 * np.pi
S_km = np.tile(S_km, (1, 2))

plt.figure()
plt.scatter(np.tile(np.arange(len(phi_km)), len(phi_km.T)),
            phi_km.T.reshape(-1),
            cmap=plt.get_cmap('viridis'),
            c=S_km.T.reshape(-1),
            s=5,
            marker='o')

cbar = plt.colorbar()
cbar.set_label(r'$\langle S_z\rangle/\hbar$', size=20)

# plt.xlabel(r'$k_\mathrm{y}$', size=24)
plt.ylabel(r'$\gamma_x$', size=24)
plt.xticks([0, Nk / 2, Nk], [r'$-\mathrm{M}$', r'$\Gamma$', r'$\mathrm{M}$'],
           size=20)
plt.yticks([0, np.pi, 2 * np.pi], [r'$0$', r'$\pi$', r'$2\pi$'], size=20)
plt.axis([0, Nk, 0, 2 * np.pi])
plt.tight_layout()
plt.savefig('phases.png')
    absprob = np.exp(0.5 * (weights.min() - weights))
    k = 0
    for i, j in enumerate(vals1):
        for m, n in enumerate(vals2):
            prob[k] = np.sum(absprob[np.where((x == j) & (y == n))])
            vals_x[k] = j
            vals_y[k] = n
            k += 1
            #pdb.set_trace()
    prob /= prob.sum()
    return vals_x, vals_y, prob, np.log(prob)


if __name__ == '__main__':

    cm = plt.get_cmap('Blues')

    # name of match console input file
    name = sys.argv[1]

    # read in match ssp file
    data = np.loadtxt(name)

    plt.close('all')

    # 1-d distributions for av, age, and 2d distribution for age-av
    plt.figure()
    res = makepdfs(data[:, 0], data[:, 5])
    plt.hist(res[0],
             weights=res[1],
             bins=len(res[0]),
Exemple #33
0
def make_plots_seg(data_dict, max_events, normed_img, pred_dict):
    """
    Copy of make_plots adapted for pid plots
    """
    target_plane_codes = {9: 1, 18: 2, 27: 3, 36: 6, 45: 4, 50: 5}
    pkeys = []
    for k in data_dict.keys():
        if len(data_dict[k]) > 0:
            pkeys.append(k)
    print('Data dictionary present keys: {}'.format(pkeys))

    types = ['energy', 'time']
    views = ['x', 'u', 'v']   # TODO? build dynamically?

    # only working with two-deep imgs these days
    # plotting_two_tensors = True

    def get_maybe_missing(data_dict, key, counter):
        try:
            return data_dict[key][counter]
        except KeyError:
            pass
        return -1

    evt_plotted = 0

    with PdfPages("evt_all.pdf") as pdf:
        for counter in range(len(data_dict[EVENTIDS])):
            evtid = data_dict[EVENTIDS][counter]
            segment = get_maybe_missing(data_dict, SEGMENTS, counter)
            planecode = get_maybe_missing(data_dict, PLANECODES, counter)
            n_hadmultmeas = get_maybe_missing(data_dict, N_HADMULTMEAS, counter)
            (run, subrun, gate, phys_evt) = decode_eventid(evtid)
            if evt_plotted > max_events:
                break
            status_string = 'Plotting entry %d: %d: ' % (counter, evtid)
            title_string = '{}/{}/{}/{}'
            title_elems = [run, subrun, gate, phys_evt]
            if segment != -1 and planecode != -1:
                title_string = title_string + ', segment {}, planecode {}'
                title_elems.extend([segment, planecode])
                if planecode in tuple(target_plane_codes.keys()):
                    title_string = title_string + ', targ {}'
                    title_elems.append(target_plane_codes[planecode[0]])
            if n_hadmultmeas != -1:
                title_string = title_string + ', n_chghad {}'
                title_elems.append(n_hadmultmeas)
            if pred_dict is not None:
                try:
                    prediction = pred_dict[str(evtid)]
                    title_string = title_string + ', pred={}'
                    title_elems.append(prediction)
                except KeyError:
                    pass
            print(status_string + title_string.format(*title_elems))

            # run, subrun, gate, phys_evt = decode_eventid(evtid)
            fig_wid = 9
            fig_height = 9
            grid_height = 3
            fig = pylab.figure(figsize=(fig_wid, fig_height))
            fig.suptitle(title_string.format(*title_elems))
            gs = pylab.GridSpec(grid_height, 3)

            for i, t in enumerate(types):
                datatyp = 'energies+times'
                # set the bounds on the color scale
                if normed_img:
                    minv = 0 if t == 'energy' else -1
                    maxv = 1
                else:
                    maxes = []
                    mins = []
                    for v in views:
                        maxes.append(
                            np.abs(np.max(data_dict[datatyp][v][counter, i, :, :]))
                        )
                        mins.append(
                            np.abs(np.max(data_dict[datatyp][v][counter, i, :, :]))
                        )
                    minv = np.max(mins)
                    maxv = np.max(maxes)
                    maxex = maxv if maxv > minv else minv
                    minv = 0 if minv < 0.0001 else 0 if t == 'energy' else -maxv
                    maxv = maxex
                for j, view in enumerate(views):
                    gs_pos = i * 3 + j
                    ax = pylab.subplot(gs[gs_pos])
                    ax.axis('on')
                    ax.xaxis.set_major_locator(pylab.NullLocator())
                    ax.yaxis.set_major_locator(pylab.NullLocator())
                    cmap = 'Reds' if t == 'energy' else 'bwr'
                    cbt = 'energy' if t == 'energy' else 'times'
                    datap = data_dict[datatyp][view][counter, i, :, :]
                    # make the plot
                    im = ax.imshow(
                        datap,
                        cmap=pylab.get_cmap(cmap),
                        interpolation='nearest',
                        vmin=minv, vmax=maxv
                    )
                    cbar = pylab.colorbar(im, fraction=0.04)
                    cbar.set_label(cbt, size=9)
                    cbar.ax.tick_params(labelsize=6)
                    pylab.title(t + ' - ' + view, fontsize=12)
                    pylab.xlabel('plane', fontsize=10)
                    pylab.ylabel('strip', fontsize=10)
            # plot pid
            for j, view in enumerate(views):
                gs_pos = 6 + j
                ax = pylab.subplot(gs[gs_pos])
                ax.axis('on')
                ax.xaxis.set_major_locator(pylab.NullLocator())
                ax.yaxis.set_major_locator(pylab.NullLocator())
                cmap = 'tab10'
                cbt = 'pid'
                datap = data_dict["pid"][view][counter, 0, :, :]
                # make the plot                
                im = ax.imshow(
                    datap,
                    cmap=pylab.get_cmap(cmap),
                    interpolation='nearest',
                    vmin=0, vmax=7
                )
                cbar = pylab.colorbar(im, fraction=0.04, ticks=[0, 1, 2, 3, 4, 5, 6, 7])
                cbar.ax.set_yticklabels(['nth', 
                                         'EM',
                                         'mu',
                                         'pi+',
                                         'pi-',
                                         'n',
                                         'p',
                                         'oth'])
                cbar.set_label("pid", size=9)
                cbar.ax.tick_params(labelsize=6)
                pylab.title("pid" + ' - ' + view, fontsize=12)
                pylab.xlabel('plane', fontsize=10)
                pylab.ylabel('strip', fontsize=10)
            
            pdf.savefig()
            evt_plotted += 1
Exemple #34
0
from math import log10, ceil
import matplotlib as mpl

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from numpy.random import randint

mpl.rcParams['font.size'] = 8
mpl.rcParams['lines.linewidth'] = 1.0
mpl.rcParams['legend.frameon'] = False
mpl.rcParams['legend.fontsize'] = 'small'

vmin = log10(1e-04)
vmax = log10(1e-02)
cmap = 'jet'
jet = cm = pylab.get_cmap(cmap)
cNorm = colors.Normalize(vmin=vmin, vmax=vmax)
pi_scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)

################################################################################
#
# Standard header to read in argument information
#
################################################################################
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("species_name", help="name of species to process")
parser.add_argument("--debug",
                    help="Loads only a subset of SNPs for speed",
                    action="store_true")
parser.add_argument("--chunk-size",
Exemple #35
0
Z_REF = NodInf_Data_REF[0][:, 1]
dZ_REF = numpy.zeros_like(Z_REF)
dZ_REF0 = Z_REF[1:] - Z_REF[:-1]
dZ_REF[0] = dZ_REF0[0] / 2
dZ_REF[1:-1] = (dZ_REF0[1:] + dZ_REF0[:-1]) / 2
dZ_REF[-1] = dZ_REF0[-1] / 2

CAS_All_Z = CAS_All * dZ_REF[None, None, None, :]
CPRS_All_Z = CPRS_All * dZ_REF[None, None, None, :]
CTRS_All_Z = CTRS_All * dZ_REF[None, None, None, :]

fig = pylab.figure()
ax = fig.add_subplot(111)
V_T = numpy.logspace(-3, 12, 15)
V = numpy.concatenate((-V_T[::-1], V_T))
cmap = pylab.get_cmap('bwr')
cols = cmap(numpy.linspace(0, 1, V.size))
im = ax.contourf(TMesh, ZMesh, CAS_All[0, 0, :, :].transpose(), V, colors=cols)
# ax.contour(TMesh,ZMesh,CAS_All[10,0,:,:].transpose(),V,colors='k')
ax.set_xlabel('Time (d)')
ax.set_ylabel('Z (cm)')
# ax.set_title('%s - h = %1.2e cm'%(NodInf_Header[iNI],hSens))
# fig.colorbar(im)

for iC in range(nC):
    # fig = pylab.figure()
    # ax =fig.add_subplot(111)
    # ax.plot(-hSens_All,numpy.nanmean(numpy.abs(CAS_All_Z[:,iC,:,:]).reshape((nH,-1))))
    # ax.set_xscale('log')
    # ax.set_xlabel('Matric Head (cm)')
    # ax.set_ylabel('CAS')
Exemple #36
0
    return welch1(p,alpha)[1:] - 1

def rconv2(x,y):
    return n.fft.irfft2(n.fft.rfft2(x) * n.conj(n.fft.rfft2(y)))

def arconv2(x):
    return n.fft.irfft2(n.abs(n.fft.rfft2(x))**2)

def recenter(x, null_auto=True):
    if null_auto: x[0,0] = 0
    return a.img.recenter(x, n.array(x.shape)/2)

if __name__ == '__main__':
    import sys
    import pylab
    cmap = pylab.get_cmap('gist_yarg')
    prms = {'cmap':pylab.get_cmap('gist_yarg'), 'interpolation':'nearest', 'origin':'lower'}
    if False:
        rs = reps_from_file(sys.argv[-1])
    else:
        p = 13
        #p = 37
        #p = 71
        rs = []
        for alpha in range(2,p):
            try: rs.append(welch1(p,alpha)); print alpha
            except(AssertionError): pass
        rs = n.array(rs)
        print 'Welch method generated %d solutions for p=%d' % (rs.shape[0], p)
    N = rs.shape[-1] 
    _d = []
Exemple #37
0
    def cartesian_map_array(self,
                            fn,
                            vmin=None,
                            vmax=None,
                            bands=8,
                            title='',
                            cblabel='',
                            ecliptic=False,
                            equatorial=False,
                            nocolorbar=False,
                            cmap=plt.get_cmap('coolwarm')):
        """
        Plot an array of cartesian maps
        
            fn : function object
                fn(iband) returns nside=12 HEALPix array
                has attributes vmin, vmax, title, cblabel
        """
        if vmin is None: vmin = fn.vmin
        if vmax is None: vmax = fn.vmax
        nrows, ncols = ((bands + 1) // 4, 4) if bands >= 4 else (1, bands)

        fig, axx = plt.subplots(nrows,
                                ncols,
                                figsize=(3 + 3 * ncols, 1 + 3 * nrows),
                                sharex=True,
                                sharey=True)
        plt.subplots_adjust(left=0.1,
                            right=0.92,
                            hspace=0.15,
                            wspace=0.01,
                            bottom=0.15)
        if ecliptic:
            lon, sinlat = self.ecliptic_coords()
        elif equatorial:
            lon, sinlat = self.equatorial_coords()
        else:
            lon = self.df.glon
            sinlat = self.singlat
        for iband, energy in enumerate(self.energy[:bands]):
            ax = axx.flatten()[iband] if bands > 1 else axx
            scat = self.basic_skyplot(ax,
                                      lon,
                                      sinlat,
                                      fn(iband).clip(vmin, vmax),
                                      title='%d MeV' % energy,
                                      vmin=vmin,
                                      vmax=vmax,
                                      s=30,
                                      edgecolor='none',
                                      colorbar=False,
                                      labels=False,
                                      cmap=cmap)

        fig.text(0.5, 0.95, getattr(fn, 'title', title), ha='center', size=14)
        if nocolorbar: return fig
        #put colorbar at right
        cbax = fig.add_axes((0.92, 0.15, 0.02, 0.7))
        cb = plt.colorbar(scat, cbax, orientation='vertical')
        cb.set_label(getattr(fn, 'cblabel', cblabel))
        fig.text(0.5, 0.025, 'longitude', ha='center', fontsize=14)
        fig.text(0.05,
                 0.5,
                 'sin(latitude)',
                 rotation='vertical',
                 va='center',
                 fontsize=14)
        return fig
    def __init__(self,
                 fig,
                 xpos,
                 ypos,
                 num=None,
                 xmin=None,
                 xmax=None,
                 ymin=None,
                 ymax=None,
                 xl=None,
                 yl=None,
                 title=None,
                 xticks=None,
                 yticks=None,
                 xlog=False,
                 xticklabels=None,
                 yticklabels=None,
                 xticklabels_rotation=0,
                 yticklabels_rotation=0,
                 ylog=False,
                 plot_width=None,
                 plot_height=None,
                 dashes=None,
                 lc=None,
                 lw=None,
                 pt=None,
                 ps=None,
                 pc=None,
                 errorbar_area=None,
                 legend_xpos=None,
                 legend_ypos=None,
                 hlines=None,
                 vlines=None,
                 hspans=None,
                 vspans=None,
                 show_colormap=False,
                 colormap=None,
                 zmin=None,
                 zmax=None,
                 zticks=None,
                 zticklabels=None,
                 zticklabels_rotation=0,
                 zl=None):

        self.fig = fig
        self.xpos = float(xpos)
        self.ypos = float(ypos)
        self.plot_width = plot_width
        self.plot_height = plot_height
        self.lc = lc
        self.lw = lw
        self.dashes = dashes
        self.pt = pt
        self.ps = ps
        self.pc = pc

        self.show_colormap = show_colormap
        self.errorbar_area = errorbar_area

        if fig.auto_panel_letters is True and num != '':
            if num is None:
                num = chr(fig.autonum)
            else:
                fig.autonum = ord(num)

            fig.autonum += 1

        self.xmin = xmin
        self.xmax = xmax
        self.ymin = ymin
        self.ymax = ymax
        self.zmin = zmin
        self.zmax = zmax
        self.zticks = zticks
        self.zticklabels = zticklabels
        self.zticklabels_rotation = zticklabels_rotation
        self.colormap = colormap
        self.zl = zl
        self.legend_xpos = legend_xpos
        self.legend_ypos = legend_ypos

        if self.plot_width is None:
            self.plot_width = fig.plot_width
        else:
            self.plot_width = float(self.plot_width)
        if self.plot_height is None:
            self.plot_height = fig.plot_height
        else:
            self.plot_height = float(self.plot_height)

        if self.lc is None:
            self.lc = fig.lc
        if self.lw is None:
            self.lw = fig.lw
        if self.ps is None:
            self.ps = fig.ps
        if self.pt is None:
            self.pt = fig.pt
        if self.pc is None:
            self.pc = fig.pc

        if self.dashes is None:
            self.dashes = fig.dashes

        if self.errorbar_area is None:
            self.errorbar_area = fig.errorbar_area

        if self.legend_xpos is None:
            self.legend_xpos = self.xpos + self.plot_width
        if self.legend_ypos is None:
            self.legend_ypos = self.ypos + self.plot_height

        self.ax = self.fig.fig.add_axes([
            self.xpos / self.fig.fig_width, self.ypos / self.fig.fig_height,
            self.plot_width / self.fig.fig_width,
            self.plot_height / self.fig.fig_height
        ])

        #self.ax.set_facecolor("none")

        self.ax.spines['right'].set_color('none')
        self.ax.spines['top'].set_color('none')

        self.ax.spines['left'].set_linewidth(self.lw / 2.)
        self.ax.spines['bottom'].set_linewidth(self.lw / 2.)
        self.ax.spines['left'].set_color(self.fig.textcolor)
        self.ax.spines['bottom'].set_color(self.fig.textcolor)
        self.ax.xaxis.set_ticks_position('bottom')
        self.ax.yaxis.set_ticks_position('left')
        self.ax.tick_params('both',
                            width=self.lw / 2.,
                            which='major',
                            tickdir="out",
                            color=self.fig.textcolor)
        self.ax.tick_params('both',
                            width=self.lw / 2.,
                            which='minor',
                            tickdir="out",
                            color=self.fig.textcolor)

        #self.ax.set_autoscalex_on(False)
        if xmin is not None:
            self.ax.set_xlim([xmin, xmax])  #, ymin, ymax])
        if ymin is not None:
            self.ax.set_ylim([ymin, ymax])  #, ymin, ymax])

        if xl is not None:
            self.ax.set_xlabel(xl,
                               horizontalalignment='center',
                               color=self.fig.textcolor)
            self.ax.xaxis.set_label_coords(0.5, -0.6 / self.plot_height)
        if yl is not None:
            self.ax.set_ylabel(yl,
                               verticalalignment='center',
                               horizontalalignment='center',
                               color=self.fig.textcolor)

            distance = -1.3 if yticks is not None else -0.5

            if '\n' in yl:
                self.ax.yaxis.set_label_coords(
                    distance / self.plot_width * self.fig.fontsize_plots / 9.,
                    0.5)
            else:
                self.ax.yaxis.set_label_coords(
                    distance / self.plot_width * self.fig.fontsize_plots / 9.,
                    0.5)

        if xlog is True:
            self.ax.set_xscale("log")

        if ylog is True:
            self.ax.set_yscale("log")

        if xticks is not None:
            self.ax.set_xticks(xticks)

            if xticklabels is None:
                xticklabels = [str(lbl) for lbl in xticks]

        if xticklabels is not None:
            xticklabels = xticklabels.copy(
            )  # make sure we do not modifiy the original

            for i in range(len(xticklabels)):
                xticklabels[i] = xticklabels[i].replace("-", '–')

            if xticklabels_rotation == 0:
                self.ax.set_xticklabels(xticklabels,
                                        rotation=xticklabels_rotation,
                                        horizontalalignment='center',
                                        color=self.fig.textcolor)
            else:
                self.ax.set_xticklabels(xticklabels,
                                        rotation=xticklabels_rotation,
                                        horizontalalignment='right',
                                        color=self.fig.textcolor)

        else:
            self.ax.spines['bottom'].set_visible(False)
            self.ax.tick_params(axis='x', which='minor', bottom='off')
            self.ax.tick_params(axis='x', which='major', bottom='off')
            self.ax.get_xaxis().set_ticks([])

        if yticks is not None:
            self.ax.set_yticks(yticks)

            if yticklabels is None:
                yticklabels = [str(lbl) for lbl in yticks]

        if yticklabels is not None:
            yticklabels = yticklabels.copy(
            )  # make sure we do not modifiy the original

            for i in range(len(yticklabels)):
                yticklabels[i] = yticklabels[i].replace("-", '–')

            self.ax.set_yticklabels(yticklabels,
                                    rotation=yticklabels_rotation,
                                    horizontalalignment='right',
                                    color=self.fig.textcolor)
        else:
            self.ax.spines['left'].set_visible(False)
            self.ax.tick_params(axis='y', which='minor', left='off')
            self.ax.tick_params(axis='y', which='major', left='off')
            self.ax.get_yaxis().set_ticks([])

        if hlines is not None:
            for hline in hlines:
                self.ax.axhline(hline,
                                linewidth=0.25 * self.lw,
                                color=self.fig.textcolor,
                                dashes=self.fig.dashes,
                                solid_capstyle="round",
                                dash_capstyle="round",
                                zorder=0)
        if vlines is not None:
            for vline in vlines:
                self.ax.axvline(vline,
                                linewidth=0.25 * self.lw,
                                color=self.fig.textcolor,
                                dashes=self.fig.dashes,
                                solid_capstyle="round",
                                dash_capstyle="round",
                                zorder=0)
        if vspans is not None:
            for vspan in vspans:
                self.ax.axvspan(vspan[0],
                                vspan[1],
                                lw=0,
                                edgecolor='none',
                                facecolor=vspan[2],
                                zorder=0,
                                alpha=vspan[3])
        if hspans is not None:
            for hspan in hspans:
                self.ax.axhspan(hspan[0],
                                hspan[1],
                                lw=0,
                                edgecolor='none',
                                facecolor=hspan[2],
                                zorder=0,
                                alpha=hspan[3])

        if title is not None:
            self.ax.set_title(title,
                              color=self.fig.textcolor,
                              fontsize=self.fig.fontsize_plots)

        if num is not None:
            if self.ax.spines['left'].get_visible():
                pl.figtext(
                    (self.xpos - 1.8 * self.fig.fontsize_plots / 9.) /
                    self.fig.fig_width,
                    (self.ypos + self.plot_height + 0.5) / self.fig.fig_height,
                    num,
                    weight='bold',
                    fontsize=self.fig.fontsize_labels,
                    ha='center',
                    va='center',
                    color=self.fig.textcolor)
            else:
                pl.figtext(
                    (self.xpos - 0.3 * self.fig.fontsize_plots / 9.) /
                    self.fig.fig_width,
                    (self.ypos + self.plot_height + 0.5) / self.fig.fig_height,
                    num,
                    weight='bold',
                    fontsize=self.fig.fontsize_labels,
                    ha='center',
                    va='center',
                    color=self.fig.textcolor)

        if self.show_colormap is True:

            cbar_ax = fig.fig.add_axes([
                (self.xpos + self.plot_width + self.plot_width / 20.) /
                self.fig.fig_width, self.ypos / self.fig.fig_height,
                (self.plot_width / 6.) / self.fig.fig_width,
                self.plot_height / self.fig.fig_height
            ])

            cbar_ax.set_facecolor("none")
            cbar_ax2 = cbar_ax.twinx()
            cbar_ax2.tick_params('both',
                                 width=self.lw / 2.,
                                 which='major',
                                 tickdir="out")

            cbar_ax2.imshow(np.c_[np.linspace(self.zmin, self.zmax, 500)],
                            extent=(0, 1, self.zmin, self.zmax),
                            aspect='auto',
                            origin='lower',
                            cmap=pl.get_cmap(self.colormap))
            cbar_ax.yaxis.set_ticks([])
            cbar_ax.xaxis.set_ticks([])

            if self.zticks is not None:
                cbar_ax2.set_yticks(self.zticks)

                if self.zticklabels is None:
                    self.zticklabels = [str(lbl) for lbl in self.zticks]

                for i in range(len(self.zticklabels)):
                    self.zticklabels[i] = self.zticklabels[i].replace("-", '–')
                cbar_ax2.set_yticklabels(
                    self.zticklabels,
                    rotation=zticklabels_rotation,
                    horizontalalignment='left',
                    color=self.fig.textcolor)  #self.fig.textcolor)
            else:
                print("need define zticks...")

            if zl is not None:
                cbar_ax2.set_ylabel(zl, color=self.fig.textcolor)
def themis_plot_phasespace_helistyle(vlsvReader, cellID, plane_x=np.array([1.,0,0]), plane_y=np.array([0,0,1.]), smooth=True, xlabel="Vx", ylabel="Vy"):
    ''' Plots a view of phasespace, as seen by a themis detector, at the given cellID, in the style that heli likes.
    :param vlsvReader:        Some VlsvReader class with a file open
    :type vlsvReader:         :class:`vlsvfile.VlsvReader`
    :param cellid:            The cell id where the distribution is supposet to be sampled NOTE: The cell id must have a velocity distribution!
    :param smooth:            Smooth re-gridded phasespace before plotting
    :param plane_x and plane_y: x and y direction of the resulting plot plane
    '''

    matrix = simulation_to_observation_frame(plane_x,plane_y)

    angles, energies, vmin, vmax, values = themis_observation_from_file( vlsvReader=vlsvReader, cellid=cellID, matrix=matrix, countrates=False)
    if vmin == 0:
        vmin = 1e-15
    if vmax < vmin:
        vmax = vmin*10

    # Regrid into cartesian space, 256x256:
    grid_r, grid_theta = np.meshgrid(energies,angles)

    grid_x = -grid_r * np.sin(grid_theta)  # turn radial grid points into (x, y)
    grid_y = -grid_r * np.cos(grid_theta)

    hires_x = np.linspace(-2200,2200,256);
    hires_y = np.linspace(-2200,2200,256);
    xi,yi = np.meshgrid(hires_x,hires_y);
    vi = griddata( (grid_x.flatten(),grid_y.flatten()), values.flatten(), (xi,yi), method='linear')

    if smooth:
        # Convolve the grid data with a gaussian kernel
        blurkernel = np.exp(-.17*np.power([6,5,4,3,2,1,0,1,2,3,4,5,6],2))
        vi = sepfir2d(vi, blurkernel, blurkernel) / 4.2983098411528502

    fig,ax=pl.subplots(figsize=(12,10))
    ax.set_aspect('equal')
    ax.set_title("Phasespace at cell " + str(cellID))
    ax.set_xlabel(xlabel+" (km/s)")
    ax.set_ylabel(ylabel+" (km/s)")
    cax = ax.pcolormesh(xi,yi,vi.T, norm=matplotlib.colors.LogNorm(vmin=vmin,vmax=vmax), vmin=vmin, vmax=vmax, cmap=pl.get_cmap("Blues"), shading='flat')
    cax2 = ax.contourf(xi,yi,vi.T, levels=np.logspace(np.log10(vmin),np.log10(vmax),20), norm=matplotlib.colors.LogNorm(vmin=vmin,vmax=vmax), vmin=vmin, vmax=vmax, cmap=pl.get_cmap("Blues"))
    #cax3 = ax.contour(xi,yi,vi.T, levels=np.logspace(np.log10(vmin),np.log10(vmax),20), norm=matplotlib.colors.LogNorm(vmin=vmin,vmax=vmax), cmap=pl.get_cmap("binary"))
    ax.grid(True)
    fig.colorbar(cax)
    pl.show()
Exemple #40
0
    def correction_plots(self,
                         cc,
                         vmin=0.5,
                         vmax=1.5,
                         title=None,
                         hist=False,
                         start=0,
                         cmap='coolwarm',
                         cbtext='correction factor',
                         **kwargs):
        from matplotlib import patches

        nrows = cc.shape[1] / 4
        #assert cc.shape[1]==8, 'Found shape {}'.format(cc.shape)

        if hist:
            hkw = dict(bins=np.linspace(vmin, vmax, 21), lw=1, histtype='step')
            fig, axx = plt.subplots(nrows,
                                    4,
                                    figsize=(14, 3 * nrows + 1),
                                    sharex=True,
                                    sharey=False)
            plt.subplots_adjust(wspace=0.3, hspace=0.15)
        else:
            fig, axx = plt.subplots(nrows,
                                    4,
                                    figsize=(12, 3 * nrows),
                                    sharex=True,
                                    sharey=True)
            plt.subplots_adjust(left=0.10,
                                wspace=0.1,
                                hspace=0.15,
                                right=0.92,
                                top=0.90)

        for i, ax in enumerate(axx.flatten()):
            if i < start:
                ax.set_visible(False)
                continue
            if hist:
                h = np.array(cc[:, i], float)
                ax.hist(h.clip(vmin, vmax), **hkw)
                ax.axvline(1.0, color='grey', ls='--')
                mypatch = patches.Patch(
                    fill=False,
                    lw=0,
                    facecolor='none',
                    label='{:4.1f} {:4.1f}'.format(100 * (h.mean() - 1),
                                                   100 * h.std()),
                )
                ax.legend(handles=[mypatch],
                          facecolor='none',
                          edgecolor='none')
            else:
                t, scat = self.skyplot(cc[:, i],
                                       ax=ax,
                                       vmin=vmin,
                                       vmax=vmax,
                                       title='{:0f}'.format(self.energy[i]),
                                       cmap=plt.get_cmap(cmap),
                                       colorbar=False,
                                       labels=False,
                                       **kwargs)
            ax.set_title('{:.0f} MeV'.format(self.energy[i]), fontsize=12)

        if not hist:
            cbax = fig.add_axes((0.94, 0.15, 0.015, 0.7))
            fig.colorbar(scat, cbax,
                         orientation='vertical').set_label(cbtext, fontsize=12)
        fig.suptitle(title, fontsize=16)
        return fig
Exemple #41
0
#! /usr/bin/env python
import aipy as a, pylab as p, numpy as n, sys, optparse

o = optparse.OptionParser()
o.set_usage('beamcal.py [options]')
a.scripting.add_standard_options(o, cal=True, pol=True, cmap=True)
o.add_option('-f', '--freq', dest='freq', type='float', default=.150,
    help='Frequency to plot beam for.  Default .150 GHz')
o.add_option('--nside', dest='nside', type='int', default=32,
    help='NSIDE parameter for HEALPix map of beam.')
o.add_option('-o', '--outfile', dest='outfile',
    help='The name of the fits file to create.')
             
opts,args = o.parse_args(sys.argv[1:])

cmap = p.get_cmap(opts.cmap)
print 'Modelling beam at %f GHz' % (opts.freq)

afreqs = n.load(args[0])['afreqs']
srclist = [f.split('__')[0] for f in args]

aa = a.cal.get_aa(opts.cal, afreqs)
cat = a.cal.get_catalog(opts.cal,srclist)
cat.compute(aa)

beam = a.map.Map(opts.nside,interp=True)

fluxcal = 'cyg'
srctimes = {}
srcfluxes = {}
srcgains = {}
Exemple #42
0
# Error bar:

# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)

plt.errorbar(x, y, xerr=0.2, yerr=0.4, capthick=2,
             capsize=5, ecolor='g', fmt='--o')
plt.title("Simplest errorbars, 0.2 in x, 0.4 in y")


# xticks interval
ax1.set_xticks(np.arange(0, 6, 0.5))

NUM_COLORS = 10
cm = pl.get_cmap('gist_rainbow')  # , gist_yarg
for i in range(3):
    axs[i].set_prop_cycle(cycler('color', [cm(1.*ii/NUM_COLORS)
                                           for ii in range(NUM_COLORS)]))


import matplotlib.gridspec as gridspec
fig = pl.figure(figsize=(12, 9))
gs1 = gridspec.GridSpec(3, 1, hspace=0.0)
axs = []
axs.append(fig.add_subplot(gs1[0]))
axs.append(fig.add_subplot(gs1[1]))
axs.append(fig.add_subplot(gs1[2]))


x = np.linspace(0, 2*np.pi, 100)
corr_r = np.corrcoef(c_mat);
corr_c = np.corrcoef(np.transpose(c_mat));
total_corr = corr_r + corr_c;

thresh_vec = np.linspace(0,1,20)
all_groups = []
all_entropy= []
all_blocks = []
all_global_dists = []
count = 1
for thresh in thresh_vec:
    plt.subplot(4,5,count)
    #test_mat, pred_group, order_vec = blockify(total_corr, thresh)
    test_mat, pred_group, order_vec = blockify(this_dist, thresh,'dis')
    all_blocks.append(test_mat)
    plt.imshow(test_mat,cmap = plt.get_cmap('viridis'))
    this_entropy = entropy_proxy(test_mat)
    #this_global_dist = global_distance(test_mat,pred_group)
    #all_global_dists.append(this_global_dist)
    all_entropy.append(this_entropy)
    all_groups.append(pred_group)
    count += 1

#plt.figure()
#plt.imshow(all_blocks[np.argmax(all_entropy)])
#print(all_groups[np.argmax(all_entropy)])
print(np.argsort(all_entropy,)[-5:])
print(np.sort(all_entropy)[-5:])
#print(np.argsort(all_global_dists))
#print(np.sort(all_global_dists))
Exemple #44
0
def check_cube(cubename, showlamrms=False, savefig=False, no_stamp=False):
    """Plot a datacube.

        This function can produce a PDF file of the data cube.

        Args:
            cubename (str): name of cube numpy file
            showlamrms (bool): display the rms of the wavelength fit,
                otherwise display average trace width
            savefig (bool): save a pdf of the plot
            no_stamp (bool): set to prevent printing DRP version stamp on plot

        Returns:
            None

        """

    if not os.path.isfile(cubename):
        sys.exit("No such file: %s" % cubename)

    cc, meta = np.load(cubename)
    fid_wave = meta['fiducial_wavelength']
    if 'drp_version' in meta:
        drp_ver = meta['drp_version']
    else:
        drp_ver = ''

    xs = [c.X_as for c in cc]
    ys = [c.Y_as for c in cc]
    if showlamrms:
        ss = [0.] * len(cc)
        for i in range(len(cc)):
            if cc[i].lamrms is not None:
                if np.isfinite(cc[i].lamrms):
                    ss[i] = cc[i].lamrms

        c, low, upp = sigmaclip(ss)
        smdn = np.nanmedian(c)
        sstd = np.nanstd(c)
        print("Nspax: %d, Nclip: %d, <RMS>: %f, RMS(std): %f" %
              (len(cc), (len(cc) - len(c)), float(smdn), float(sstd)))
        # smx = smdn + 3. * sstd
        # smn = smdn - 3. * sstd
        # if smn < 0.:
        #     smn = 0.
        smn = 0.
        smx = 1.2
        cbtitle = "Wavelength RMS [nm]"
        outf = "cube_lambdarms.pdf"
    else:
        ss = [c.trace_sigma for c in cc]
        smx = 2
        smn = 0.8
        cbtitle = "RMS trace width [pix]"
        outf = "cube_trace_sigma.pdf"

    pl.figure(1)
    pl.scatter(xs,
               ys,
               marker='H',
               linewidth=0,
               s=35,
               c=ss,
               vmin=smn,
               vmax=smx,
               cmap=pl.get_cmap('jet'))
    if not no_stamp:
        pl.title("Hexagonal Grid of Cube Positions")
    pl.xlim(15, -15)
    pl.ylim(-15, 15)

    pl.colorbar(label=cbtitle)
    pl.xlabel("RA offset [asec] @ %6.1f nm" % fid_wave)
    pl.ylabel("Dec offset [asec]")
    # Add drp version
    if len(drp_ver) > 0 and not no_stamp:
        ax = pl.gca()
        ax.annotate('DRP: ' + drp_ver,
                    xy=(0.0, 0.01),
                    xytext=(0, 0),
                    xycoords=('axes fraction', 'figure fraction'),
                    textcoords='offset points',
                    size=6,
                    ha='center',
                    va='bottom')

    pl.grid(True)
    pl.ioff()
    if savefig:
        pl.savefig(outf)
        print("Figure saved to " + outf)
    else:
        pl.show()
Exemple #45
0
print 'BpCMB: %.8e %.8e' % (bpCMB.max(), bpCMB.min())
print 'reconstruct BpCMB: %.8e %.8e' % (bpsurf.max(), bpsurf.min())

fig = P.figure(figsize=(12, 4))
P.subplots_adjust(right=0.99,
                  left=0.01,
                  top=0.99,
                  bottom=0.01,
                  wspace=0.02,
                  hspace=0.02)
ax = fig.add_subplot(231, frameon=False)
im = ax.contourf(x,
                 y,
                 symmetrize(brCMB, g.minc),
                 16,
                 cmap=P.get_cmap('RdYlBu_r'))
P.axis('off')
ax = fig.add_subplot(232, frameon=False)
im = ax.contourf(x,
                 y,
                 symmetrize(btCMB, g.minc),
                 16,
                 cmap=P.get_cmap('RdYlBu_r'))
P.axis('off')
ax = fig.add_subplot(233, frameon=False)
im = ax.contourf(x,
                 y,
                 symmetrize(bpCMB, g.minc),
                 16,
                 cmap=P.get_cmap('RdYlBu_r'))
P.axis('off')
Exemple #46
0
#Textos para la legenda
lab = np.linspace(args.vmin, args.vmax, 4)
texto = ['Bajo', 'Medio', 'Alto', 'Muy alto']
labText = ['%dmm\n%s' % (i, j) for i, j in zip(lab, texto)]
#se fija si si hay algo para graficar
if len(pos) > 0:
    #Acumula la lluvia para el periodo
    Vsum = np.zeros(cu.ncells)
    for i in pos:
        v, r = wmf.models.read_int_basin(rutebin, i, cu.ncells)
        v = v.astype(float)
        v = v / 1000.0
        Vsum += v
    #Genera la figura
    c = cu.Plot_basinClean(Vsum,
                           cmap=pl.get_cmap('viridis', 10),
                           show_cbar=True,
                           vmin=args.vmin,
                           vmax=args.vmax,
                           cbar_ticksize=16,
                           cbar_ticks=lab,
                           cbar_ticklabels=labText,
                           cbar_aspect=17,
                           ruta=args.rutaFigura,
                           show=False,
                           figsize=(10, 12))
    c[1].set_title('Mapa Lluvia de Radar Acumulada', fontsize=16)
    if args.verbose:
        print 'Aviso: Se ha producido una grafica nueva con valores diferentes de cero para ' + args.rutaFigura[
            49:-4]
        print fecha_f - fecha_i
Exemple #47
0
 # print np.max(evt)
 for i in range(len(evt)):
     ax = pylab.subplot(gs[i])
     ax.axis('on')
     ax.xaxis.set_major_locator(pylab.NullLocator())
     ax.yaxis.set_major_locator(pylab.NullLocator())
     # images are normalized such the max e-dep has val 1, independent
     # of view, so set vmin, vmax here to keep matplotlib from
     # normalizing each view on its own
     minv = 0
     cmap = 'jet'
     if have_times:
         minv = -1
         cmap = 'bwr'
     im = ax.imshow(evt[i][0],
                    cmap=pylab.get_cmap(cmap),
                    interpolation='nearest',
                    vmin=minv,
                    vmax=1)
     cbar = pylab.colorbar(im, fraction=0.04)
     cbar.set_label(colorbar_tile, size=9)
     cbar.ax.tick_params(labelsize=6)
     pylab.title(titles[i], fontsize=12)
     pylab.xlabel("plane", fontsize=10)
     pylab.ylabel("strip", fontsize=10)
 if labels_shp is not None:
     figname = 'evt_%s_%s_%s_%s_targ_%d_pcode_%d.pdf' % \
               (run, subrun, gate, phys_evt, targ, pcode)
 else:
     figname = 'evt_%s_%s_%s_%s.pdf' % \
               (run, subrun, gate, phys_evt)
Exemple #48
0
    (at your option) any later version.

    Astaroth is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Astaroth.  If not, see <http://www.gnu.org/licenses/>.
'''
import pylab as plt 
import numpy as np 
import matplotlib.gridspec as gridspec
import matplotlib.colors as colors

CM_INFERNO = plt.get_cmap('inferno')

def plot_3(mesh, input_grid, title = '', fname = 'default', bitmap=False,
	   slicetype = 'middle', colrange=None, colormap=CM_INFERNO ,
           contourplot=False, points_from_centre = -1, bfieldlines=False, velfieldlines=False, trimghost = 0):

    fig = plt.figure(figsize=(8, 8))
    grid = gridspec.GridSpec(2, 3, wspace=0.4, hspace=0.4, width_ratios=[1,1, 0.15])
    ax00   = fig.add_subplot( grid[0,0] )
    ax10   = fig.add_subplot( grid[0,1] )
    ax11   = fig.add_subplot( grid[1,1] )
    axcbar = fig.add_subplot( grid[:,2] )

    print(mesh.minfo.contents.keys())

    if slicetype == 'middle':
Exemple #49
0
def get_colors(k):
    cm = pylab.get_cmap('gist_rainbow')
    colors = []
    for i in range(k):
        colors.append(cm(1. * i / k))
    return colors
Exemple #50
0
 wave = fixup_wave(wave, f.samplerate)
 # Apply noise cancellation to signal
 wave = filter_signal(wave, f.samplerate)
 # Generate plot of wave, spectrogram, and power and save as image file
 pl.subplot(3, 1, 1)
 pl.plot(wave)
 pl.title('start={}, dur={:.1f}, sig={:.1f}'.format(
     hhmmss(d[0]), d[1], d[2]))
 # start_time, duration, significance
 pl.xticks([])
 pl.subplot(3, 1, 2)
 pl.specgram(wave,
             SPECTROGRAM_NFFT,
             f.samplerate,
             noverlap=SPECTROGRAM_NFFT - SPECTROGRAM_STEP,
             cmap=pl.get_cmap('inferno'))
 pl.xticks([])
 pl.ylim([750, 1750])
 pl.subplot(3, 1, 3)
 pl.plot(t[start_i:stop_i], meteor_power[start_i:stop_i])
 pl.savefig(
     os.path.join(output_path,
                  source_name + " - " + hhmmss(d[0]) + ".png"))
 pl.show()
 # pl.close()
 # Generate wav file for detection
 # Renormalise for WAV format (+/-1. limits)
 peak = max(np.max(wave), -np.min(wave))
 wave = np.divide(wave, 1.01 * peak)
 sf.write(
     os.path.join(output_path,
Exemple #51
0
    def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
        self.midpoint = midpoint
        Normalize.__init__(self, vmin, vmax, clip)

    def __call__(self, value, clip=None):
        # I'm ignoring masked values and all kinds of edge cases to make a
        # simple example...
        x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
        return np.ma.masked_array(np.interp(value, x, y))


from pylab import get_cmap

data = NP_D
print data.min(), data.max()
plt.pcolor(data, cmap=get_cmap("Reds"))
#cmap=get_cmap("Rlues"))
#cmap=hm)
#norm = MidpointNormalize(midpoint=100),

ax.set_frame_on(False)
ax.xaxis.tick_top()
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
ax.set_xticks(np.arange(len(X_names)) + 0.5, minor=False)
ax.set_yticks(np.arange(len(Y_names)) + 0.5, minor=False)
ax.set_xticklabels(X_names, rotation=90)

i = 0
for xtick in ax.get_xticklabels():
    xtick.set_color(X_colors[i])
Exemple #52
0
def draw_graph(graph,
               vertex_label='label',
               secondary_vertex_label=None,
               edge_label='label',
               secondary_edge_label=None,
               vertex_color=None,
               vertex_alpha=0.6,
               edge_color=None,
               edge_alpha=0.5,
               size=10,
               size_x_to_y_ratio=1,
               node_size=600,
               font_size=9,
               layout='graphviz',
               prog='neato',
               node_border=False,
               colormap='YlOrRd',
               vmin=0,
               vmax=1,
               invert_colormap=False,
               verbose=True,
               file_name=None,
               title_key='id',
               ignore_for_layout="edge_attribute",
               logscale=False):
    """Plot graph layout."""
    if size is not None:
        size_x = size
        size_y = int(float(size) / size_x_to_y_ratio)
        plt.figure(figsize=(size_x, size_y))
    plt.grid(False)
    plt.axis('off')

    if vertex_label is not None:
        if secondary_vertex_label:
            vertex_labels = dict()
            for u, d in graph.nodes(data=True):
                label1 = _serialize_list(d.get(vertex_label, 'N/A'))
                label2 = _serialize_list(d.get(secondary_vertex_label, 'N/A'))
                vertex_labels[u] = '%s\n%s' % (label1, label2)
        else:
            vertex_labels = dict()
            for u, d in graph.nodes(data=True):
                label = d.get(vertex_label, 'N/A')
                vertex_labels[u] = _serialize_list(label)

    edges_normal = [(u, v) for (u, v, d) in graph.edges(data=True)
                    if d.get('nesting', False) is False]
    edges_nesting = [(u, v) for (u, v, d) in graph.edges(data=True)
                     if d.get('nesting', False) is True]

    if edge_label is not None:
        if secondary_edge_label:
            edge_labels = dict([(
                (
                    u,
                    v,
                ), '%s\n%s' %
                (d.get(edge_label, 'N/A'), d.get(secondary_edge_label, 'N/A')))
                                for u, v, d in graph.edges(data=True)])
        else:
            edge_labels = dict([((
                u,
                v,
            ), d.get(edge_label, 'N/A'))
                                for u, v, d in graph.edges(data=True)])

    if vertex_color is None:
        node_color = 'white'
    elif vertex_color in ['_labels_', '_label_', '__labels__', '__label__']:
        node_color = []
        for u, d in graph.nodes(data=True):
            label = d.get('label', '.')
            node_color.append(hash(_serialize_list(label)))
        color_set = set(node_color)
        color_map = {c: i for i, c in enumerate(color_set)}
        node_color = [color_map[c] for c in node_color]
    else:
        if invert_colormap:
            node_color = [
                -d.get(vertex_color, 0) for u, d in graph.nodes(data=True)
            ]
        else:
            node_color = [
                d.get(vertex_color, 0) for u, d in graph.nodes(data=True)
            ]
        if logscale is True:
            log_threshold = 0.01
            node_color = [
                math.log(c) if c > log_threshold else math.log(log_threshold)
                for c in node_color
            ]

    if edge_color is None:
        edge_colors = 'black'
    elif edge_color in ['_labels_', '_label_', '__labels__', '__label__']:
        edge_colors = [
            hash(str(d.get('label', '.')))
            for u, v, d in graph.edges(data=True) if 'nesting' not in d
        ]
    else:
        if invert_colormap:
            edge_colors = [
                -d.get(edge_color, 0) for u, v, d in graph.edges(data=True)
                if 'nesting' not in d
            ]
        else:
            edge_colors = [
                d.get(edge_color, 0) for u, v, d in graph.edges(data=True)
                if 'nesting' not in d
            ]

    tmp_edge_set = [(a, b, d) for (a, b, d) in graph.edges(data=True)
                    if ignore_for_layout in d]
    graph.remove_edges_from(tmp_edge_set)

    if layout == 'graphviz':
        pos = nx.graphviz_layout(graph, prog=prog, args="-Gstart=rand")
    elif layout == "RNA":
        import RNA
        rna_object = RNA.get_xy_coordinates(graph.graph['structure'])
        pos = {
            i: (rna_object.get(i).X, rna_object.get(i).Y)
            for i in range(len(graph.graph['structure']))
        }
    elif layout == 'circular':
        pos = nx.circular_layout(graph)
    elif layout == 'random':
        pos = nx.random_layout(graph)
    elif layout == 'spring':
        pos = nx.spring_layout(graph)
    elif layout == 'shell':
        pos = nx.shell_layout(graph)
    elif layout == 'spectral':
        pos = nx.spectral_layout(graph)
    else:
        raise Exception('Unknown layout format: %s' % layout)

    if node_border is False:
        linewidths = 0.001
    else:
        linewidths = 1

    graph.add_edges_from(tmp_edge_set)

    nx.draw_networkx_nodes(graph,
                           pos,
                           node_color=node_color,
                           alpha=vertex_alpha,
                           node_size=node_size,
                           linewidths=linewidths,
                           cmap=plt.get_cmap(colormap))

    if vertex_label is not None:
        nx.draw_networkx_labels(graph,
                                pos,
                                vertex_labels,
                                font_size=font_size,
                                font_color='black')
    nx.draw_networkx_edges(graph,
                           pos,
                           edgelist=edges_normal,
                           width=2,
                           edge_color=edge_colors,
                           cmap=plt.get_cmap(colormap),
                           alpha=edge_alpha)
    nx.draw_networkx_edges(graph,
                           pos,
                           edgelist=edges_nesting,
                           width=1,
                           edge_color='k',
                           style='dotted',
                           alpha=0.3)
    if edge_label is not None:
        nx.draw_networkx_edge_labels(graph,
                                     pos,
                                     edge_labels=edge_labels,
                                     font_size=font_size)
    if title_key:
        title = str(graph.graph.get(title_key, ''))
        font = FontProperties()
        font.set_family('monospace')
        plt.title(title, fontproperties=font)
    if size is not None:
        # here we decide if we output the image.
        # note: if size is not set, the canvas has been created outside
        # of this function.
        # we wont write on a canvas that we didn't create ourselves.
        if file_name is None:
            plt.show()
        else:
            plt.savefig(file_name,
                        bbox_inches='tight',
                        transparent=True,
                        pad_inches=0)
            plt.close()
    def _plotFunction(self):
        if self.evalFunction is None:
            return

        self.lock.acquire()

        # Clean up old plot
        for patch in self.plottedPatches:
            patch.remove()
        self.plottedPatches = []

        self.colorMapping = dict()
        self.colors = cycle(["b", "g", "r", "c", "m", "y"])

        cmap = pylab.get_cmap("jet")

        # Check if the observed function returns discrete or continuous value
        discreteFunction = isinstance(self.functionObservable,
                                      FunctionOverStateSpaceObservable) \
                                and self.functionObservable.discreteValues
        if not discreteFunction:
            # The values of the observed function over the 2d state space
            values = numpy.ma.array(numpy.zeros(
                (self.maze.getColumns(), self.maze.getRows())),
                                    mask=numpy.zeros((self.maze.getColumns(),
                                                      self.maze.getRows())))

        # Iterate over all states and compute the value of the observed function
        dimensions = [
            self.stateSpace[dimName] for dimName in ["column", "row"]
        ]
        for column in range(self.maze.getColumns()):
            for row in range(self.maze.getRows()):
                # Create state object
                state = State((column, row), dimensions)
                # Evaluate function for this state
                if isinstance(self.functionObservable,
                              FunctionOverStateSpaceObservable):
                    functionValue = self.evalFunction(state)
                else:  # StateActionValuesObservable
                    # Determine chosen option first
                    selectedOption = None
                    for option in self.actions:
                        selectedOptionName = str(
                            self.suboptionComboBox.currentText())
                        if str(option) == selectedOptionName:
                            selectedOption = option
                            break
                    assert selectedOption is not None
                    functionValue = self.evalFunction(state, option)

                # Map function value onto color value
                if discreteFunction:
                    # Deal with situations where the function is only defined over
                    # part of the state space
                    if functionValue == None or functionValue in [
                            numpy.nan, numpy.inf, -numpy.inf
                    ]:
                        continue
                    # Determine color value for function value
                    if not functionValue in self.colorMapping:
                        # Choose value for function value that occurrs for the
                        # first time
                        self.colorMapping[functionValue] = self.colors.next()
                    patch = self.maze.plotSquare(
                        self.axis, (column, row),
                        self.colorMapping[functionValue])
                    self.plottedPatches.append(patch[0])
                else:
                    # Remember values since we have to know the min and max value
                    # before we can plot
                    values[column, row] = functionValue
                    if functionValue == None or functionValue in [
                            numpy.nan, numpy.inf, -numpy.inf
                    ]:
                        values.mask[column, row] = True

        # Do the actual plotting for functions with continuous values
        if not discreteFunction:
            minValue = values.min()
            maxValue = values.max()
            for column in range(self.maze.getColumns()):
                for row in range(self.maze.getRows()):
                    if values.mask[column, row]: continue
                    value = (values[column, row] - minValue) / (maxValue -
                                                                minValue)
                    patch = self.maze.plotSquare(self.axis, (column, row),
                                                 cmap(value),
                                                 zorder=0)
                    self.plottedPatches.append(patch[0])

        # Set limits
        self.axis.set_xlim(0, len(self.maze.structure[0]) - 1)
        self.axis.set_ylim(0, len(self.maze.structure) - 1)

        # Update legend
        self.legendWidget.clear()
        if discreteFunction:
            for functionValue, colorValue in self.colorMapping.items():
                if isinstance(functionValue, tuple):
                    functionValue = functionValue[0]  # deal with '(action,)'
                rgbaColor = matplotlib.colors.ColorConverter().to_rgba(
                    colorValue)
                item = QtGui.QListWidgetItem(str(functionValue),
                                             self.legendWidget)
                color = QtGui.QColor(int(rgbaColor[0] * 255),
                                     int(rgbaColor[1] * 255),
                                     int(rgbaColor[2] * 255))
                item.setTextColor(color)
                self.legendWidget.addItem(item)
        else:
            for value in numpy.linspace(values.min(), values.max(), 10):
                rgbaColor = cmap(
                    (value - values.min()) / (values.max() - values.min()))
                item = QtGui.QListWidgetItem(str(value), self.legendWidget)
                color = QtGui.QColor(int(rgbaColor[0] * 255),
                                     int(rgbaColor[1] * 255),
                                     int(rgbaColor[2] * 255))
                item.setTextColor(color)
                self.legendWidget.addItem(item)

        self.canvas.draw()

        self.lock.release()
Exemple #54
0
        "Sunday": 6
    }
    processed_data['day'] = raw_data['DayOfWeek'].replace(weekdays)
    districts = {
        raw_data['PdDistrict'].unique()[i]: i
        for i in range(0, len(raw_data['PdDistrict'].unique()))
    }
    processed_data['district'] = raw_data['PdDistrict'].replace(districts)
    processed_data['PdDistrict'] = raw_data['PdDistrict']
    processed_data['time'] = processed_data['date'].apply(lambda x: x.time())
    processed_data['hour'] = processed_data['time'].apply(maketime)

    return (processed_data)


jet = P.get_cmap('jet')
greys = P.get_cmap('pink')

#Print a plot of where prostitution took place by year.


def crime_loc_plot(types="all", y="all"):
    print("printing...")
    printdata = processed_data
    if types != "all":
        printdata = printdata[printdata['Category'].isin(types)]
    if y != "all":
        printdata = printdata[(printdata['year'] == y)]
    printdata.info()
    P.figure(figsize=(10, 10))
    P.scatter(printdata['X'],
Exemple #55
0
    def plot(self):
        hfname = 'OmFrag.html'
        hfile = lib_file.htmlfile(hfname)
        hfile.pre('Electron-hole correlation plots')
        hfile.write(
            '<h2>Electron-hole correlation plots of the Omega matrices for the individual states.</h2>'
        )

        htable = lib_file.htmltable(ncol=4)

        matplotlib.rc('font', size=self['fsize'])

        if self['grid']:
            edgecolors = 'k'
        else:
            edgecolors = None

        for state in self.state_list:
            if self['plot_type'] == 1:
                plot_arr = state['OmFrag']
            elif self['plot_type'] == 2:
                plot_arr = numpy.sqrt(state['OmFrag'])
            else:
                raise error_handler.ElseError(str(self['plot_type']),
                                              'plot_type')

            if self['sscale']:
                vmin = self['vmin']
                vmax = self['vmax']
            else:
                vmin = 0.
                vmax = state['OmFrag'].max()

            # Completely delete the small elements
            # for x in numpy.nditer(plot_arr, op_flags = ['readwrite']):
            #     if x < vmin:
            #         x[...] = -1. # numpy.nan

            pylab.figure(figsize=(2, 2))
            pylab.pcolor(plot_arr,
                         cmap=pylab.get_cmap(name=self['cmap']),
                         vmin=vmin,
                         vmax=vmax,
                         edgecolors=edgecolors)

            # *** Different colouring of different parts ***
            # frag_lists = [[0, 2, 4, 6], [1, 3, 5]]
            # cmaps = ['Reds', 'Blues']
            # OmDim = len(plot_arr)
            # for frag in frag_lists:
            #     tmp_arr = numpy.array([[numpy.nan for i in range(OmDim)] for j in range(OmDim)])
            #     for i in frag:
            #         tmp_arr[i,i] = plot_arr[i,i]
            #     pylab.pcolor(tmp_arr, cmap=pylab.get_cmap(cmaps.pop(0)), vmin=0., vmax=vmax, edgecolors=edgecolors)

            if self['axis']:
                pylab.axis('on')
                if self['ticks']:
                    pylab.tick_params(which='both', length=0)
                    if self['cticks']:
                        pylab.xticks([x + 0.5 for x in range(len(plot_arr))],
                                     self['xticks'])
                        pylab.yticks([y + 0.5 for y in range(len(plot_arr))],
                                     self['yticks'])
                    else:
                        pylab.xticks([x + 0.5 for x in range(len(plot_arr))],
                                     [x + 1 for x in range(len(plot_arr))])
                        pylab.yticks([y + 0.5 for y in range(len(plot_arr))],
                                     [y + 1 for y in range(len(plot_arr))])
                else:
                    pylab.xticks([])
                    pylab.yticks([])
            else:
                pylab.axis('off')

            if self['cbar']: pylab.colorbar()

            pname = 'pcolor_%s.%s' % (state['name'], self['output_format'])
            print("Writing %s ..." % pname)
            pylab.tight_layout()
            pylab.savefig(pname, dpi=self['plot_dpi'])
            pylab.close()

            tel = '<img src="%s", border="1" width="200">\n' % pname
            tel += '<br>%s' % state['name']
            htable.add_el(tel)

        # create a plot with the e/h axes and optionally the scale
        pylab.figure(figsize=(3, 2))
        matplotlib.rc('font', size=14)
        ax = pylab.axes()
        ax.arrow(0.15,
                 0.15,
                 0.5,
                 0.,
                 head_width=0.05,
                 head_length=0.1,
                 fc='r',
                 ec='r')
        ax.text(0.20, 0.03, 'hole', color='r')
        ax.arrow(0.15,
                 0.15,
                 0.,
                 0.5,
                 head_width=0.05,
                 head_length=0.1,
                 fc='b',
                 ec='b')
        ax.text(0.02, 0.20, 'electron', rotation='vertical', color='b')

        pylab.axis('off')
        if self['sscale']:
            pylab.savefig('axes_no.%s' % self['output_format'],
                          dpi=self['plot_dpi'])
            #            pylab.figure(figsize=(2,2))

            pylab.pcolor(numpy.zeros([1, 1]),
                         cmap=pylab.get_cmap(name=self['cmap']),
                         vmin=self['vmin'],
                         vmax=self['vmax'])

            pylab.colorbar()

        pylab.savefig('axes.%s' % self['output_format'], dpi=self['plot_dpi'])

        tel = '<img src="axes.%s", border="1" width="200">\n' % self[
            'output_format']
        tel += '<br>Axes / Scale'
        htable.add_el(tel)

        hfile.write(htable.ret_table())
        hfile.post()

        print(
            " HTML file %s containing the electron-hole correlation plots written."
            % hfname)
Exemple #56
0
def plot_rels(data,
              labels=None,
              colors=None,
              outfile="rels",
              latent=None,
              alpha=0.8):
    ns, n = data.shape
    if labels is None:
        labels = list(map(str, range(n)))
    ncol = 5
    # ncol = 4
    nrow = int(np.ceil(float(n * (n - 1) / 2) / ncol))
    #nrow=1
    #pylab.rcParams.update({'figure.autolayout': True})
    fig, axs = pylab.subplots(nrow, ncol)
    fig.set_size_inches(5 * ncol, 5 * nrow)
    #fig.set_canvas(pylab.gcf().canvas)
    pairs = list(combinations(range(n), 2))  #[:4]
    pairs = sorted(
        pairs,
        key=lambda q: q[0]**2 + q[1]**2)  # Puts stronger relationships first
    if colors is not None:
        colors = (colors - np.min(colors)) / (np.max(colors) -
                                              np.min(colors)).clip(1e-7)

    for ax, pair in zip(axs.flat, pairs):
        if latent is None:
            ax.scatter(data[:, pair[0]],
                       data[:, pair[1]],
                       marker='.',
                       edgecolors='none',
                       alpha=alpha)
        else:
            # cs = 'rgbcmykrgbcmyk'
            markers = 'x+.o,<>^^<>,+x.'
            for j, ind in enumerate(np.unique(latent)):
                inds = (latent == ind)
                ax.scatter(data[inds, pair[0]],
                           data[inds, pair[1]],
                           c=colors[inds],
                           cmap=pylab.get_cmap("jet"),
                           marker=markers[j],
                           alpha=0.5,
                           edgecolors='none',
                           vmin=0,
                           vmax=1)

        ax.set_xlabel(shorten(labels[pair[0]]))
        ax.set_ylabel(shorten(labels[pair[1]]))

    for ax in axs.flat[axs.size - 1:len(pairs) - 1:-1]:
        ax.scatter(data[:, 0], data[:, 1], marker='.')

    pylab.rcParams['font.size'] = 12  #6
    pylab.draw()
    #fig.set_tight_layout(True)
    fig.tight_layout()
    for ax in axs.flat[axs.size - 1:len(pairs) - 1:-1]:
        ax.set_visible(False)
    filename = outfile + '.png'
    if not os.path.exists(os.path.dirname(filename)):
        os.makedirs(os.path.dirname(filename))
    fig.savefig(outfile + '.png')  #df')
    pylab.close('all')
    return True
Exemple #57
0
 def show(self):
     Z = np.array(self.to_matrix(self.randoms, self.size))
     imshow(Z, cmap=get_cmap("Spectral"), interpolation='nearest')
     show()
Exemple #58
0
    def Plot_CV_Inacc(self, coords, threshold, labels, limits, savename):
        import matplotlib.gridspec as gridspec
        if labels == None or len(labels) != coords.shape[1]:
            new_labels = []
            for i in range(coords.shape[0]):
                new_labels.append('X%s' % i)
            labels = new_labels

        statistic = 100 * (self.y_GP / self.y_compare - 1)
        if len(statistic.shape) > 1:
            statistic_avg = np.zeros(statistic.shape[0])
            for i in range(len(statistic_avg)):
                statistic_avg[i] = np.mean(statistic[i, :])
            statistic = statistic_avg

        count_inacc = len(np.where(statistic > threshold)[0])
        cmap = plt.get_cmap('jet')
        colors = [cmap(i) for i in np.linspace(0, 1, count_inacc)]

        fig = plt.figure(figsize=(12, 10))  #figsize = (20,14)
        gs1 = gridspec.GridSpec(coords.shape[1] - 1, coords.shape[1] - 1)
        p = 0  # subplot number
        for i in range(coords.shape[1] - 1):
            l = i + 1  # which y-axis statistic is plotted on each row.
            for j in range(coords.shape[1] - 1):
                ax1 = plt.subplot(gs1[p])
                if j > i:
                    ax1.axis('off')
                else:
                    ax1.scatter(coords[:, j],
                                coords[:, l],
                                color='dimgrey',
                                s=20)
                    color_idx = 0
                    for s in range(coords.shape[0]):
                        if statistic[s] > threshold:
                            ax1.scatter(coords[s, j],
                                        coords[s, l],
                                        color=colors[color_idx],
                                        s=30)
                            color_idx += 1

                    # Decide what the axis limits should be. If limits=None, it doesn't set any.
                    # If limits is [a,b], limits are set to be a*min and b*max in each dimension.
                    # Else, limits is interpreted as [ [x1,x2],[y1,y2],[z1,z2]...] for each dimension.
                    if limits != None:
                        if len(np.array(limits).shape) == 1:
                            ax1.set_xlim([
                                limits[0] * coords[:, j].min(),
                                limits[1] * coords[:, j].max()
                            ])
                            ax1.set_ylim([
                                limits[0] * coords[:, l].min(),
                                limits[1] * coords[:, l].max()
                            ])
                        else:
                            ax1.set_xlim([limits[j][0], limits[j][1]])
                            ax1.set_ylim([limits[l][0], limits[l][1]])

# If the axes tick labels are too busy, uncomment the following!:
                    # Set every other x/y-tick to be invisible
                    #if len(ax1.get_xticklabels()) > 5: # Too many things will plot on x-axis,
                    # so only plot every third
                    #	for thing in ax1.get_xticklabels():
                    #		if thing not in ax1.get_xticklabels()[::3]:
                    #			thing.set_visible(False)
                    #else:
                    #	for thing in ax1.get_xticklabels()[::2]:
                    #		thing.set_visible(False)
                    #for thing in ax1.get_yticklabels()[::2]:
                    #	thing.set_visible(False)

                    # Get rid of x/y ticks completely for subplots not at the edge
                    if j == 0:
                        ax1.set_ylabel(labels[l])
                    else:
                        ax1.set_yticks([])
                    if i == coords.shape[1] - 2:
                        ax1.set_xlabel(labels[j])
                    else:
                        ax1.set_xticks([])
                p += 1
        fig.suptitle(
            r'Training nodes for which mean accuracy worse than %s per cent (coloured points)'
            % threshold)
        plt.savefig(savename)
        plt.show()
        return
# Creation of Array
A=np.zeros(t,dtype=np.uint8) 
for i in range(h):
    for j in range(w):
        A[i,j]=[i%256,j%256,(i+j)%256]    # Assigning Colors to Each pixel
i=Image.fromarray(A,"RGB")
i.show()
pyplot.imshow(i)
pyplot.show()

from pylab import imshow, show, get_cmap
from numpy import random

Z = random.random((50,50))   # Test data

imshow(Z, cmap=get_cmap("Spectral"), interpolation='nearest')
show()

import pylab as plt
import numpy as np

Z = np.random.random((500,500))   # Test data
plt.imshow(Z, cmap='gray', interpolation='nearest')
plt.show()

!pip install -q matplotlib-venn

!apt-get -qq install -y libfluidsynth1

import matplotlib.pyplot as plt
import numpy as np
Exemple #60
0
Z= random.random((size,size))


#-------------------------------------------------filtering------------------------------------------------------------
for i in range(ITERATIONS):
    Z = scipy.ndimage.filters.median_filter(Z, size=(size/10,size/10))
    Z = scipy.ndimage.filters.median_filter(Z, size=(size/10, size/10))

    Z = scipy.ndimage.filters.gaussian_gradient_magnitude(Z, 1)

#Z = scipy.ndimage.filters.sobel(Z)

#---------------------------------------------------plotting-----------------------------------------------------------

    plt.subplot(2, 2, 1)
    imshow(Z, cmap=get_cmap("Spectral"), interpolation='bicubic')
    plt.subplot(2, 2, 2)
    plt.imshow(Z, cmap=get_cmap('cubehelix'), interpolation='bicubic')
    plt.subplot(2, 2, 3)
    imshow(Z, cmap=get_cmap("copper"), interpolation='bicubic')
    plt.subplot(2, 2, 4)
    imshow(Z, cmap='gray', interpolation='bicubic')


    #----------------------------------------------------saving------------------------------------------------------------
    if SAVE:
        filename = 'output'
        i = 0
        while os.path.exists('{}{:d}.png'.format(filename, i)):
            i += 1
        plt.savefig('{}{:d}.png'.format(filename, i))