Beispiel #1
0
def create_2_plots_v(mic1, mic2, title1, title2, xlabel1, ylabel1, xlabel2, ylabel2, colormap):

    fig, axes = plt.subplots(2, sharex=True)
    mic_array = array(mic1)
    dimensions = mic_array.shape
    nx = dimensions[0]
    ny = dimensions[1]
    axes[0].imshow(mic1, extent=(0, nx, ny, 0),cmap=cm.get_cmap(colormap))
    axes[0].set_title(title1)
    axes[0].set_xlabel(xlabel1)
    axes[0].set_ylabel(ylabel1)
    axes[0].set_ylim([0,ny])
    
    mic_array = array(mic2)
    dimensions = mic_array.shape
    nx = dimensions[0]
    ny = dimensions[1]
    print(nx, ny)
    axes[1].imshow(mic2, extent=(0, nx, ny, 0),cmap=cm.get_cmap(colormap))
    axes[1].set_title(title2)
    axes[1].set_xlabel(xlabel2)
    axes[1].set_ylabel(ylabel2)
    axes[1].set_ylim([0,ny])
    plt.axis('tight')
    plt.autoscale(enable=True, axis='y', tight=True)

    plt.show()
Beispiel #2
0
    def __plot(self, spectrum):
        x, y, z = create_mesh(spectrum, True)
        self.parent.clear_plots()

        if self.settings.autoL:
            vmin, vmax = self.barBase.get_clim()
        else:
            zExtent = self.extent.get_l()
            vmin = zExtent[0]
            vmax = zExtent[1]
        if self.parent.settings.wireframe:
            self.parent.plot = \
                self.axes.plot_wireframe(x, y, z,
                                         rstride=1, cstride=1,
                                         linewidth=0.1,
                                         cmap=cm.get_cmap(self.settings.colourMap),
                                         gid='plot_line',
                                         antialiased=True,
                                         alpha=1)
        else:
            self.parent.plot = \
                self.axes.plot_surface(x, y, z,
                                       rstride=1, cstride=1,
                                       vmin=vmin, vmax=vmax,
                                       linewidth=0,
                                       cmap=cm.get_cmap(self.settings.colourMap),
                                       gid='plot_line',
                                       antialiased=True,
                                       alpha=1)

        return self.extent.get_peak_flt()
Beispiel #3
0
def plotprop(ax,d,xvar='npart',yvar='time',sclfact=None,tunit='s',
             nlim={},**exkw):
    """Plot time vs. npart for processor number"""
    from matplotlib import colors,cm
    syms=['.','x','^','s']
    lins=['-',':',';','.']
    if   xvar=='npart': nvar='nproc'
    elif xvar=='nproc': nvar='npart'
    else: raise Exception('Invalid x variable: {}'.format(xvar))
    nlist=set(d[nvar])
    if   nvar=='npart': cmap=cm.get_cmap('cool')
    elif nvar=='nproc': cmap=cm.get_cmap('cool')
    lab=exkw.get('lab','')
    lin=exkw.get('lin',lins[0])
    sym=exkw.get('sym',syms[0])
    p=[]
    for i,n in enumerate(sorted(nlist)):
        # Get x data and label
        idx=(d[nvar]==n)
        x=d[xvar][idx]
        xlab=xvar.title()
        if   nvar=='npart': ilab=lab+'log{} = {:3.2f}'.format(nvar.title(),np.log10(n))
        elif nvar=='nproc': ilab=lab+'{} = {}'.format(nvar.title(),n)
        else: raise Exception('Unsupported nvar: {}'.format(nvar))
        if   xvar=='npart': xscl='log'
        elif xvar=='nproc': xscl='linear'
        else: raise Exception('Unsupported xvar: {}'.format(xvar))
        # Get y data and label
        if   yvar=='time':
            y=d['time' ][idx]
            if sclfact=='npart': 
                y/=d['npart'][idx]
            elif isinstance(sclfact,(float,int,np.ndarray)):
                y*=sclfact
            ylab='Time ({})'.format(tunit)
            yscl='log'
        elif yvar=='overhead':
            y=d['To'   ][idx]
            ylab='Overhead ({})'.format(tunit)
            yscl='log'
        elif yvar=='speedup':
            y=d['S'    ][idx]
            ylab='Speedup'
            yscl=None
        else: raise Exception('Invalid variable: {}'.format(yvar))
        # Sort by increasing x
        idxsort=np.argsort(x)
        x=x[idxsort]
        y=y[idxsort]
        # Add properties to list
        nlim.setdefault(xvar,(min(x),max(x)))
        nlim.setdefault(nvar,(min(nlist),max(nlist)))
        if   nvar=='npart': norm=colors.LogNorm(*nlim[nvar])
        elif nvar=='nproc': norm=colors.Normalize(*nlim[nvar])
        else: raise Exception('Unsupported nvar: {}'.format(nvar))
        clr=cmap(norm(n))
        p.append({'xvar':xvar,'x':x,'xlab':xlab,'xlim':nlim[xvar],'xscl':xscl,
                  'yvar':yvar,'y':y,'ylab':ylab,'ylim':None      ,'yscl':yscl,
                  'ax':ax,'style':lin,'marker':sym,'color':clr,'label':ilab})
    return p
Beispiel #4
0
def mplcmap_to_palette(cmap, ncolors=None, categorical=False):
    """
    Converts a matplotlib colormap to palette of RGB hex strings."
    """
    from matplotlib.colors import Colormap, ListedColormap

    ncolors = ncolors or 256
    if not isinstance(cmap, Colormap):
        import matplotlib.cm as cm
        # Alias bokeh Category cmaps with mpl tab cmaps
        if cmap.startswith('Category'):
            cmap = cmap.replace('Category', 'tab')
        try:
            cmap = cm.get_cmap(cmap)
        except:
            cmap = cm.get_cmap(cmap.lower())
    if isinstance(cmap, ListedColormap):
        if categorical:
            palette = [rgb2hex(cmap.colors[i%cmap.N]) for i in range(ncolors)]
            return palette
        elif cmap.N > ncolors:
            palette = [rgb2hex(c) for c in cmap(np.arange(cmap.N))]
            if len(palette) != ncolors:
                palette = [palette[int(v)] for v in np.linspace(0, len(palette)-1, ncolors)]
            return palette
    return [rgb2hex(c) for c in cmap(np.linspace(0, 1, ncolors))]
def main(months=None):
    """
    Note: if you want to compare more than 2 simulations at the same time
    make sure that the differences are plotted correctly
    :param months:
    """
    matplotlib.rc("font", size=20)
    # List of simulations to compare
    label_to_path = OrderedDict([
        ("(1) Without interflow", "/skynet3_rech1/huziy/hdf_store/quebec_0.1_crcm5-hcd-rl.hdf5"),
        ("(2) With interflow-a", "/skynet3_rech1/huziy/hdf_store/quebec_0.1_crcm5-hcd-rl-intfl_ITFS.hdf5"),
        # ("With interflow (b)",
        # "/skynet3_rech1/huziy/hdf_store/quebec_0.1_crcm5-hcd-rl-intfl_ITFS_avoid_truncation1979-1989.hdf5")
    ])

    nsims = len(label_to_path)
    width_ratios = nsims * [1.0, ] + [0.05, ] + [1.3, 0.05]
    gs = GridSpec(1, nsims + 3, width_ratios=width_ratios, wspace=0.25)

    cdelta = 0.05
    clevels = np.arange(-1.0, 1.0 + cdelta, cdelta)
    cnorm = BoundaryNorm(clevels, len(clevels) - 1)
    cmap = cm.get_cmap("RdBu_r", len(clevels) - 1)

    start_year = 1980
    end_year = 1989

    keys = [k.replace(" ", "-") for k in label_to_path]
    keys.extend([str(i) for i in (start_year, end_year)])
    keys.append("-".join(str(m) for m in months))
    img_path = "corr-SM-LH_{}_{}_{}-{}_{}.png".format(*keys)

    fig = plt.figure()
    assert isinstance(fig, Figure)
    fig.set_figwidth(fig.get_figwidth() * 3)

    im = None
    sim_label_to_corr = OrderedDict()
    for col, (sim_label, sim_path) in enumerate(label_to_path.items()):
        ax = fig.add_subplot(gs[0, col])
        im, corr = plot_for_simulation(axis=ax, sim_path=sim_path, cmap=cmap, cnorm=cnorm,
                                       start_year=start_year, end_year=end_year, months=months)
        ax.set_title(sim_label)
        sim_label_to_corr[sim_label] = corr

    plt.colorbar(im, cax=fig.add_subplot(gs[0, nsims]))

    # plot differences in correlation
    cdelta = 0.05
    clevels = np.arange(-0.5, -cdelta, cdelta)
    clevels = clevels.tolist() + [-c for c in reversed(clevels)]
    cnorm = BoundaryNorm(clevels, len(clevels) - 1)
    cmap = cm.get_cmap("RdBu_r", len(clevels) - 1)

    im = plot_correlation_diff(sim_label_to_corr, file_for_basemap=list(label_to_path.values())[0],
                               ax=fig.add_subplot(gs[0, nsims + 1]), cnorm=cnorm, cmap=cmap)

    plt.colorbar(im, cax=fig.add_subplot(gs[0, nsims + 2]))
    # fig.tight_layout()
    fig.savefig(img_path)
def main():

    get_file = lambda x: "cru_ts3.23.1901.2014.{0}.100mean.pkl".format(x)

    tair_data = pickle.load(open(FILEPATH + get_file('tmp'), 'rb'))
    rain_data = pickle.load(open(FILEPATH + get_file('pre'), 'rb'))

    sav_patch = pickle.load(open(PATCHPATH, 'rb'))

    fig = plt.figure(figsize=(10, 6), frameon=False)
    fig.add_axes([0, 0, 1.0, 1.0])

    n_plots = 2
    grid = gridspec.GridSpec(n_plots, 1, hspace=0.3)
    subaxs = [plt.subplot(grid[i]) for i in range(n_plots)]

    # Mean Annual Temperature plot
    make_map(subaxs[0], tair_data, sav_patch['clip'], \
             cmap=get_cmap(MAPCOLOR), \
             levels=np.arange(15, 35, 0.5), \
             cticks=np.arange(15, 35, 2.5), \
             title="Global Savanna Bioregion \\\\ Mean Annual Temperature (1901 to 2013)")

    # Mean Annual Rainfall plot
    make_map(subaxs[1], rain_data, sav_patch['clip'], \
             cmap=get_cmap(MAPCOLOR), \
             levels=np.logspace(1, 3, 100), \
             cticks=[10, 50, 100, 200, 500, 1000], \
             norm=SymLogNorm(linthresh=0.3, linscale=0.03), \
             title="Global Savanna Bioregion \\\\ Mean Annual Precipitation (1901 - 2013)")

    plt.savefig(SAVEPATH)
Beispiel #7
0
    def __plot_storage(prefix, show_cb=False, row=0, col=0, plot_deviations=True):

        if plot_deviations:
            clevs = [0, 1e3, 1e4, 1e5, 1.0e6, 1e7, 1e8, 1.0e9]
            clevs = [-c for c in reversed(clevs)][:-1] + clevs
            cmap = cm.get_cmap("bwr", len(clevs) - 1)
        else:
            clevs = [0, 1e3, 1e4, 1e5, 1.0e6, 1e7, 1e8, 1.0e9]
            cmap = cm.get_cmap("YlGnBu", len(clevs) - 1)

        norm = BoundaryNorm(boundaries=clevs, ncolors=len(clevs) - 1)

        _storage = ds["{}_{}".format(prefix, storage_var_name)][:]
        ax = fig.add_subplot(gs[row, col])
        _storage = _storage.where(_storage > storage_lower_limit_m3)
        _storage = maskoceans(lons2d_, lats2d, _storage)
        _storage = np.ma.masked_where(np.isnan(_storage), _storage)


        if plot_deviations:
            cs = bmap.pcolormesh(xx, yy, _storage - bankfull_storage, norm=norm, cmap=cmap)
        else:
            cs = bmap.pcolormesh(xx, yy, _storage, norm=norm, cmap=cmap)


        ext = "both" if plot_deviations else "max"


        cb = bmap.colorbar(cs, location="bottom", format=FuncFormatter(__storage_cb_format_ticklabels), extend=ext)
        cb.ax.set_visible(show_cb)
        cb.ax.set_xlabel(r"${\rm m^3}$")
        ax.set_title(prefix)
        axes.append(ax)
        return _storage
def update_plot():
	rf_scale = rf_slider.get_value()
	n_scale = needle_slider.get_value()
	g_scale = ground_slider.get_value()
			
	f.clear()

	a = f.add_subplot(211)
	cmap = cm.get_cmap('spectral', 100)
	im = rf_scale**2*pseudoz + n_scale*needlez + g_scale*groundz
	implot = a.imshow( im, interpolation='nearest', cmap=cmap )
	f.colorbar(implot)
	
	m = np.mean( im )
	s = np.std( im )

	implot.set_clim(m-s, m+s)

	a = f.add_subplot(212)
	cmap = cm.get_cmap('spectral', 100)
	im = rf_scale**2*pseudox + n_scale*needlex + g_scale*groundx
	implot = a.imshow( im, interpolation='nearest', cmap=cmap )
	f.colorbar(implot)
	
	m = np.mean( im )
	s = np.std( im )

	implot.set_clim(0., m+0.1*s)
	canvas.draw()
Beispiel #9
0
def mapPerPeriod(aodperDegree, lats, longs, title, savefile, cmapname,minv=0,maxv=0):
    # Make plot with vertical (default) colorbar
  
    fig, ax = plt.subplots()

    data = aodperDegree
    datafile = cbook.get_sample_data('C:/Users/alex/marspython/aerosol/gr.png')
    img = imread(datafile)

    ax.imshow(img, zorder=1, alpha=0.3,
              extent=[float(min(longs))-0.5, float(max(longs))+0.5, float(min(lats)) - 0.5, float(max(lats))+0.5])

    if minv<>0 or maxv<>0 :
        cax = ax.imshow(data, zorder=0, interpolation='spline16', cmap=cm.get_cmap(cmapname),
                    extent=[float(min(longs)), float(max(longs)), float(min(lats)), float(max(lats))],
                    vmin=minv,vmax=maxv)
    else:
        cax = ax.imshow(data, zorder=0, interpolation='spline16', cmap=cm.get_cmap(cmapname),
                    extent=[float(min(longs)), float(max(longs)), float(min(lats)), float(max(lats))])
    ax.set_title(title)

    # Add colorbar, make sure to specify tick locations to match desired ticklabels
    #cbar = fig.colorbar(cax, ticks=[-1, 0, 1])
    cbar = fig.colorbar(cax)
    #cbar.ax.set_yticklabels(['< -1', '0', '> 1'])  # vertically oriented colorbar
    pylab.savefig(savefile + ".png")
Beispiel #10
0
def featurePosPlot(featureList, name, k=1, save=None):
    font = {'family' : 'monospace',
        'weight' : 'normal',
        'size'   : '6'}
    plt.rc('font', **font)
    fig = plt.figure(k)
    fig.suptitle(name)
    ax = fig.add_subplot(221)
    sc = ax.scatter([2,2,3,3,3,2], [3,1,1,2,3,2], c=featureList['mav'], s=1000, cmap=cm.get_cmap('binary'))
    ax.set_title("mav")
    plt.colorbar(sc, ticks = featureList['mav'])
    ax.grid(True)
    ax = fig.add_subplot(224)
    sc = ax.scatter([2,2,3,3,3,2], [3,1,1,2,3,2], c=featureList['ni'], s=1000, cmap=cm.get_cmap('binary'))
    ax.set_title("ni")
    plt.colorbar(sc, ticks = featureList['ni'])
    ax.grid(True)
    
    ax = fig.add_subplot(222)
    sc = ax.scatter([2,2,3,3,3,2], [3,1,1,2,3,2], c=featureList['rmsd'], s=1000, cmap=cm.get_cmap('binary'))
    plt.colorbar(sc, ticks = featureList['rmsd'])
    ax.set_title("rmsd")
    ax.grid(True)
    ax = fig.add_subplot(223)
    sc = ax.scatter([2,2,3,3,3,2], [3,1,1,2,3,2], c=featureList['var'], s=1000, cmap=cm.get_cmap('binary'))
    ax.set_title("var")
    plt.colorbar(sc, ticks = featureList['var'])
    ax.grid(True)
    
    if save:
        save.savefig(k)
    else:
        plt.show()
Beispiel #11
0
def _plot_radiation_pattern_quiver(ax3d, ned_mt, type):
    """
    Private routine that plots the wave farfield into an
    :class:`~mpl_toolkits.mplot3d.axes3d.Axes3D` object

    :type ax3d: :class:`mpl_toolkits.mplot3d.axes3d.Axes3D`
    :param ax3d: matplotlib Axes3D object
    :param ned_mt: the 6 comp moment tensor in NED orientation
    :type type: str
    :param type: 'P' or 'S' (P or S wave).
    """
    import matplotlib.pyplot as plt
    if MATPLOTLIB_VERSION < [1, 4]:
        msg = ("Matplotlib 3D quiver plot needs matplotlib version >= 1.4.")
        raise ImportError(msg)

    type = type.upper()
    if type not in ("P", "S"):
        msg = ("type must be 'P' or 'S'")
        raise ValueError(msg)
    is_p_wave = type == "P"

    # precompute even spherical grid and directional cosine array
    points = _equalarea_spherical_grid(nlat=14)

    if is_p_wave:
        # get radiation pattern
        disp = farfield(ned_mt, points, type="P")
        # normalized magnitude:
        magn = np.sum(disp * points, axis=0)
        magn /= np.max(np.abs(magn))
        cmap = get_cmap('bwr')
    else:
        # get radiation pattern
        disp = farfield(ned_mt, points, type="S")
        # normalized magnitude (positive only):
        magn = np.sqrt(np.sum(disp * disp, axis=0))
        magn /= np.max(np.abs(magn))
        cmap = get_cmap('Greens')

    # plot
    # there is a mlab3d bug that quiver vector colors and lengths
    # can only be changed if we plot each arrow independently
    for loc, vec, mag in zip(points.T, disp.T, magn.T):
        norm = plt.Normalize(-1., 1.)
        color = cmap(norm(mag))
        if is_p_wave:
            loc *= (1. + mag / 2.)
            length = abs(mag) / 2.0
        else:
            length = abs(mag) / 5.0
        ax3d.quiver(loc[0], loc[1], loc[2], vec[0], vec[1], vec[2],
                    length=length, color=color)
    ax3d.set(xlim=(-1.5, 1.5), ylim=(-1.5, 1.5), zlim=(-1.5, 1.5),
             xticks=[-1, 1], yticks=[-1, 1], zticks=[-1, 1],
             xticklabels=['South', 'North'],
             yticklabels=['West', 'East'],
             zticklabels=['Up', 'Down'],
             title='{} wave farfield'.format(type))
    ax3d.view_init(elev=-110., azim=0.)
Beispiel #12
0
  def plot (self, xres, yres, plain, spectra, nchan, freq, bw, tsamp, nsamps):
    self.openPlot(xres, yres, plain)

    tmin = 0
    tmax = nsamps * tsamp

    fmin = freq - (bw/2)
    fmax = freq + (bw/2)

    if numpy.amax(spectra) == numpy.amin(spectra):
      spectra[0][0] = 1

    if self.zap:
      spectra[0,:] = 0

    if self.log:
      vmax = numpy.log(numpy.amax(spectra))
      self.ax.imshow(spectra, extent=(tmin, tmax, fmin, fmax), aspect='auto', 
                     origin='lower', interpolation='nearest', norm=LogNorm(vmin=0.0001,vmax=vmax), 
                     cmap=cm.get_cmap('gray'))
    else:
      self.ax.imshow(spectra, extent=(tmin, tmax, fmin, fmax), aspect='auto', 
                     origin='lower', interpolation='nearest', 
                     cmap=cm.get_cmap('gray'))

    self.closePlot()
    def ChangePlotType(self, event):
        
        self.figure.clear()
        
        # Create an image plot
        if event.GetId() == 100:
            self.subplot = self.figure.add_subplot(111)
            self.plot = self.subplot.imshow(self.z_values, cmap=cm.get_cmap('gnuplot2'), norm=None, aspect='equal',
                                            interpolation=None, alpha=None, vmin=self.minValue, vmax=self.maxValue,
                                            origin='lower')
            self.plot_type = constants.IMAGE

        # Create a 3D wire plot
        if event.GetId() == 101:
            self.subplot = self.figure.add_subplot(111, projection='3d')
            self.plot = self.subplot.plot_wireframe(self.x_values, self.y_values, self.z_values)
            self.plot_type = constants.WIREFRAME
            
        # Create a 3D surface plt    
        if event.GetId() == 102:
            self.subplot = self.figure.add_subplot(111, projection='3d')
            self.plot = self.subplot.plot_surface(self.x_values, self.y_values, self.z_values, rstride=1, cstride=1,
                                                  cmap=cm.get_cmap('cool'), linewidth=0, antialiased=False)
            self.plot_type = constants.SURFACE

        if event.GetId() == 103:
            self.subplot = self.figure.add_subplot(111)
            dataCopy = self.z_values.copy(order='K')
            x_values = np.arange(0, dataCopy.size)
            self.subplot.plot(x_values, dataCopy.flatten('A'))
            self.plot_type = constants.TWOD_PLOT
            
        self.canvas.draw()
        
        return
def plotKernel(xRange, yRange, kernel, label):
    fig = plt.figure()
    
    plt.subplot(1,2,1)
    
    # adding the Contour lines with labels
    kernelMax = np.max(kernel)
    kernelMin = np.min(kernel)
    kernelValueThreshold = 10**-1
    
    if np.abs(kernelMax - kernelMin) < kernelValueThreshold:
        print "kernel value range is < " + str(kernelValueThreshold) + ", therefore image will not contains contours"
    else:
        contourIncrement = np.round(np.abs((kernelMax - kernelMin)) * 0.1, 2)
        contourRange = np.arange(np.min(kernel), np.max(kernel) , contourIncrement )
    
        cset = contour(kernel,contourRange, linewidths=2,cmap=cm.get_cmap('set2'))
        plt.clabel(cset,inline=True,fmt='%1.1f',fontsize=10)

    # latex fashion title
#     title('$z=3*e^{-(x^2+y^2)}$')
    title(label)
    
    plt.imshow(kernel,cmap=cm.get_cmap('gray')) # drawing the function

    ax = fig.add_subplot(1, 2, 2, projection='3d')
    surf = ax.plot_surface(xRange, yRange, kernel, rstride=1, cstride=1, 
    cmap=cm.get_cmap('RdBu'),linewidth=0, antialiased=False)
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    
    plt.show()
Beispiel #15
0
def cmap_discretize(cmap, n_colors=10):
    """Return discretized colormap.

    Parameters
    ----------
    cmap : str or colormap object
        Colormap to discretize.
    n_colors : int
        Number of discrete colors to divide `cmap` into.

    Returns
    ----------
    disc_cmap : LinearSegmentedColormap
        Discretized colormap.
    """
    try:
        cmap = cm.get_cmap(cmap)
    except:
        cmap = cm.get_cmap(eval(cmap))
    colors_i = np.concatenate((np.linspace(0, 1., n_colors), (0., 0., 0., 0.)))
    colors_rgba = cmap(colors_i)
    indices = np.linspace(0, 1., n_colors + 1)
    cdict = {}
    for ki, key in enumerate(('red', 'green', 'blue')):
        cdict[key] = [(indices[i], colors_rgba[i - 1, ki], colors_rgba[i, ki])
                      for i in range(n_colors + 1)]

    return mpl.colors.LinearSegmentedColormap(cmap.name + "_%d" % n_colors,
                                              cdict, 1024)
Beispiel #16
0
def save_seg_plot(outfile_path, title_str1, title_str2,
                  ref_intervals, ref_labels, est_intervals, est_labels,
                  cmap='Accent'):
    fig = plt.figure(figsize=(9, 3))

    ulabel, invind = np.unique(ref_labels, return_inverse=True)
    norm = mpl.colors.Normalize(vmin=np.min(invind), vmax=np.max(invind))
    cmap = cm.get_cmap(cmap)
    m = cm.ScalarMappable(norm=norm, cmap=cmap)

    plt.subplot(211)
    seg = [interval[0] for interval in ref_intervals[1:]]
    plt.vlines(seg, 0, 1, linewidth=1)
    for interval, i in zip(ref_intervals, invind):
        plt.fill_between([interval[0], interval[1]], 0, 1, color=m.to_rgba(i))
    plt.title('Ground truth segmentation - ' + title_str1)
    plt.xlim(0, ref_intervals[-1][1])
    plt.yticks([])
    plt.xticks([])

    ax = fig.add_subplot(212)
    ulabel, invind = np.unique(est_labels, return_inverse=True)
    norm = mpl.colors.Normalize(vmin=np.min(invind), vmax=np.max(invind))
    cmap = cm.get_cmap(cmap)
    m = cm.ScalarMappable(norm=norm, cmap=cmap)
    seg = [interval[0] for interval in est_intervals[1:]]
    plt.vlines(seg, 0, 1, linewidth=1)
    for interval, i in zip(est_intervals, invind):
        plt.fill_between([interval[0], interval[1]], 0, 1, color=m.to_rgba(i))
    plt.title('Detected segmentation - ' + title_str2)
    plt.xlim(0, est_intervals[-1][1])
    plt.yticks([])
    plt.xticks([])
    plt.tight_layout()
    plt.savefig(outfile_path)
Beispiel #17
0
    def showMask(self, splot, mask):
        if mask != None:
            nr, nc = mask.shape
            extent = [-0.5, nc-0.5, -0.5, nr-0.5]

            if self.displayMaskFlag == self.MASK_SHOWN:
                labels = _N.unique(mask)
                for il, lab in enumerate(labels):
                    if lab != 0:
                        if self.maskCm!=None : cm = self.maskCm[lab]
                        else : cm = get_cmap('binary')
                        splot.contour((mask==lab).astype(int), 1,
                                      cmap=cm, linewidths=2., extent=extent,alpha=.7)
                                     #cmap=cm, linewidths=1.5, extent=extent,alpha=.7)
            if self.displayMaskFlag == self.MASK_ONLY:
                if self.maskLabel == 0:
                    labels = _N.unique(mask)
                    for il, lab in enumerate(labels):
                        if lab != 0:
                            if self.maskCm != None:
                                cm = self.maskCm[lab]
                            else:
                                cm = get_cmap('binary')
                            ml = (mask==lab).astype(int)
                            print 'contouf of mask label %d -> %d pos' \
                                %(lab, ml.sum())
                            splot.contourf(ml, 1,
                                           cmap=cm, linewidths=1., extent=extent)
                elif (mask==self.maskLabel).sum() > 0:
                    if self.maskCm != None:
                        cm = self.maskCm[_N.where(mask==self.maskLabel)[0]]
                    else:
                        cm = get_cmap('binary')
                    ax.contourf((mask==self.maskLabel).astype(int), 1,
                                cmap=cm, linewidths=1.5, extent=extent)
Beispiel #18
0
    def _create_palette(self):
        '''Create a palette based on Matplotlib colormap name

        default number of color palette is 250.
        it means 6 colors are possible to use for other purposes.
        the last palette (255) is white and the second last (254) is black.

        Modifies
        --------
        self.palette : numpy array (uint8)

        '''
        # test if given colormap name is in builtin or added colormaps
        try:
            cmap = cm.get_cmap(self.cmapName)
        except:
            self.logger.error('%s is not a valid colormap' % self.cmapName)
            self.cmapName = self._cmapName

        # get colormap by name
        cmap = cm.get_cmap(self.cmapName)

        # get colormap look-up
        cmapLUT = np.uint8(cmap(range(self.numOfColor)) * 255)
        # replace all last colors to black and...
        lut = np.zeros((3, 256), 'uint8')
        lut[:, :self.numOfColor] = cmapLUT.T[:3]
        # ...and the most last color to white
        lut[:, -1] = 255

        # set palette to be used by PIL
        self.palette = lut.T.flatten().astype(np.uint8)
Beispiel #19
0
def mh_colors(number):
    if number <= 8:
        colors = [cm.get_cmap('Set1')(1. * i / 8.0)
                  for i in range(9)]
    else:
        colors = [cm.get_cmap('gist_rainbow')(1. * i / (number - 1))
                  for i in range(number)]
    return colors
 def getColorMap(self):
     if (COLOR_CHOICES[self.colorMap.get()] is 'other'): 
         cmap = cm.get_cmap(self.otherColorMap.get())
     else:
         cmap = cm.get_cmap(COLOR_CHOICES[self.colorMap.get()])
     if cmap is None:
         cmap = cm.jet
     return cmap
Beispiel #21
0
    def __init__(self, ax, images, viewer, view=2, display_cross='hv', im_params=None):
        self.axes = ax
        self.images = images  # this is a list of images
        self.viewer = viewer
        self.view = view
        self.display_cross = display_cross

        self.image_dim = self.images[0].data.shape
        self.figs = []

        self.cross_to_display = None
        self.aspect_ratio = None
        for i, image in enumerate(images):
            data_to_display = None
            if self.view == 1:
                self.cross_to_display = [[[self.viewer.current_point.y, self.viewer.current_point.y], [-10000, 10000]],
                                         [[-10000, 10000], [self.viewer.current_point.z, self.viewer.current_point.z]]]
                self.aspect_ratio = self.viewer.aspect_ratio[0]
                data_to_display = image.data[int(self.image_dim[0] / 2), :, :]

            elif self.view == 2:
                self.cross_to_display = [[[self.viewer.current_point.x, self.viewer.current_point.x], [-10000, 10000]],
                                         [[-10000, 10000], [self.viewer.current_point.z, self.viewer.current_point.z]]]
                self.aspect_ratio = self.viewer.aspect_ratio[1]
                data_to_display = image.data[:, int(self.image_dim[1] / 2), :]
            elif self.view == 3:
                self.cross_to_display = [[[self.viewer.current_point.x, self.viewer.current_point.x], [-10000, 10000]],
                                         [[-10000, 10000], [self.viewer.current_point.y, self.viewer.current_point.y]]]
                self.aspect_ratio = self.viewer.aspect_ratio[2]
                data_to_display = image.data[:, :, int(self.image_dim[2] / 2)]

            if str(i) in im_params.images_parameters:
                my_cmap = copy(cm.get_cmap(im_params.images_parameters[str(i)].cmap))
                my_interpolation = im_params.images_parameters[str(i)].interp
                my_alpha = float(im_params.images_parameters[str(i)].alpha)
            else:
                my_cmap = cm.get_cmap('gray')
                my_interpolation = 'nearest'
                my_alpha = 1.0

            my_cmap.set_under('b', alpha=0)
            self.figs.append(self.axes.imshow(data_to_display, aspect=self.aspect_ratio, alpha=my_alpha))
            self.figs[-1].set_cmap(my_cmap)
            self.figs[-1].set_interpolation(my_interpolation)

        self.axes.set_axis_bgcolor('black')
        self.axes.set_xticks([])
        self.axes.set_yticks([])

        self.line_horizontal = Line2D(self.cross_to_display[1][1], self.cross_to_display[1][0], color='white')
        self.line_vertical = Line2D(self.cross_to_display[0][1], self.cross_to_display[0][0], color='white')
        if 'h' in display_cross:
            self.axes.add_line(self.line_horizontal)
        if 'v' in display_cross:
            self.axes.add_line(self.line_vertical)

        self.zoom_factor = 1.0
Beispiel #22
0
def cmap(data, robust=True, cmap_seq='magma', cmap_bool='gray_r', cmap_div='coolwarm'):
    '''Get a default colormap from the given data.

    If the data is boolean, use a black and white colormap.

    If the data has both positive and negative values,
    use a diverging colormap.

    Otherwise, use a sequential colormap.

    Parameters
    ----------
    data : np.ndarray
        Input data

    robust : bool
        If True, discard the top and bottom 2% of data when calculating
        range.

    cmap_seq : str
        The sequential colormap name

    cmap_bool : str
        The boolean colormap name

    cmap_div : str
        The diverging colormap name

    Returns
    -------
    cmap : matplotlib.colors.Colormap
        The colormap to use for `data`

    See Also
    --------
    matplotlib.pyplot.colormaps
    '''

    data = np.atleast_1d(data)

    if data.dtype == 'bool':
        return get_cmap(cmap_bool)

    data = data[np.isfinite(data)]

    if robust:
        min_p, max_p = 2, 98
    else:
        min_p, max_p = 0, 100

    max_val = np.percentile(data, max_p)
    min_val = np.percentile(data, min_p)

    if min_val >= 0 or max_val <= 0:
        return get_cmap(cmap_seq)

    return get_cmap(cmap_div)
    def color_map(x, palette=palette):
        """To be consumed by np.vectorize to transform nan values to black
        and provide the color map"""

        if np.isnan(x):
            return [0, 0, 0]
        elif x < 0:
            return list(cm.get_cmap(palette)(0, bytes=True)[:3])
        else:
            return list(cm.get_cmap(palette)(x, bytes=True)[:3])
def plotImageComparison(sourceImage, filteredImage):
    
    plt.subplot(3,1,1)
    plt.imshow(sourceImage, cmap=cm.get_cmap('gray'))
    plt.subplot(3,1,2)
    plt.imshow(filteredImage, cmap=cm.get_cmap('gray'))
    plt.subplot(3,1,3)
    plt.imshow(filteredImage, cmap=cm.get_cmap('gray'))
    plt.imshow(filteredImage - sourceImage, cmap=cm.get_cmap('gray'))
    plt.show()
Beispiel #25
0
 def plot(self, xys, neighborhoods=None, shpfile=None, outfile=None,
         title=None):
     if self.happy_ending:
         cm = get_cmap('RdBu')
         cm = get_cmap('Accent')
         f = plt.figure()
         ax = f.add_subplot(111)
         grid = ax.scatter(xys[:, 0], xys[:, 1], alpha=0.75, linewidths=0, \
                 s=80, marker=None, color='0.6', cmap=cm)
         axys = xys[self.agent_xyids, :]
         ax.scatter(axys[:, 0], axys[:, 1], alpha=0.8, linewidths=0, \
                 s=20, marker='o', c=self.group_map, cmap=cm)
         props = self.prop_groups + [1. - sum(self.prop_groups)]
         if title == None:
             title = "%i agents | %s share | %.2f similar wanted"\
                     %(self.pop_size, '_'.join(map(str, props)), \
                             self.pct_similar_wanted)
         plt.title(title, color='0.3')
         ax.set_frame_on(False)
         ax.axes.get_yaxis().set_visible(False)
         ax.axes.get_xaxis().set_visible(False)
         if neighborhoods:
             nr, nc = neighborhoods
             r = len(set(xys[:, 1]))
             ir = int(np.round((r*1.)/nr))
             nrb = [i+ir for i in range(-ir, r, ir)]
             nrb[-1] += 0.5
             nrb[0] -= 0.5
             c = len(set(xys[:, 0]))
             ic = int(np.round((c*1.)/nc))
             ncb = [i+ic for i in range(-ic, c, ic)]
             ncb[0] -= 0.5
             ncb[-1] += 0.5
             # Horizontal lines
             for i in nrb:
                 plt.hlines(i-0.5, xmin=-1, xmax=c, color='k')
             # Vertical lines
             for i in ncb:
                 plt.vlines(i-0.5, ymin=-1, ymax=r, color='k')
         elif shpfile:
             from pysal.contrib.viz import mapping as viz
             shp = ps.open(shpfile)
             patchco = viz.map_poly_shp(shp)
             patchco.set_facecolor('none')
             patchco.set_edgecolor('0.3')
             patchco.set_linewidth(0.3)
             ax = viz.setup_ax([patchco], ax)
         fc = '1'
         f.set_facecolor(fc)
         if not outfile:
             plt.show()
         else:
             plt.savefig(outfile, facecolor=fc)
     else:
         print 'No use in plotting a bad ending'
Beispiel #26
0
def crossSectionPlot(
    pts, axes=(0, 1, 2), margin=0.1, limits="None", color="axis3", cmap="Blues_r", negcmap=None, alpha=None
):

    # compute max and min values if not already given
    if limits == "None":
        maxVals = np.max(pts, axis=0)
        minVals = np.min(pts, axis=0)
    else:
        maxVals = np.asarray(limits.max)
        minVals = np.asarray(limits.min)

    # easier names for which indices serve which purpose
    xInd = axes[0]
    yInd = axes[1]
    if color == "axis3":
        colorInd = axes[2]

    # compute axis limits
    offsets = (margin / (1.0 - margin)) * ((maxVals - minVals) / 2)
    axisMin = minVals - offsets
    axisMax = maxVals + offsets

    # special case where coloring by z-axis
    if color == "axis3":
        color = pts[:, colorInd]

    # get colors/alphas
    if negcmap is None:
        if type(cmap) is np.ndarray:
            c = np.array([cmap[x] for x in color])
        else:
            cmap = get_cmap(cmap)
            norm = Normalize(min(color), max(color))
            c = cmap(norm(color))
    else:
        cmapPos, cmapNeg = get_cmap(cmap), get_cmap(negcmap)
        pos, neg = np.where(color >= 0)[0], np.where(color < 0)[0]
        colorPos, colorNeg = color[pos], -color[neg]
        c = np.zeros((color.shape[0], 4))
        if pos.size != 0:
            normPos = Normalize(0, max(colorPos))
            c[pos, :] = cmapPos(normPos(colorPos))
        if neg.size != 0:
            normNeg = Normalize(0, max(colorNeg))
            c[neg, :] = cmapNeg(normNeg(colorNeg))
    if alpha is not None:
        c[:, 3] = alpha

    # generate plot
    plt.scatter(pts[:, xInd], pts[:, yInd], c=c, lw=0)
    plt.xlim([minVals[xInd] - offsets[xInd], maxVals[xInd] + offsets[xInd]])
    plt.ylim([minVals[yInd] - offsets[yInd], maxVals[yInd] + offsets[yInd]])
Beispiel #27
0
def myerrorbar(ax, x, y, xerr=None, yerr=None, zorder=0, color=None, 
	marker=None, size=None, colorbar=False, cmap=None, vmin=None, vmax=None):
	import matplotlib.pyplot as plt
	from matplotlib import cm
	
	sc = ax.scatter(x, y, marker=marker, s=size, c=color, 
		zorder=zorder, cmap=cmap, vmin=vmin, vmax=vmax)
	ax.sc = sc

	if colorbar:
		#create colorbar according to the scatter plot
		clb = plt.colorbar(sc)

	#create errorbar plot and return the outputs to a,b,c

	#convert time to a color tuple using the colormap used for scatter
	if color is not None:
		if not isinstance(color, str):
			a,b,c = ax.errorbar(x, y, xerr=xerr, yerr=yerr, fmt='.',
				zorder=zorder-1)

			color = np.array(color).astype(float)
			# if colorbar:
			# 	time_color = clb.to_rgba(color)
			# else:
			if isinstance(cmap, str):
				cmap = cm.get_cmap(cmap)
			elif cmap is None:
				cmap = cm.get_cmap()
			if vmin is None:
				color = cmap((color - np.nanmin(color))/nanptp(color))
			else:
				color = cmap(((color - vmin)/(vmax - vmin)).clip(0.,1.))

			# adjust the color of c[0], which is a LineCollection, 
			#	to the colormap
			if xerr is not None:
				m = np.isfinite(x) * np.isfinite(y) * np.isfinite(xerr)
				c[0].set_color(color[m])

				if yerr is not None:
					m = np.isfinite(x) * np.isfinite(y) * np.isfinite(yerr)
					c[1].set_color(color[m])

			elif yerr is not None:
				m = np.isfinite(x) * np.isfinite(y) * np.isfinite(yerr)
				c[0].set_color(color[m])


			
		else:
			a,b,c = ax.errorbar(x, y, xerr=xerr, yerr=yerr, fmt='',
				zorder=zorder-1, color=color)
Beispiel #28
0
def plot_z2(f, fignum=None, range=None, color_map='gray'):

    # plt.figure(fignum)

    if range is None:
        plt.imshow(f, interpolation='nearest', cmap=cm.get_cmap(color_map))
    else:
        plt.imshow(f, interpolation='nearest', cmap=cm.get_cmap(color_map),
                   vmin=range[0], vmax=range[1])

    plt.xticks(np.arange(f.shape[1]), [str(i) for i in np.arange(f.shape[1])])
    plt.yticks(np.arange(f.shape[0]), [str(i) for i in np.arange(f.shape[0])])
Beispiel #29
0
 def get_color_map(self,name=None,reverse=False):
     """A function to get a matplotlib colour map by name"""
     if name is None: name = self.default_map        
     if name.endswith('_r'):
         name = name[:-2] # remove "_r"
         reverse = not reverse
     # Use the standard maps
     if reverse:
         cm = mplcm.get_cmap(name+'_r')
     else:
         cm = mplcm.get_cmap(name)
     return cm #LinearSegmentedColormap.from_list(cm)
Beispiel #30
0
    def _plotMinimalization(self):
        """
        Plots a two dimensional map of the minimization.
        Also plots the best fit model and the spectroscopic data profiles.
        """
        #minima profiles
        fig = plt.figure(1)
        ax = fig.add_subplot(111)
        ax.plot(self.fitting['model'], label='Model (Slit Profiles)')
        ax.plot(self.result['bestfit'], label='Best Fit')
        plt.legend(shadow=True, fancybox=True, loc='best')
        plt.xlim(0, ax.get_xlim()[1])
        plt.ylim(0, ax.get_ylim()[1])
        plt.ylabel('Flux [microJy]')
        plt.savefig('MinimaProfile.pdf')
        plt.close()

        #minima map
        data = self.result['outputs']
        d = np.asarray([[x[0], x[1], x[2], x[4]] for x in data])
        msk = d[:, 0] == self.result['rotation']
        plt.title('Chisq Minimalization Map: Rotation = %.2f' % self.result['rotation'])
        plt.scatter(d[:, 1][msk],
                    d[:, 2][msk],
                    c=1. / d[:, 3][msk],
                    s=20,
                    cmap=cm.get_cmap('jet'),
                    edgecolor='none',
                    alpha=0.2)
        plt.xlim(-self.fitting['xrange'], self.fitting['xrange'])
        plt.ylim(-self.fitting['yrange'], self.fitting['yrange'])
        plt.xlabel('X [pixels]')
        plt.ylabel('Y [pixels]')
        plt.savefig('MinimaMapChisq.png')
        plt.close()

        #minima map2
        d = np.asarray([[x[1], x[2], x[6]] for x in data])
        plt.title('Correlation Minimalization Map: Rotation = %.2f' % self.result['rotation'])
        plt.scatter(d[:, 0][msk],
                    d[:, 1][msk],
                    c=d[:, 2][msk],
                    s=20,
                    cmap=cm.get_cmap('jet'),
                    edgecolor='none',
                    alpha=0.2)
        plt.xlim(-self.fitting['xrange'], self.fitting['xrange'])
        plt.ylim(-self.fitting['yrange'], self.fitting['yrange'])
        plt.xlabel('X [pixels]')
        plt.ylabel('Y [pixels]')
        plt.savefig('MinimaMapCorr.png')
        plt.close()
Beispiel #31
0
def simple_plot(resource,
                variable='air',
                lat='lat',
                lon='lon',
                timestep=0,
                output=None):
    """
    Generates a nice and simple plot.
    """
    print("Plotting {}, timestep {} ...".format(resource, timestep))

    pl_data = Dataset(resource)

    pl_val = pl_data.variables[variable][timestep, :, :]
    pl_lat = pl_data.variables[lat][:]
    pl_lon = pl_data.variables[lon][:]

    fig = plt.figure()
    fig.set_size_inches(18.5, 10.5, forward=True)

    ax = plt.axes(projection=ccrs.PlateCarree())
    ax.coastlines(linewidth=0.8)
    ax.gridlines()

    vmin = np.min(pl_val)
    vmax = np.max(pl_val)

    levels = np.linspace(vmin, vmax, 30)

    cmap = get_cmap("RdBu_r")

    data_map = ax.contourf(pl_lon,
                           pl_lat,
                           pl_val,
                           levels=levels,
                           extend='both',
                           cmap=cmap,
                           projection=ccrs.PlateCarree())
    data_cbar = plt.colorbar(data_map, extend='both', shrink=0.6)
    data_cont = ax.contour(pl_lon,
                           pl_lat,
                           pl_val,
                           levels=levels,
                           linewidths=0.5,
                           colors="white",
                           linestyles='dashed',
                           projection=ccrs.PlateCarree())

    plt.clabel(data_cont, inline=1, fmt='%1.0f')
    title = 'Simple plot for %s' % (variable)
    plt.title(title)
    plt.tight_layout()

    if not output:
        output = 'myplot_%s.png' % (uuid.uuid1())

    plt.savefig(output)
    fig.clf()
    plt.close(fig)

    print("Plot written to {}".format(output))
    return output
Beispiel #32
0
    accuracyWithoutSP = classificationAccuracyVsNoise(None, inputVectors,
                                                      noiseLevelList)

    epochs = 800

    activeColumnsCurrentEpoch = np.zeros((numInputVector, columnNumber))
    activeColumnsPreviousEpoch = np.zeros((numInputVector, columnNumber))
    connectedCounts = np.zeros((columnNumber, ))
    numBitDiffTrace = []
    numConnectedSynapsesTrace = []
    numNewlyConnectedSynapsesTrace = []
    numEliminatedSynapsesTrace = []
    entropyTrace = []

    fig, ax = plt.subplots()
    cmap = cm.get_cmap('jet')
    for epoch in range(epochs):
        print "training SP epoch {}".format(epoch)
        # calcualte overlap curve here
        if epoch % 50 == 0 and trackOverlapCurveOverTraining:
            inputOverlapScore, outputOverlapScore = calculateOverlapCurve(
                sp, inputVectors, inputVectorType)
            plt.plot(np.mean(inputOverlapScore, 0),
                     np.mean(outputOverlapScore, 0),
                     color=cmap(float(epoch) / epochs))

        activeColumnsPreviousEpoch = copy.copy(activeColumnsCurrentEpoch)
        connectedCountsPreviousEpoch = copy.copy(connectedCounts)

        # train SP here,
        # Learn is turned off at the first epoch to gather stats of untrained SP
Beispiel #33
0
# BACKGROUND CORRECTION
bkg = 1.3e-5
bkgstr = str(bkg * 1e6)[:4]
bkgstr= bkgstr.replace('.', '_')
bkgstr = 'bkg' + bkgstr

sub_img = img - bkg  # -(astropy_conv_mask_1sigma*img)
sub_img[sub_img < 0] = np.nan


plt.clf()
wcs_hdr = WCS(hdu[0].header)
fig, ax = mp.plot_casa(figsize=[8, 6], coords=True, wcs=wcs_hdr)
im = ax.imshow(sub_img, origin='lower', norm=LogNorm(vmin=5e-6, vmax=2e-4))
cbar = mp.set_colorbar(fig, im, title=r'Flux density [Jy]')
cmap = cm.get_cmap()
cmap.set_bad(color='black')
ax.set_title('bkg subtracted image (' + str(bkg) + 'Jy)')
plt.savefig(outpath + '4_fig_spitzer_reprobin3_' + str(bkgstr) + '.pdf', bbox_inches='tight', dpi=100)
plt.show()
plt.close(fig)

sub_img[np.isnan(sub_img)] = 0

header = hdu[0].header
header['history'] = '--------------------------------------------------'
header['history'] = 'Used script:    4_1subbkg_spitzer.py'
header['history'] = 'Author:         Vladimir Domcek'
header['history'] = 'Date and time:  ' + time.strftime('%X %x %Z')
header['history'] = 'Main changes: '
header['history'] = 'Background subtraction with value: ' + str(bkg)
Beispiel #34
0
def get_sub_cmap(cmap, start, stop, *, N=None):
    """
    Creates a :obj:`~matplotlib.cm.ListedColormap` object using the colors in
    the range `[start, stop]` of the provided `cmap` and returns it.

    This function can be used to create a colormap that only uses a portion of
    an existing colormap.
    If `N` is not set to *None*, this function creates a qualitative colormap
    from `cmap` instead.

    Parameters
    ----------
    cmap : str or :obj:`~matplotlib.colors.Colormap` object
        The registered name of the colormap in :mod:`matplotlib.cm` or its
        corresponding :obj:`~matplotlib.colors.Colormap` object.
    start, stop : float
        The normalized range of the colors in `cmap` that must be in the
        sub-colormap.

    Optional
    --------
    N : int or None. Default: None
        The number of color segments to take from the provided `cmap` within
        the range given by the provided `start` and `stop`.
        If *None*, take all colors in `cmap` within this range.

    Returns
    -------
    sub_cmap : :obj:`~matplotlib.colors.ListedColormap`
        The created colormap that uses a subset of the colors in `cmap`.
        If `N` is not *None*, this will be a qualitative colormap.

    Example
    -------
    Creating a colormap using the first 80% of the 'rainforest' colormap::

        >>> get_sub_cmap('cmr.rainforest', 0, 0.8)

    Creating a qualitative colormap containing five colors from the middle 60%
    of the 'lilac' colormap:

        >>> get_sub_cmap('cmr.lilac', 0.2, 0.8, N=5)

    Notes
    -----
    As it can create artifacts, this function does not interpolate between the
    colors in `cmap` to fill up the space. Therefore, using values for `start`
    and `stop` that are too close to each other, may result in a colormap that
    contains too few different colors to be smooth.
    It is recommended to use at least 128 different colors in a colormap for
    optimal results (*CMasher* colormaps have 256 or 511 different colors, for
    sequential or diverging colormaps respectively).
    One can check the number of colors in a colormap with
    :attr:`matplotlib.colors.Colormap.N`.

    Any colormaps created using this function are not registered in either
    *CMasher* or *MPL*.

    """

    # Obtain the colormap
    cmap = mplcm.get_cmap(cmap)

    # Check value of N to determine suffix for the name
    suffix = '_sub' if N is None else '_qual'

    # Obtain colors
    colors = take_cmap_colors(cmap, N, cmap_range=(start, stop))

    # Create new colormap
    sub_cmap = LC(colors, cmap.name + suffix, N=len(colors))

    # Return sub_cmap
    return (sub_cmap)
    return df, encoder, columns_


# This filter is not being used. Because the 'accuracy' is better without this filter.
# df2, enc_relieff, columns_relieff = importance_relieff_fit(df, target_encoded)

# %% [markdown]
# ## PCA
# The following is an implementation of the `Principal Component Analysis`.<br>

# %%
### PCA ----
# OneDrive\GMBD\MACHINE LEARNING II (MBD-EN-BL2020J-1_32R202_380379)\Session 9 - Forum - Dimensionality Reduction\Notebook on PCA\PCA_v2.ipynb

name = "Accent"
cmap = get_cmap(name)  # type: matplotlib.colors.ListedColormap
colors = cmap.colors  # type: list


def pca_transform(data, target, n=2, encoder=None):
    """Applies the principal component algorithm to the data frame.

    Args:
        data (DataFrame): Source data
        target (str): Column name
        n (int, optional): Number of components to be calculated. Defaults to 2.
        encoder (obj, optional): Object of the type 'PCA'. Defaults to None.

    Returns:
        DataFrame: Same as source
        List: Variance explained by each PC.
Beispiel #36
0
def gauge(labels=['LOW', 'MEDIUM', 'HIGH', 'VERY HIGH', 'EXTREME'],
          colors='jet_r',
          cat=1,
          title='',
          fname='./gauge.png'):
    """
    some sanity checks first
    
    """

    N = len(labels)

    if cat > N:
        raise Exception(
            "\n\nThe category ({}) is greated than the length\nof the labels ({})"
            .format(cat, N))
    """
    if colors is a string, we assume it's a matplotlib colormap
    and we discretize in N discrete colors 
    """

    if isinstance(colors, str):
        cmap = cm.get_cmap(colors, N)
        cmap = cmap(np.arange(N))
        colors = cmap[::-1, :].tolist()
    if isinstance(colors, list):
        if len(colors) == N:
            colors = colors[::-1]
        else:
            raise Exception(
                "\n\nnumber of colors {} not equal to number of categories{}\n"
                .format(len(colors), N))
    """
    begins the plotting
    """

    fig, ax = plt.subplots()

    ang_range, mid_points = degree_range(N)

    labels = labels[::-1]
    """
    plots the sectors and the arcs
    """
    patches = []
    for ang, c in zip(ang_range, colors):
        # sectors
        patches.append(Wedge((0., 0.), .4, *ang, facecolor='w', lw=2))
        # arcs
        patches.append(
            Wedge((0., 0.), .4, *ang, width=0.10, facecolor=c, lw=2,
                  alpha=0.5))

    [ax.add_patch(p) for p in patches]
    """
    set the labels (e.g. 'LOW','MEDIUM',...)
    """

    for mid, lab in zip(mid_points, labels):

        ax.text(0.35 * np.cos(np.radians(mid)), 0.35 * np.sin(np.radians(mid)), lab, \
            horizontalalignment='center', verticalalignment='center', fontsize=14, \
            fontweight='bold', rotation = rot_text(mid))
    """
    set the bottom banner and the title
    """
    r = Rectangle((-0.4, -0.1), 0.8, 0.1, facecolor='w', lw=2)
    ax.add_patch(r)

    ax.text(0, -0.05, title, horizontalalignment='center', \
         verticalalignment='center', fontsize=22, fontweight='bold')
    """
    plots the arrow now
    """

    pos = mid_points[abs(cat - N)]

    ax.arrow(0, 0, 0.225 * np.cos(np.radians(pos)), 0.225 * np.sin(np.radians(pos)), \
                 width=0.04, head_width=0.09, head_length=0.1, fc='k', ec='k')

    ax.add_patch(Circle((0, 0), radius=0.02, facecolor='k'))
    ax.add_patch(Circle((0, 0), radius=0.01, facecolor='w', zorder=11))
    """
    removes frame and ticks, and makes axis equal and tight
    """

    ax.set_frame_on(False)
    ax.axes.set_xticks([])
    ax.axes.set_yticks([])
    ax.axis('equal')
    plt.tight_layout()
    fig.savefig(fname, dpi=200)
    fig.pyplot(fname, dpi=200)
Beispiel #37
0
    def _UpdateDataSetValues(self):
        """
"""
        self.dataSetValues = None
        self.imageData = None
        self.npinx = self.npiny = 0

        self.channelMode = self.dmgr.IsChannelType(self.curDataSet)
        ds_type = self.dmgr.GetDataSetType(self.curDataSet)
        self.nodalMode = self.dmgr.IsNodalType(ds_type)

        #	-- Must have data
        #	--
        core = dset = None
        if self.dmgr.HasData():
            dset = self.dmgr.GetH5DataSet(self.curDataSet, self.timeValue)
            core = self.dmgr.GetCore()

        if dset is not None and core is not None:
            #		-- "Item" refers to channel or pin
            #		--
            item_factors = None
            if self.state.weightsMode == 'on':
                item_factors = self.dmgr.GetFactors(self.curDataSet)

            dset_array = np.array(dset)
            dset_shape = dset.shape
            ##      if self.nodalMode:
            ##        #self.npinx = self.npiny = item_col_limit = item_row_limit = 2
            ##        self.npinx = self.npiny = 2
            ##      else:
            ##	item_col_limit = core.npinx
            ##	item_row_limit = core.npiny
            ##        if self.channelMode:
            ##	  item_col_limit += 1
            ##	  item_row_limit += 1
            ##        self.npinx = min( item_col_limit, dset_shape[ 1 ] )
            ##        self.npiny = min( item_row_limit, dset_shape[ 0 ] )
            if self.nodalMode:
                self.npinx = self.npiny = 2
            else:
                self.npinx = dset_shape[1]
                self.npiny = dset_shape[0]

            draw_value_flag = \
                self.curDataSet is not None and \
         dset_shape[ 0 ] == 1 and dset_shape[ 1 ] == 1
            node_value_draw_list = []
            #assy_value_draw_list = []
            del self.textDrawList[:]

            axial_level = min(self.axialValue.pinIndex, dset_shape[2] - 1)
            axial_value = \
                self.dmgr.GetAxialValue( self.curDataSet, core_ndx = axial_level )

            self.cellRange = self.dmgr.ExtractSymmetryExtent()
            im_wd = self.cellRange[4] * self.npinx
            im_ht = self.cellRange[5] * self.npiny

            self.dataSetValues = np.empty((im_wd, im_ht), dtype=np.float64)
            self.dataSetValues[:] = np.nan
            self.imageData = np.zeros((im_wd, im_ht, 4), dtype=np.uint8)

            #		-- Create mapper
            #		--
            ds_range = self._ResolveDataRange(
                self.curDataSet,
                self.timeValue if self.state.scaleMode == 'state' else -1.0)
            if self.scaleType == 'log':
                norm = colors.LogNorm(vmin=max(ds_range[0], 1.0e-16),
                                      vmax=max(ds_range[1], 1.0e-16),
                                      clip=True)
            else:
                norm = colors.Normalize(vmin=ds_range[0],
                                        vmax=ds_range[1],
                                        clip=True)
            self.mapper = cm.ScalarMappable(norm=norm,
                                            cmap=cm.get_cmap(
                                                self.colormapName))
            self.mapper.set_array(dset_array)
            #trans_color_arr = np.array( [ 200, 200, 200, 255 ], dtype = np.uint8 )
            fc = np.array(self.fig.get_facecolor()) * 255.0
            trans_color_arr = fc.astype(np.uint8)

            #		-- Map data values to colors
            #		--
            im_row = 0
            for assy_row in range(self.cellRange[1], self.cellRange[3]):
                im_row_to = im_row + self.npiny
                im_col = 0

                for assy_col in range(self.cellRange[0], self.cellRange[2]):
                    im_col_to = im_col + self.npinx
                    assy_ndx = core.coreMap[assy_row, assy_col] - 1

                    if assy_ndx < 0 or assy_ndx >= dset_shape[3]:
                        self.imageData[ im_row : im_row_to, im_col : im_col_to ] = \
                            trans_color_arr

                    else:  # if assy_ndx >= 0 and assy_ndx < dset_shape[ 3 ]:
                        cur_array = dset_array[:, :, axial_level, assy_ndx]
                        cur_colors = self.mapper.to_rgba(cur_array, bytes=True)
                        if item_factors is not None:
                            cur_factors = item_factors[:, :, axial_level,
                                                       assy_ndx]
                            cur_colors[cur_factors == 0] = trans_color_arr
                            cur_colors[np.isnan(cur_array)] = trans_color_arr
                            cur_colors[np.isinf(cur_array)] = trans_color_arr

                        if self.nodalMode:
                            cur_array = cur_array.reshape((2, 2))
                            cur_colors = cur_colors.reshape((2, 2, 4))
                        self.dataSetValues[ im_row : im_row_to, im_col : im_col_to ] = \
                            cur_array
                        self.imageData[ im_row : im_row_to, im_col : im_col_to ] = \
                     cur_colors
                    #end else assy_ndx >= 0 and assy_ndx < dset_shape[ 3 ]

                    im_col = im_col_to
            #end for assy_col in range( self.cellRange[ 0 ], self.cellRange[ 2 ] )

                im_row = im_row_to
            #end for assy_row in range( self.cellRange[ 1 ], self.cellRange[ 3 ] )

            if draw_value_flag:
                for r in range(im_ht):
                    for c in range(im_wd):
                        if not np.array_equal(self.imageData[r, c],
                                              trans_color_arr):
                            clr = Widget.GetContrastColor(*self.imageData[r,
                                                                          c])
                            self.textDrawList.append((self._CreateValueString(
                                self.dataSetValues[r,
                                                   c]), np.array(clr) / 255.0,
                                                      c + 0.5, r + 0.5))
            #end if draw_value_flag

            tickbase = self.npiny / 2.0
            self.ytickLocs = [(i * self.npiny) + tickbase
                              for i in range(self.cellRange[5])]
            self.ytickLabels = [
                core.GetRowLabel(i)
                for i in range(self.cellRange[1], self.cellRange[3])
            ]

            tickbase = self.npinx / 2.0
            self.xtickLocs = [(i * self.npinx) + tickbase
                              for i in range(self.cellRange[4])]
            self.xtickLabels = [
                core.GetColLabel(i)
                for i in range(self.cellRange[0], self.cellRange[2])
            ]
def draw_Time_Crossection_rh_uv_Temp(
                    rh_2D=None, u_2D=None, v_2D=None,TMP_2D=None,terrain_2D=None,
                    t_range=None,model=None,lw_ratio=None,output_dir=None):        

    plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)                    
    # # 画图
    # Define the figure object and primary axes
    fig = plt.figure(1, figsize=(lw_ratio[0], lw_ratio[1]))
    ax = plt.axes()

 #   utl.add_public_title_sta(title=rh_2D.attrs['model']+'模式预报时间剖面',initTime=rh_2D['forecast_reference_time'].values, fontsize=23)

    # Plot RH using contourf
    #rh_contour = ax.contourf(rh_2D['time'].values, rh_2D['level'].values, np.squeeze(rh_2D['data'].values.swapaxes(1,0)),
    #                        levels=np.arange(0, 106, 5), cmap='RdBu')

    startcolor = '#1E90FF'   #蓝色
    midcolor = '#F1F1F1'     #白色
    endcolor = '#696969'     #灰色
    cmap2 = col.LinearSegmentedColormap.from_list('own2',['#1E90FF','#94D8F6','#F1F1F1','#BFBFBF','#696969'])
    # extra arguments are N=256, gamma=1.0
    cm.register_cmap(cmap=cmap2)

    rh_2D['data'].values[rh_2D['data'].values > 100]=100
    rh_contour = ax.contourf(rh_2D['time'].values, rh_2D['level'].values, np.squeeze(rh_2D['data'].values.swapaxes(1,0)),
                            levels=np.arange(0, 101, 0.5), cmap=cm.get_cmap('own2'),extend='max')
    rh_colorbar = fig.colorbar(rh_contour,ticks=[20,40,60,80,100])
    rh_colorbar.set_label('相对湿度(%)',size=15)

    ax.barbs(u_2D['time'].values, u_2D['level'].values,
            np.squeeze(u_2D['data'].values.swapaxes(1,0))*2.5,
            np.squeeze(v_2D['data'].values.swapaxes(1,0))*2.5, color='k')

    TMP_contour = ax.contour(TMP_2D['time'].values, TMP_2D['level'].values,  np.squeeze(TMP_2D['data'].values.swapaxes(1,0)),
                            levels=np.arange(-100, 100, 2), colors='#F4511E', linewidths=1)
    TMP_contour.clabel(TMP_contour.levels[1::2], fontsize=12, colors='#F4511E', inline=1,
                        inline_spacing=8, fmt='%i', rightside_up=True, use_clabeltext=True)

    TMP_contour_zero = ax.contour(TMP_2D['time'].values, TMP_2D['level'].values,  np.squeeze(TMP_2D['data'].values.swapaxes(1,0)),
                            levels=[0], colors='k', linewidths=2)
    TMP_contour_zero.clabel([0], fontsize=22, colors='k', inline=1,
                        inline_spacing=8, fmt='%i', rightside_up=True, use_clabeltext=True)

    startcolor = '#8B4513'   #棕色
    endcolor='#DAC2AD' #绿 
    cmap2 = col.LinearSegmentedColormap.from_list('own3',[endcolor,startcolor])
    # extra arguments are N=256, gamma=1.0
    cm.register_cmap(cmap=cmap2)
    if(terrain_2D.values.max() > 0):
        terrain_contour = ax.contourf(terrain_2D['time'].values, terrain_2D['level'].values,  np.squeeze(terrain_2D.values.swapaxes(1,0)),
                                levels=np.arange(0, terrain_2D.values.max(), 0.1), cmap=cm.get_cmap('own3'),zorder=100)  

    xstklbls = mpl.dates.DateFormatter('%m月%d日%H时')
    ax.xaxis.set_major_formatter(xstklbls)
    for label in ax.get_xticklabels():
        label.set_rotation(30)
        label.set_fontsize(15)
        label.set_horizontalalignment('right')

    for label in ax.get_yticklabels():
        label.set_fontsize(15)
            
    ax.set_yscale('symlog')
    ax.set_ylabel('高度 (hPa)', fontsize=15)
    ax.set_yticklabels(np.arange(1000, 50, -100))
    ax.set_yticks(np.arange(1000, 50, -100))
    ax.set_ylim(rh_2D['level'].values.max(), rh_2D['level'].values.min())
    ax.set_xlim([rh_2D['time'].values[0], rh_2D['time'].values[-1]])

    #forecast information
    bax=plt.axes([0.10,0.88,.25,.07],facecolor='#FFFFFFCC')
    bax.axis('off')
    bax.axis([0, 10, 0, 10])

    initTime = pd.to_datetime(
        str(rh_2D['forecast_reference_time'].values)).replace(tzinfo=None).to_pydatetime()
    if(sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if(sys.platform[0:3] == 'win'):        
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    plt.text(2.5, 7.5,'起报时间: '+initTime.strftime("%Y年%m月%d日%H时"),size=11)
    plt.text(2.5, 5.0,'['+str(rh_2D.attrs['model'])+']'+'模式时间剖面',size=11)
    plt.text(2.5, 2.5,'预报点: '+str(rh_2D.attrs['points']['lon'])+
        ', '+str(rh_2D.attrs['points']['lat']),size=11)
    plt.text(2.5, 0.5,'www.nmc.cn',size=11)
    utl.add_logo_extra_in_axes(pos=[0.1,0.88,.07,.07],which='nmc', size='Xlarge')
    ax.set_title('['+model+'] '+'温度, 相对湿度, 水平风', loc='right', fontsize=23)

    #出图——————————————————————————————————————————————————————————
    if(output_dir != None ):
        plt.savefig(output_dir+'时间剖面产品_起报时间_'+
        str(rh_2D['forecast_reference_time'].values)[0:13]+
        '_预报时效_'+str(t_range[0])+'_至_'+str(t_range[1])
        +'.png', dpi=200,bbox_inches='tight')
        plt.close()
    else:
        plt.show()                                
def draw_Crosssection_Wind_Temp_RH(
                    cross_rh=None, cross_Temp=None, cross_u=None,
                    cross_v=None,cross_terrain=None,
                    gh=None,
                    h_pos=None,st_point=None,ed_point=None,lw_ratio=None,
                    levels=None,map_extent=(50, 150, 0, 65),model=None,
                    output_dir=None):

    plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)

    initTime = pd.to_datetime(
    str(cross_Temp['forecast_reference_time'].values)).replace(tzinfo=None).to_pydatetime()
    fcst_time=initTime+timedelta(hours=gh['forecast_period'].values[0])
    
    fig = plt.figure(1, figsize=(lw_ratio[0],lw_ratio[1]))
    ax = plt.axes()
    cross_rh['data'].values[cross_rh['data'].values > 100]=100

    # example 2: use the "fromList() method
    startcolor = '#1E90FF'   #蓝色
    midcolor = '#F1F1F1'     #白色
    endcolor = '#696969'     #灰色
    cmap2 = col.LinearSegmentedColormap.from_list('own2',['#1E90FF','#94D8F6','#F1F1F1','#BFBFBF','#696969'])
    # extra arguments are N=256, gamma=1.0
    cm.register_cmap(cmap=cmap2)
    
    # we can skip name here as it was already defined

    rh_contour = ax.contourf(cross_rh['lon'], cross_rh['level'], cross_rh['data'],
                            levels=np.arange(0, 101, 0.5), cmap=cm.get_cmap('own2'))
    rh_colorbar = fig.colorbar(rh_contour,ticks=[20,40,60,80,100])

    # Plot potential temperature using contour, with some custom labeling
    Temp_contour = ax.contour(cross_Temp['lon'], cross_Temp['level'],cross_Temp['data'].values,
                            levels=np.arange(-100, 100, 2), colors='#A0522D', linewidths=1)

    Temp_contour.clabel(np.arange(-100, 100, 2), fontsize=16, colors='#A0522D', inline=1,
                        inline_spacing=8, fmt='%i', rightside_up=True, use_clabeltext=True)

    Temp_zero_contour = ax.contour(cross_Temp['lon'], cross_Temp['level'],cross_Temp['data'].values,
                            levels=[0], colors='k', linewidths=3)

    try:
        Temp_zero_contour.clabel([0], fontsize=22, colors='k', inline=1,
                            inline_spacing=8, fmt='%i', rightside_up=True, use_clabeltext=True)
    except:
        print('No Zero Line')                            

    wind_slc_vert = list(range(0, len(levels), 1))
    wind_slc_horz = slice(5, 100, 5)
    ax.barbs(cross_u['lon'][wind_slc_horz], cross_u['level'][wind_slc_vert],
            cross_u['t_wind'][wind_slc_vert, wind_slc_horz]*2.5,    
            cross_v['n_wind'][wind_slc_vert, wind_slc_horz]*2.5, color='k')

    startcolor = '#8B4513'   #棕色
    endcolor='#DAC2AD' #绿 
    cmap2 = col.LinearSegmentedColormap.from_list('own3',[endcolor,startcolor])
    # extra arguments are N=256, gamma=1.0
    cm.register_cmap(cmap=cmap2)
    terrain_contour = ax.contourf(cross_terrain['lon'], cross_terrain['level'], cross_terrain.values,
                            levels=np.arange(0, 500, 1), cmap=cm.get_cmap('own3'),zorder=100)
    # Adjust the y-axis to be logarithmic
    ax.set_yscale('symlog')
    ax.set_yticklabels(np.arange(levels[0], levels[-1], -100))
    ax.set_ylim(levels[0], levels[-1])
    ax.set_yticks(np.arange(levels[0], levels[-1], -100))

    # Define the CRS and inset axes
    data_crs = ccrs.PlateCarree()
    ax_inset = fig.add_axes(h_pos, projection=data_crs)
    ax_inset.set_extent(map_extent, crs=data_crs)
    # Plot geopotential height at 500 hPa using xarray's contour wrapper
    ax_inset.contour(gh['lon'], gh['lat'], np.squeeze(gh['data']),
                    levels=np.arange(500, 600, 4), cmap='inferno')
    # Plot the path of the cross section
    endpoints = data_crs.transform_points(ccrs.Geodetic(),
                                        *np.vstack([st_point, ed_point]).transpose()[::-1])
    ax_inset.scatter(endpoints[:, 0], endpoints[:, 1], c='k', zorder=2)
    ax_inset.plot(cross_u['lon'], cross_u['lat'], c='k', zorder=2)
    # Add geographic features
    ax_inset.coastlines()
    utl.add_china_map_2cartopy_public(
            ax_inset, name='province', edgecolor='black', lw=0.8, zorder=105)
    # Set the titles and axes labels
    ax_inset.set_title('')

    ax.set_title('['+model+'] '+'温度, 相对湿度, 沿剖面风', loc='right', fontsize=25)
    ax.set_ylabel('Pressure (hPa)')
    ax.set_xlabel('Longitude')
    rh_colorbar.set_label('Relative Humidity (%)')

    if(sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if(sys.platform[0:3] == 'win'):        
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    bax=fig.add_axes([0.10,0.88,.25,.07],facecolor='#FFFFFFCC')
    bax.axis('off')
    #bax.set_yticks([])
    #bax.set_xticks([])
    bax.axis([0, 10, 0, 10])        
    plt.text(2.5, 7.5,'起报时间: '+initTime.strftime("%Y年%m月%d日%H时"),size=11)
    plt.text(2.5, 5,'预报时间: '+fcst_time.strftime("%Y年%m月%d日%H时"),size=11)
    plt.text(2.5, 2.5,'预报时效: '+str(int(gh['forecast_period'].values[0]))+'小时',size=11)
    plt.text(2.5, 0.5,'www.nmc.cn',size=11)

    utl.add_logo_extra_in_axes(pos=[0.1,0.88,.07,.07],which='nmc', size='Xlarge')

    # show figure
    if(output_dir != None):
        plt.savefig(output_dir+'温度_相对湿度_沿剖面风_预报_'+
        '起报时间_'+initTime.strftime("%Y年%m月%d日%H时")+
        '预报时效_'+str(int(gh['forecast_period'].values[0]))+'小时'+'.png', dpi=200,bbox_inches='tight')
        plt.close()
    
    if(output_dir == None):
        plt.show()                 
Beispiel #40
0
def take_cmap_colors(cmap, N, *, cmap_range=(0, 1), return_fmt='float'):
    """
    Takes `N` equally spaced colors from the provided colormap `cmap` and
    returns them.

    Parameters
    ----------
    cmap : str or :obj:`~matplotlib.colors.Colormap` object
        The registered name of the colormap in :mod:`matplotlib.cm` or its
        corresponding :obj:`~matplotlib.colors.Colormap` object.
    N : int or None
        The number of colors to take from the provided `cmap` within the given
        `cmap_range`.
        If *None*, take all colors in `cmap` within this range.

    Optional
    --------
    cmap_range : tuple of float. Default: (0, 1)
        The normalized value range in the colormap from which colors should be
        taken.
        By default, colors are taken from the entire colormap.
    return_fmt : {'float'/'norm'; 'int'/'8bit'; 'str'/'hex'}. Default: 'float'
        The format of the requested colors.
        If 'float'/'norm', the colors are returned as normalized RGB tuples.
        If 'int'/'8bit', the colors are returned as 8-bit RGB tuples.
        If 'str'/'hex', the colors are returned using their hexadecimal string
        representations.

    Returns
    -------
    colors : list of {tuple; str}
        The colors that were taken from the provided `cmap`.

    Examples
    --------
    Taking five equally spaced colors from the 'rainforest' colormap::

        >>> take_cmap_colors('cmr.rainforest', 5)
        [(0.0, 0.0, 0.0),
         (0.226123592, 0.124584033, 0.562997277),
         (0.0548210513, 0.515835251, 0.45667819),
         (0.709615979, 0.722863985, 0.0834727592),
         (1.0, 1.0, 1.0)]

    Requesting their 8-bit RGB values instead::

        >>> take_cmap_colors('cmr.rainforest', 5, return_fmt='int')
        [(0, 0, 0),
         (58, 32, 144),
         (14, 132, 116),
         (181, 184, 21),
         (255, 255, 255)]

    Requesting HEX-code values instead::

        >>> take_cmap_colors('cmr.rainforest', 5, return_fmt='hex')
        ['#000000', '#3A2090', '#0E8474', '#B5B815', '#FFFFFF']

    Requesting colors in a specific range::

        >>> take_cmap_colors('cmr.rainforest', 5, cmap_range=(0.2, 0.8),
                             return_fmt='hex')
        ['#3E0374', '#10528A', '#0E8474', '#5CAD3C', '#D6BF4A']

    Note
    ----
    Using this function on a perceptually uniform sequential colormap, like
    those in *CMasher*, allows one to pick a number of line colors that are
    different but still sequential. This is useful when plotting a set of lines
    that describe the same property, but have a different initial state.

    """

    # Convert provided fmt to lowercase
    return_fmt = return_fmt.lower()

    # Obtain the colormap
    cmap = mplcm.get_cmap(cmap)

    # Check if provided cmap_range is valid
    if not ((0 <= cmap_range[0] <= 1) and (0 <= cmap_range[1] <= 1)):
        raise ValueError("Input argument 'cmap_range' does not contain "
                         "normalized values!")

    # Extract and convert start and stop to their integer indices (inclusive)
    start = int(np.floor(cmap_range[0] * cmap.N))
    stop = int(np.ceil(cmap_range[1] * cmap.N)) - 1

    # Pick colors
    if N is None:
        index = np.arange(start, stop + 1, dtype=int)
    else:
        index = np.array(np.rint(np.linspace(start, stop, num=N)), dtype=int)
    colors = cmap(index)

    # Convert colors to proper format
    if return_fmt in ('float', 'norm', 'int', '8bit'):
        colors = np.apply_along_axis(to_rgb, 1, colors)
        if return_fmt in ('int', '8bit'):
            colors = np.array(np.rint(colors * 255), dtype=int)
        colors = list(map(tuple, colors))
    else:
        colors = list(map((lambda x: to_hex(x).upper()), colors))

    # Return colors
    return (colors)
Beispiel #41
0
# Only plot partial Figure 7

import joblib
import numpy as np
import matplotlib.pyplot as plt

train_latent, real_y_train_un = joblib.load('./data_files/fig_ICSD_latent.joblib')

from matplotlib import cm
cmap = cm.get_cmap('viridis', 2)

fig = plt.figure()
plt.rcParams["figure.figsize"] = [8.5, 7]
font = {
        'family': 'Avenir',
        'weight': 'normal',
        'size': 26
    }
math_font = 'stixsans'
plt.rc('font', **font)
plt.rcParams['mathtext.fontset'] = math_font
plt.rcParams['axes.labelsize'] = font['size']
plt.rcParams['xtick.labelsize'] = font['size']-2
plt.rcParams['ytick.labelsize'] = font['size']-2
plt.rcParams['legend.fontsize'] = font['size']-2

i = 2

fig, ax = plt.subplots(1, 2, figsize=(13,5.3))
s0 = ax[0].scatter(train_latent[:,0],train_latent[:,i],s=7,c=np.squeeze(real_y_train_un.iloc[:,1]), cmap=cmap) # real_y_train_un[:,1]
cbar = plt.colorbar(s0, ax=ax[0], ticks=[0.15, 0.85])
Beispiel #42
0
def save_topview(data, tracks_manager, reconstructions, output_path):
    points = []
    colors = []
    for rec in reconstructions:
        for point in rec.points.values():
            track = tracks_manager.get_track_observations(point.id)
            if len(track) < 2:
                continue
            coords = point.coordinates
            points.append(coords)

            r, g, b = [], [], []
            for obs in track.values():
                r.append(obs.color[0])
                g.append(obs.color[1])
                b.append(obs.color[2])
            colors.append((statistics.median(r), statistics.median(g),
                           statistics.median(b)))

    all_x = []
    all_y = []
    for rec in reconstructions:
        for shot in rec.shots.values():
            o = shot.pose.get_origin()
            all_x.append(o[0])
            all_y.append(o[1])
            if not shot.metadata.gps_position.has_value:
                continue
            gps = shot.metadata.gps_position.value
            all_x.append(gps[0])
            all_y.append(gps[1])

    # compute camera's XY bounding box
    low_x, high_x = np.min(all_x), np.max(all_x)
    low_y, high_y = np.min(all_y), np.max(all_y)

    # get its size
    size_x = high_x - low_x
    size_y = high_y - low_y

    # expand bounding box by some margin
    margin = 0.05
    low_x -= size_x * margin
    high_x += size_y * margin
    low_y -= size_x * margin
    high_y += size_y * margin

    # update size
    size_x = high_x - low_x
    size_y = high_y - low_y

    im_size_x = 2000
    im_size_y = int(im_size_x * size_y / size_x)
    topview = np.zeros((im_size_y, im_size_x, 3))

    # splat points using gaussian + max-pool
    splatting = 15
    size = 2 * splatting + 1
    kernel = _get_gaussian_kernel(splatting, 2)
    kernel /= kernel[splatting, splatting]
    for point, color in zip(points, colors):
        x, y = int((point[0] - low_x) / size_x * im_size_x), int(
            (point[1] - low_y) / size_y * im_size_y)
        if not ((0 < x < (im_size_x - 1)) and (0 < y < (im_size_y - 1))):
            continue

        k_low_x, k_low_y = -min(x - splatting, 0), -min(y - splatting, 0)
        k_high_x, k_high_y = (
            size - max(x + splatting - (im_size_x - 2), 0),
            size - max(y + splatting - (im_size_y - 2), 0),
        )
        h_low_x, h_low_y = max(x - splatting, 0), max(y - splatting, 0)
        h_high_x, h_high_y = min(x + splatting + 1,
                                 im_size_x - 1), min(y + splatting + 1,
                                                     im_size_y - 1)

        for i in range(3):
            current = topview[h_low_y:h_high_y, h_low_x:h_high_x, i]
            splat = kernel[k_low_y:k_high_y, k_low_x:k_high_x]
            topview[h_low_y:h_high_y, h_low_x:h_high_x,
                    i] = np.maximum(splat * (color[i] / 255.0), current)

    plt.clf()
    plt.imshow(topview)

    # display computed camera's XY
    linewidth = 1
    markersize = 4
    for rec in reconstructions:
        sorted_shots = sorted(rec.shots.values(),
                              key=lambda x: x.metadata.capture_time.value)
        c_camera = cm.get_cmap("cool")(0 / len(reconstructions))
        c_gps = cm.get_cmap("autumn")(0 / len(reconstructions))
        for j, shot in enumerate(sorted_shots):
            o = shot.pose.get_origin()
            x, y = int((o[0] - low_x) / size_x * im_size_x), int(
                (o[1] - low_y) / size_y * im_size_y)
            plt.plot(
                x,
                y,
                linestyle="",
                marker="o",
                color=c_camera,
                markersize=markersize,
                linewidth=1,
            )

            # also display camera path using capture time
            if j < len(sorted_shots) - 1:
                n = sorted_shots[j + 1].pose.get_origin()
                nx, ny = int((n[0] - low_x) / size_x * im_size_x), int(
                    (n[1] - low_y) / size_y * im_size_y)
                plt.plot([x, nx], [y, ny],
                         linestyle="-",
                         color=c_camera,
                         linewidth=linewidth)

            # display GPS error
            if not shot.metadata.gps_position.has_value:
                continue
            gps = shot.metadata.gps_position.value
            gps_x, gps_y = int((gps[0] - low_x) / size_x * im_size_x), int(
                (gps[1] - low_y) / size_y * im_size_y)
            plt.plot(
                gps_x,
                gps_y,
                linestyle="",
                marker="v",
                color=c_gps,
                markersize=markersize,
                linewidth=1,
            )
            plt.plot([x, gps_x], [y, gps_y],
                     linestyle="-",
                     color=c_gps,
                     linewidth=linewidth)

    plt.xticks(
        [0, im_size_x / 2, im_size_x],
        [0, f"{int(size_x / 2):.0f}", f"{size_x:.0f} meters"],
        fontsize="small",
    )
    plt.yticks(
        [im_size_y, im_size_y / 2, 0],
        [0, f"{int(size_y / 2):.0f}", f"{size_y:.0f} meters"],
        fontsize="small",
    )

    plt.savefig(
        os.path.join(output_path, "topview.png"),
        dpi=300,
        bbox_inches="tight",
    )
Beispiel #43
0
                                       'm_2':(m_min_ns, m_max_ns), \
                                       'm_c':(m_c_min, m_c_max), \
                                       'q_inv':(q_inv_min, q_inv_max)}, \
                               label='SMF Priors')
        bgw_gds = gd.MCSamples(samples=bgw_samples, \
                               names=['d', 'm_1', 'm_2', 'm_c', 'q_inv'], \
                               labels=[r'D_L', 'm_1', 'm_2', 'M_c', '1/q'], \
                               ranges={'d':(d_min, d_max), \
                                       'm_1':(m_min_bh_bgw, m_max_bh_bgw), \
                                       'm_2':(m_min_ns_bgw, m_max_ns_bgw), \
                                       'm_c':(m_c_min, m_c_max), \
                                       'q_inv':(q_inv_min, q_inv_max)}, \
                               label='Bilby Priors')
        g = gdp.get_subplot_plotter()
        g.settings.lw_contour = lw
        cm = mpcm.get_cmap('plasma')
        g.triangle_plot([bgw_gds, smf_gds], filled=True, \
                        line_args=[{'lw':lw, 'color':'C0'}, \
                                   {'lw':lw, 'color':'C1'}], \
                        colors=['C0', 'C1'])
        n_pars = smf_samples.shape[1]
        for i in range(n_pars):
            for j in range(0, i + 1):
                g.subplots[i, j].grid(False)
        plot_file = outdir + '/' + label + '_bilby_prior_comp.pdf'
        g.export(plot_file)
        exit()

# calculate tidal deformabilities for all NSs
lambdas = np.zeros(n_inj)
for i in range(n_inj):
                                            max_distance = 500.)
        df_bh.at[df_bh_ss.index, 'distance_along_line'] = dists_
        elevs_ = spatial_functions.xy_2_var(em_section_data,
                                           bh_coords,
                                           'elevation',
                                            max_distance = 500.)
        df_bh.at[df_bh_ss.index, 'AEM_elevation'] = elevs_
    # Remove from memory
    rj_section_data = None
    det_section_data = None
    gc.collect()


# Define colour stretch for em data

viridis = cm.get_cmap('viridis')
lm_colours = [matplotlib.colors.rgb2hex(x) for x in viridis(np.linspace(0, 1, 18))]

plasma = cm.get_cmap('plasma')
hm_colours = [matplotlib.colors.rgb2hex(x) for x in plasma(np.linspace(0, 1, 23))]

def list2options(list):
    options = []
    for l in list:
        options.append({'label': str(l), 'value': l})
    return options

def subset_df_by_line(df_, line, line_col = 'SURVEY_LINE'):
    mask = df_[line_col] == line
    return df_[mask]
def main():
    locs, labels = [], []
    days_duration = []
    last_finish_date = None

    repo = Repo('.')

    plt.style.use('seaborn-darkgrid')
    fig, (ax_top, ax_bot) = plt.subplots(nrows=2, ncols=1)
    fig.set_figwidth(17)
    fig.set_figheight(10)
    for day_num in range(1, 25 + 1):
        dir_path = f"day_{day_num}"
        locs.append(day_num)
        labels.append(day_num)

        files = get_files(dir_path)

        def is_file_relative(path):
            if '/venv/' in path:
                return False
            if path and extension(path) not in languges[day_num]:
                return False
            if not is_file_in_repo(repo, path):
                return False
            return True

        files = list(filter(is_file_relative, files))
        # plot lines of code
        stacked = 0
        for ext in languges[day_num]:
            lines = sum(
                map(count_lines, filter(lambda f: extension(f) == ext, files)))
            if stacked:
                args = {'bottom': stacked}
            else:
                args = {}
            lang_name = ext_lang[ext]
            ax_top.bar(day_num,
                       lines,
                       label=lang_name,
                       **args,
                       color=colors[lang_name])
            stacked = lines

        start_date, end_date = commit_dates(repo, dir_path)
        start_date, end_date = datetime.fromtimestamp(
            start_date), datetime.fromtimestamp(end_date)
        if last_finish_date is not None:
            start_date = min(start_date, last_finish_date)
        last_finish_date = end_date
        days_duration.append((end_date - start_date).days + 1)
    # plot duration
    duration_cmap = cm.get_cmap('copper')
    duration_norm = Normalize(vmin=min(days_duration), vmax=max(days_duration))
    for day_num, duration in enumerate(days_duration):
        ax_bot.bar(x=day_num + 1,
                   height=duration,
                   color=duration_cmap(duration_norm(duration)))

    plt.setp(ax_bot, xticks=locs, xticklabels=labels)
    plt.setp(ax_top, xticks=locs, xticklabels=labels)
    handles, labels = ax_top.get_legend_handles_labels()
    by_label = dict(zip(labels, handles))
    ax_top.set_ylabel("Lines of code")
    ax_top.set_xlabel("Day")
    ax_bot.set_ylabel("Completion duration")
    ax_bot.set_xlabel("Day")
    fig.suptitle("Advent of Code summary", fontsize=16)
    ax_top.legend(by_label.values(), by_label.keys(), ncol=8)
    plt.savefig('docs/summary.png')
    plt.show()
Beispiel #46
0
    torqueimage.data = torquedensity_average.T
    torqueimage.pixelx = grid.X.shape[0]
    torqueimage.pixely = grid.Y.shape[0]

    # ... and plot it
    fig = plt.figure()
    fig.subplots_adjust(top=0.97, right=0.88, bottom=0.12, left=0.10)
    ax = fig.add_subplot(111)
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.1)
    vmax, vmin, absvmin = 5e3, -5e3, 0.01
    ax, im = plot_slice(ax,
                        torqueimage,
                        extent=extent,
                        scale='semilog',
                        cmap=cm.get_cmap('bwr'),
                        vmax=vmax,
                        vmin=vmin,
                        absvmin=absvmin)
    cbar = plt.colorbar(im, cax=cax)
    maxlog = int(np.ceil(np.log10(vmax)))
    minlog = int(np.ceil(np.log10(-vmin)))
    logthresh = int(np.round(np.log10(absvmin)))

    #generate logarithmic ticks
    ctick_locs = ([-(10**x) for x in xrange(minlog, logthresh - 1, -2)] +
                  [0.0] + [(10**x) for x in xrange(logthresh, maxlog + 1, 2)])
    cbar.set_ticks(ctick_locs[1:-1])
    ctick_labels = []
    for tick in ctick_locs:
        if (tick != 0):
Beispiel #47
0
def plot_DT(DT, state, ncol=4, nrow=3):
    '''
    Plots day-dependent doubling time against time for the selected counties.
    
    input
    ======
    
    DT : list
        Contains name of county, day array and DT array containing the 8 last data-points 
        where fit was possible
    
        name : str
            Name of specific region
    
        day : np.array
            Array of 8 days before and including the fit day
    
        val_DT : list
            list containing the calculated day-depending doubling times
    
        rates : list
            list containing rates (mortality rate, recovery rate, still ill rate)
    
    
    state : list
            output from load_RKI
    
    ncol : int
        Number of columns in plot (should not be changed for now.)

    nrow : int
        Number of rows in plot (should not be changed for now.)
    
    returns
    =======
    
    Saves diagram as PDF.
    
    '''
    ######################################
    # DT for state
    #######################

    ####
    # move to March time frame
    #########

    day_max = 150.
    day_ticks = [
        14, 18, 22, 26, 30, 3, 7, 11, 15, 19, 23, 27, 1, 5, 9, 13, 17, 21, 25,
        29, 2, 6, 10, 14, 18, 22, 26, 30, 3, 7, 11, 15, 19, 23, 27
    ]

    dat_states = state[1]

    state_day = []
    for i in range(len(dat_states)):
        y, m, d = dat_states[i].split('/')
        if m == '01': state_day.append(int(d) - 29 - 31)
        if m == '02': state_day.append(int(d) - 29)
        if m == '03': state_day.append(int(d))
        if m == '04': state_day.append(int(d) + 31)
        if m == '05': state_day.append(int(d) + 31 + 30)
        if m == '06': state_day.append(int(d) + 31 + 30 + 31)
        if m == '07': state_day.append(int(d) + 31 + 30 + 31 + 30)

    #########
    # fit
    #########
    def func(x, a, b):  #, c):
        #return a * np.exp(b * x)# + c
        #return a * b**(c*x)
        return np.log(a) + b * x

    x = np.arange(10, day_max, 0.5)

    # fit only when there are more than 8 data points and cases every day.
    data_points = range(8, len(state_day) + 1)
    state_day = np.array(state_day)
    state_num = np.array(state[0])
    DTs_state = []

    from scipy.optimize import curve_fit
    for cut in data_points:
        popt, pcov = curve_fit(func, state_day[cut - 8:cut],
                               np.log(state_num[cut - 8:cut]))

        #########
        # doubling time
        #########
        DT_state = np.round(np.log(2) / popt[1], 2)
        DTs_state.append(DT_state)

    fig, axs = plt.subplots(nrow, ncol, figsize=(28, 21))
    fig2, axs2 = plt.subplots(nrow, ncol, figsize=(28, 21))
    fig3, axs3 = plt.subplots(nrow, ncol, figsize=(28, 21))
    fig4, axs4 = plt.subplots(nrow, ncol, figsize=(28, 21))
    plt.subplots_adjust(left=None,
                        bottom=None,
                        right=None,
                        top=None,
                        wspace=0.1,
                        hspace=0.1)
    axs[0, 0].set_title('Entwicklung der Verdopplungszeiten auf Kreisebene')
    axs[0, 1].set_title('Evolution of the Doubeling Time for German Counties')
    axs[0, 2].set_title('Entwicklung der Verdopplungszeiten auf Kreisebene')
    axs[0, 3].set_title('Evolution of the Doubling Time for German Counties')

    print len(DT.keys())

    # sort after Landkreis name not ID
    DT_ids = DT.keys()

    DT_names = []
    for key in DT_ids:
        DT_names.append(DT[key][0])
        print key, DT[key][0]

    DT_ids = np.array(DT_ids)
    DT_names = np.array(DT_names)

    DT_index = np.argsort(DT_names)
    DT_ids = DT_ids[DT_index]
    DT_names = DT_names[DT_index]

    #print '*' * 10
    #print DT_names[95], DT_ids[95]

    sorted_keys = DT_ids

    from matplotlib.cm import get_cmap
    cmap = get_cmap('inferno')  # type: matplotlib.colors.ListedColormap

    for i in range(len(sorted_keys)):

        if i in range(0, 8):
            ax = axs[0, 0]
            ax2 = axs2[0, 0]
            ax3 = axs3[0, 0]
            ax4 = axs4[0, 0]
            line_col = 20 + 30 * (8 - i)

        if i in range(8, 16):
            ax = axs[0, 1]
            ax2 = axs2[0, 1]
            ax3 = axs3[0, 1]
            ax4 = axs4[0, 1]
            line_col = 20 + 30 * (16 - i)

        if i in range(16, 24):
            ax = axs[0, 2]
            ax2 = axs2[0, 2]
            ax3 = axs3[0, 2]
            ax4 = axs4[0, 2]
            line_col = 20 + 30 * (24 - i)

        if i in range(24, 32):
            ax = axs[0, 3]
            ax2 = axs2[0, 3]
            ax3 = axs3[0, 3]
            ax4 = axs4[0, 3]
            line_col = 20 + 30 * (32 - i)

        if i in range(32, 40):
            ax = axs[1, 0]
            ax2 = axs2[1, 0]
            ax3 = axs3[1, 0]
            ax4 = axs4[1, 0]
            line_col = 20 + 30 * (40 - i)

        if i in range(40, 48):
            ax = axs[1, 1]
            ax2 = axs2[1, 1]
            ax3 = axs3[1, 1]
            ax4 = axs4[1, 1]
            line_col = 20 + 30 * (48 - i)

        if i in range(48, 56):
            ax = axs[1, 2]
            ax2 = axs2[1, 2]
            ax3 = axs3[1, 2]
            ax4 = axs4[1, 2]
            line_col = 20 + 30 * (56 - i)

        if i in range(56, 64):
            ax = axs[1, 3]
            ax2 = axs2[1, 3]
            ax3 = axs3[1, 3]
            ax4 = axs4[1, 3]
            line_col = 20 + 30 * (64 - i)

        if i in range(64, 72):
            ax = axs[2, 0]
            ax2 = axs2[2, 0]
            ax3 = axs3[2, 0]
            ax4 = axs4[2, 0]
            line_col = 20 + 30 * (72 - i)

        if i in range(72, 80):
            ax = axs[2, 1]
            ax2 = axs2[2, 1]
            ax3 = axs3[2, 1]
            ax4 = axs4[2, 1]
            line_col = 20 + 30 * (80 - i)

        if i in range(80, 88):
            ax = axs[2, 2]
            ax2 = axs2[2, 2]
            ax3 = axs3[2, 2]
            ax4 = axs4[2, 2]
            line_col = 20 + 30 * (88 - i)

        if i in range(88, 96):
            ax = axs[2, 3]
            ax2 = axs2[2, 3]
            ax3 = axs3[2, 3]
            ax4 = axs4[2, 3]
            line_col = 20 + 30 * (96 - i)

        key = sorted_keys[i]
        if i in [0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96]:
            ax.semilogy(state_day[7:],
                        DTs_state,
                        '.:k',
                        label=state[2] + ' average')
            print '-' * 20
            print state[2], DTs_state[-1], int(state_day[7:][-1])
            print '-' * 20

        ax.semilogy(DT[key][1],
                    DT[key][2],
                    '.-',
                    c=cmap(line_col),
                    label=DT[key][0])
        ax2.loglog(DT[key][3],
                   DT[key][4],
                   '.-',
                   c=cmap(line_col),
                   label=DT[key][0])
        print DT[key][2][-1], int(DT[key][1][-1]), DT[key][0]

        ax3.plot(DT[key][5]['day'],
                 DT[key][5]['death_rate'],
                 '*-',
                 c=cmap(line_col),
                 label=DT[key][0])
        ax4.plot(DT[key][1],
                 DT[key][6],
                 '.-',
                 c=cmap(line_col),
                 label=DT[key][0])
        #ax3.plot(DT[key][5]['day'], DT[key][5]['recover_rate'], 'o-', c = cmap(line_col), label=DT[key][0])
        #ax3.plot(DT[key][5]['day'], DT[key][5]['ill_rate'], 'x-', c = cmap(line_col), label=DT[key][0])

    ######
    # axis

    #factor_1 = 100/60.
    x_pos = 57

    credit2 = 'Christine Greif\nhttp://www.usm.uni-muenchen.de/~koepferl\nThis work is licensed under CC-BY-SA 4.0\nData: NPGEO-DE'

    link = axs[2, 3].text(x_pos, 0.7, credit2, fontsize=8, va='top')
    link = axs3[2, 3].text(x_pos, -2, credit2, fontsize=8)
    link = axs4[2, 3].text(x_pos, -1., credit2, fontsize=8)
    link = axs2[2, 3].text(3.5, 0.5, credit2, fontsize=8, va='top')

    link.set_url('http://www.usm.uni-muenchen.de/~koepferl')

    axs[0, 0].set_ylabel('Verdopplungszeiten (Tage)')
    axs[1, 0].set_ylabel('Doubling Time DT (days)')
    axs[2, 0].set_ylabel('Verdopplungszeiten (Tage)')

    for ax in axs.reshape(-1):
        ax.set_ylim(1.5, 500.9)
        ax.set_xlim(13, day_max)

        from matplotlib.ticker import ScalarFormatter
        for axis in [ax.xaxis, ax.yaxis]:
            axis.set_major_formatter(ScalarFormatter())
        ax.grid(True, which="both")

        ax.set_xticks(np.arange(14, day_max, 4))
        ax.set_xticklabels(day_ticks)

        ax.legend(loc='upper left')

        #if ax in [axs[2,0], axs[2,1], axs[2,2], axs[2,3]]:
        ax.text(13, 0.8, 'Maerz/March')
        ax.text(31, 0.8, 'April')
        ax.text(31 + 30, 0.8, 'Mai/May')
        ax.text(31 + 30 + 31, 0.8, 'Juni/June')
        ax.text(31 + 30 + 31 + 30, 0.8, 'Juli/July')

    for ax2 in axs2.reshape(-1):

        from matplotlib.ticker import ScalarFormatter
        for axis in [ax2.xaxis, ax2.yaxis]:
            axis.set_major_formatter(ScalarFormatter())
        ax2.grid(True, which="both")

        ax2.set_ylim(1.5, 2000)
        ax2.set_xlim(1.5, 10000)
        ax2.legend(loc='upper left')

        if ax2 in [axs2[2, 0], axs2[2, 1], axs2[2, 2], axs2[2, 3]]:
            ax2.set_xlabel('Totale Fallzahlen (total number of cases)')
        if ax2 in [axs2[0, 0], axs2[1, 0], axs2[2, 0]]:
            ax2.set_ylabel(
                'Fallzahlen in der letzten Woche (number of new cases last week)'
            )

    for ax3 in axs3.reshape(-1):
        ax3.set_ylim(0, 20.9)
        ax3.set_xlim(13, day_max)

        ax3.grid(True, which="both")
        ax3.set_xticks(np.arange(14, day_max, 4))
        ax3.set_xticklabels(day_ticks)

        if ax3 in [axs3[0, 0], axs3[1, 0], axs3[2, 0]]:
            ax3.set_ylabel('Sterberaten in %')

        ax3.legend(loc='upper left')

        #if ax in [axs[2,0], axs[2,1], axs[2,2], axs[2,3]]:
        offset3 = -0.07 * ax3.get_ylim()[1]
        ax3.text(13, offset3, 'Maerz/March')
        ax3.text(31, offset3, 'April')
        ax3.text(31 + 30, offset3, 'Mai/May')
        ax3.text(31 + 30 + 31, offset3, 'Juni/June')
        ax3.text(31 + 30 + 31 + 30, offset3, 'Juli/July')

    for ax4 in axs4.reshape(-1):
        ax4.set_ylim(0, 4.9)
        ax4.set_xlim(13, day_max)

        ax4.grid(True, which="both")
        ax4.set_xticks(np.arange(14, day_max, 4))
        ax4.set_xticklabels(day_ticks)

        ax4.legend(loc='upper left')

        #if ax in [axs[2,0], axs[2,1], axs[2,2], axs[2,3]]:
        offset4 = -0.07 * ax4.get_ylim()[1]
        ax4.text(13, offset4, 'Maerz/March')
        ax4.text(31, offset4, 'April')
        ax4.text(31 + 30, offset4, 'Mai/May')
        ax4.text(31 + 30 + 31, offset4, 'Juni/June')
        ax4.text(31 + 30 + 31 + 30, offset4, 'Juli/July')

        if ax4 in [axs4[1, 0]]:
            ax4.set_ylabel(
                'geschaetzte Reproduktionszahl R (Anzahl letzten 4 Meldungen / Anzahl der letzten 4 Meldungen davor)'
            )

    #plt.show()
    fig.savefig('DT_' + state[2] + '.pdf',
                dpi=300,
                overwrite=True,
                bbox_inches='tight')
    fig2.savefig('loglog_' + state[2] + '.pdf',
                 dpi=300,
                 overwrite=True,
                 bbox_inches='tight')
    fig3.savefig('rate_' + state[2] + '.pdf',
                 dpi=300,
                 overwrite=True,
                 bbox_inches='tight')
    fig4.savefig('R_' + state[2] + '.pdf',
                 dpi=300,
                 overwrite=True,
                 bbox_inches='tight')
Beispiel #48
0
    def __init__(
        self,
        ax,
        cmap=None,
        norm=None,
        alpha=1.0,
        values=None,
        boundaries=None,
        orientation='vertical',
        extend='neither',
        spacing='uniform',  # uniform or proportional
        ticks=None,
        format=None,
        drawedges=False,
        filled=True,
    ):
        self.ax = ax

        if cmap is None:
            cmap = cm.get_cmap()
        if norm is None:
            norm = colors.Normalize()
        self.alpha = alpha
        cm.ScalarMappable.__init__(self, cmap=cmap, norm=norm)
        self.values = values
        self.boundaries = boundaries
        self.extend = extend
        self.spacing = spacing
        self.orientation = orientation
        self.drawedges = drawedges
        self.filled = filled

        # artists
        self.solids = None
        self.lines = None
        self.dividers = None
        self.extension_patch1 = None
        self.extension_patch2 = None

        if orientation == "vertical":
            self.cbar_axis = self.ax.yaxis
        else:
            self.cbar_axis = self.ax.xaxis

        if format is None:
            if isinstance(self.norm, colors.LogNorm):
                # change both axis for proper aspect
                self.ax.set_xscale("log")
                self.ax.set_yscale("log")
                self.cbar_axis.set_minor_locator(ticker.NullLocator())
                formatter = ticker.LogFormatter()
            else:
                formatter = None
        elif isinstance(format, str):
            formatter = ticker.FormatStrFormatter(format)
        else:
            formatter = format  # Assume it is a Formatter

        if formatter is None:
            formatter = self.cbar_axis.get_major_formatter()
        else:
            self.cbar_axis.set_major_formatter(formatter)

        if np.iterable(ticks):
            self.cbar_axis.set_ticks(ticks)
        elif ticks is not None:
            self.cbar_axis.set_major_locator(ticks)
        else:
            self._select_locator(formatter)

        self._config_axes()

        self.update_artists()

        self.set_label_text('')
def draw_traj(t,v,d,v_LV_derived,d_LV,t_ita,ita,oscillations_FV,oscillationS_LV,fig_name,run,set,split):
    # [t0s_i, t0e_i, t_min_i, t_max_i, t1s_i, t1e_i, tau0, tau_min, tau_max, tau1, ep0, ep1, ep2] = \
    #     eta_pattern(t, ita, oscillations_FV[split-1], expected_frequency)
    t_p = t[0]
    t_p_max = t[-1]
    regression = False
    # if tau_max>0.75:
    #     t_p=t[t_min_i]
    #     t_p_max=t[t_max_i]
    #     regression=True
    # if min(t1e_i-t1s_i,t0e_i-t0s_i)>2*expected_frequency:
    # print(run, set, split, round(tau0, 2), round(tau_min, 2), round(tau_max, 2), round(tau1, 2), int(ep0), int(ep1), int(ep2))

    speed_range=get_speed_range(run)
    fig = plt.figure(figsize=(8, 12), dpi=300)
    ax = fig.add_subplot(311)
    ax.set_position([0.15, 0.7, 0.82, 0.25])
    color_indicator = np.array(v)
    points = np.array([np.array(t), np.array(d)]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    norm = plt.Normalize(speed_range[0], speed_range[1])
    lc = LineCollection(segments, cmap='jet_r', norm=norm)
    lc.set_array(color_indicator)
    lc.set_linewidth(1)
    line = ax.add_collection(lc)
    color_indicator = np.array(v_LV_derived)
    points = np.array([np.array(t), np.array(d_LV)]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    norm = plt.Normalize(speed_range[0], speed_range[1])
    lc = LineCollection(segments, cmap='jet_r', norm=norm)
    lc.set_array(color_indicator)
    lc.set_linewidth(1)
    line = ax.add_collection(lc)
    plt.ylabel('location(m)', fontsize=16)
    plt.ylim([min(d), max(d_LV)])
    plt.xlim(t[0]+3,t[-1])
    plt.title(fig_name,fontsize=16)
    ax.locator_params(nbins=5, axis='x')

    # plt.xlim([t[t0s_i], t[t1e_i]])

    cmap_jet = pcm.get_cmap('jet_r')
    sm = plt.cm.ScalarMappable(cmap=cmap_jet, norm=plt.Normalize(vmin=speed_range[0], vmax=speed_range[1]))
    cbar = plt.colorbar(sm, orientation='horizontal', cax=plt.axes([0.2, 0.65, 0.65, 0.025]))
    cbar.set_label('speed (m/s)', fontsize=16)

    bx = fig.add_subplot(312)
    bx.set_position([0.15, 0.35, 0.82, 0.25])
    ita_range=[0,3]
    plt.plot(t_ita, ita, color='g',label='direct measured from radar')
    # if regression:
    #     plt.plot([t[t0s_i], t[t0e_i], t_p, t_p_max, t[t1s_i], t[t1e_i]], [tau0, tau0, tau_min, tau_max, tau1, tau1], color='k', linewidth=2)
    #     plt.text(t[t0s_i+400], 1.3, '$\eta^0:$' + str(round(tau0, 2)) + '   $\eta^{min}:$' + str(round(tau_min, 2))
    #              + '   $\eta^{max}:$' + str(round(tau_max, 2))+ ' $\eta^1:$' + str(round(tau1, 2)),
    #              fontsize=16)
    #     plt.plot([t[t_min_i], t[t_min_i]], ita_range, color='k', linestyle='--', linewidth=1, alpha=.5)
    #     plt.plot([t[t_max_i], t[t_max_i]], ita_range, color='k', linestyle='--', linewidth=1, alpha=.5)
    plt.ylabel(r'$\tau$', fontsize=16)
    plt.xlim(t[0]+3,t[-1])
    bx.locator_params(nbins=5, axis='x')

    # plt.xlim([t[t0s_i], t[t1e_i]])
    plt.ylim(ita_range)

    cx = fig.add_subplot(313)
    cx.set_position([0.15, 0.075, 0.82, 0.225])
    plt.plot(t, v, color='r', label='Follower')
    plt.plot(t, v_LV_derived, color='g', label='Leader')
    t_shift = [t[x] + 1.87 * ita[x] for x in range(len(t))]
    # plt.plot(t_shift, v_LV_derived, color='b', linestyle='--', label='shifted LV')
    cx.locator_params(nbins=5, axis='x')

    # if regression:
    #     plt.plot([t[t_min_i], t[t_min_i]], speed_range, color='k', linestyle='--', linewidth=1, alpha=.5)
    #     plt.plot([t[t_max_i], t[t_max_i]], speed_range, color='k', linestyle='--', linewidth=1, alpha=.5)
    # plt.plot(t, v_LV_measured, color='k', label='LV (direct measured from radar)')
    for o in oscillations_FV:
        plt.scatter(o[6],o[7],color='r',s=60)
        plt.scatter(o[8],o[9],color='r',s=60)
        plt.scatter(o[2],o[3],color='r',s=60)
        plt.scatter(o[4],o[5],color='r',s=60)
        # plt.text(o[2],o[3],str(o[12])+'s\nd=-'+str(o[13])+'$m/s^2$')
        # plt.text(o[4],o[5],str(o[14])+'s\na='+str(o[15])+'$m/s^2$')
        # plt.text(o[6],o[7],str(o[16])+'s')
        plt.scatter(o[0],o[1],color='k',marker='*',s=60)
    for o in oscillationS_LV:
        plt.scatter(o[6],o[7],color='g',s=60)
        plt.scatter(o[8],o[9],color='g',s=60)
        plt.scatter(o[2],o[3],color='g',s=60)
        plt.scatter(o[4],o[5],color='g',s=60)
        plt.scatter(o[0],o[1],color='k',marker='*',s=60)
    plt.xlabel('time (s)', fontsize=20)
    plt.ylabel('speed(m/s)', fontsize=20)
    plt.legend(loc=4,fontsize=16)
    plt.xlim(t[0]+3,t[-1])

    # plt.xlim([t[t0s_i], t[t1e_i]])
    plt.ylim(speed_range)
    plt.savefig(fig_name + '.png')
    plt.close()
Beispiel #50
0
def plot_three_way(hist,
                   title,
                   filename=None,
                   x_axis_title=None,
                   minimum=None,
                   maximum=None,
                   bins=101,
                   cmap=None):  # the famous 3 way plot (enhanced)
    if cmap is None:
        if maximum == 'median' or maximum is None:
            cmap = cm.get_cmap('coolwarm')
        else:
            cmap = cm.get_cmap('cool')
    # TODO: set color for bad pixels
    # set nan to special value
    # masked_array = np.ma.array (a, mask=np.isnan(a))
    # cmap = matplotlib.cm.jet
    # cmap.set_bad('w',1.0)
    # ax.imshow(masked_array, interpolation='nearest', cmap=cmap)
    if minimum is None:
        minimum = 0.0
    elif minimum == 'minimum':
        minimum = np.ma.min(hist)
    if maximum == 'median' or maximum is None:
        maximum = 2 * np.ma.median(hist)
    elif maximum == 'maximum':
        maximum = np.ma.max(hist)
    if maximum < 1 or hist.all() is np.ma.masked:
        maximum = 1.0

    x_axis_title = '' if x_axis_title is None else x_axis_title
    fig = Figure()
    FigureCanvas(fig)
    fig.patch.set_facecolor('white')
    ax1 = fig.add_subplot(311)
    create_2d_pixel_hist(fig,
                         ax1,
                         hist,
                         title=title,
                         x_axis_title="column",
                         y_axis_title="row",
                         z_min=minimum if minimum else 0,
                         z_max=maximum,
                         cmap=cmap)
    ax2 = fig.add_subplot(312)
    create_1d_hist(fig,
                   ax2,
                   hist,
                   bins=bins,
                   x_axis_title=x_axis_title,
                   y_axis_title="#",
                   x_min=minimum,
                   x_max=maximum)
    ax3 = fig.add_subplot(313)
    create_pixel_scatter_plot(fig,
                              ax3,
                              hist,
                              x_axis_title="channel=row + column*336",
                              y_axis_title=x_axis_title,
                              y_min=minimum,
                              y_max=maximum)
    fig.tight_layout()
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
# In[23]:

# TEST Training, validation and test RMSE (2c)
Test.assertTrue(
    np.allclose([rmseTrainBase, rmseValBase, rmseTestBase],
                [21.305869, 21.586452, 22.136957]), 'incorrect RMSE value')

# #### ** Visualization 3: Predicted vs. actual **
# #### We will visualize predictions on the validation dataset. The scatter plots below visualize tuples storing i) the predicted value and ii) true label.  The first scatter plot represents the ideal situation where the predicted value exactly equals the true label, while the second plot uses the baseline predictor (i.e., `averageTrainYear`) for all predicted values.  Further note that the points in the scatter plots are color-coded, ranging from light yellow when the true and predicted values are equal to bright red when they drastically differ.

# In[24]:

from matplotlib.colors import ListedColormap, Normalize
from matplotlib.cm import get_cmap
cmap = get_cmap('YlOrRd')
norm = Normalize()

actual = np.asarray(parsedValData.map(lambda lp: lp.label).collect())
error = np.asarray(
    parsedValData.map(lambda lp: (lp.label, lp.label)).map(
        lambda (l, p): squaredError(l, p)).collect())
clrs = cmap(np.asarray(norm(error)))[:, 0:3]

fig, ax = preparePlot(np.arange(0, 100, 20), np.arange(0, 100, 20))
plt.scatter(actual,
            actual,
            s=14**2,
            c=clrs,
            edgecolors='#888888',
            alpha=0.75,
Beispiel #52
0
def plot_scurves(occupancy_hist,
                 scan_parameters,
                 title='S-Curves',
                 ylabel='Occupancy',
                 max_occ=None,
                 scan_parameter_name=None,
                 min_x=None,
                 max_x=None,
                 x_scale=1.0,
                 y_scale=1.,
                 filename=None):  # tornado plot
    occ_mask = np.all(occupancy_hist == 0, axis=2)
    if max_occ is None:
        max_occ = math.ceil(2 * np.ma.median(np.amax(occupancy_hist, axis=2)))
        if np.allclose(max_occ, 0.0):
            max_occ = 1.0
    if len(occupancy_hist.shape) < 3:
        raise ValueError('Found array with shape %s' %
                         str(occupancy_hist.shape))

    n_pixel = occupancy_hist.shape[0] * occupancy_hist.shape[1]

    cmap = cm.get_cmap('cool')
    for index, scan_parameter in enumerate(scan_parameters):
        compressed_data = np.ma.masked_array(occupancy_hist[:, :, index],
                                             mask=occ_mask,
                                             copy=True).compressed()
        heatmap, xedges, yedges = np.histogram2d(
            compressed_data, [scan_parameter] * compressed_data.shape[0],
            range=[[0, max_occ], [scan_parameters[0], scan_parameters[-1]]],
            bins=(max_occ + 1, len(scan_parameters)))
        if index == 0:
            hist = heatmap
        else:
            hist += heatmap
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    fig.patch.set_facecolor('white')
    if len(scan_parameters) > 1:
        scan_parameter_dist = (np.amax(scan_parameters) -
                               np.amin(scan_parameters)) / (
                                   len(scan_parameters) - 1)
    else:
        scan_parameter_dist = 0
    extent = [
        yedges[0] - scan_parameter_dist / 2,
        yedges[-1] * x_scale + scan_parameter_dist / 2,
        xedges[-1] * y_scale + 0.5, xedges[0] - 0.5
    ]
    norm = colors.LogNorm()
    im = ax.imshow(hist,
                   interpolation='nearest',
                   aspect="auto",
                   cmap=cmap,
                   extent=extent,
                   norm=norm)
    ax.invert_yaxis()
    if min_x is not None or max_x is not None:
        ax.set_xlim((min_x if min_x is not None else np.amin(scan_parameters),
                     max_x if max_x is not None else np.amax(scan_parameters)))
    fig.colorbar(im)
    ax.set_title(title + ' for %d pixel(s)' %
                 (n_pixel - np.count_nonzero(occ_mask)))
    if scan_parameter_name is None:
        ax.set_xlabel('Scan parameter')
    else:
        ax.set_xlabel(scan_parameter_name)
    ax.set_ylabel(ylabel)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Beispiel #53
0
    def __init__(self, *args, **kwargs):
        super(EngineHiCTrack, self).__init__(*args, **kwargs)

        log.debug('FILE {}'.format(self.properties))
        # log.debug('pRegion {}'.format(pRegion))
        region = None
        if self.properties['region'] is not None:
            if self.properties['region'][2] == 1e15:
                region = [str(self.properties['region'][0])]
            elif len(self.properties['region']) == 3:
                start = int(self.properties['region'][1]) - int(
                    self.properties['depth'])
                if start < 0:
                    start = 0
                end = int(self.properties['region'][2]) + int(
                    self.properties['depth'])

                region = [
                    str(self.properties['region'][0]) + ':' + str(start) +
                    '-' + str(end)
                ]

        # initialize matrix as HiCMatrix object with no data
        self.hic_ma = HiCMatrix.hiCMatrix(pMatrixFile=None,
                                          pChrnameList=region)
        # create matrix to fill out data and intervals
        if 'matrix shape' not in self.properties:
            self.properties['matrix shape'] = 1000
        if 'binsize' not in self.properties:
            self.properties['binsize'] = 3000
        if 'intervals start' not in self.properties:
            self.properties['intervals start'] = 0

        self.hic_ma.matrix, self.hic_ma.cut_intervals = \
            self.definematrix(self.properties['matrix shape'], self.properties['binsize'], self.properties['intervals start'], self.properties['chrom'])

        self.hic_ma.interval_trees, self.hic_ma.chrBinBoundaries = \
            self.hic_ma.intervalListToIntervalTree(self.hic_ma.cut_intervals)

        if len(self.hic_ma.matrix.data) == 0:
            self.log.error("Matrix {} is empty".format(
                self.properties['file']))
            exit(1)
        if 'show_masked_bins' in self.properties and self.properties[
                'show_masked_bins'] == 'yes':
            pass
        else:
            self.hic_ma.maskBins(self.hic_ma.nan_bins)

        # check that the matrix can be log transformed
        if 'transform' in self.properties:
            if self.properties['transform'] == 'log1p':
                if self.hic_ma.matrix.data.min() + 1 < 0:
                    self.log.error(
                        "\n*ERROR*\nMatrix contains negative values.\n"
                        "log1p transformation can not be applied to \n"
                        "values in matrix: {}".format(self.properties['file']))
                    exit(1)

            elif self.properties['transform'] == '-log':
                if self.hic_ma.matrix.data.min() < 0:
                    self.log.error(
                        "\n*ERROR*\nMatrix contains negative values.\n"
                        "log(-1 * <values>) transformation can not be applied to \n"
                        "values in matrix: {}".format(self.properties['file']))
                    exit(1)

            elif self.properties['transform'] == 'log':
                if self.hic_ma.matrix.data.min() < 0:
                    self.log.error(
                        "\n*ERROR*\nMatrix contains negative values.\n"
                        "log transformation can not be applied to \n"
                        "values in matrix: {}".format(self.properties['file']))
                    exit(1)

        binsize = self.hic_ma.getBinSize()
        max_depth_in_bins = int(self.properties['depth'] / binsize)

        # work only with the lower matrix
        # and remove all pixels that are beyond
        # 2 * max_depth_in_bis which are not required
        # (this is done by subtracting a second sparse matrix
        # that contains only the lower matrix that wants to be removed.
        limit = 2 * max_depth_in_bins
        self.hic_ma.matrix = scipy.sparse.triu(self.hic_ma.matrix, k=0, format='csr') - \
            scipy.sparse.triu(self.hic_ma.matrix, k=limit, format='csr')
        self.hic_ma.matrix.eliminate_zeros()

        # fill the main diagonal, otherwise it looks
        # not so good. The main diagonal is filled
        # with an array containing the max value found
        # in the matrix
        if sum(self.hic_ma.matrix.diagonal()) == 0:
            self.log.info(
                "Filling main diagonal with max value because it empty and looks bad...\n"
            )
            max_value = self.hic_ma.matrix.data.max()
            main_diagonal = scipy.sparse.dia_matrix(
                ([max_value] * self.hic_ma.matrix.shape[0], [0]),
                shape=self.hic_ma.matrix.shape)
            self.hic_ma.matrix = self.hic_ma.matrix + main_diagonal

        self.plot_inverted = False
        if 'orientation' in self.properties and self.properties[
                'orientation'] == 'inverted':
            self.plot_inverted = True

        self.norm = None

        if 'colormap' not in self.properties:
            self.properties['colormap'] = DEFAULT_MATRIX_COLORMAP
        self.cmap = cm.get_cmap(self.properties['colormap'])
        self.cmap.set_bad('white')
        #self.cmap.set_over('blue')
        self.background = True
Beispiel #54
0
def get_cmap_type(cmap):
    """
    Checks what the colormap type (sequential; diverging; cyclic; qualitative;
    misc) of the provided `cmap` is and returns it.

    Parameters
    ----------
    cmap : str or :obj:`~matplotlib.colors.Colormap` object
        The registered name of the colormap in :mod:`matplotlib.cm` or its
        corresponding :obj:`~matplotlib.colors.Colormap` object.

    Returns
    -------
    cm_type : {'sequential'; 'diverging'; 'cyclic'; 'qualitative'; 'misc'}
        A string stating which of the defined colormap types the provided
        `cmap` has.

    """

    # Obtain the colormap
    cmap = mplcm.get_cmap(cmap)

    # Get RGB values for colormap
    rgb = cmap(np.arange(cmap.N))[:, :3]

    # Get lightness values of colormap
    lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb)
    L = lab[:, 0]
    diff_L = np.diff(L)

    # Obtain central values of lightness
    N = cmap.N - 1
    central_i = [int(np.floor(N / 2)), int(np.ceil(N / 2))]
    diff_L0 = np.diff(L[:central_i[0] + 1])
    diff_L1 = np.diff(L[central_i[1]:])

    # Obtain perceptual differences of last two and first two values
    lab_red = lab[[-2, -1, 0, 1]]
    deltas = np.sqrt(np.sum(np.diff(lab_red, axis=0)**2, axis=-1))

    # Check the statistics of cmap and determine the colormap type
    # QUALITATIVE
    # If the colormap has less than 40 values, assume it is qualitative
    if (cmap.N < 40):
        return ('qualitative')

    # MISC 1
    # If the colormap has only a single lightness, it is misc
    elif np.allclose(diff_L, 0):
        return ('misc')

    # SEQUENTIAL
    # If the lightness values always increase or decrease, it is sequential
    elif np.isclose(np.abs(np.sum(diff_L)), np.sum(np.abs(diff_L))):
        return ('sequential')

    # DIVERGING
    # If the lightness values have a central extreme and sequential sides
    # Then it is diverging
    elif (np.isclose(np.abs(np.sum(diff_L0)), np.sum(np.abs(diff_L0)))
          and np.isclose(np.abs(np.sum(diff_L1)), np.sum(np.abs(diff_L1)))):
        # If the perceptual difference between the last and first value is
        # comparable to the other perceptual differences, it is cyclic
        if (np.all(np.abs(np.diff(deltas)) < deltas[::2])
                and np.diff(deltas[::2])):
            return ('cyclic')

        # Otherwise, it is a normal diverging colormap
        else:
            return ('diverging')

    # MISC 2
    # If none of the criteria above apply, it is misc
    else:
        return ('misc')
Beispiel #55
0
 def test_mpl_colormap_instance(self):
     from matplotlib.cm import get_cmap
     cmap = get_cmap('Greys')
     colors = process_cmap(cmap, 3)
     self.assertEqual(colors, ['#ffffff', '#959595', '#000000'])
Beispiel #56
0
def create_cmap_overview(cmaps=None,
                         *,
                         savefig=None,
                         use_types=True,
                         sort='alphabetical',
                         show_grayscale=True,
                         plot_profile=False,
                         dark_mode=False,
                         title="Colormap Overview",
                         wscale=1,
                         hscale=1):
    """
    Creates an overview plot containing all colormaps defined in the provided
    `cmaps`.

    Optional
    --------
    cmaps : list of {str; :obj:`~matplotlib.colors.Colormap` objects}, dict \
        of lists or None. Default: None
        A list of all colormaps that must be included in the overview plot.
        If dict of lists, the keys define categories for the colormaps.
        If *None*, all colormaps defined in *CMasher* are used instead.
    savefig : str or None. Default: None
        If not *None*, the path where the overview plot must be saved to.
        Else, the plot will simply be shown.
    use_types : bool. Default: True
        Whether all colormaps in `cmaps` should be categorized into their
        colormap types (sequential; diverging; cyclic; qualitative; misc).
        If `cmaps` is a dict, this value is ignored.
    sort : {'alphabetical'/'name'; 'lightness'}, function or None. Default: \
        'alphabetical'
        String or function indicating how the colormaps should be sorted in the
        overview.
        If 'alphabetical', the colormaps are sorted alphabetically on their
        name.
        If 'lightness', the colormaps are sorted based on their lightness
        profile.
        If function, a function definition that takes a
        :obj:`~matplotlib.colors.Colormap` object and returns the sorted
        position of that colormap.
        If *None*, the colormaps retain the order they were given in.
    show_grayscale : bool. Default: True
        Whether to show the grayscale versions of the given `cmaps` in the
        overview.
    plot_profile : bool or float. Default: False
        Whether the lightness profiles of all colormaps should be plotted. If
        not *False*, the lightness profile of a colormap is plotted on top of
        its gray-scale version and `plot_profile` is used for setting the alpha
        (opacity) value.
        If `plot_profile` is *True*, it will be set to `0.25`.
        If `show_grayscale` is *False*, this value is ignored.
    dark_mode : bool. Default: False
        Whether the colormap overview should be created using mostly dark
        colors.
    title : str or None. Default: "Colormap Overview"
        String to be used as the title of the colormap overview.
        If empty or *None*, no title will be used.
    wscale, hscale : float. Default: (1, 1)
        Floats that determine with what factor the colormap subplot dimensions
        in the overview should be scaled with.
        The default values uses the default dimensions for the subplots (which
        are determined by other input arguments).

    Notes
    -----
    The colormaps in `cmaps` can either be provided as their registered name in
    :mod:`matplotlib.cm`, or their corresponding
    :obj:`~matplotlib.colors.Colormap` object.
    Any provided reversed colormaps (colormaps that end their name with '_r')
    are ignored if their normal versions were provided as well.

    If `plot_profile` is not set to *False*, the lightness profiles are plotted
    on top of the gray-scale colormap versions, where the y-axis ranges from 0%
    lightness to 100% lightness.
    The lightness profile transitions between black and white at 50% lightness.

    """

    # Check value of show_grayscale
    if show_grayscale:
        # If True, the overview will have two columns
        ncols = 2
    else:
        # If False, the overview will have one column and no profile plotted
        ncols = 1
        wscale *= 0.5
        plot_profile = False

    # Determine positions
    wscale = 0.2 + 0.8 * wscale
    left_pos = 0.2 / wscale
    spacing = 0.01 / wscale

    # If plot_profile is True, set it to its default value
    if plot_profile is True:
        plot_profile = 0.25

    # Check if dark mode is requested
    if dark_mode:
        # If so, use dark grey for the background and light grey for the text
        edge_color = '#24292E'
        face_color = '#24292E'
        text_color = '#9DA5B4'
    else:
        # If not, use white for the background and black for the text
        edge_color = '#FFFFFF'
        face_color = '#FFFFFF'
        text_color = '#000000'

    # If cmaps is None, use cmap_d.values
    if cmaps is None:
        cmaps = cmrcm.cmap_d.values()

    # If sort is a string, obtain proper function
    if isinstance(sort, str):
        # Convert sort to lowercase
        sort = sort.lower()

        # Check what string was provided and obtain sorting function
        if sort in ('alphabetical', 'name'):

            def sort(x):
                return (x.name)
        elif (sort == 'lightness'):
            sort = _get_cmap_lightness_rank

    # Create empty list of cmaps
    cmaps_list = []

    # If cmaps is a dict, it has cm_types defined
    if isinstance(cmaps, dict):
        # Set use_types to True
        use_types = True

        # Define empty dict of colormaps
        cmaps_dict = odict()

        # Save provided cmaps as something else
        input_cmaps = cmaps

        # Loop over all cm_types
        for cm_type, cmaps in input_cmaps.items():
            # Add empty list of colormaps to cmaps_dict with this cm_type
            cmaps_dict[cm_type] = []

            # Loop over all cmaps and remove reversed versions
            for cmap in cmaps:
                if isinstance(cmap, str):
                    cmaps_dict[cm_type].append(mplcm.get_cmap(cmap))
                else:
                    cmaps_dict[cm_type].append(cmap)

    # Else, it is a list with no cm_types
    else:
        # If cm_types are requested
        if use_types:
            # Define empty dict with the base cm_types
            cm_types = [
                'sequential', 'diverging', 'cyclic', 'qualitative', 'misc'
            ]
            cmaps_dict = odict([[cm_type, []] for cm_type in cm_types])

            # Loop over all cmaps and remove reversed versions
            for cmap in cmaps:
                cm_type = get_cmap_type(cmap)
                if isinstance(cmap, str):
                    cmaps_dict[cm_type].append(mplcm.get_cmap(cmap))
                else:
                    cmaps_dict[cm_type].append(cmap)
        else:
            # Loop over all cmaps and remove reversed versions
            for cmap in cmaps:
                if isinstance(cmap, str):
                    cmaps_list.append(mplcm.get_cmap(cmap))
                else:
                    cmaps_list.append(cmap)

    # If use_types is True, a dict is currently used
    if use_types:
        # Convert entire cmaps_dict into a list again
        for key, value in cmaps_dict.items():
            # If this cm_type has at least 1 colormap, sort and add them
            if value:
                # Obtain the names of all colormaps
                names = [x.name for x in value]

                # Remove all reversed colormaps that also have their original
                off_dex = len(names) - 1
                for i, name in enumerate(reversed(names)):
                    if name.endswith('_r') and name[:-2] in names:
                        value.pop(off_dex - i)

                # Sort the colormaps if requested
                if sort is not None:
                    value.sort(key=sort)

                # Add to list
                cmaps_list.append((key, False))
                cmaps_list.extend(value)

    # Else, a list is used
    else:
        # Obtain the names of all colormaps
        names = [x.name for x in cmaps_list]

        # Remove all reversed colormaps that also have their original
        off_dex = len(names) - 1
        for i, name in enumerate(reversed(names)):
            if name.endswith('_r') and name[:-2] in names:
                cmaps_list.pop(off_dex - i)

        # Sort the colormaps if requested
        if sort is not None:
            cmaps_list.sort(key=sort)

    # Add title to cmaps_list if requested
    if title:
        cmaps_list.insert(0, (title, True))

    # Obtain the colorspace converter for showing cmaps in grey-scale
    cspace_convert = cspace_converter("sRGB1", "CAM02-UCS")

    # Create figure instance
    height = (0.4 * len(cmaps_list) + 0.1) * hscale
    fig, axs = plt.subplots(figsize=(6.4 * wscale, height),
                            nrows=len(cmaps_list),
                            ncols=ncols,
                            edgecolor=edge_color,
                            facecolor=face_color)

    # Adjust subplot positioning
    fig.subplots_adjust(top=(1 - 0.05 / height),
                        bottom=0.05 / height,
                        left=left_pos,
                        right=1.0 - spacing,
                        wspace=0.05)

    # If cmaps_list only has a single element, make sure axs is a list
    if (len(cmaps_list) == 1):
        axs = [axs]

    # Loop over all cmaps defined in cmaps list
    for ax, cmap in zip(axs, cmaps_list):
        # Obtain axes objects and turn them off
        if show_grayscale:
            # Obtain Axes objects
            ax0, ax1 = ax

            # Turn axes off
            ax0.set_axis_off()
            ax1.set_axis_off()
        else:
            # Obtain Axes object
            ax0 = ax

            # Turn axis off
            ax0.set_axis_off()

        # Obtain position bbox of ax0
        pos0 = ax0.get_position()

        # If cmap is a tuple, it defines a title or cm_type
        if isinstance(cmap, tuple):
            # Calculate title_pos
            title_pos = left_pos + (1 - spacing - left_pos) / 2

            # If it is a title
            if cmap[1]:
                # Write the title as text in the correct position
                fig.text(title_pos,
                         pos0.y0 + pos0.height / 2,
                         cmap[0],
                         va='center',
                         ha='center',
                         fontsize=18,
                         c=text_color)

            # If it is a cm_type
            else:
                # Write the cm_type as text in the correct position
                fig.text(title_pos,
                         pos0.y0,
                         cmap[0],
                         va='bottom',
                         ha='center',
                         fontsize=14,
                         c=text_color)

        # Else, this is a colormap
        else:
            # Obtain the colormap type
            cm_type = get_cmap_type(cmap)

            # Get array of all values for which a colormap value is requested
            x = np.arange(cmap.N)

            # Get RGB values for colormap
            rgb = cmap(x)[:, :3]

            # Get lightness values of colormap
            lab = cspace_convert(rgb)
            L = lab[:, 0]

            # Normalize lightness values
            L /= 99.99871678

            # Get corresponding RGB values for lightness values using neutral
            rgb_L = cmrcm.neutral(L)[:, :3]

            # Add colormap subplot
            ax0.imshow(rgb[np.newaxis, ...], aspect='auto')

            # Check if the lightness profile was requested
            if plot_profile and (cm_type != 'qualitative'):
                # Determine the points that need to be plotted
                plot_L = -(L - 0.5)
                points = np.stack([x, plot_L], axis=1)

                # Determine the colors that each point must have
                # Use black for L >= 0.5 and white for L <= 0.5.
                colors = np.zeros_like(plot_L, dtype=int)
                colors[plot_L >= 0] = 1

                # Split points up into segments with the same color
                s_idx = np.nonzero(np.diff(colors))[0] + 1
                segments = np.split(points, s_idx)

                # Loop over all pairs of adjacent segments
                for i, (seg1,
                        seg2) in enumerate(zip(segments[:-1], segments[1:])):
                    # Determine the point in the center of these segments
                    central_point = (seg1[-1] + seg2[0]) / 2

                    # Add this point to the ends of these segments
                    # This ensures that the color changes in between segments
                    segments[i] = np.concatenate(
                        [segments[i], [central_point]], axis=0)
                    segments[i + 1] = np.concatenate(
                        [[central_point], segments[i + 1]], axis=0)

                # Create an MPL LineCollection object with these segments
                lc = LineCollection(segments,
                                    cmap=cmrcm.neutral,
                                    alpha=plot_profile)
                lc.set_linewidth(1)

                # Determine the colors of each segment
                s_colors = [colors[0]]
                s_colors.extend(colors[s_idx])
                s_colors = np.array(s_colors)

                # Set the values of the line-collection to be these colors
                lc.set_array(s_colors)

                # Add line-collection to this subplot
                ax1.add_collection(lc)

            # Add gray-scale colormap subplot if requested
            if show_grayscale:
                ax1.imshow(rgb_L[np.newaxis, ...], aspect='auto')

            # Plot the name of the colormap as text
            x_text = pos0.x0 - spacing
            y_text = pos0.y0 + pos0.height / 2
            fig.text(x_text,
                     y_text,
                     cmap.name,
                     va='center',
                     ha='right',
                     fontsize=10,
                     c=text_color)

    # If savefig is not None, save the figure
    if savefig is not None:
        dpi = 100 if (path.splitext(savefig)[1] == '.svg') else 250
        plt.savefig(savefig,
                    dpi=dpi,
                    facecolor=face_color,
                    edgecolor=edge_color)
        plt.close(fig)

    # Else, simply show it
    else:
        plt.show()
Beispiel #57
0
def plot_graph(in_dir, item):
    '''plot the communities graph which nodes and edges are extracted from
    the json file coocnetworks.json built by the function describe_corpus:

        {
        "nodes":[
            {"type":"AU","name":0,"item":"Abanades S","size":8},
            ...................................................
        ],
        "links":[
            {"type":"AU","source":0,"target":8,"Ncooc":5},
            ..............................................
        ]
        }

    where type = "AU", "S", "I", "CU", "S2", "IK", "AK", "TK", "R", "RJ"
    
    Returns the graph G.
    '''

    # Standard library imports
    import json
    import pprint
    from pathlib import Path

    # 3rd party imports
    import community as community_louvain
    import matplotlib.cm as cm
    import matplotlib.pyplot as plt
    import networkx as nx
    import numpy as np
    import pandas as pd

    # Local imports
    from .BiblioSpecificGlobals import LABEL_MEANING
    from .BiblioSpecificGlobals import VALID_LABEL_GRAPH


    assert (item in VALID_LABEL_GRAPH),\
            f'unknown type {TYPE}: should be {", ".join(VALID_LABEL_GRAPH)}'

    # Extract nodes and edgesSets the graph  from the json coocnetworks.json
    # for type=TYPE
    # -----------------------------------------------------------
    file_coocnetworks = in_dir / Path('coocnetworks.json')
    with open(file_coocnetworks, 'r') as read_file:
        cooc = json.load(read_file)

    df = pd.DataFrame(cooc['links']).query('type==@item')
    G = nx.from_pandas_edgelist(df, source='source', target='target')
    dg = pd.DataFrame(cooc['nodes']).query('type==@item')
    G.add_nodes_from(dg['name'])
    for index, row in dg.iterrows():
        src_attr_dict = {k: row.to_dict()[k] for k in ['item', 'size']}
        G.nodes[row['name']].update(src_attr_dict)

    # compute the best partition
    partition = community_louvain.best_partition(G)
    nx.set_node_attributes(G, partition, 'community_id')

    # draw the graph
    pos = nx.spring_layout(G)
    node_size = np.array(list(nx.get_node_attributes(G, 'size').values())) * 70
    cmap = cm.get_cmap('viridis', max(partition.values()) + 1)
    fig = plt.figure(figsize=(15, 15))
    nx.draw_networkx_nodes(G,
                           pos,
                           partition.keys(),
                           node_size=node_size,
                           cmap=cmap,
                           node_color=list(partition.values()))
    nx.draw_networkx_edges(
        G,
        pos,
        alpha=0.9,
        width=1.5,
        edge_color='k',
        style='solid',
    )

    labels = nx.draw_networkx_labels(G, pos=pos, font_size=8, font_color='w')

    plt.title(
        f'Graph partition using the {LABEL_MEANING[item]} and the Louvain algorithm'
    )
    plt.show()

    node = nx.get_node_attributes(G, 'item')
    pprint.pprint(node)

    df = pd.DataFrame({
        node_id: [num_partition, node[node_id]]
        for node_id, num_partition in partition.items()
    }).T

    for g in df.groupby([0]):
        print(f'N° partition:{g[0]}, items: {g[1][1].to_list()}')

    del df, dg, src_attr_dict, partition, labels, node

    return G
Beispiel #58
0
                                                         n_records)

# # Data Pre-Processing :
# Before we move on to modeling we're going to perform some preprocessing on our dataset to adjust the quality of our variables.

# In[34]:

X_train = train[[
    'Months since Last Donation', 'Number of Donations',
    'Total Volume Donated (c.c.)', 'Months since First Donation'
]]
y_train = train['Made_Donation_in_March_2007']

# In[19]:

cmap = cm.get_cmap('gnuplot')
scatter = pd.scatter_matrix(X_train,
                            c=y_train,
                            marker='o',
                            s=40,
                            hist_kwds={'bins': 15},
                            figsize=(9, 9),
                            cmap=cmap)

# # Log Transformation
# Notice the strong positive skew present in the features. In order to compress the range of our dataset and deal with outliers we will perform a log transformation using np.log().

# In[46]:

skewed = [
    'Months since Last Donation', 'Number of Donations',
Beispiel #59
0
    def __init__(self,
                 path,
                 deadPixeltol=2,
                 aspect="auto",
                 Linescan=True,
                 autoclose=False,
                 save=False):
        self.shift_is_held = False
        self.path = path
        self.deadPixeltol = deadPixeltol
        self.aspect = aspect
        self.Linescan = Linescan
        self.leftpressed = False
        if autoclose:
            plt.ioff()
        else:
            plt.ion()

        dirname, filename = os.path.split(self.path)
        filename, ext = os.path.splitext(filename)

        hyppath = self.path
        specpath = os.path.join(dirname, filename + '_X_axis.asc')
        filepath = os.path.join(dirname,
                                filename + '_SEM image after carto.tif')
        start = time.time()
        data = pd.read_csv(hyppath, delimiter='\t', header=None).to_numpy()
        end = time.time()
        print(end - start)
        #data = np.loadtxt(hyppath)
        xlen = int(data[0, 0])  #nbr de pts selon x
        ylen = int(data[1, 0])  #nbr de pts selon y
        wavelenght = np.loadtxt(specpath)
        self.wavelenght = wavelenght[:2048]  #bins du spectro
        xcoord = data[0, 1:]
        ycoord = data[1, 1:]
        CLdata = data[
            2:,
            1:]  #tableau de xlen * ylen points (espace) et 2048 longueur d'onde CLdata[:,n] n = numero du spectr
        self.hypSpectrum = np.transpose(
            np.reshape(np.transpose(CLdata),
                       (ylen, xlen, len(self.wavelenght))), (0, 1, 2))

        #correct dead / wrong pixels
        self.hypSpectrum, self.hotpixels = correct_dead_pixel(
            self.hypSpectrum, tol=self.deadPixeltol)

        self.wavelenght = ma.masked_array(self.wavelenght, mask=False)
        hypmask = np.resize(self.wavelenght.mask, self.hypSpectrum.shape)
        self.hypSpectrum = ma.masked_array(self.hypSpectrum, mask=hypmask)

        xscale_CL, yscale_CL, acceleration, image = scaleSEMimage(filepath)
        if self.Linescan:
            self.fig, (self.ax, self.bx, self.cx) = plt.subplots(
                3, 1, sharex=True, gridspec_kw={'height_ratios': [1, 1, 3]})
        else:
            self.fig, (self.ax, self.bx, self.cx) = plt.subplots(3,
                                                                 1,
                                                                 sharex=True,
                                                                 sharey=True)
        self.fig.patch.set_alpha(0)  #Transparency style
        self.fig.subplots_adjust(top=0.9,
                                 bottom=0.12,
                                 left=0.15,
                                 right=0.82,
                                 hspace=0.1,
                                 wspace=0.05)
        newX = np.linspace(xscale_CL[int(xcoord.min())],
                           xscale_CL[int(xcoord.max())], len(xscale_CL))
        newY = np.linspace(yscale_CL[int(ycoord.min())],
                           yscale_CL[int(ycoord.max())], len(yscale_CL))
        self.X = np.linspace(np.min(newX), np.max(newX),
                             self.hypSpectrum.shape[1])
        self.Y = np.linspace(np.min(newY), np.max(newY),
                             self.hypSpectrum.shape[0])

        nImage = np.array(
            image.crop(
                (xcoord.min(), ycoord.min(), xcoord.max(), ycoord.max())))
        self.ax.imshow(
            nImage,
            cmap='gray',
            vmin=0,
            vmax=65535,
            interpolation="None",
            extent=[np.min(newX),
                    np.max(newX),
                    np.max(newY),
                    np.min(newY)])

        self.hypimage = np.nansum(self.hypSpectrum, axis=2)
        jet = cm.get_cmap("jet")
        jet.set_bad(color='k')
        self.hyperspectralmap = cm.ScalarMappable(cmap=jet)
        self.hyperspectralmap.set_clim(vmin=np.nanmin(self.hypimage),
                                       vmax=np.nanmax(self.hypimage))
        self.lumimage = self.bx.imshow(
            self.hypimage,
            cmap=self.hyperspectralmap.cmap,
            norm=self.hyperspectralmap.norm,
            interpolation="None",
            extent=[np.min(newX),
                    np.max(newX),
                    np.max(newY),
                    np.min(newY)])
        if self.Linescan:
            self.linescan = np.nansum(self.hypSpectrum, axis=0)
            self.linescanmap = cm.ScalarMappable(cmap=jet)
            self.linescanmap.set_clim(vmin=np.nanmin(self.linescan),
                                      vmax=np.nanmax(self.linescan))
            # ATTENTION pcolormesh =/= imshow
            #imshow takes values at pixel
            #pcolormesh takes values between
            temp = np.linspace(newX.min(), newX.max(), self.X.size + 1)
            self.im = self.cx.pcolormesh(temp,
                                         eV_To_nm / self.wavelenght,
                                         self.linescan.T,
                                         cmap=self.linescanmap.cmap,
                                         shading='flat',
                                         rasterized=True)

            #dX=np.diff(self.X).mean()
            #newX = np.arange(min(self.X),max(self.X)+dX,dX)-dX/2
            #            dW = np.diff(self.wavelenght).mean()
            #            newW = np.arange(min(self.wavelenght),max(self.wavelenght)+dW,dW)-dW/2
            #self.im=self.cx.pcolormesh(newX,eV_To_nm/self.wavelenght,self.linescan.T,cmap=self.linescanmap.cmap,shading = 'flat',rasterized=True)
            def format_coord(x, y):
                xarr = self.X
                yarr = eV_To_nm / self.wavelenght
                if ((x > xarr.min()) and (x <= xarr.max()) and (y > yarr.min())
                        and (y <= yarr.max())):
                    col = np.argmin(abs(xarr - x))  #np.searchsorted(xarr, x)-1
                    row = np.argmin(abs(yarr - y))  #np.searchsorted(yarr, y)-1
                    z = self.linescan.T[row, col]
                    return f'x={x:1.4f}, y={y:1.4f}, lambda={eV_To_nm/y:1.2f}, z={z:1.2e}   [{row},{col}]'
                else:
                    return f'x={x:1.4f}, y={y:1.4f}, lambda={eV_To_nm/y:1.2f}'

            self.cx.format_coord = format_coord
            self.cx.set_ylabel("Energy (eV)")
            self.cx.set_xlabel("distance (µm)")
            self.cx.set_aspect(self.aspect)
        else:
            self.im = self.cx.imshow(self.wavelenght[np.argmax(
                self.hypSpectrum, axis=2)],
                                     cmap='viridis',
                                     extent=[
                                         np.min(newX),
                                         np.max(newX),
                                         np.max(newY),
                                         np.min(newY)
                                     ])
            self.cx.set_aspect(aspect)
        self.bx.set_aspect(self.aspect)
        self.ax.set_aspect(self.aspect)
        self.ax.get_shared_y_axes().join(self.ax, self.bx)
        self.ax.set_ylabel("distance (µm)")
        #    fig.text(ax.get_position().bounds[0]-0.11, ax.get_position().bounds[1],'distance (µm)',fontsize=16, va='center', rotation='vertical')

        pos = self.cx.get_position().bounds
        cbar_ax = self.fig.add_axes([0.85, pos[1], 0.05, pos[-1] * 0.9])
        self.fig.colorbar(self.linescanmap, cax=cbar_ax)
        cbar_ax.ticklabel_format(axis='both', style='sci', scilimits=(0, 0))

        pos = self.bx.get_position().bounds
        cbar_ax = self.fig.add_axes([0.85, pos[1], 0.05, pos[-1] * 0.9])
        self.fig.colorbar(self.hyperspectralmap, cax=cbar_ax)
        cbar_ax.ticklabel_format(axis='both', style='sci', scilimits=(0, 0))
        if save == True:
            self.fig.savefig(os.path.join(dirname, filename + ".png"), dpi=300)

        if autoclose == True:
            plt.close(self.fig)
            return None
        else:
            self.spec_fig, self.spec_ax = plt.subplots()
            self.spec_data, = self.spec_ax.plot(
                eV_To_nm / self.wavelenght, np.zeros(self.wavelenght.shape[0]))
            self.spec_ax.set_ylim((0, self.hypSpectrum.max()))
            self.spec_ax.set_xlabel('Energy (eV)')
            self.spec_ax.set_ylabel('Intensity (a.u)')
            self.spec_fig.subplots_adjust(top=0.885,
                                          bottom=0.125,
                                          left=0.13,
                                          right=0.94)
            self.spec_ax.ticklabel_format(axis='y',
                                          style='sci',
                                          scilimits=(0, 0))
            self.spec_minbar = self.spec_ax.axvline(eV_To_nm /
                                                    self.wavelenght.max())
            self.spec_maxbar = self.spec_ax.axvline(eV_To_nm /
                                                    self.wavelenght.min())

            #if Linescan:
            #self.cursor = MultiCursor(self.fig.canvas, (self.ax, self.bx), color='r', lw=1,horizOn=True, vertOn=True)
            def onmotion(event):
                if self.leftpressed:
                    x = event.xdata
                    y = event.ydata
                    if ((event.inaxes is not None) and (x > self.X.min())
                            and (x <= self.X.max()) and (y > self.Y.min())
                            and (y <= self.Y.max())):
                        indx = np.argmin(abs(x - self.X))
                        indy = np.argmin(abs(y - self.Y))
                        self.spec_data.set_ydata(self.hypSpectrum.data[indy,
                                                                       indx])
                        self.spec_fig.canvas.draw_idle()

            def onclick(event):
                if event.button == 1:
                    self.leftpressed = True
                    #self.cursor.active = True
                    #if event.dblclick:


#                        if not(self.cursor.visible):
#                            self.fig.canvas.blit(self.fig.bbox)
#self.cursor.active = not(self.cursor.active)
#                        self.cursor.visible = not(self.cursor.visible)
#                        self.fig.canvas.draw_idle()
#                        self.fig.canvas.blit(self.fig.bbox)
#                    elif self.cursor.active:
#                    x = event.xdata
#                    y = event.ydata
#                    if ((event.inaxes is not None) and (x > self.X.min()) and (x <= self.X.max()) and
#                        (y > self.Y.min()) and (y <= self.Y.max())):
#                        indx = np.argmin(abs(x-self.X))
#                        indy=np.argmin(abs(y-self.Y))
#                        self.spec_data.set_ydata(self.hypSpectrum.data[indy,indx])
#                        self.spec_fig.canvas.draw_idle()
                elif event.button == 3:
                    self.wavelenght = ma.masked_array(self.wavelenght.data,
                                                      mask=False)
                    hypmask = np.resize(self.wavelenght.mask,
                                        self.hypSpectrum.shape)
                    self.hypSpectrum = ma.masked_array(self.hypSpectrum.data,
                                                       mask=hypmask)
                    self.hypimage = np.nansum(self.hypSpectrum, axis=2)
                    self.lumimage.set_array(self.hypimage)
                    self.hyperspectralmap.set_clim(
                        vmin=np.nanmin(self.hypimage),
                        vmax=np.nanmax(self.hypimage))
                    self.cx.set_ylim(eV_To_nm / self.wavelenght.max(),
                                     eV_To_nm / self.wavelenght.min())
                    # TODO : A recoder
                    self.linescan = np.nansum(self.hypSpectrum, axis=0)
                    self.spec_maxbar.set_xdata(
                        np.repeat(eV_To_nm / self.wavelenght.min(), 2))
                    self.spec_minbar.set_xdata(
                        np.repeat(eV_To_nm / self.wavelenght.max(), 2))
                    self.im.set_array(
                        (self.linescan.T[:, :]).ravel())  #flat shading
                    #self.im.set_array((self.linescan.T).ravel())#gouraud shading
                    self.linescanmap.set_clim(vmin=np.nanmin(self.linescan),
                                              vmax=np.nanmax(self.linescan))
                    self.im.set_norm(self.linescanmap.norm)
                    #self.im.set_cmap(self.linescanmap.cmap)
                    self.fig.canvas.draw_idle()
                    self.spec_fig.canvas.draw_idle()
                    self.fig.canvas.blit(self.fig.bbox)

            def onrelease(event):
                if event.button == 1:
                    self.leftpressed = False
                    #self.cursor.active = False
            def onselect(ymin, ymax):
                indmin = np.argmin(abs(eV_To_nm / self.wavelenght - ymin))
                indmax = np.argmin(abs(eV_To_nm / self.wavelenght - ymax))
                #indmin resp.max est lindex tel que wavelenght[indmin] minimise
                # la distance entre la position du clic et la longueur d'onde
                #                print(eV_To_nm/self.wavelenght[indmin])
                #                print(eV_To_nm/self.wavelenght[indmax])
                if abs(indmax - indmin) < 1: return

                self.wavelenght = ma.masked_outside(self.wavelenght.data,
                                                    eV_To_nm / ymax,
                                                    eV_To_nm / ymin)
                hypmask = np.resize(self.wavelenght.mask,
                                    self.hypSpectrum.shape)
                self.hypSpectrum = ma.masked_array(self.hypSpectrum.data,
                                                   mask=hypmask)
                self.hypimage = np.nansum(self.hypSpectrum, axis=2)
                self.lumimage.set_array(self.hypimage)
                self.hyperspectralmap.set_clim(vmin=np.nanmin(self.hypimage),
                                               vmax=np.nanmax(self.hypimage))
                self.cx.set_ylim(eV_To_nm / self.wavelenght.max(),
                                 eV_To_nm / self.wavelenght.min())
                self.linescan = np.nansum(self.hypSpectrum, axis=0)
                self.spec_maxbar.set_xdata(
                    np.repeat(eV_To_nm / self.wavelenght.min(), 2))
                self.spec_minbar.set_xdata(
                    np.repeat(eV_To_nm / self.wavelenght.max(), 2))
                self.im.set_array(
                    (self.linescan.T[:, :]).ravel())  #flat shading
                #self.im.set_array((self.linescan.T).ravel())#gouraud shading
                self.linescanmap.set_clim(vmin=np.nanmin(self.linescan),
                                          vmax=np.nanmax(self.linescan))
                self.im.set_norm(self.linescanmap.norm)
                #self.im.set_cmap(self.linescanmap.cmap)
                self.fig.canvas.draw_idle()
                self.spec_fig.canvas.draw_idle()
                self.fig.canvas.blit(self.fig.bbox)

            self.span = None
            if Linescan:
                self.span = SpanSelector(self.cx,
                                         onselect,
                                         'vertical',
                                         useblit=True,
                                         rectprops=dict(alpha=0.5,
                                                        facecolor='red'),
                                         button=1)
            self.fig.canvas.mpl_connect('button_press_event', onclick)
            self.fig.canvas.mpl_connect('motion_notify_event', onmotion)
            self.fig.canvas.mpl_connect('button_release_event', onrelease)
            plt.show(block=True)
Beispiel #60
0
def _get_cmap_lightness_rank(cmap):
    """
    Returns a tuple of objects used for sorting the provided `cmap` based
    on its lightness profile.

    Parameters
    ----------
    cmap : str or :obj:`~matplotlib.colors.Colormap` object
        The registered name of the colormap in :mod:`matplotlib.cm` or its
        corresponding :obj:`~matplotlib.colors.Colormap` object.

    Returns
    -------
    L_type : int
        The type of lightness profile of `cmap`.
        This is only used for sequential colormaps.
    L_start : float
        The starting lightness value of `cmap`.
        For diverging colormaps, this is the central lightness value.
    L_rng : float
        The lightness range (L_max-L_min) of `cmap`.
    L_rmse : float
        The RMSE of the lightness profile of `cmap`.
        For diverging colormaps, this is the max RMSE of either half.
    name : str
        The name of `cmap`.
        For qualitative and miscellaneous colormaps, this is the only value
        that is used.

    """

    # Obtain the colormap
    cmap = mplcm.get_cmap(cmap)

    # Get RGB values for colormap
    rgb = cmap(np.arange(cmap.N))[:, :3]

    # Get lightness values of colormap
    lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb)
    L = lab[:, 0]

    # Determine the deltas of the lightness profile
    deltas = np.diff(L)
    derivs = (cmap.N - 1) * deltas

    # Set lightness profile type to 0
    L_type = 0

    # Determine the RMSE of the lightness profile of a sequential colormap
    if (get_cmap_type(cmap) == 'sequential'):
        # Take RMSE of entire lightness profile
        L_rmse = np.around(np.std(derivs), 1)

        # Calculate starting lightness value
        L_start = np.around(L[0], 1)

        # Determine type of lightness profile
        L_type += ~(np.sum(rgb[0]) == 0) * 2
        L_type += ((np.sum(rgb[0]) == 0) == (np.sum(rgb[-1]) == 3))

    # Diverging/cyclic colormaps
    elif get_cmap_type(cmap) in ('diverging', 'cyclic'):
        # Calculate RMSE of both halves
        central_i = [int(np.floor(cmap.N / 2)), int(np.ceil(cmap.N / 2))]
        L_rmse = np.max([
            np.around(np.std(derivs[:central_i[0]]), 1),
            np.around(np.std(derivs[central_i[1]:]), 1)
        ])

        # Calculate central lightness value
        L_start = np.around(np.average(L[central_i]), 1)

    # Determine lightness range for sequential/diverging/cyclic colormaps
    if get_cmap_type(cmap) in ('sequential', 'diverging', 'cyclic'):
        L_min = np.around(np.min(L), 1)
        L_max = np.around(np.max(L), 1)
        L_rng = np.around(np.abs(L_max - L_min), 1)

    # For qualitative/misc colormaps, set all lightness values to zero
    else:
        L_type = L_start = L_rng = L_rmse = 0

    # Return lightness contributions to the rank
    return (L_type, L_start, L_rng, L_rmse, cmap.name)