Example #1
0
    def _plot_output(self, type, latpositions, longpositions, data, media_file):
        fig = plt.figure(figsize=plt.figaspect(0.3))
        image = self.input_config.image
        impositions = self.input_config.positions
        imfactors = self.input_config.factors
        intensities = self.input_config.intensities

        writer = FFMpegFileWriter(fps=5, codec='mpeg4')
        writer.setup(
            fig, media_file, dpi=80,
            frame_prefix=os.path.splitext(media_file)[0]+'_')
        writer.frame_format = 'png'

        step = 100
        plt.hold(False)

        #TODO keep DRY
        U, V = np.mgrid[0:np.pi/2:complex(0, self.PARALLELS),
                        0:2*np.pi:complex(0, self.MERIDIANS)]
        X = np.cos(V)*np.sin(U)
        Y = np.sin(V)*np.sin(U)
        Z = np.cos(U)
        for i, d in enumerate(data):
            if i % step == 0:
                ax1 = fig.add_subplot(1, 3, 1)
                ax1.set_title('Image')
                if type == 'image':
                    ax1.imshow(image, cmap=cm.Greys_r)
                elif type == 'video':
                    # TODO show red rectangle
                    ax1 = fig.add_subplot(1, 3, 1)
                    xind = impositions[i, 0:2]
                    yind = impositions[i, 2:4]
                    ax1.imshow(image[int(xind[0]):int(xind[1]),
                                     int(yind[0]):int(yind[1])],
                               cmap=cm.Greys_r)
                else:
                    raise ValueError('Invalid value for media type: {}'
                                     ', valid values image, video'.format(type))
                
                colors = self.compute_colors(U, V, latpositions, 
                                             longpositions, intensities[i])
                ax2 = fig.add_subplot(1, 3, 2, projection='3d')
                ax2.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=cm.gray(colors),
                                 antialiased=False, shade=False)
                ax2.set_title('Intensities')
                colors = self.compute_colors(U, V, latpositions, 
                                             longpositions, data[i])
                ax3 = fig.add_subplot(1, 3, 3, projection='3d')
                ax3.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=cm.gray(colors),
                                 antialiased=False, shade=False)
                ax3.set_title('Photoreceptor outputs')
                fig.canvas.draw()
                writer.grab_frame()
        writer.finish()
Example #2
0
    def get_colors(self, qty):

        qty = np.power(qty / qty.max(), 1.0 / CONTRAST)

        if COLORMAP == 0:
            rgba = cm.gray(qty, alpha=ALPHA)
        elif COLORMAP == 1:
            rgba = cm.afmhot(qty, alpha=ALPHA)
        elif COLORMAP == 2:
            rgba = cm.hot(qty, alpha=ALPHA)
        elif COLORMAP == 3:
            rgba = cm.gist_heat(qty, alpha=ALPHA)
        elif COLORMAP == 4:
            rgba = cm.copper(qty, alpha=ALPHA)
        elif COLORMAP == 5:
            rgba = cm.gnuplot2(qty, alpha=ALPHA)
        elif COLORMAP == 6:
            rgba = cm.gnuplot(qty, alpha=ALPHA)
        elif COLORMAP == 7:
            rgba = cm.gist_stern(qty, alpha=ALPHA)
        elif COLORMAP == 8:
            rgba = cm.gist_earth(qty, alpha=ALPHA)
        elif COLORMAP == 9:
            rgba = cm.spectral(qty, alpha=ALPHA)

        return rgba
Example #3
0
def generateGreyTile(x, y, zoom, allRecords):
    timestamp = int(time.time())
    nw_corner = num2deg(x, y, zoom)
    se_corner = num2deg(x+1, y+1, zoom)

    lats = [min(nw_corner[0], se_corner[0]), max(nw_corner[0], se_corner[0])]
    lngs = [min(nw_corner[1], se_corner[1]), max(nw_corner[1], se_corner[1])]

    lats2 = np.around([lats[0] - .0002, lats[1] + .0002], decimals=4)
    lngs2 = np.around([lngs[0] - .0002, lngs[1] + .0002], decimals=4)

    timestamp = int(time.time())

    df = allRecords[
            (allRecords.lat >= lats2[0]) &
            (allRecords.lat <= lats2[1]) &
            (allRecords.lng >= lngs2[0]) &
            (allRecords.lng <= lngs2[1])
        ]
    df = df.reset_index(drop=True)
    timestamp = int(time.time())

    if len(df) != 0:

        bins = [
            np.arange(lngs2[0]-.00005, lngs2[1]+.00005, .0001),
            np.arange(lats2[0]-.00005, lats2[1]+.00005, .0001)
        ]

        zi, xi, yi = np.histogram2d(
            df['lng'], df['lat'],
            bins=bins, normed=False
        )

        zi = np.ma.masked_equal(zi, 0)
        zi = ((np.clip(zi, -90, -29) + 91) * 4.25).astype(int)
        zi = np.rot90(zi)

        s = 1024


        color = np.uint8(cm.gray(zi/225.0) * 225)
        color = imresize(color, size=(s,s), interp='nearest')

        lat_len = zi.shape[0]*.0001
        lng_len = zi.shape[1]*.0001

        x1 = ((lngs[0]-(lngs2[0]-.00005))/lng_len)*s
        x2 = s-(((lngs2[1]+.00005) - lngs[1])/lng_len)*s

        y1 = (((lats2[1]+.00005) - lats[1])/lat_len)*s
        y2 = s-((lats[0]-(lats2[0]-.00005))/lat_len)*s

        color = color[y1:y2+1,x1:x2+1]
        color = imresize(color, size=(256,256), interp='nearest')

        return Image.fromarray(color)
Example #4
0
def play_rates(rates, patches, num_levels=255, time=None,
        repeat=True, frametime=100):
    """
    Plays a movie representation of the firing rate of a list of cells, by
    coloring a list of patches with a color proportional to the firing rate. This
    is useful, for example, in conjunction with ``plot_cells``, to color the
    ellipses fitted to a set of receptive fields proportional to the firing rate.

    Parameters
    ----------
    rates : array_like
        An ``(N, T)`` matrix of firing rates. ``N`` is the number of cells, and
        ``T`` gives the firing rate at a each time point.

    patches : list
        A list of ``N`` matplotlib patch elements. The facecolor of these patches is
        altered according to the rates values.

    Returns
    -------
    anim : matplotlib.animation.Animation
        The object representing the full animation.
    """
    # Validate input
    if rates.ndim == 1:
        rates = rates.reshape(1, -1)
    if isinstance(patches, Ellipse):
        patches = [patches]
    N, T = rates.shape

    # Approximate necessary colormap
    colors = cm.gray(np.arange(num_levels))
    rscale = np.round((num_levels - 1) * (rates - rates.min()) /
                      (rates.max() - rates.min())).astype('int').reshape(N, T)

    # set up
    fig = plt.gcf()
    ax = plt.gca()
    if time is None:
        time = np.arange(T)

    # Animation function (called sequentially)
    def animate(t):
        for i in range(N):
            patches[i].set_facecolor(colors[rscale[i, t]])
        ax.set_title('Time: %0.2f seconds' % (time[t]), fontsize=20)

    # Call the animator
    anim = animation.FuncAnimation(fig, animate,
                                   np.arange(T), interval=frametime, repeat=repeat)
    return anim
Example #5
0
def PlotBands(procar):
    # Iterate over bands to collect data.
    for i in range(1, procar.Nb+1):
        # Iterate over k-points to build (kx, energy) pairs for this band.
        # Entries in surface are 0 (bulk states) or 1 (surface states).
        # surface controls the color of the markers.
        kx, energy, surface = [], [], []
        for k in procar.kPoints:
            kx.append(k.kx)
            b = k.Band(i)
            energy.append(b.energy)
            if hasattr(b, 'surface') and b.surface:
                print(str(k.kx) + " " + str(i))
                surface.append(cm.gray(0.0))
            else:
                surface.append(cm.gray(0.99))
        # plot band as thin green line (to clarify connection btwn markers)
        plt.plot(kx, energy, 'g-', linewidth=1)
        # plot band as markers: bulk -> white, surface -> black
        plt.scatter(kx, energy, facecolors=surface, edgecolor='b',
                    marker='o', cmap=cm.gray, linewidth=1, s=50)

    # Display the plot
    plt.show()
Example #6
0
def drawShape(m, ax, paraTable):
    for conshpfn in paraTable["ShapeFile"].unique():
        for i, conShape in enumerate(getPointArray(conshpfn)):
            tempParaTable = concat([paraTable[paraTable["ShapeFile"]==conshpfn]], ignore_index = True)
            partLimit = tempParaTable.ix[i,"PartLimit"]
            normal = tempParaTable.ix[i,"Normal"]
            shpsegs = []
            for j, conShapePart in enumerate(conShape):
                if j < partLimit:
                    lons, lats = zip(*conShapePart)
                    x, y = m(lons, lats)
                    shpsegs.append(zip(x,y))
                    lines = LineCollection(shpsegs,antialiaseds=(1,))
                    lines.set_facecolors(cm.gray(1 - normal))
                    lines.set_linewidth(0.01)
                    ax.add_collection(lines)
Example #7
0
def plotDelay(resultFilenames):
    # Size-Delay values from each file
    sizeValues = []
    delayValues = []

    # Loop over files and parse size=delay values
    for resultFilename in resultFilenames :
        # Append a new array for this file's size-delay values
        sizeValues.append ([])
        delayValues.append ([])
        index = len (sizeValues) - 1
        resultFile = open (resultFilename)
        
        inSizeDelayBlock = False
        for line in resultFile :
            if not inSizeDelayBlock :
                if "(Packet Size, Delay) Values:" in line :
                    inSizeDelayBlock = True
            else :
                if re.search ("\([-+]?[0-9]*\.?[0-9]+, [-+]?[0-9]*\.?[0-9]+\)", line) :
                    splitLine = line.split (",")
                    packetSize = int (splitLine[0][1:])
                    delay = float (splitLine[1][1:-2]) / 1000.0;
                    sizeValues[index].append (packetSize)
                    delayValues[index].append (delay)
                else :
                    inSizeDelayBlock = False
 
    maxDelay = 0.0
    for i in range (0, len (delayValues)) :
        for delayValue in delayValues[i] :
            if delayValue > maxDelay :
                maxDelay = delayValue

    matplotlib.rcParams.update({'font.size':17})
    matplotlib.rcParams.update({'figure.autolayout': True})

    colors = cm.gray ( np.linspace (0, 1, len (delayValues)))
    shortenedfilenames = []
    for name in resultFilenames:
        shortenedfilenames.append(name.split('.')[0])
    plt.hist(delayValues, 20, color=colors, label=shortenedfilenames)
    plt.legend()
    plt.xlabel ("Packet Delay (us)")
    plt.ylabel ("Occurrences")
    plt.savefig ("delay.pdf")
    plt.close()
Example #8
0
def write_lfs(datadict, max_lfs=2):
    with open('lfs_out.off', 'w') as f:
        f.write("COFF\n")
        # max_lfs = nanmax(datadict['lfs'])
        m,n = datadict['coords'].shape
        f.write("{} 0 0\n".format(m))

        for p, lfs in zip(datadict['coords'], datadict['lfs']):
            if not isnan(lfs):
                red=green=blue=0
                colorval = 255-int(255 * (lfs/max_lfs))
                if colorval > 255: colorval = 255
                if colorval < 0: colorval = 0

                rgba = cm.gray([colorval])[0]

                f.write("{0} {1} {2} {3} {4} {5} {6}\n".format(p[0], p[1], p[2], int(rgba[0]*255),int(rgba[1]*255),int(rgba[2]*255),int(rgba[3]*255)))
Example #9
0
def plot_countries(m, ax):
    global cfg
    global args
    colors = {}
    countries = []
    country_index = []

    # create temp color index and country index
    for ncountry, shapedict in enumerate(m.countries_info):
        country_name = shapedict['NAME'].decode('utf-8')
        if country_name in cfg['iso_atwo_fixes'].keys():
            country_code = cfg['iso_atwo_fixes'][country_name]
        else:
            country_code = shapedict['ISO_A2']

        if cfg['color_random']:
            colors[country_code] = rgb2hex((random.uniform(0,1),random.uniform(0,1),random.uniform(0,1)))
        else:
            colors[country_code] = rgb2hex(cm.gray(cfg['country_color_map'].get(country_code, 255) * cfg['color_step']))

        if cfg['country_color_map'].get(country_code, 255) == 255:
            if args.verbose:
                print "cannot map {country_name}({country_code})".format(country_name= country_name, country_code=country_code)

        if country_code not in countries:
            if args.verbose:
                print "adding {country_name}({country_code}) using color {country_color} ({country_color_raw}) to index.".format(country_name=country_name, country_code=country_code, country_color=colors[country_code], country_color_raw=cfg['country_color_map'].get(country_code, 255))
            countries.append(country_code)
        country_index.append(country_code)

    if args.verbose:
        print "added {country_count} countries to index.".format(country_count=len(countries))

    # plot countries
    for cindex, cc in enumerate(country_index):
        xx,yy = zip(*m.countries[cindex])
        if cc in cfg['color_overwrites'].keys():
            color = cfg['color_overwrites'][cc]
            if cfg['fill_overwrites']:
                ax.fill(xx,yy,color,edgecolor=color)
        else:
            color = colors[cc]
            if cfg['auto_fill_country']:
                ax.fill(xx,yy,color,edgecolor=color)
Example #10
0
def save_image_no_border(img):
    fig, ax = plt.subplots(figsize=(1, 1), dpi=224)
    ax.imshow(img, cmap='jet')
    ax.imshow(CAMs, alpha=0.4, cmap='jet')
    ax.axis('off')
    fig.frameon = False

    #with open("/home/cbrengman/Documents/Travel/AGU_2019/Talk/CAM_comb.tif",'wb') as outfile:
    #    fig.canvas.print_tif(outfile)

    from matplotlib import cm
    img = np.asarray(img)
    img = Image.fromarray(np.uint8(cm.gray(img) * 255))
    cam = Image.fromarray(np.uint8(cm.jet(CAMs[0]) * 255))
    ogcam = Image.fromarray(np.uint8(cm.jet(OGCAMs[0]) * 255))
    comb = Image.blend(img, cam, alpha=0.4)
    img.save('/home/cbrengman/Documents/transfer/img3.tif')
    cam.save('/home/cbrengman/Documents/transfer/img33_cam.tif')
    comb.save('/home/cbrengman/Documents/transfer/img3_comb.tif')
    ogcam.save('/home/cbrengman/Documents/transfer/img3_ogcam.tif', dpi=(7, 7))
def calculate_auto_corr(container, in_dir, opt_end="", s_color=False):
    """Calculate a matrix of autocorrs for each unit in a container"""
    ax1, fig1 = nc_plot._make_ax_if_none(None)
    auto_corr_matrix = np.empty((len(container), 20), dtype=float)
    color = iter(cm.gray(np.linspace(0, 0.8, len(container))))
    for i, ndata in enumerate(container):
        auto_corr_data = ndata.isi_auto_corr(bins=1, bound=[0, 20])
        auto_corr_matrix[i] = (auto_corr_data["isiCorr"] /
                               ndata.spike.get_unit_stamp().size)
        bins = auto_corr_data['isiAllCorrBins']
        bin_centres = bins[:-1] + np.mean(np.diff(bins)) / 2
        c = next(color) if s_color else "k"
        ax1.plot(bin_centres / 1000, auto_corr_matrix[i], c=c)
        ax1.set_xlim([0.000, 0.02])
        ax1.set_xticks([0.000, 0.005, 0.01, 0.015, 0.02])
    ax1.axvline(x=0.006, c="r", ls="--")

    plot_loc = os.path.join(in_dir, "nc_plots", "autocorr" + opt_end + ".png")
    fig1.savefig(plot_loc, dpi=400)
    return auto_corr_matrix
def calculate_isi_hist(container, in_dir, opt_end="", s_color=False):
    """Calculate a matrix of isi_hists for each unit in a container"""
    ax1, fig1 = nc_plot._make_ax_if_none(None)
    isi_hist_matrix = np.empty((len(container), 60), dtype=float)
    color = iter(cm.gray(np.linspace(0, 0.8, len(container))))
    for i, ndata in enumerate(container):
        res_isi, bins = log_isi(ndata)
        isi_hist_matrix[i] = res_isi
        bin_centres = bins[:-1] + np.mean(np.diff(bins)) / 2
        c = next(color) if s_color else "k"
        ax1.plot(bin_centres, res_isi, c=c)
        ax1.set_xlim([-3, 1])
        ax1.set_xticks([-3, -2, -1, 0])
    ax1.axvline(x=np.log10(0.006), c="r", ls="--")

    plot_loc = os.path.join(
        in_dir, "nc_plots", "logisi" + opt_end + ".png")
    fig1.savefig(plot_loc, dpi=400)

    return isi_hist_matrix
def drawLimits(useObjects,filt="Ks",useGrayscale=False):
	colorDict={}
	for ii,obj in enumerate(useObjects):
		if obj not in limitDict[filt].keys():
			print obj + " not found"
		else:
			if useGrayscale:
				colormap = cm.gray((ii)/(float(len(useObjects))),1)
			else:
				colormap = cm.spectral((ii)/(float(len(useObjects))),1)
			dists = []; deltaMag = []
			for xx in range(len(apertures)):
				if limitDict[filt][obj][xx][1] != "-":
					dists.append(eval(apertures[xx]))
					deltaMag.append(eval(limitDict[filt][obj][xx]))
		#	print "\n\n",dists,"\n",deltaMag,"\n\n"
				
			pylab.semilogx(dists,deltaMag,linewidth=2,linestyle='solid',color=colormap,label=obj+" "+instrUsed)
			colorDict[obj]=colormap
	return colorDict
Example #14
0
def plot_sphere(beta, alpha, f):
    alpha = np.concatenate((alpha, alpha[:, :1]), axis=1)
    beta = np.concatenate((beta, beta[:, :1]), axis=1)
    f = np.concatenate((f, f[:, :1]), axis=1)

    x = np.sin(beta) * np.cos(alpha)
    y = np.sin(beta) * np.sin(alpha)
    z = np.cos(beta)

    fc = cm.gray(f)
    fc = plt.get_cmap("bwr")(f)

    ax = plt.gca()
    ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=fc)

    ax.view_init(azim=-90, elev=90)
    ax.set_axis_off()
    a = 0.6
    ax.set_xlim3d(-a, a)
    ax.set_ylim3d(-a, a)
    ax.set_zlim3d(-a, a)
Example #15
0
def plot_fb8(fb8, npts):
    """
    Plot fb8 on 3D sphere
    """
    xs = fb8.spherical_coordinates_to_nu(*grid(npts))
    pdfs = fb8.pdf(xs)
    z,x,y = xs.T

    fig = plt.figure(figsize=plt.figaspect(1.))
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_surface(x.reshape(npts, npts),
                    y.reshape(npts, npts),
                    z.reshape(npts, npts),
                    alpha=0.5,
                    rstride=1, cstride=1,
                    facecolors=cm.gray(pdfs.reshape(npts, npts)/pdfs.max()))
    # ax.set_xticks([])
    # ax.set_yticks([])
    # ax.set_zticks([])
    ax.set_axis_off()
    ax.set_title(make_title(fb8), fontsize=12, y=0.18)
    plt.tight_layout(-5)
Example #16
0
def test():
    import numpy as np
    from matplotlib import cm
    #from pylab import cm, rand

    from PYME.DSView.LUT import lut

    lut1 = (255 *
            cm.gray(np.linspace(0, 1, 256))[:, :3].T).astype('uint8').copy()
    print((lut1.shape))

    def testLut():
        d = (100 * np.random.rand(5, 5)).astype('uint16')
        o = np.zeros((5, 5, 3), 'uint8')

        lut.applyLUTu8(d.astype('uint8'), .01, 0, lut1, o)
        lut.applyLUTu16(d, .01, 0, lut1, o)
        lut.applyLUTf(d.astype('uint16'), .01, 0, lut1, o)

        print(o)
        print((lut1.T[((d + 0) * .01 * 256).astype('i')]))

    testLut()
Example #17
0
def surf_plot(mg,
              surface='topographic__elevation',
              title='Surface plot of topography'):
    fig = plt.figure()
    ax = fig.gca(projection='3d')

    # Plot the surface.
    Z = mg.at_node[surface].reshape(mg.shape)
    color = cm.gray((Z - Z.min()) / (Z.max() - Z.min()))
    surf = ax.plot_surface(mg.node_x.reshape(mg.shape),
                           mg.node_y.reshape(mg.shape),
                           Z,
                           rstride=1,
                           cstride=1,
                           facecolors=color,
                           linewidth=0.,
                           antialiased=False)
    ax.view_init(elev=35, azim=-120)
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')
    ax.set_zlabel('Elevation')
    plt.title(title)
    plt.show()
def image_update(Qdata, fig, maxrep, Nplot, dBf, stop_flag):
    renderer = fig.select(dict(name="echoes", type=GlyphRenderer))
    source = renderer[0].data_source
    img = source.data["image"][0]

    while (not stop_flag.is_set()):
        Xrcv_seg = Qdata.get()

        # convert Xcrv_seg to dBf
        Xrcv_seg_dB = 10.0 * log10(Xrcv_seg)

        # enforce minimum dBf
        Xrcv_seg_dB[Xrcv_seg_dB < -dBf] = -dBf

        # convert to image intensity out of 1
        new_line = (Xrcv_seg_dB + dBf) / dBf

        img = np.roll(img, 1, 0)
        view = img.view(dtype=np.uint8).reshape((maxrep, Nplot, 4))
        view[0, :, :] = cm.gray(new_line) * 255

        source.data["image"] = [img]
        push_notebook()
        Qdata.queue.clear()
Example #19
0
def PlotMultiBar(xticks, ArrayBarTuples, inTitle, yLabel, inwidth=0.2, colorbounds=[0.3,0.6]):
    locs = numpy.arange(1, len(xticks) + 1)
    width = inwidth
    
    colors = [cm.gray(i) for i in numpy.linspace(colorbounds[0],colorbounds[1], len(ArrayBarTuples))]
    colorcycler = cycle(colors)
    
    fig = plt.figure()
    ax = plt.subplot(111)
    
    locAdj = 0
    for datatuple in ArrayBarTuples:
        locAdj += 1
        plt.bar(locs + locAdj*width, datatuple[0], yerr=datatuple[1], color=next(colorcycler), width=width,\
                antialiased=True, label=datatuple[3], ecolor='k') # color=datatuple[2]
        
    box = ax.get_position()
    ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
    ax.legend(loc='upper center', bbox_to_anchor = (0.5, -0.05), fancybox=True, shadow=True, ncol=locAdj)
    plt.title(inTitle)
    plt.xticks((locs + (locAdj * (width/2)) + width), xticks)
    plt.ylabel(yLabel)
    
    return fig
    def cb_mouse_motion(self, event):
        """
        Callback to process a mouse movement event.

        If the group selection option is enabled, then any points with
        Y-coordinate less than the cursor's Y-coordinate will be marked in a
        different opacity level, but not highlighted. If the user clicks with
        the mouse, then the points will be highlighted, but this event is
        processed in another method.

        This method also processes tooltip-related events when the group
        selection is disabled. If the user hovers the mouse cursor over a data
        point, then the name associated to that point will be shown in a
        tooltip.

        Parameters
        ----------
        event: matplotlib.backend_bases.MouseEvent
            Data about the event.
        """
        # We remove the horizonal line here (if any), regardless of the mouse
        # cursor position. We also restore the points colors.
        if self._hthresh_line:
            lines = self.axes.get_lines()
            for l in lines:
                self.axes.lines.remove(l)
                del l

            self._hthresh_line = None

            for i, p in enumerate(self.axes.collections):
                if i not in self._reference_idx:
                    p.set_facecolor(self._points_colors[i])
            self.draw()

        # Restoring the points' original size.
        if self._point_artists:
            for art in self._point_artists:
                if art is None:
                    continue
                art.set_sizes([self._plot_params['s']])

        if event.xdata is None or event.ydata is None or self._points is None:
            return False
        if self.group_selection_enabled:
            # We must get only the points above the cursor.
            diff = self._points - event.ydata
            above = []
            above = [i for i in reversed(self._yidx_points) if diff[i] >= 0]

            for a in above:
                if a in self._reference_idx:
                    continue
                self.axes.collections[a].set_facecolor(cm.gray(200))

                self._hthresh_line = self.axes.axhline(y=event.ydata,
                                                       c='b',
                                                       linewidth=2)
        else:
            # Testing if the cursor is over a point. If it is, we plot the
            # tooltip and notify this event by calling the registered
            # callback, if any.
            if not self.curvenames:
                return False
            else:
                hover_idx = None
                for i, art in enumerate(self._point_artists):
                    if not art:
                        continue
                    contains, _ = art.contains(event)
                    if contains:
                        art.set_sizes([self._plot_params['s'] * 3])
                        if i > len(self.curvenames):
                            return False
                        hover_idx = i
                        break

                if hover_idx is not None:
                    palette = QPalette()
                    palette.setColor(QPalette.ToolTipBase,
                                     QColor(252, 243, 207))
                    palette.setColor(QPalette.ToolTipText, QColor(0, 0, 0))
                    QToolTip.setPalette(palette)
                    QToolTip.setFont(QFont('Arial', 14, QFont.Bold))
                    pos = self.mapToGlobal(
                        QPoint(event.x,
                               self.height() - event.y))
                    QToolTip.showText(pos,
                                      '{}'.format(self.curvenames[hover_idx]))
                else:
                    QToolTip.hideText()

                if self._cb_notify_tooltip:
                    self._cb_notify_tooltip(self.name, hover_idx)

        self.draw()
def grayhist(img, stats=False):
    """
    入力 : BGR画像, 統計量の表示の有無(Optional)
    出力 : グレースケールのimshow, Histgram(+統計量)
    """
    # スタイルの設定。seabornの設定は残るため、常に最初に書いておく
    sns.set()
    sns.set_style(style='ticks')

    # プロット全体と個々のグラフのインスタンス
    fig = plt.figure(figsize=[15, 4])
    ax1 = fig.add_subplot(1, 2, 1)

    sns.set_style(style='whitegrid')
    ax2 = fig.add_subplot(1, 2, 2)

    # グレースケール画像化→三重配列に戻す
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
    ax1.imshow(img)

    img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    # 一次元配列化
    img = np.array(img).flatten()
    # 本来rangeは[0,255]となるはずだが、255に値が集まりすぎたので弾いた
    img = img[img != 255]

    # 軸の刻み目
    ax2.set_xticks(np.linspace(0, 255, 9).astype(int))

    # ヒストグラムを計算→色をつける
    N, bins, patches = ax2.hist(img, range=(0, 255), bins=256)
    for (i, patch) in enumerate(patches):
        color = cm.gray(bins[i] / 256)
        patch.set_facecolor(color)

    if stats == True:  # 統計量を表示する
        mean = img.mean()
        std = np.std(img)
        median = np.median(img)
        mode = sstats.mode(img)[0][0]

        # 統計量のラインをひく
        ax2.axvline(mean, color='#d95763', linestyle='solid', linewidth=3)
        ax2.axvline(median, color='#6abe30', linestyle='solid', linewidth=2)
        ax2.axvline(mode, color='#ba9641', linestyle='solid', linewidth=2)
        ax2.axvline(mean + std,
                    color='#d95763',
                    linestyle='dashdot',
                    linewidth=1)
        ax2.axvline(mean - std,
                    color='#d95763',
                    linestyle='dashdot',
                    linewidth=1)

        # 統計量の説明の文字
        ax2.text(mean,
                 N.max() * 1.075,
                 "$\mu$",
                 color='#d95763',
                 horizontalalignment='center')
        ax2.text(median,
                 N.max() * 1.18,
                 "median",
                 color='#6abe30',
                 rotation=45)
        ax2.text(mode, N.max() * 1.15, "mode", color='#ba9641', rotation=45)
        ax2.text(mean + std,
                 N.max() * 1.075,
                 "$\mu+\sigma$",
                 color='#d95763',
                 horizontalalignment='center')
        ax2.text(mean - std,
                 N.max() * 1.075,
                 "$\mu-\sigma$",
                 color='#d95763',
                 horizontalalignment='center')

        fig.tight_layout()
        plt.show()

        print("mean    : ", mean)
        print("stddev  : ", std)
        print("median  : ", median)
        print("mode    : ", mode)

    else:
        fig.tight_layout()
        plt.show()
Example #22
0
def plot_spectra_grid(file_set, ligands, *args, **kwargs):
    #Example Syntax:
    #   plot_spectra_grid(file_set,ligands,protein=['Src'],ligand=['Bosutinib'])
    #   plot_spectra_grid(file_set,ligands)
    #   plot_spectra_grid(file_set,ligands,output='Figure1')
    protein = kwargs.get('protein', None)
    ligand = kwargs.get('ligand', None)
    output = kwargs.get('output', None)

    if protein != None:
        these_proteins = protein
    else:
        these_proteins = file_set.keys()
    if ligand != None:
        these_ligands = ligand
    else:
        these_ligands = ligands
    print(these_proteins)
    print(len(these_proteins))
    print(these_ligands)
    print(len(these_ligands))

    grid = len(these_proteins) + len(these_ligands)
    if grid == 2:
        my_figsize = (12, 8)
    else:
        my_figsize = (24, 18)

    fig, axes = plt.subplots(nrows=len(these_ligands),
                             ncols=len(these_proteins),
                             figsize=my_figsize,
                             sharey=True,
                             sharex=True)

    for j, protein in enumerate(these_proteins):
        for k, ligand in enumerate(these_ligands):
            index = ligands.index(ligand)
            file = file_set[protein][index]

            if grid == 2:
                my_axes = None
            else:
                my_axes = axes[k, j]

            # pick a title
            title = "%s - %s" % (protein, ligand)

            # make a dataframe
            df = xml2df(file)

            # plot the spectra
            #fig = plt.figure();
            for i in range(11):
                df['fluorescence'].iloc[:, i].plot(ylim=(0, 100000),
                                                   xlim=(400, 600),
                                                   linewidth=3,
                                                   ax=my_axes,
                                                   c=cm.hsv(i * 15),
                                                   title=title)
                df['fluorescence'].iloc[:, 11 + i].plot(ylim=(0, 100000),
                                                        xlim=(400, 600),
                                                        legend=False,
                                                        ax=my_axes,
                                                        linewidth=4,
                                                        c=cm.gray(i * 15 + 50),
                                                        fontsize=20,
                                                        title=title)

            sns.despine()
            plt.yticks([])
            plt.tight_layout()

    if output != None:
        plt.savefig('%s.png' % output)
Example #23
0
def main():
    backgroundimage = plt.imread("worldmap.jpg", format='jpg')                
    inputfile = "normalizedcoordinates.txt"
    latitude= np.loadtxt(inputfile, dtype=float, delimiter=",", usecols=[0])
    longitude= np.loadtxt(inputfile, dtype=float, delimiter=",", usecols=[1])
    X = []
    for i in range(len(latitude)):                                            
        X.append((longitude[i], latitude[i]))
    X = np.asarray(X)
	######### Alkuperäinen data  ##############
    fig, ax = plt.subplots()
    x0,x1 = ax.get_xlim()
    y0,y1 = ax.get_ylim()
    for j in range(len(X)):     
        plt.scatter(X[j, 0], X[j, 1], c=cm.jet(0),s=7, marker='o')
    ax.imshow(backgroundimage, extent=[x0,x1,y0,y1], aspect='auto', alpha=0.8)
    plt.title("Earthquakes around the world in July 2017 (Original data)")
    plt.xlabel("Latitude")
    plt.ylabel("Longitude")
    ######## Silhouette score  ################
    num_clusters = Silhouette_score(X)
    ##########  K-Means  ########################	
    fig1, ax1 = plt.subplots()
    x0,x1 = ax1.get_xlim()
    y0,y1 = ax1.get_ylim()
	
    print("Best value for number of clusters based on silhouette_score was {}".format(num_clusters))
    labels, cluster_centers = Kmeans(X, num_clusters)
    for j in range(len(labels)):     
        plt.scatter(X[j, 0], X[j, 1], c=cm.jet(labels[j]/num_clusters),s=7, marker='o') #Piirretään näytteet kuvaajaan eri väreillä kmeans luokittelutiedon perusteella
    for i in range(len(cluster_centers)):
        plt.scatter(cluster_centers[i,0], cluster_centers[i,1], marker='x', s=140, linewidth=3, c = cm.jet(i/num_clusters), zorder = 10) #Piirretään myös kuvaajan kmeans algoritmin klusterikeskipisteet
    ax1.imshow(backgroundimage, extent=[x0,x1,y0,y1], aspect='auto', alpha=0.8)
    plt.title("Clustering with K-means")
    plt.xlabel("Latitude")
    plt.ylabel("Longitude")
	################# DBSCAN  ###########################
    fig2, ax2 = plt.subplots()
    x0,x1 = ax2.get_xlim()
    y0,y1 = ax2.get_ylim()
	
    labels = Dbscan(X)
    n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
    print('Estimated number of clusters for DBSCAN: {}'.format(n_clusters))
	
    unique_labels = set(labels)
    for k in range(len(labels)):
        if labels[k] == -1:
            plt.scatter(X[k, 0], X[k, 1], c=cm.gray(0), s=7,marker = 'o')
        else:
            plt.scatter(X[k, 0], X[k, 1], c=cm.jet(labels[k]/len(unique_labels)), s=5,marker = 'o')	

    ax2.imshow(backgroundimage, extent=[x0,x1,y0,y1], aspect='auto', alpha=0.8)
    plt.title("Clustering with DBSCAN")
    plt.xlabel("Latitude")
    plt.ylabel("Longitude")
	############## Kokoava hierarkinen klusterointi ###########################
    fig3, ax3 = plt.subplots()
    x0,x1 = ax3.get_xlim()
    y0,y1 = ax3.get_ylim()
	
    labels = Agglomerative_clustering(X, num_clusters)
    for k in range(len(labels)):    
        plt.scatter(X[k, 0], X[k, 1], c=cm.jet(labels[k]/num_clusters),s=7, marker='o')
    ax3.imshow(backgroundimage, extent=[x0,x1,y0,y1], aspect='auto', alpha=0.8)
    plt.title("Clustering with AgglomerativeClustering")
    plt.xlabel("Latitude")
    plt.ylabel("Longitude")
		
    plt.show()
Example #24
0
def scatterEuler3d(fig, angs, cnt, color_map='cool', hide_zero_marker=False, **extra):
    ''' Plot the angular histogram using a 3D scatter plot
    
    :Parameters:
        
        fig : Figure
              Matplotlib figure handle
        angs : array
               Array of view angles
        cnt : array
              Histogram for each view angle 
        color_map : str
                    Name of color map
        hide_zero_marker : bool
                           If true, hide the zero projection count marker
        extra : dict
                Unused keyword arguments
    '''
    
    cmap = getattr(cm, color_map)
    cnt = cnt.astype(numpy.float)
    nhist = cnt.copy()
    if nhist.min() != nhist.max():
        nhist-=nhist.min()
        nhist/=nhist.max()
    
    ax = mplot3d.Axes3D(fig)
    data = numpy.zeros((len(angs), 3))
    for i in xrange(len(angs)):
        if i == 0: print angs[i, :]
        data[i, :] = spider_transforms.euler_to_vector(*angs[i, :])
    nonzero = numpy.nonzero(cnt)
    ax.scatter3D(data[nonzero, 0].ravel(), data[nonzero, 1].ravel(), data[nonzero, 2].ravel(), c=nhist, cmap=cmap)
    if not hide_zero_marker:
        nonzero = numpy.nonzero(cnt==0)
        if len(nonzero) > 0:
            ax.scatter3D(data[nonzero, 0].ravel(), data[nonzero, 1].ravel(), data[nonzero, 2].ravel(), color=cm.gray(0.5), marker='x') # @UndefinedVariable
Example #25
0
h5 = h5py.File(sys.argv[1])
print(h5.attrs['cluttercount'])
print(h5.attrs['range'])

for i in range(0,150,10):
    print(i)

    # Thresholded images for the radars
    binary = {}
    for radar in ['NL60', 'NL61']:
        binary[radar] = np.greater(h5[radar],i)
    binary['overlap'] = np.product(binary.values(), 0)
    for k, v in binary.items():
        Image.fromarray(
            cm.gray(
                colors.Normalize()(v),
                bytes=True,
            ),
        ).save('threshold_{:03.0f}_{}.png'.format(float(i), k))
    rgba = np.zeros(binary['overlap'].shape + (4,), dtype=np.uint8)
    mask = ~np.bool8(binary['overlap'])
    rgba[..., 0] = binary['NL60'] * mask
    rgba[..., 1] = 0
    rgba[..., 2] = binary['NL61'] * mask
    rgba[..., 3] = np.logical_or(binary['NL60'], binary['NL61'])
    Image.fromarray(
        rgba * 255,
    ).save('threshold_{:03.0f}_{}.png'.format(float(i), 'color'))

Example #26
0
    for val in val_loader:
        #X_val = next(iter(val))
        X_val = val.type(dtype)
        X_val = X_val.to(device)
        X_hat_val = decoder(X_val)
        X_hat_val = X_hat_val.cpu().view(10 * 9, 160)
        X_hat_val = X_hat_val.detach().numpy()
        list_of_arrays.append(X_hat_val)
    return list_of_arrays


reconstruct(decoder, device, dtype, val_loader)
cnt = 0
for item in list_of_arrays:
    #print(item)
    im = Image.fromarray(np.uint8(cm.gray(item) * 255))
    new_img = im.resize((480, 270))
    new_img = new_img.convert('RGB')
    if cnt in range(10):
        new_img.save(
            "C:/Users/Manda/Documents/NCF/Practical_Data_Science/critters/latent_images/0"
            + str(cnt) + ".jpg")
    else:
        new_img.save(
            "C:/Users/Manda/Documents/NCF/Practical_Data_Science/critters/latent_images/"
            + str(cnt) + ".jpg")
    cnt += 1

image_folder = 'C:/Users/Manda/Documents/NCF/Practical_Data_Science/critters/latent_images/'
fps = 5
image_files = [
Example #27
0
def plot_angles(angs, hist, mapargs, color_map='cool', area_mult=1.0, alpha=0.9, hide_zero_marker=False, use_scale=False, label_view=[], **extra):
    ''' Plot the angular histogram using a map projection from basemap
    
    .. note::
         
        Basemap uses longitude latitude conventions, but the given angles are in
        colatitude, longitude convention.
    
    :Parameters:
        
        angs : array
               Array of view angles
        cnt : array
              Histogram for each view angle 
        mapargs : dict
                  Arguments specific to a map projection in basemap
        color_map : str
                    Name of color map
        area_mult : float
                    Scaling factor for size display
        alpha : float
                Transparency factor
        hide_zero_marker : bool
                           If true, hide the zero projection count marker
        use_scale : bool
                    If true, then display scale for size and color
        label_view : list
                     Label each view with text
        extra : dict
                Unused keyword arguments 
    '''
    
    cmap = getattr(cm, color_map)
    m = basemap.Basemap(**mapargs)
    
    # Y -> latitude
    # Z -> longitude
    
    #longitude, latitude = 90-colatitude
    x, y = m(angs[:, 1], 90.0-angs[:, 0])
    sel = hist < 1
    hist = hist.astype(numpy.float)
    s = numpy.sqrt(hist)*area_mult
    nhist = hist.copy()
    nhist-=nhist.min()
    nhist/=nhist.max()
    m.drawparallels(numpy.arange(-90.,120.,30.))
    m.drawmeridians(numpy.arange(0.,420.,60.))
    im = m.scatter(x, y, s=s, marker="o", c=cmap(nhist), alpha=alpha, edgecolors='none')
    
    font_tiny=matplotlib.font_manager.FontProperties()
    font_tiny.set_size('xx-small')
    
    if len(label_view) > 0:
        for i in label_view:
            if i > len(angs): 
                _logger.warn("Cannot label view: %d when there are only %d views (skipping)"%(i, len(angs)))
                continue
            ytext = -15 if i%2==0 else 15
            pylab.annotate('%d: %.1f,%.1f'%(i+1, angs[i, 0], angs[i, 1]), xy=(x[i],y[i]),  xycoords='data',
                                    xytext=(-15, ytext), textcoords='offset points',
                                    arrowprops=dict(arrowstyle="->"), fontproperties =font_tiny
                                    )
    
    if numpy.sum(sel) > 0 and not hide_zero_marker:
        im = m.scatter(x[sel], y[sel], numpy.max(s), marker="x", c=cm.gray(0.5))#@UndefinedVariable
    
    if not use_scale:
        im = matplotlib.cm.ScalarMappable(cmap=cmap, norm=matplotlib.colors.Normalize())
        im.set_array(hist)
        m.colorbar(im, "right", size="3%", pad='1%')
    else:
        fontP=matplotlib.font_manager.FontProperties()
        fontP.set_size('small')
        inc = len(hist)/10
        lines = []
        labels = []
        idx = numpy.argsort(hist)[::-1]
        for j in xrange(0, len(hist), inc):
            i=idx[j]
            labels.append("%s"%hist[i])
            lines.append(matplotlib.lines.Line2D(range(1), range(1), color=cmap(nhist[i]), marker='o', markersize=s[i]/2, linestyle='none', markeredgecolor='white'))
        if numpy.sum(sel) > 0 and not hide_zero_marker:
            i=idx[len(idx)-1]
            labels.append("%s"%hist[i])
            lines.append(matplotlib.lines.Line2D(range(1), range(1), color=cm.gray(0.5), marker='x', markersize=numpy.max(s)/5, linestyle='none')) #@UndefinedVariable
        pylab.legend(tuple(lines),tuple(labels), numpoints=1, frameon=False, loc='center left', bbox_to_anchor=(1, 0.5), prop = fontP)
Example #28
0
plt.scatter(train_x, train_y, color="RED")

# 簡単に学習させてみる
# エポックで回してみる
epoch = 1000
for ep in range(epoch):
    # まずはデータをシャッフル
    perm = numpy.random.permutation(len(train_x))
    train_x = numpy.array(train_x)[perm]
    train_y = numpy.array(train_y)[perm]

    for (x, y) in zip(train_x, train_y):
        # 完璧なChainer風に仕上げた
        model.zerograds()
        loss = model([x], [y])
        loss.backward()
        optimizer.update()

# 最終結果をプロット
plot_y = model(plot_x).data
plt.plot(plot_x,
         plot_y,
         label=str(ep + 1) + " epoch score",
         color=cm.gray(1 - ep / epoch))

# 表示
plt.ylim([-5, 5])
plt.legend()
plt.title("learning rate = " + str(alpha))
plt.savefig("images/dim" + str(dim) + ".png")
Example #29
0

######
ax = fig.add_subplot(131)

import matplotlib.cm as cm

i = 3 #Picked team number 3

        
d = max_depth(C[i])

depth_colors = []
for j in C[i].nodes():
    depth_percentage = C[i].node[j]['depth']/d
    depth_colors.append(cm.gray(depth_percentage))
    
same_age_colors = []
same_media_colors = []
same_relationship_colors = []
for e in C[i].edges():
    if C[i].node[e[0]]['age']=='unknown' or C[i].node[e[1]]['age']=='unknown':
        same_age_colors.append('green')
    elif C[i].node[e[0]]['age']==C[i].node[e[1]]['age']:
        same_age_colors.append('blue')
    else:
        same_age_colors.append('red')
    if C[i].node[e[0]]['source_through']==0 or C[i].node[e[1]]['source_through']==0:
        same_media_colors.append('green')
    elif C[i].node[e[0]]['source_through']==C[i].node[e[1]]['source_through']:
        same_media_colors.append('blue')
Example #30
0
        # N.B. for a transparent background -> 4th column == 1.
        cmap = cm.jet(range(256))
        cmap[0, :3] = 1.0
        cmap = mpl.colors.ListedColormap(cmap)

        try:
            plt.style.use(["goose", "goose-latex"])
        except OSError:
            pass

        fig, axes = plt.subplots(figsize=(18, 6), nrows=1, ncols=3)

        ax = axes[0]
        im = ax.imshow(img,
                       clim=(0, 1),
                       cmap=mpl.colors.ListedColormap(cm.gray([0, 255])))
        ax.xaxis.set_ticks([0, 20])
        ax.yaxis.set_ticks([0, 20])
        ax.set_xlim([-0.5, 20.5])
        ax.set_ylim([-0.5, 20.5])
        ax.set_xlabel(r"$x$")
        ax.set_ylabel(r"$y$")
        ax.set_title(r"image")
        div = make_axes_locatable(ax)
        cax = div.append_axes("right", size="5%", pad=0.1)
        cbar = plt.colorbar(im, cax=cax)
        cbar.set_ticks([0, 1])

        ax = axes[1]
        im = ax.imshow(CD, clim=(0, np.max(C) + 1), cmap=cmap)
        ax.xaxis.set_ticks([0, 20])
Example #31
0
def plot_multiple_traces(obj, ida):
    for i, trace in enumerate(obj.traces[obj.current_position]):
        c = cm.gray(i/len(obj.traces[obj.current_position]),1)
        obj.ax[ida].plot(obj.t, trace, color=c)

    obj.last_position = len(obj.traces) - 1
            title='Presidential Approval Rating')

days_func = lambda x: x - x.iloc[0]
pres_41_45['Days in Office']=pres_41_45.groupby('President')['End Date']\
.transform(days_func)
pres_41_45.head()
pres_41_45.groupby('President').head(3)
pres_41_45.dtypes
pres_41_45['Days in Office'] = pres_41_45['Days in Office'].dt.days
pres_41_45['Days in Office'].head()
pres_pivot = pres_41_45.pivot(index='Days in Office',
                              columns='President',
                              values='Approving')
pres_pivot.head()
plot_kwargs = dict(figsize=(16, 6),
                   color=cm.gray([.3, .7]),
                   style=['-', '--'],
                   title='Approval Rating')
pres_pivot.loc[:250,
               ['Donald J. Trump', 'Barack Obama']].ffill().plot(**plot_kwargs)
pres_rm = pres_41_45.groupby('President', sort=False).rolling('90D', on='End Date')['Approving']\
.mean()
pres_rm.head()

styles = ['-.', '-', ':', '-', ':']
colors = [.9, .3, .7, .3, .9]
color = cm.Greys(colors)
title = '90 Day Approval Rating Rolling Average'
plot_kwargs = dict(figsize=(16, 6), style=styles, color=color, title=title)
correct_col_order = pres_41_45.President.unique()
pres_rm.unstack('President')[correct_col_order].plot(**plot_kwargs)
Example #33
0
def get_random_plot(name, direc):
    """
    Random plot generation method.
    Inputs:
    name: (string) name of the plot which will be saved.
    Outputs:
    ax : (matplotlib obj) Matplotlib object of the axes of the plot
    fig : (matplotlib obj) Matplotlib object of the figure of the plot
    x, y : (list, list) Actuall x and y coordinates of the points.
    s : (list) sizes of the points.
    categories : (list) categories of the points.
    tick_size : (list) Tick size on the plot. [width, length]
    axes_x_pos, axes_y_pos: (float, float) Position of the labels of the axis.
    """

    # PLOT STYLE
    style = random.choice(styles)
    plt.style.use(style)

    # POINT DISTRIBUTION
    distribution = random.choice(point_dist)

    # RESOLUTION AND TICK SIZE
    dpi = int(dpi_min + np.random.rand(1)[0] * (dpi_max - dpi_min))
    figsize = (figsize_min + np.random.rand(2) *
               (figsize_max - figsize_min)).astype(int)
    tick_size = [(tick_size_width_min + np.random.rand(1)[0] *
                  (tick_size_width_max - tick_size_width_min)),
                 (tick_size_length_min + np.random.rand(1)[0] *
                  (tick_size_length_max - tick_size_length_min))]
    tick_size.sort()
    fig, ax = plt.subplots(figsize=figsize, dpi=dpi)

    # ACTUAL POINTS
    points_nb = int(points_nb_min + (np.random.rand(1)[0]**1.5) *
                    (points_nb_max - points_nb_min))
    #print points_nb
    x_scale = int(x_min_top + np.random.rand(1)[0] * (x_max_top - x_min_top))
    #print x_scale
    y_scale = int(y_min_top + np.random.rand(1)[0] * (y_max_top - y_min_top))
    #print y_scale
    x_scale_range = x_scale + int(np.random.rand(1)[0] * x_scale_range_max)
    #print x_scale_range
    y_scale_range = y_scale + int(np.random.rand(1)[0] * y_scale_range_max)
    #print y_scale_range
    x_min = (-np.random.rand(1)[0] + np.random.rand(1)[0]) * 10**(x_scale)
    x_max = (-np.random.rand(1)[0] +
             np.random.rand(1)[0]) * 10**(x_scale_range)
    x_min, x_max = min(x_min, x_max), max(x_min, x_max)
    y_min = (-np.random.rand(1)[0] + np.random.rand(1)[0]) * 10**(y_scale)
    y_max = (-np.random.rand(1)[0] +
             np.random.rand(1)[0]) * 10**(y_scale_range)
    y_min, y_max = min(y_min, y_max), max(y_min, y_max)

    if distribution == 'uniform':
        x = x_min + np.random.rand(points_nb) * (x_max - x_min)
        y = y_min + np.random.rand(points_nb) * (y_max - y_min)
    elif distribution == 'linear':
        x = x_min + np.random.rand(points_nb) * (x_max - x_min)
        y = x * (max(y_max, -y_min) / (max(x_max, -x_min))) * random.choice(
            [-1.0, 1.0]) + (y_min + np.random.rand(points_nb) *
                            (y_max - y_min)) * np.random.rand(1)[0] / 2.0
    elif distribution == 'quadratic':
        x = x_min + np.random.rand(points_nb) * (x_max - x_min)
        y = x**2 * (1.0 / (max(x_max, -x_min)))**2 * max(
            y_max, -y_min) * random.choice(
                [-1.0, 1.0]) + (y_min + np.random.rand(points_nb) *
                                (y_max - y_min)) * np.random.rand(1)[0] / 2.0

    # POINTS VARIATION
    nb_points_var = 1 + int(np.random.rand(1)[0] * max_points_variations)
    nb_points_var_colors = 1 + int(np.random.rand(1)[0] * nb_points_var)
    nb_points_var_markers = 1 + int(
        np.random.rand(1)[0] * (nb_points_var - nb_points_var_colors))
    nb_points_var_size = max(
        1, 1 + nb_points_var - nb_points_var_colors - nb_points_var_markers)

    rand_color_number = np.random.rand(1)[0]
    if rand_color_number <= 0.5:
        colors = cm.rainbow(np.random.rand(nb_points_var_colors))
    elif rand_color_number > 0.5 and rand_color_number <= 0.7:
        colors = cm.gnuplot(np.random.rand(nb_points_var_colors))
    elif rand_color_number > 0.7 and rand_color_number <= 0.8:
        colors = cm.copper(np.random.rand(nb_points_var_colors))
    else:
        colors = cm.gray(np.linspace(0, 0.6, nb_points_var_colors))
    s_set = (size_points_min + np.random.rand(nb_points_var_size) *
             (size_points_max - size_points_min))**2
    markers_subset = list(np.random.choice(markers,
                                           size=nb_points_var_markers))
    markers_empty = np.random.rand(1)[0] > 0.75
    markers_empty_ratio = random.choice([0.0, 0.5, 0.7])

    # BUILDING THE PLOT
    s = []
    categories = []
    cat_dict = {}
    index_cat = 0

    for _x, _y, in zip(x, y):
        s_ = random.choice(s_set)
        c_ = random.choice(colors)
        m_ = random.choice(markers_subset)
        if m_ in markers_with_full and markers_empty:
            e_ = np.random.rand(1)[0] > markers_empty_ratio
        else:
            e_ = False
        cat = [s_, c_, m_, e_]

        if cat_in_dict(cat, cat_dict) is False:
            cat_dict[index_cat] = cat
            index_cat += 1
        categories.append(cat_in_dict(cat, cat_dict))
        s.append(s_)
        if e_:
            plt.scatter(_x, _y, s=s_, color=c_, marker=m_, facecolors='none')

        else:
            plt.scatter(_x, _y, s=s_, color=c_, marker=m_)

    # PAD BETWEEN TICKS AND LABELS
    #labs = [item.get_text() for item in ax.get_xticklabels()]
    #print labs
    pad_x = max(tick_size[1] + 0.5,
                int(pad_min + np.random.rand(1)[0] * (pad_max - pad_min)))
    pad_y = max(tick_size[1] + 0.5,
                int(pad_min + np.random.rand(1)[0] * (pad_max - pad_min)))
    direction_ticks_x = random.choice(direction_ticks)
    direction_ticks_y = random.choice(direction_ticks)

    # NON-DEFAULT TICKS PROB, WITH THRESHOLD OF 0.6
    weid_ticks_prob = np.random.rand(1)[0]

    # TICKS STYLE AND LOCATION (X AXIS)
    if np.random.rand(1)[0] > 0.5:
        axes_x_pos = 1
        ax.xaxis.tick_top()
        ax.xaxis.set_label_position("top")
        if weid_ticks_prob > 0.6:
            ax.xaxis.set_tick_params(width=tick_size[0],
                                     length=tick_size[1],
                                     color='black',
                                     pad=pad_x,
                                     direction=direction_ticks_x,
                                     bottom=np.random.rand(1)[0] > 0.5,
                                     top=True)
        else:
            ax.xaxis.set_tick_params(bottom=np.random.rand(1)[0] > 0.5,
                                     top=True)
        if np.random.rand(1)[0] > 0.5:
            ax.spines['bottom'].set_visible(False)
            ax.xaxis.set_tick_params(bottom=False)
            if np.random.rand(1)[0] > 0.5:
                axes_x_pos = np.random.rand(1)[0]
                ax.spines['top'].set_position(('axes', axes_x_pos))
    else:
        axes_x_pos = 0
        if weid_ticks_prob > 0.6:
            ax.xaxis.set_tick_params(width=tick_size[0],
                                     length=tick_size[1],
                                     color='black',
                                     pad=pad_x,
                                     direction=direction_ticks_x,
                                     bottom=True,
                                     top=np.random.rand(1)[0] > 0.5)
        else:
            ax.xaxis.set_tick_params(bottom=True,
                                     top=np.random.rand(1)[0] > 0.5)
        if np.random.rand(1)[0] > 0.5:
            ax.spines['top'].set_visible(False)
            ax.xaxis.set_tick_params(top=False)
            if np.random.rand(1)[0] > 0.5:
                axes_x_pos = np.random.rand(1)[0]
                ax.spines['bottom'].set_position(('axes', axes_x_pos))

    # TICKS STYLE AND LOCATION (Y AXIS)
    if np.random.rand(1)[0] > 0.5:
        axes_y_pos = 1
        ax.yaxis.tick_right()
        ax.yaxis.set_label_position("right")
        if weid_ticks_prob > 0.6:
            ax.yaxis.set_tick_params(width=tick_size[0],
                                     length=tick_size[1],
                                     color='black',
                                     pad=pad_y,
                                     direction=direction_ticks_y,
                                     left=np.random.rand(1)[0] > 0.5,
                                     right=True)
        else:
            ax.yaxis.set_tick_params(left=np.random.rand(1)[0] > 0.5,
                                     right=True)
        if np.random.rand(1)[0] > 0.5:
            ax.spines['left'].set_visible(False)
            ax.yaxis.set_tick_params(left=False)
            if np.random.rand(1)[0] > 0.5:
                axes_y_pos = np.random.rand(1)[0]
                ax.spines['right'].set_position(('axes', axes_y_pos))
    else:
        axes_y_pos = 0
        if weid_ticks_prob > 0.6:
            ax.yaxis.set_tick_params(width=tick_size[0],
                                     length=tick_size[1],
                                     color='black',
                                     pad=pad_y,
                                     direction=direction_ticks_y,
                                     left=True,
                                     right=np.random.rand(1)[0] > 0.5)
        else:
            ax.yaxis.set_tick_params(left=True,
                                     right=np.random.rand(1)[0] > 0.5)
        if np.random.rand(1)[0] > 0.5:
            ax.spines['right'].set_visible(False)
            ax.yaxis.set_tick_params(right=False)
            if np.random.rand(1)[0] > 0.5:
                axes_y_pos = np.random.rand(1)[0]
                ax.spines['left'].set_position(('axes', axes_y_pos))

    # LABEL ROTATION
    if np.random.rand(1)[0] > 0.77:
        plt.xticks(rotation=int(np.random.rand(1)[0] * 90))
    if np.random.rand(1)[0] > 0.77:
        plt.yticks(rotation=int(np.random.rand(1)[0] * 90))

    # SUB-TICKs
    if weid_ticks_prob > 0.6:
        color_subtick = random.choice(color_subtick_list)
        length_subtick = 0.75 * np.random.rand(1)[0] * tick_size[1]
        if np.random.rand(1)[0] > 0.7:
            minorLocator = AutoMinorLocator()
            ax.xaxis.set_minor_locator(minorLocator)
            ax.xaxis.set_tick_params(which='minor',
                                     length=length_subtick,
                                     direction=direction_ticks_x,
                                     color=color_subtick,
                                     bottom=ax.spines['bottom'].get_visible(),
                                     top=ax.spines['top'].get_visible())
        if np.random.rand(1)[0] > 0.7:
            minorLocator = AutoMinorLocator()
            ax.yaxis.set_minor_locator(minorLocator)
            ax.yaxis.set_tick_params(which='minor',
                                     length=length_subtick,
                                     direction=direction_ticks_y,
                                     color=color_subtick,
                                     left=ax.spines['left'].get_visible(),
                                     right=ax.spines['right'].get_visible())

    # FONT AND SIZE FOR LABELS (tick labels, axes labels and title)
    font = random.choice(font_list)
    size_ticks = int(tick_label_size_min + np.random.rand(1)[0] *
                     (tick_label_size_max - tick_label_size_min))
    size_axes = int(axes_label_size_min + np.random.rand(1)[0] *
                    (axes_label_size_max - axes_label_size_min))
    size_title = int(title_size_min + np.random.rand(1)[0] *
                     (title_size_max - title_size_min))
    ticks_font = font_manager.FontProperties(fname=font,
                                             style='normal',
                                             size=size_ticks,
                                             weight='normal',
                                             stretch='normal')
    axes_font = font_manager.FontProperties(fname=font,
                                            style='normal',
                                            size=size_axes,
                                            weight='normal',
                                            stretch='normal')
    title_font = font_manager.FontProperties(fname=font,
                                             style='normal',
                                             size=size_title,
                                             weight='normal',
                                             stretch='normal')

    # TEXTS FOR AXIS LABELS AND TITLE
    label_x_length = int(axes_label_length_min + np.random.rand(1)[0] *
                         (axes_label_length_max - axes_label_length_min))
    #print label_x_length
    label_y_length = int(axes_label_length_min + np.random.rand(1)[0] *
                         (axes_label_length_max - axes_label_length_min))
    title_length = int(title_length_min + np.random.rand(1)[0] *
                       (title_length_max - title_length_min))
    x_label = ("".join([
        random.choice(string.ascii_letters + '       ')
        for i in range(label_x_length)
    ])).strip()
    #print x_label
    y_label = ("".join([
        random.choice(string.ascii_letters + '       ')
        for i in range(label_y_length)
    ])).strip()
    title = ("".join([
        random.choice(string.ascii_letters + '       ')
        for i in range(title_length)
    ])).strip()
    plt.xlabel(x_label, fontproperties=axes_font)
    plt.ylabel(y_label, fontproperties=axes_font, color='black')
    if axes_x_pos == 1:
        plt.title(title, fontproperties=title_font, color='black', y=1.1)
    else:
        plt.title(title, fontproperties=title_font, color='black')

    for label in ax.get_xticklabels():
        label.set_fontproperties(ticks_font)

    for label in ax.get_yticklabels():
        label.set_fontproperties(ticks_font)

    # GRID
    if np.random.rand(1)[0] > 0.7:
        plt.grid(b=True,
                 which='major',
                 color=random.choice(color_grid),
                 linestyle=random.choice(linestyles))

    # AXIS LIMITS
    xmin = min(x)
    xmax = max(x)
    deltax = 0.05 * abs(xmax - xmin)
    plt.xlim(xmin - deltax, xmax + deltax)
    ymin = min(y)
    ymax = max(y)
    deltay = 0.05 * abs(ymax - ymin)
    plt.ylim(ymin - deltay, ymax + deltay)

    # BACKGROUND AND PATCH COLORS
    if np.random.rand(1)[0] > 0.75:
        color_bg = (1 - colorbg_transparant_max
                    ) + colorbg_transparant_max * np.random.rand(3)
        ax.set_axis_bgcolor(color_bg)
    if np.random.rand(1)[0] > 0.75:
        color_bg = (1 - colorbg_transparant_max
                    ) + colorbg_transparant_max * np.random.rand(3)
        fig.patch.set_facecolor(color_bg)

    # MAKE SURE THE PLOT FITS INSIDE THE FIGURES
    try:
        plt.tight_layout()

        plt.savefig("./data/{}/".format(direc) + name,
                    dpi='figure',
                    facecolor=fig.get_facecolor())
    except RuntimeError:
        pass

    return ax, fig, x, y, s, categories, tick_size, axes_x_pos, axes_y_pos
    cd = CarbonData(
        "/home/bahnsen/carbon_nn/carbondata/MixedCarbon/non_relaxed_single0.8_non_relaxed_single0.2/",
        random_seed=None,
        with_forces=True)

    index = 500

    positions = cd.data_positions[:index]
    E_real = cd.data_energies[:index]
    E_nn, outside = ml.get_energy_of_structures(positions)

    print(E_real)
    print(E_nn)

    import matplotlib.cm as cm
    colors = cm.gray((1 / 13) * outside)

    for i in range(len(E_nn)):
        x = E_real[i]
        y = E_nn[i]
        c = colors[i]
        plt.scatter(x, y, color=c, edgecolor='k')

    plt.plot([-180, -165], [-180, -165], '--k')
    plt.show()
    exit()
    # ------------

    _, step, AME = ml.get_scalar('loss/mean_absolute_error_1')
    _, step, AME_test = ml.get_scalar('loss/mean_absolute_error_test_1')
def datevec2datetime(d_vec):
    '''
    Returns datetime list from a datevec matrix
    d_vec = [[y1 m1 d1 H1 M1],[y2 ,2 d2 H2 M2],..]
    '''
    return [datetime.datetime(d[0], d[1], d[2], d[3], d[4]) for d in d_vec]

dwtDates = np.array(datevec2datetime(DWT['DWT']['dates']))
dwtBmus = DWT['DWT']['bmus']
dwtBMUS = dwtBmus
order = DWT['DWT']['order']

import matplotlib.cm as cm

etcolors = cm.rainbow(np.linspace(0, 1, numDWTs-5))
tccolors = np.flipud(cm.gray(np.linspace(0,1,6)))

dwtcolors = np.vstack((etcolors,tccolors[1:,:]))





repmatDesviacion = np.tile(DWT['PCA']['Desviacion'], (25,1))
repmatMedia = np.tile(DWT['PCA']['Media'], (25,1))
Km_ = np.multiply(DWT['KMA']['centroids'],repmatDesviacion) + repmatMedia



[mK, nK] = np.shape(Km_)
Example #36
0
                zOuterInd = np.where((np.round(2 * xFRFtrough) / 2 == bathyX))
                zOuterTrough[tt] = bathy[zOuterInd[0]]
        #barPatch = mpatches.Patch(color='red', label='sandbar')
        #troughPatch = mpatches.Patch(color='blue', label='trough')

fig2 = plt.figure(figsize=(8, 8))
plt.plot(time, innerBar, 'bo')
plt.plot(time, outerBar, 'ro')
plt.show()

fig11, ax11 = plt.subplots(2, 1)
#ax10 = fig.add_subplot(111)
#ax10.set_prop_cycle(plt.cycler('color', plt.cm.jet(np.linspace(0, 1, numClusters))))
import matplotlib.cm as cm
colors = cm.rainbow(np.linspace(0, 1, numClusters))
colors2 = cm.gray(np.linspace(0, 1, numClusters))
for i in range(numClusters):
    bmuIndex = np.where((KMA.bmus == sortedPeakInd[i]))
    ax11[0].scatter(time[bmuIndex],
                    outerBar[bmuIndex],
                    label=time[i],
                    color=colors[i])
    ax11[1].scatter(time[bmuIndex], innerBar[bmuIndex], color=colors[i])

ax11[0].set_ylabel('xFRF')
ax11[1].set_ylabel('xFRF')

plt.show()

fig3 = plt.figure(figsize=(10, 10))
gs = gridspec.GridSpec(10, 10, wspace=0.0, hspace=0.0)
CMAP_JET = glumpy.colormap.Colormap(
    (value[0], (r[0], g[0], b[0])), (value[16], (r[16], g[16], b[16])),
    (value[32], (r[32], g[32], b[32])), (value[48], (r[48], g[48], b[48])),
    (value[64], (r[64], g[64], b[64])), (value[96], (r[96], g[96], b[96])),
    (value[112], (r[112], g[112], b[112])), (value[128],
                                             (r[128], g[128], b[128])),
    (value[144], (r[144], g[144], b[144])), (value[160],
                                             (r[160], g[160], b[160])),
    (value[176], (r[176], g[176], b[176])), (value[192],
                                             (r[192], g[192], b[192])),
    (value[208], (r[208], g[208], b[208])), (value[224],
                                             (r[224], g[224], b[224])),
    (value[240], (r[240], g[240], b[240])), (value[255],
                                             (r[255], g[255], b[255])))

jet = cm.gray(range(0, 256))
r, g, b, a = jet[:, 0], jet[:, 1], jet[:, 2], jet[:, 3]
value = np.linspace(0.0, 1.0, 256, endpoint=True)
CMAP_GRAY = glumpy.colormap.Colormap(
    (value[0], (r[0], g[0], b[0])), (value[16], (r[16], g[16], b[16])),
    (value[32], (r[32], g[32], b[32])), (value[48], (r[48], g[48], b[48])),
    (value[64], (r[64], g[64], b[64])), (value[96], (r[96], g[96], b[96])),
    (value[112], (r[112], g[112], b[112])), (value[128],
                                             (r[128], g[128], b[128])),
    (value[144], (r[144], g[144], b[144])), (value[160],
                                             (r[160], g[160], b[160])),
    (value[176], (r[176], g[176], b[176])), (value[192],
                                             (r[192], g[192], b[192])),
    (value[208], (r[208], g[208], b[208])), (value[224],
                                             (r[224], g[224], b[224])),
    (value[240], (r[240], g[240], b[240])), (value[255],
Example #38
0
    def compute(self):

        from matplotlib import cm

        # make a copy for changes
        data = self.getData('in').copy()

        # get extra dimension parameters and modify data
        dimfunc = self.getVal('Extra Dimension')
        dimval = self.getVal('Slice/Tile Dimension')
        if data.ndim == 3 and dimfunc < 2:
            if dimfunc == 0:  # slice data
                slval = self.getVal('Slice') - 1
                if dimval == 0:
                    data = data[slval, ...]
                elif dimval == 1:
                    data = data[:, slval, :]
                else:
                    data = data[..., slval]
            else:  # tile data
                ncol = self.getVal('# Columns')
                nrow = self.getVal('# Rows')

                # add some blank tiles
                data = np.rollaxis(data, dimval)
                N, xres, yres = data.shape
                N_new = ncol * nrow
                pad_vals = ((0, N_new - N), (0, 0), (0, 0))
                data = np.pad(data, pad_vals, mode='constant')

                # from http://stackoverflow.com/a/13990648/333308
                data = np.reshape(data, (nrow, ncol, xres, yres))
                data = np.swapaxes(data, 1, 2)
                data = np.reshape(data, (nrow * xres, ncol * yres))

        # Read in parameters, make a little floor:ceiling adjustment
        gamma = self.getVal('Gamma')
        lval = self.getAttr('L W F C:', 'val')
        cval = self.getVal('Complex Display')

        if 'Complex Display' in self.widgetEvents():
            if cval == 4:
                self.setAttr('Color Map',
                             buttons=self.complex_cmaps,
                             collapsed=self.getAttr('Color Map', 'collapsed'),
                             val=0)
            # elif self.getAttr('Color Map', 'buttons') != self.real_cmaps:
            # there is no "get_buttons" method, so for now this will reset the
            # colormap whenever "Complex Display" is changed
            # this could/will be added in a future framework update
            else:
                self.setAttr('Color Map',
                             buttons=self.real_cmaps,
                             collapsed=self.getAttr('Color Map', 'collapsed'),
                             val=0)

        cmap = self.getVal('Color Map')
        sval = self.getVal('Scalar Display')
        zval = self.getVal('Zero Ref')
        fval = self.getVal('Fix Range')
        rmin = self.getVal('Range Min')
        rmax = self.getVal('Range Max')

        flor = 0.01 * lval['floor']
        ceil = 0.01 * lval['ceiling']
        if ceil == flor:
            if ceil == 1.:
                flor = 0.999
            else:
                ceil += 0.001

        # SHOW COMPLEX DATA
        if np.iscomplexobj(data) and cval == 4:
            mag = np.abs(data)
            phase = np.angle(data, deg=True)

            # normalize the mag
            data_min = 0.
            if fval:
                data_max = rmax
            else:
                data_max = mag.max()
                self.setAttr('Range Max', val=data_max)
            data_range = data_max - data_min
            dmask = np.ones(data.shape)
            new_min = data_range * flor + data_min
            new_max = data_range * ceil + data_min
            mag = np.clip(mag, new_min, new_max)

            if new_max > new_min:
                if (
                        gamma == 1
                ):  # Put in check for gamma=1, the common use case, just to save time
                    mag = (mag - new_min) / (new_max - new_min)
                else:
                    mag = pow((mag - new_min) / (new_max - new_min), gamma)
            else:
                mag = np.ones(mag.shape)

            # ADD BORDERS
            edgpix = self.getVal('Edge Pixels')
            blkpix = self.getVal('Black Pixels')
            if (edgpix + blkpix) > 0:
                # new image will be h2 x w2
                # frame defines edge pixels to paint with phase table
                h, w = mag.shape
                h2 = h + 2 * (edgpix + blkpix)
                w2 = w + 2 * (edgpix + blkpix)
                mag2 = np.zeros((h2, w2))
                phase2 = np.zeros((h2, w2))
                frame = np.zeros((h2, w2)) == 1
                frame[0:edgpix, :] = frame[h2 - edgpix:h2, :] = True
                frame[:, 0:edgpix] = frame[:, w2 - edgpix:w2] = True

                mag2[edgpix + blkpix:edgpix + blkpix + h,
                     edgpix + blkpix:edgpix + blkpix + w] = mag
                mag2[frame] = 1

                phase2[edgpix + blkpix:edgpix + blkpix + h,
                       edgpix + blkpix:edgpix + blkpix + w] = phase
                xloc = np.tile(np.linspace(-1., 1., w2), (h2, 1))
                yloc = np.transpose(np.tile(np.linspace(1., -1., h2), (w2, 1)))
                phase2[frame] = np.degrees(np.arctan2(yloc[frame],
                                                      xloc[frame]))

                mag = mag2
                phase = phase2

            # now colorize!
            if cmap == 0:  # HSV
                phase_cmap = cm.hsv
            elif cmap == 1:  # HSL
                try:
                    import seaborn as sns
                except:
                    self.log.warn(
                        "Seaborn (required for HSL map) not available! Falling back on HSV."
                    )
                    phase_cmap = cm.hsv
                else:  # from http://stackoverflow.com/a/34557535/333308
                    import matplotlib.colors as col
                    hlsmap = col.ListedColormap(sns.color_palette("hls", 256))
                    phase_cmap = hlsmap
            elif cmap == 2:  #HUSL
                try:
                    import seaborn as sns
                except:
                    self.log.warn(
                        "Seaborn (required for HUSL map) not available! Falling back on HSV."
                    )
                    phase_cmap = cm.hsv
                else:  # from http://stackoverflow.com/a/34557535/333308
                    import matplotlib.colors as col
                    huslmap = col.ListedColormap(sns.color_palette(
                        "husl", 256))
                    phase_cmap = huslmap
            elif cmap == 3:  # coolwarm
                phase_cmap = cm.coolwarm

            mag_norm = mag
            phase_norm = (phase + 180) / 360
            # phase shift to match old look better
            if cmap != 3:
                phase_norm = (phase_norm - 1 / 3) % 1
            colorized = 255 * cm.gray(mag_norm) * phase_cmap(phase_norm)
            red = colorized[..., 0]
            green = colorized[..., 1]
            blue = colorized[..., 2]
            alpha = colorized[..., 3]

        # DISPLAY SCALAR DATA
        elif dimfunc != 2:

            if np.iscomplexobj(data):
                if cval == 0:  # Real
                    data = np.real(data)
                elif cval == 1:  # Imag
                    data = np.imag(data)
                elif cval == 2:  # Mag
                    data = np.abs(data)
                elif cval == 3:  # Phase
                    data = np.angle(data, deg=True)

            if sval == 1:  # Mag
                data = np.abs(data)
            elif sval == 2:  # Sign
                sign = np.sign(data)
                data = np.abs(data)

            # normalize the data
            if fval:
                data_min = rmin
                data_max = rmax
            else:
                data_min = data.min()
                data_max = data.max()

            if sval != 2:
                if zval == 1:
                    data_min = 0.
                elif zval == 2:
                    data_max = max(abs(data_min), abs(data_max))
                    data_min = -data_max
                elif zval == 3:
                    data_max = 0.
                data_range = data_max - data_min
                self.setAttr('Range Min', val=data_min)
                self.setAttr('Range Max', val=data_max)
            else:
                data_min = 0.
                data_max = max(abs(data_min), abs(data_max))
                data_range = data_max
                self.setAttr('Range Min', val=-data_range)
                self.setAttr('Range Max', val=data_range)

            dmask = np.ones(data.shape)
            new_min = data_range * flor + data_min
            new_max = data_range * ceil + data_min
            data = np.minimum(np.maximum(data, new_min * dmask),
                              new_max * dmask)

            if new_max > new_min:
                if (
                        gamma == 1
                ):  # Put in check for gamma=1, the common use case, just to save time
                    data = 255. * (data - new_min) / (new_max - new_min)
                else:
                    data = 255. * pow(
                        (data - new_min) / (new_max - new_min), gamma)
            else:
                data = 255. * np.ones(data.shape)

            if sval != 2:  #Not Signed Data (Pass or Mag)
                # Show based on a color map
                if cmap == 0:  # Grayscale
                    red = green = blue = np.uint8(data)
                    alpha = 255. * np.ones(blue.shape)
                else:
                    rd = np.zeros(data.shape)
                    gn = np.zeros(data.shape)
                    be = np.zeros(data.shape)
                    zmask = np.zeros(data.shape)
                    fmask = np.ones(data.shape)

                    if cmap == 1:  # IceFire
                        hue = 4. * (data / 256.)
                        hindex0 = hue < 1.
                        hindex1 = np.logical_and(hue >= 1., hue < 2.)
                        hindex2 = np.logical_and(hue >= 2., hue < 3.)
                        hindex3 = np.logical_and(hue >= 3., hue < 4.)

                        be[hindex0] = hue[hindex0]
                        gn[hindex0] = zmask[hindex0]
                        rd[hindex0] = zmask[hindex0]

                        gn[hindex1] = (hue - 1.)[hindex1]
                        rd[hindex1] = (hue - 1.)[hindex1]
                        be[hindex1] = fmask[hindex1]

                        gn[hindex2] = fmask[hindex2]
                        rd[hindex2] = fmask[hindex2]
                        be[hindex2] = (3. - hue)[hindex2]

                        rd[hindex3] = fmask[hindex3]
                        gn[hindex3] = (4. - hue)[hindex3]
                        be[hindex3] = zmask[hindex3]

                    elif cmap == 2:  # Fire
                        hue = 4. * (data / 256.)
                        hindex0 = hue < 1.
                        hindex1 = np.logical_and(hue >= 1., hue < 2.)
                        hindex2 = np.logical_and(hue >= 2., hue < 3.)
                        hindex3 = np.logical_and(hue >= 3., hue < 4.)

                        be[hindex0] = hue[hindex0]
                        rd[hindex0] = zmask[hindex0]
                        gn[hindex0] = zmask[hindex0]

                        be[hindex1] = (2. - hue)[hindex1]
                        rd[hindex1] = (hue - 1.)[hindex1]
                        gn[hindex1] = zmask[hindex1]

                        rd[hindex2] = fmask[hindex2]
                        gn[hindex2] = (hue - 2.)[hindex2]
                        be[hindex2] = zmask[hindex2]

                        rd[hindex3] = fmask[hindex3]
                        gn[hindex3] = fmask[hindex3]
                        be[hindex3] = (hue - 3.)[hindex3]

                    elif cmap == 3:  # Hot
                        hue = 3. * (data / 256.)
                        hindex0 = hue < 1.
                        hindex1 = np.logical_and(hue >= 1., hue < 2.)
                        hindex2 = np.logical_and(hue >= 2., hue < 3.)

                        rd[hindex0] = hue[hindex0]
                        be[hindex0] = zmask[hindex0]
                        gn[hindex0] = zmask[hindex0]

                        gn[hindex1] = (hue - 1.)[hindex1]
                        rd[hindex1] = fmask[hindex1]
                        be[hindex1] = zmask[hindex1]

                        rd[hindex2] = fmask[hindex2]
                        gn[hindex2] = fmask[hindex2]
                        be[hindex2] = (hue - 2.)[hindex2]

                    if cmap == 4:  # Hot2, from ASIST (http://asist.umin.jp/index-e.htm)
                        rindex0 = data < 20.0
                        rindex1 = np.logical_and(data >= 20.0, data <= 100.0)
                        rindex2 = np.logical_and(data > 100.0, data < 128.0)
                        rindex3 = np.logical_and(data >= 128.0, data <= 191.0)
                        rindex4 = data > 191.0
                        rd[rindex0] = data[rindex0] * 4.0
                        rd[rindex1] = 80.0 - (data[rindex1] - 20.0)
                        rd[rindex3] = (data[rindex3] - 128.0) * 4.0
                        rd[rindex4] = data[rindex4] * 0.0 + 255.0
                        rd = rd / 255.0

                        gindex0 = data < 45.0
                        gindex1 = np.logical_and(data >= 45.0, data <= 130.0)
                        gindex2 = np.logical_and(data > 130.0, data < 192.0)
                        gindex3 = data >= 192.0
                        gn[gindex1] = (data[gindex1] - 45.0) * 3.0
                        gn[gindex2] = data[gindex2] * 0.0 + 255.0
                        gn[gindex3] = 252.0 - (data[gindex3] - 192.0) * 4.0
                        gn = gn / 255.0

                        bindex0 = (data < 1.0)
                        bindex1 = np.logical_and(data >= 1.0, data < 86.0)
                        bindex2 = np.logical_and(data >= 86.0, data <= 137.0)
                        bindex3 = data > 137.0
                        be[bindex1] = (data[bindex1] - 1.0) * 3.0
                        be[bindex2] = 255.0 - (data[bindex2] - 86.0) * 5.0
                        be = be / 255.0

                    elif cmap == 5:  # BGR
                        hue = 4. * (data / 256.)
                        hindex0 = hue < 1.
                        hindex1 = np.logical_and(hue >= 1., hue < 2.)
                        hindex2 = np.logical_and(hue >= 2., hue < 3.)
                        hindex3 = np.logical_and(hue >= 3., hue < 4.)

                        be[hindex0] = hue[hindex0]
                        gn[hindex0] = zmask[hindex0]
                        rd[hindex0] = zmask[hindex0]

                        gn[hindex1] = (hue - 1.)[hindex1]
                        rd[hindex1] = zmask[hindex1]
                        be[hindex1] = fmask[hindex1]

                        gn[hindex2] = fmask[hindex2]
                        rd[hindex2] = (hue - 2.)[hindex2]
                        be[hindex2] = (3. - hue)[hindex2]

                        rd[hindex3] = fmask[hindex3]
                        gn[hindex3] = (4. - hue)[hindex3]
                        be[hindex3] = zmask[hindex3]

                    blue = np.uint8(255. * rd)
                    red = np.uint8(255. * be)
                    green = np.uint8(255. * gn)
                    alpha = np.uint8(255. * np.ones(blue.shape))

            else:  #Signed data, positive numbers green, negative numbers magenta
                red = np.zeros(data.shape)
                green = np.zeros(data.shape)
                blue = np.zeros(data.shape)
                red[sign <= 0] = data[sign <= 0]
                blue[sign <= 0] = data[sign <= 0]
                green[sign >= 0] = data[sign >= 0]

                red = red.astype(np.uint8)
                green = green.astype(np.uint8)
                blue = blue.astype(np.uint8)
                alpha = np.uint8(data)

        # DISPLAY RGB image
        else:

            if data.shape[-1] > 3:
                red = data[:, :, 0].astype(np.uint8)
                green = data[:, :, 1].astype(np.uint8)
                blue = data[:, :, 2].astype(np.uint8)
                if (data.ndim == 3 and data.shape[-1] == 4):
                    alpha = data[:, :, 3].astype(np.uint8)
                else:
                    alpha = 255. * np.ones(blue.shape)
            else:
                self.log.warn("input veclen of " + str(data.shape[-1]) +
                              " is incompatible")
                return 1

        h, w = red.shape[:2]
        image1 = np.zeros((h, w, 4), dtype=np.uint8)
        image1[:, :, 0] = red
        image1[:, :, 1] = green
        image1[:, :, 2] = blue
        image1[:, :, 3] = alpha
        format_ = QtGui.QImage.Format_RGB32

        image = QtGui.QImage(image1.data, w, h, format_)

        #send the RGB values to the output port
        imageTru = np.zeros((h, w, 4), dtype=np.uint8)
        imageTru[:, :, 0] = red
        imageTru[:, :, 1] = green
        imageTru[:, :, 2] = blue
        imageTru[:, :, 3] = alpha
        image.ndarray = imageTru
        if image.isNull():
            self.log.warn("Image Viewer: cannot load image")

        self.setAttr('Viewport:', val=image)
        self.setData('out', imageTru)

        return 0
Example #39
0
        import matplotlib.cm as cm
        from mpl_toolkits.axes_grid1 import make_axes_locatable

        try:
            plt.style.use(["goose", "goose-latex"])
        except OSError:
            pass

        cmap = mpl.colors.ListedColormap(
            np.array([[0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 1.0]], dtype="float64")
        )

        fig, axes = plt.subplots(figsize=(18, 12), nrows=2, ncols=3)

        ax = axes[0, 0]
        im = ax.imshow(img, clim=(0, 1), cmap=mpl.colors.ListedColormap(cm.gray([0, 255])))
        D = ax.imshow(W, clim=(0, 1), cmap=cmap)
        ax.xaxis.set_ticks([0, 500])
        ax.yaxis.set_ticks([0, 500])
        ax.set_xlabel(r"$x$")
        ax.set_ylabel(r"$y$")
        ax.set_title(r"$\mathcal{I}$ (black/white) + $\mathcal{W}$ (red)")
        div = make_axes_locatable(ax)
        cax = div.append_axes("right", size="5%", pad=0.1)
        cbar = plt.colorbar(im, cax=cax)
        cbar.set_ticks([0, 1])

        ax = axes[0, 1]
        im = ax.imshow(WI, clim=(0, 1), cmap="jet", extent=(-50, 50, -50, 50))
        ax.xaxis.set_ticks([-50, 0, +50])
        ax.yaxis.set_ticks([-50, 0, +50])
        scaled.append(new_value)

    #set scaled colour values
    cmap_dem = make_colormap([
        c('#010071'), scaled[0],
        c('#010071'),
        c('#1f78b4'), scaled[1],
        c('#1f78b4'),
        c("#89e2ff"), scaled[2],
        c("#0b6e24"),
        c("#dfc485"), scaled[3],
        c("#dfc485"),
        c('#8d7c58'), scaled[4],
        c("#8d7c58"),
        c("#a49fa3"), scaled[5],
        c("#a49fa3")
    ])

    im = Image.fromarray(np.uint8(cmap_dem(rs_dem) * 255))

    #create hillshade
    ls = LightSource(azdeg=315, altdeg=45)
    hs = ls.hillshade(read_dem, vert_exag=0.04, fraction=1.35)
    hsimg = Image.fromarray(np.uint8(cm.gray(hs) * 255))

    #blend hillshade to RGB image using multiplication
    blend = ImageChops.multiply(im, hsimg)

    #write image to disc
    blend.save('OUTFILEPATH.tif')
Example #41
0
def plot_spectra_grid(file_set,protein,ligands,ligand):
    grid = len(protein) + len(ligand)
    
    # pick the correct file
    proteins = file_set.keys()
    index = ligands.index(ligand)
    file = file_set[protein][index]
    
    # pick a title
    title = "%s - %s" %(protein, ligand)
    
    # make a dataframe
    df = xml2df(file)
    
    # plot the spectra
    fig = plt.figure();
    ax = df['fluorescence'].iloc[:,12].plot(ylim=(0,100000),legend=False, linewidth=4,color='m');
    ax.axvline(x=480,color='0.7',linestyle='--');
    for i in range(11):
        #s = df['fluorescence'].iloc[:,i].plot(ylim=(0,100000),linewidth=3,c=cm.hsv(i*15), ax = ax, title=title);
        df['fluorescence'].iloc[:,i].plot(ylim=(0,100000),linewidth=3,c=cm.hsv(i*15), ax = ax);
        df['fluorescence'].iloc[:,11+i].plot(ylim=(0,100000),legend=False, linewidth=4,c=cm.gray(i*15+50), ax = ax, fontsize =20);
    sns.despine()
    plt.xlim(320,600)
    plt.yticks([])
    plt.xlabel('wavelength (nm)', fontsize=20)
    plt.tight_layout();
    plt.savefig('%s.eps'%title, type='eps', dpi=1000)
Example #42
0
    def cb_mouse_motion(self, event):
        """
        Callback to process a mouse movement event.

        If the group selection option is enabled, then any points with
        Y-coordinate less than the cursor's Y-coordinate will be marked in a
        different opacity level, but not highlighted. If the user clicks with
        the mouse, then the points will be highlighted, but this event is
        processed in another method.

        This method also processes tooltip-related events when the group
        selection is disabled. If the user hovers the mouse cursor over a data
        point, then the name associated to that point will be shown in a
        tooltip.

        Parameters
        ----------
        event: matplotlib.backend_bases.MouseEvent
            Data about the event.
        """
        # We remove the horizonal line here (if any), regardless of the mouse
        # cursor position. We also restore the lines colors.
        if self._hthresh_line:
            for i, l in enumerate(self.axes.lines):
                if l == self._hthresh_line:
                    del self.axes.lines[i]
                    break
            self._hthresh_line = None

            for i, line in enumerate(self.axes.lines):
                if self._is_normal_curve_idx(i):
                    line.set_color(self._curves_colors[i])

        if self._ts_line:
            for i, l in enumerate(self.axes.lines):
                if l == self._ts_line:
                    del self.axes.lines[i]
                    break

        # Restoring the lines' widths.
        if self._plotted_series:
            for art in self._plotted_series:
                if not art:
                    continue
                art[0].set_linewidth(self._plot_params['linewidth'])

        self.draw()

        if event.xdata is None or event.ydata is None or self._rank_series is None:
            return True

        self._ts_line = self.axes.axvline(x=event.xdata, c='b', ls='--')

        # If the group selection is enabled, we show a preview of all curves
        # that will be highlighted should the user click the mouse button.
        if self.group_selection_enabled:
            ts = int(event.xdata - self.time_range[0] + 0.5)
            if self.rank_inverted:
                for i, series in enumerate(self._rank_series):
                    if series[ts] < event.ydata and self._is_normal_curve_idx(
                            i):
                        self.axes.lines[i].set_color(cm.gray(200))
            else:
                for i, series in enumerate(self._rank_series):
                    if series[ts] > event.ydata and self._is_normal_curve_idx(
                            i):
                        self.axes.lines[i].set_color(cm.gray(200))

            self._hthresh_line = self.axes.axhline(y=event.ydata,
                                                   c='b',
                                                   linewidth=2)
        else:
            hover_idx = None
            for i, art in enumerate(self._plotted_series):
                if not art:
                    continue
                contains, _ = art[0].contains(event)
                if contains:
                    art[0].set_linewidth(self._plot_params['linewidth'] * 2)
                    if not self.curvenames or i > len(self.curvenames):
                        return False
                    hover_idx = i
                    break

            if hover_idx is not None:
                palette = QPalette()
                palette.setColor(QPalette.ToolTipBase, QColor(252, 243, 207))
                palette.setColor(QPalette.ToolTipText, QColor(0, 0, 0))
                QToolTip.setPalette(palette)
                QToolTip.setFont(QFont('Arial', 14, QFont.Bold))
                pos = self.mapToGlobal(QPoint(event.x,
                                              self.height() - event.y))
                QToolTip.showText(pos, '{}'.format(self.curvenames[hover_idx]))
            else:
                QToolTip.hideText()
                self.update()

            if self._cb_notify_tooltip:
                self._cb_notify_tooltip(self.name, hover_idx)

        self.draw()
def bg2RGBA(bg):
    img = bg / 4 + 0.25  # rescale to range of approx. 0..1 float
    img = np.uint8(cm.gray(img) * 255)
    return img
Example #44
0
def summary_bar_plot(summary, sig_ref=None, sig_thresh='>0.05', ymin=0.5, 
    show_data=[0,1,2], legend=False):
    """Bar plot of summary statistics with SEM errorbars
    
    Arguments:
    summary -- summary results object
    ymin -- y-axis minimum
    show_data -- which data to show: list of integers, where 0=remapping,
        1=rate_remapping, and 2=turnover
    sig_ref -- index number of condition that will be reference for determining
        statistical significance
    sig_thresh -- string indicating threshold relationship for placing a 
        significance mark (star/asterisk): either '<' or '>' followed by float
        threshold value
    legend -- whether to display a legend
    """
    from pylab import figure, axes, rcParams
    from matplotlib import cm
    
    # Plot parameters
    fig_size = 9, 6
    show_data = array(show_data)
    num_data = len(show_data)
    bar_w = 1/float(num_data+1)
    
    # Significance parameters
    sig_less = True
    if sig_thresh[0] == '>':
        sig_less = False
    sig_value = float(sig_thresh[1:])
    if sig_ref is not None:
        print '* Significance indicates p%s%.5f.'%(sig_thresh[0], sig_value)

    # Create the figure and axes
    old_fig_size = rcParams['figure.figsize']
    rcParams['figure.figsize'] = fig_size
    f = figure()
    f.set_size_inches(fig_size)
    f.suptitle('Remapping Sample Summary Data')
    ax = axes()
    
    # Create the bar data
    left = []
    height = []
    yerr = []
    xticklabels = []
    sig_x = []
    sig_y = []
    c = 0
    for i,row in enumerate(summary['data']):
        if not summary['visible'][i]:
            continue
        if num_data == 1:
            left.extend([c-0.5*bar_w])
        elif num_data == 2:
            left.extend([c-bar_w, c])
        elif num_data == 3:
            left.extend([c-1.5*bar_w, c-0.5*bar_w, c+0.5*bar_w])
        height.extend(list(row[show_data]))
        yerr.extend(list(row[3+show_data]/1.96))
        xticklabels.append(summary['labels'][i])
        
        if sig_ref is not None and sig_ref <> i:
            for n in xrange(num_data):
                sig_mark = False
                if sig_less:
                    if summary['pvals'][show_data[n], sig_ref, i] < sig_value:
                        sig_mark = True
                else:
                    if summary['pvals'][show_data[n], sig_ref, i] >= sig_value:
                        sig_mark = True
                if sig_mark:
                    sig_x.append(left[n-num_data]+0.5*bar_w)
                    sig_y.append(height[n-num_data]+yerr[n-num_data]+0.02)
        
        c += 1
    
    # Create the bar chart and legend
    bar_cols = cm.gray(([0.25, 0.6, 0.8][:num_data])*c)
    bar_h = ax.bar(left, height, width=bar_w, yerr=yerr, 
        ec='k', color=bar_cols, linewidth=0, ecolor='k', capsize=3, aa=False)
    if legend:
        labels = ['Remapping', 'Rate Remapping', 'Turnover']
        data_labels = [labels[i] for i in show_data]
        ax.legend(bar_h[:num_data], data_labels)
    if sig_ref is not None:
        ax.plot(sig_x, sig_y, 'k*', ms=8)
    ax.hlines(1.0, xmin=-0.5, xmax=c-0.5, linestyle=':', color='k')
    ax.set_xlim(-0.5, c-0.5)
    ax.set_ylim(ymin, 1.1)
    ax.set_xticks(arange(c))
    ax.set_xticklabels(xticklabels)
    
    rcParams['figure.figsize'] = old_fig_size
    return f
Example #45
0
 def _make_gray(self, data):
     data = data.astype(np.float) - np.nanmin(data)
     data /= np.nanmax(data)
     return (255 * plt_cm.gray(data)).astype('uint8')
def make_gif(h5name,dielectric_bg = True,data_name = None,normalize = False):
    """makes a gif animation of the real part of the field in the file h5name.
    if dielectric_bg is a h5 name, will also plot the dielectric landscape. in case dielectric_bg = True
    will look for a file dielectric.h5 as well"""
    f = h5py.File(h5name)
    if data_name == None:
        data_name = f.keys()[-1]
    d = f[data_name]
    if normalize:
        d = d/abs(array(d).flatten()).max()
    if dielectric_bg == True:
        where = "./" + os.path.dirname(h5name) + "/dielectric.h5"
        if os.path.exists(where):
            dielectric_bg = where
        else:
            dielectric_bg = None
    if dielectric_bg != None:
        diel = h5py.File(dielectric_bg)
        diel_val = transpose(array(diel["eps"]))
        imdiel = diel_val
        diel.close()
    else:
        imdiel = transpose(ones(shape(d[:,:,0])))
        #m = max(imdiel.flatten())
    di = uint8(dstack((imdiel,imdiel,imdiel,imdiel)))
    images2gif.writeGif(h5name[:-3] + ".gif",[Image.fromarray(cm.jet(0.5+transpose(d[:,:,i]), bytes=True)*(di==1.0) + cm.gray(0.5+transpose(d[:,:,i]) , bytes=True)*(di!=1.0)) for i in range(shape(d)[-1])])
    f.close()
Example #47
0
layer_index = utils.find_layer_idx(model, 'visualized_layer')

# Swap softmax with linear
model.layers[layer_index].activation = activations.linear
model = utils.apply_modifications(model)

# Numbers to visualize
indices_to_visualize = [0, 12, 38, 83, 112, 74, 190]

# Visualize
for index_to_visualize in indices_to_visualize:
    input_image = input_test[index_to_visualize]
    input_class = np.argmax(target_test[index_to_visualize])
    # Matplotlib preparations
    fig, axes = plt.subplots(1, 3)
    # Generate visualization
    visualization = visualize_cam(model,
                                  layer_index,
                                  filter_indices=input_class,
                                  seed_input=input_image)
    axes[0].imshow(input_image[..., 0], cmap='gray')
    axes[0].set_title('Input')
    axes[1].imshow(visualization)
    axes[1].set_title('Grad-CAM')
    heatmap = np.uint8(cm.jet(visualization)[..., :3] * 255)
    original = np.uint8(cm.gray(input_image[..., 0])[..., :3] * 255)
    axes[2].imshow(overlay(heatmap, original))
    axes[2].set_title('Overlay')
    fig.suptitle(f'MNIST target = {input_class}')
    plt.show()
Example #48
0
def flow_gray(data):
    v = ((data > 0)*(data < 1)).reshape(list(data.shape) +  [1])*cm.gray(data)
    v += (data == 0).reshape(list(data.shape) + [1]) * np.array([0, 1., 0, 0]).reshape(list(np.ones(data.ndim) + [3]))
    v += (data == 1).reshape(list(data.shape) + [1]) * np.array([1., 0, 1., 0]).reshape(list(np.ones(data.ndim) + [3]))
    return v