Example #1
1
        def save_scatter(data, colours, title, ylabel, savePath, yLimTuple=None):
            fig = plt.figure()
            ax = fig.add_subplot(111)
            plt.title(title)
            plt.xlabel("Trials")
            plt.ylabel(ylabel)

            # Sort by value
            data, colours = zip(*sorted(zip(data, colours)))

            nov_data = [(i, d) for (i, d, c) in zip(range(len(data)), data, colours) if c == "r"]
            inter_data = [(i, d) for (i, d, c) in zip(range(len(data)), data, colours) if c == "g"]
            exp_data = [(i, d) for (i, d, c) in zip(range(len(data)), data, colours) if c == "b"]

            nov = ax.scatter(zip(*nov_data)[0], zip(*nov_data)[1], color="r", marker="o", s=60)
            inter = ax.scatter(zip(*inter_data)[0], zip(*inter_data)[1], color="g", marker="^", s=60)
            exp = ax.scatter(zip(*exp_data)[0], zip(*exp_data)[1], color="b", marker="*", s=60)

            plt.legend((nov, inter, exp), ["Novice", "Intermediate", "Expert"], loc=2)
            plt.xticks([])
            plt.gca().set_xlim(-1, len(data))
            if yLimTuple:
                plt.gca().set_xlim(yLimTuple)
            plt.tight_layout()
            with open(savePath, "w") as figOut:
                plt.savefig(figOut)
Example #2
0
def scatter(x, y, equal=False, xlabel=None, ylabel=None, xinvert=False, yinvert=False):
    """
    Plot a scatter with simple formatting options
    """
    plt.scatter(x, y, 200, color=[0.3, 0.3, 0.3], edgecolors="white", linewidth=1, zorder=2)
    sns.despine()
    if xlabel:
        plt.xlabel(xlabel)
    if ylabel:
        plt.ylabel(ylabel)
    if equal:
        plt.axes().set_aspect("equal")
        plt.plot([0, max([x.max(), y.max()])], [0, max([x.max(), y.max()])], color=[0.6, 0.6, 0.6], zorder=1)
        bmin = min([x.min(), y.min()])
        bmax = max([x.max(), y.max()])
        rng = abs(bmax - bmin)
        plt.xlim([bmin - rng * 0.05, bmax + rng * 0.05])
        plt.ylim([bmin - rng * 0.05, bmax + rng * 0.05])
    else:
        xrng = abs(x.max() - x.min())
        yrng = abs(y.max() - y.min())
        plt.xlim([x.min() - xrng * 0.05, x.max() + xrng * 0.05])
        plt.ylim([y.min() - yrng * 0.05, y.max() + yrng * 0.05])
    if xinvert:
        plt.gca().invert_xaxis()
    if yinvert:
        plt.gca().invert_yaxis()
    def draw(self):
        cols, rows = self.size
        minx, maxx = self.xlimits
        miny, maxy = self.ylimits

        width, height = self.cell_dimensions

        x = map(lambda i: minx + width*i, range(cols+1))
        y = map(lambda i: miny + height*i, range(rows+1))

        f = plt.figure(figsize=self.figsize)

        hlines = np.column_stack(np.broadcast_arrays(x[0], y, x[-1], y))
        vlines = np.column_stack(np.broadcast_arrays(x, y[0], x, y[-1]))
        lines = np.concatenate([hlines, vlines]).reshape(-1, 2, 2)
        line_collection = LineCollection(lines, color="black", linewidths=0.5)
        ax = plt.gca()
        ax.add_collection(line_collection)
        ax.set_xlim(x[0]-1, x[-1]+1)
        ax.set_ylim(y[0]-1, y[-1]+1)
        plt.gca().set_aspect('equal', adjustable='box')
        plt.axis('off')
        self.draw_obstacles(plt.gca())

        return plt.gca()
Example #4
0
def vis_all_detection(im_array, detections, imdb_classes=None, thresh=0.):
    """
    visualize all detections in one image
    :param im_array: [b=1 c h w] in rgb
    :param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ]
    :param imdb_classes: list of names in imdb
    :param thresh: threshold for valid detections
    :return:
    """
    import matplotlib.pyplot as plt
    import random
    im = image_processing.transform_inverse(im_array, config.PIXEL_MEANS)
    plt.imshow(im)
    for j in range(1, len(imdb_classes)):
        color = (random.random(), random.random(), random.random())  # generate a random color
        dets = detections[j]
        for i in range(dets.shape[0]):
            bbox = dets[i, :4]
            score = dets[i, -1]
            if score > thresh:
                rect = plt.Rectangle((bbox[0], bbox[1]),
                                     bbox[2] - bbox[0],
                                     bbox[3] - bbox[1], fill=False,
                                     edgecolor=color, linewidth=2)
                plt.gca().add_patch(rect)
                plt.gca().annotate('{} {:.3f}'.format(imdb_classes[j], score),
                                   rect.get_xy(), color='w')
    plt.show()
Example #5
0
    def test_simple(self):
        # First sub-plot
        plt.subplot(221)
        plt.title('Default')
        iplt.contourf(self.cube)
        plt.gca().coastlines()

        # Second sub-plot
        plt.subplot(222, projection=ccrs.Mollweide(central_longitude=120))
        plt.title('Molleweide')
        iplt.contourf(self.cube)
        plt.gca().coastlines()

        # Third sub-plot (the projection part is redundant, but a useful
        # test none-the-less)
        ax = plt.subplot(223, projection=iplt.default_projection(self.cube))
        plt.title('Native')
        iplt.contour(self.cube)
        ax.coastlines()

        # Fourth sub-plot
        ax = plt.subplot(2, 2, 4, projection=ccrs.PlateCarree())
        plt.title('PlateCarree')
        iplt.contourf(self.cube)
        ax.coastlines()

        self.check_graphic()
Example #6
0
def _check_plot_works(f, freq=None, series=None, *args, **kwargs):
    import matplotlib.pyplot as plt

    fig = plt.gcf()
    plt.clf()
    ax = fig.add_subplot(211)
    orig_ax = kwargs.pop('ax', plt.gca())
    orig_axfreq = getattr(orig_ax, 'freq', None)

    ret = f(*args, **kwargs)
    assert(ret is not None)  # do something more intelligent

    ax = kwargs.pop('ax', plt.gca())
    if series is not None:
        dfreq = series.index.freq
        if isinstance(dfreq, DateOffset):
            dfreq = dfreq.rule_code
        if orig_axfreq is None:
            assert(ax.freq == dfreq)

    if freq is not None and orig_axfreq is None:
        assert(ax.freq == freq)

    ax = fig.add_subplot(212)
    try:
        kwargs['ax'] = ax
        ret = f(*args, **kwargs)
        assert(ret is not None)  # do something more intelligent
    except Exception:
        pass

    with ensure_clean() as path:
        plt.savefig(path)
Example #7
0
 def plot(self):
     if self.pos == None:
         self.pos = nx.graphviz_layout(self)
     NODE_SIZE = 500
     plt.clf()
     nx.draw_networkx_nodes(self, pos=self.pos,
                            nodelist=self.normal,
                            node_color=NORMAL_COLOR,
                            node_size=NODE_SIZE)
     nx.draw_networkx_nodes(self, pos=self.pos,
                            nodelist=self.contam,
                            node_color=CONTAM_COLOR,
                            node_size=NODE_SIZE)
     nx.draw_networkx_nodes(self, pos=self.pos,
                            nodelist=self.immune,
                            node_color=IMMUNE_COLOR,
                            node_size=NODE_SIZE)
     nx.draw_networkx_nodes(self, pos=self.pos,
                            nodelist=self.dead,
                            node_color=DEAD_COLOR,
                            node_size=NODE_SIZE)
     nx.draw_networkx_edges(self, pos=self.pos,
                            edgelist=self.nondead_edges(),
                            width=2,
                            edge_color='0.2')
     nx.draw_networkx_labels(self, pos=self.pos,
                             font_color='0.95', font_size=11)
     plt.gca().get_xaxis().set_visible(False)
     plt.gca().get_yaxis().set_visible(False)
     plt.draw()
def plot_band_array(band_array,refl_extent,colorlimit,ax=plt.gca(),title='',cbar ='on',cmap_title='',colormap='spectral'):
    
    '''plot_band_array reads in and plots a single band of a reflectance array
    --------
    Parameters
    --------
        band_array: flightline array of reflectance values, created from h5refl2array function
        refl_extent: extent of reflectance data to be plotted (xMin, xMax, yMin, yMax) - use metadata['extent'] from h5refl2array function
        colorlimit: range of values to plot (min,max). Best to look at the histogram of reflectance values before plotting to determine colorlimit.
        ax: optional, default = current axis
        title: string, optional; plot title
        cmap_title: string, optional; colorbar title
        colormap: string, optional; see https://matplotlib.org/examples/color/colormaps_reference.html for list of colormaps
    --------
    Returns 
    --------
        plots flightline array of single band of reflectance data
    --------
    See Also
    --------
    plot_subset_band:
        plots a subset of a full flightline reflectance band array 
    Example:
    --------
    plot_band_array(SERC_b56_clean,sercRefl_md['extent'],(0,0.3),ax,title='SERC Band 56 Reflectance',cmap_title='Reflectance',colormap='spectral') ''' 
    
    plot = plt.imshow(band_array,extent=refl_extent,clim=colorlimit); 
    if cbar == 'on':
        cbar = plt.colorbar(plot,aspect=40); plt.set_cmap(colormap); 
        cbar.set_label(cmap_title,rotation=90,labelpad=20)
    plt.title(title); ax = plt.gca(); 
    ax.ticklabel_format(useOffset=False, style='plain'); #do not use scientific notation #
    rotatexlabels = plt.setp(ax.get_xticklabels(),rotation=90); #rotate x tick labels 90 degrees
Example #9
0
def _plot(x, Y, file_name):
	title = file_name.replace('_', ' ').upper()
	fig = plt.figure(figsize=(8,4))
	ax = fig.add_subplot(111)
	plt.subplots_adjust(left=0.075, right=0.96, top=0.92, bottom=0.08)
	#ax.set_autoscaley_on(False)
	#ax.set_ylim([0,0.1])
	ax.set_xlim(0, RANGE[1])
	
	powerlaw = lambda x, amp, index: amp * (x**index)
	for y in Y:
		day, region = y
		amp, index = DATA[day][region]
		label = '{region} ({day})'.format(day=day, region=region).upper()
		ax.plot(x, powerlaw(x, amp, index), label=label, linewidth=1, color=COLORS[region], alpha=0.95, linestyle=LINESTYLE[day])
	
	formatter = FuncFormatter(lambda v, pos: str(round(v*100, 2))+'%')
	plt.gca().yaxis.set_major_formatter(formatter)
	formatter = FuncFormatter(lambda v, pos: '' if v/1000 == 0 else str(int(v/1000))+'km')
	plt.gca().xaxis.set_major_formatter(formatter)
	ax.set_title(title, fontsize=11)
	ax.legend(fontsize=10)

	if not os.path.exists('data/' + my.DATA_FOLDER + 'disp_stat/'):
		os.makedirs('data/' + my.DATA_FOLDER + 'disp_stat/')
	plt.savefig('data/' + my.DATA_FOLDER + 'disp_stat/' + file_name + '.png')
	print 'Stored chart: %s' % file_name
Example #10
0
 def png(self, start_timestamp, end_timestamp):
     self.load(start_timestamp, end_timestamp)
     plt.figure(figsize=(10, 7.52))
     plt.rc("axes", labelsize=12, titlesize=14)
     plt.rc("font", size=10)
     plt.rc("legend", fontsize=7)
     plt.rc("xtick", labelsize=8)
     plt.rc("ytick", labelsize=8)
     plt.axes([0.08, 0.08, 1 - 0.27, 1 - 0.15])
     for plot in self.plots:
         plt.plot(self.timestamps, self.plots[plot], self.series_fmt(plot), label=self.series_label(plot))
     plt.axis("tight")
     plt.gca().xaxis.set_major_formatter(
         matplotlib.ticker.FuncFormatter(lambda x, pos=None: time.strftime("%H:%M\n%b %d", time.localtime(x)))
     )
     plt.gca().yaxis.set_major_formatter(
         matplotlib.ticker.FuncFormatter(lambda x, pos=None: locale.format("%.*f", (0, x), True))
     )
     plt.grid(True)
     plt.legend(loc=(1.003, 0))
     plt.xlabel("Time/Date")
     plt.title(
         self.description()
         + "\n%s to %s"
         % (
             time.strftime("%H:%M %d-%b-%Y", time.localtime(start_timestamp)),
             time.strftime("%H:%M %d-%b-%Y", time.localtime(end_timestamp)),
         )
     )
     output_buffer = StringIO.StringIO()
     plt.savefig(output_buffer, format="png")
     return output_buffer.getvalue()
Example #11
0
def main():
    fname = iris.sample_data_path('ostia_monthly.nc')
    
    # load a single cube of surface temperature between +/- 5 latitude
    cube = iris.load_cube(fname, iris.Constraint('surface_temperature', latitude=lambda v: -5 < v < 5))
    
    # Take the mean over latitude
    cube = cube.collapsed('latitude', iris.analysis.MEAN)
    
    # Now that we have our data in a nice way, lets create the plot
    # contour with 20 levels
    qplt.contourf(cube, 20)
    
    # Put a custom label on the y axis 
    plt.ylabel('Time / years')
    
    # Stop matplotlib providing clever axes range padding
    plt.axis('tight')
    
    # As we are plotting annual variability, put years as the y ticks
    plt.gca().yaxis.set_major_locator(mdates.YearLocator())
    
    # And format the ticks to just show the year
    plt.gca().yaxis.set_major_formatter(mdates.DateFormatter('%Y'))
    
    plt.show()
Example #12
0
 def test_coord_coord_map(self):
     x = self.cube.coord('longitude')
     y = self.cube.coord('latitude')
     c = self.cube.data
     self.draw_method(x, y, c=c, edgecolor='none')
     plt.gca().coastlines()
     self.check_graphic()
Example #13
0
 def test_plot_tmerc(self):
     filename = tests.get_data_path(('NetCDF', 'transverse_mercator',
                                     'tmean_1910_1910.nc'))
     self.cube = iris.load_cube(filename)
     iplt.pcolormesh(self.cube[0])
     plt.gca().coastlines()
     self.check_graphic()
Example #14
0
def imshow_active_cells(grid, values, var_name=None, var_units=None,
                grid_units=(None, None), symmetric_cbar=False,
                cmap='pink'):
    """
    .. deprecated:: 0.6
    Use :meth:`imshow_active_cell_grid`, above, instead.
    """
    data = values.view()
    data.shape = (grid.shape[0]-2, grid.shape[1]-2)

    y = np.arange(data.shape[0]) - grid.dx * .5
    x = np.arange(data.shape[1]) - grid.dx * .5

    if symmetric_cbar:
        (var_min, var_max) = (data.min(), data.max())
        limit = max(abs(var_min), abs(var_max))
        limits = (-limit, limit)
    else:
        limits = (None, None)

    plt.pcolormesh(x, y, data, vmin=limits[0], vmax=limits[1], cmap=cmap)

    plt.gca().set_aspect(1.)
    plt.autoscale(tight=True)

    plt.colorbar()

    plt.xlabel('X (%s)' % grid_units[1])
    plt.ylabel('Y (%s)' % grid_units[0])

    if var_name is not None:
        plt.title('%s (%s)' % (var_name, var_units))

    plt.show()
def main():
    fig,ax=plt.subplots()
    ax.set_xlim([-0.5,2.5])
    ax.set_ylim([-0.5,2.5])
    deg=0
    A=rot(-deg)@[email protected]([[np.sqrt(2),0],[0,1]])@rot(deg)
    xy1=np.array([1,0])
    transxy1=trans(A,xy1)
    xy2=np.array([0,1])
    transxy2=trans(A,xy2)
    xy3=np.array([1,1])
    transxy3=trans(A,xy3)
    xy4=trans(rot(30),np.array([1,0]))
    transxy4=trans(A,xy4)

    plot_vector(ax,xy1,color=0.1)
    plot_vector(ax,transxy1,color=0.1)
    plot_vector(ax,xy2,color=0.2)
    plot_vector(ax,transxy2,color=0.2)
    plot_vector(ax,xy3,color=0.3)
    plot_vector(ax,transxy3,color=0.3)
    plot_vector(ax,xy4,color=0.4)
    plot_vector(ax,transxy4,color=0.4)
    plt.gca().set_aspect('equal', adjustable='box')
    plt.show()
Example #16
0
def mass_tri_plot(data, savedir, name='plot', Type='speed', Map=False):
    """
    Plots all time series.  Makes use of multiprocessing for speed.
    """
    trigrid = data['trigrid']
    #get the data to plot
    try:
        toPlot = data[Type]
    except KeyError:
        print Type + " is not an element of data.  Please calculate it."
        raise Exception("Invalid dictionary entry")
    #set the variable as a global variable
    global plotvar 
    plotvar = toPlot
    global saveDir
    saveDir = savedir
    global grid
    grid = trigrid
    #see if the save directory exists, or make it
    if not os.path.exists(savedir):
        os.makedirs(savedir)
    l = toPlot.shape[0]
    
    p = Pool(4)
    plt.gca().set_aspect('equal')
    p.map(save_plot, range(50))
    clearall()
Example #17
0
def el_plot(data, Map=False, show=True):
    """
    Plot the elevation for the region from the last time series
    
    :Parameters:
        **data** -- the standard python data dictionary
        
        **Map** -- {True, False} (optional): Optional argument.  If True,
            the elevation will be plotted on a map.  
    """
    trigrid = data['trigrid']
    plt.gca().set_aspect('equal')
    plt.tripcolor(trigrid, data['zeta'][-1,:])
    plt.colorbar()
    plt.title("Elevation")
    if Map:
        #we set the corners of where the map should show up
        llcrnrlon, urcrnrlon = plt.xlim()
        llcrnrlat, urcrnrlat = plt.ylim()
        #we construct the map.  Note that resolution serves to increase
        #or decrease the detail in the coastline.  Currently set to 
        #'i' for 'intermediate'
        m = Basemap(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, \
            resolution='i', suppress_ticks=False)
        #set color for continents.  Default is grey.
        m.fillcontinents(color='ForestGreen')
        m.drawmapboundary()
        m.drawcoastlines()
    if show:
        plt.show()
Example #18
0
def plot_events(events, map_object, beachball_size=0.02, project=None):
    """
    """
    for event in events:
        # Add beachball plot.
        x, y = map_object(event["longitude"], event["latitude"])

        focmec = [event["m_rr"], event["m_tt"], event["m_pp"], event["m_rt"],
                  event["m_rp"], event["m_tp"]]
        # Attempt to calculate the best beachball size.
        width = max((map_object.xmax - map_object.xmin,
                     map_object.ymax - map_object.ymin)) * beachball_size
        b = Beach(focmec, xy=(x, y), width=width, linewidth=1, facecolor="red")
        b.set_picker(True)
        b._project = project
        b._event_name = os.path.splitext(
            os.path.basename(event["filename"]))[0]
        b.detailed_event_description = (
            "Event %.1f %s\n"
            "Lat: %.1f, Lng: %.1f, Depth: %.1f km\n"
            "Time: %s\n"
            "%s"
        ) % (event["magnitude"], event["magnitude_type"], event["latitude"],
             event["longitude"], event["depth_in_km"], event["origin_time"],
             event["event_name"])

        b.set_zorder(200000000)
        plt.gca().add_collection(b)
    _set_global_pick_handler()
Example #19
0
def plot_event_histogram(events, plot_type):
    from matplotlib.dates import date2num, num2date
    from matplotlib import ticker

    plt.figure(figsize=(12, 4))

    values = []
    for event in events:
        if plot_type == "depth":
            values.append(event["depth_in_km"])
        elif plot_type == "time":
            values.append(date2num(event["origin_time"].datetime))

    plt.hist(values, bins=250)

    if plot_type == "time":
        plt.gca().xaxis.set_major_formatter(ticker.FuncFormatter(
            lambda numdate, _: num2date(numdate).strftime('%Y-%d-%m')))
        plt.gcf().autofmt_xdate()
        plt.xlabel("Origin time (UTC)")
        plt.title("Origin time distribution (%i events)" % len(events))
    elif plot_type == "depth":
        plt.xlabel("Event depth in km")
        plt.title("Hypocenter depth distribution (%i events)" % len(events))

    plt.tight_layout()
Example #20
0
def select_image(images, selection_callback):
    """
    Givel an array of images, show them all and allow seection by clicking.
    :param images:
    :param selection_callback:
    :return:
    """

    data = put_data_in_grid(images, is_color_data=True)

    plt.figure(figsize=(12, 12))
    plt.imshow(data)
    plt.gca().tick_params(labelbottom = 'off')
    plt.gca().tick_params(labelleft = 'off')

    # dbplot(first_ims, 'First BBox Images')
    def callback(event):
        n_cols = int(np.ceil(np.sqrt(len(images))))
        n_rows = int(np.ceil(len(images)/n_cols))
        ax_size_x = plt.gca().get_xlim()[1]
        ax_size_y = plt.gca().get_ylim()[0]

        frac_x = event.xdata/ax_size_x
        frac_y = event.ydata/ax_size_y
        print (frac_x, frac_y)

        col_ix = int(n_cols*frac_x)
        row_ix = int((n_rows+1)*frac_y)

        ix = row_ix*n_cols + col_ix

        selection_callback(ix)

    plt.gcf().canvas.callbacks.connect('button_press_event', callback)
    plt.show()
def plot_monte_carlo_ukf():

    def f(x,y):
        return x+y, .1*x**2 + y*y

    mean = (0, 0)
    p = np.array([[32, 15], [15., 40.]])

    # Compute linearized mean
    mean_fx = f(*mean)

    #generate random points
    xs, ys = multivariate_normal(mean=mean, cov=p, size=3000).T
    fxs, fys = f(xs, ys)

    plt.subplot(121)
    plt.gca().grid(b=False)

    plt.scatter(xs, ys, marker='.', alpha=.2, color='k')
    plt.xlim(-25, 25)
    plt.ylim(-25, 25)

    plt.subplot(122)
    plt.gca().grid(b=False)

    plt.scatter(fxs, fys, marker='.', alpha=0.2, color='k')

    plt.ylim([-10, 200])
    plt.xlim([-100, 100])
    plt.show()
def show_stocks_correlation():
    plt.gca().set_color_cycle([ 'red', 'yellow', 'green', 'blue'])
    plt.plot(usa_processed.date, usa_processed.nasdaq_adj_close_rate)
    plt.plot(usa_processed.date, usa_processed.snp_adj_close_rate)
    plt.legend(['NASDAQ adjusted closing price', 'S&P500 adjusted closing price'], loc='upper left')
    plt.show()
    print usa_processed['snp_adj_close_rate'].corr(usa_processed['nasdaq_adj_close_rate'], method='spearman')
Example #23
0
def plot_bold_signal(timeseries, x, y):
	# plots timeseries of two given nodes in a specific time interval
	
	v1  = timeseries[:, x]
	v2  = timeseries[:, y]
	
	T   = len(v1)	
	time = np.linspace(0, T-1, T) / float(60000)
	
	[R_pearson , p_value] = sistat.pearsonr(v1 , v2)
	
	## if the given signal downsampled :
	#time_bds = np.arange(0,  530,  float(530)/len(v1) )/float(60)
	#pl.plot(time_bds, v1, 'r',label=('node '+str(x)))
	#pl.plot(time_bds, v2, 'b',label=('node '+str(y)))
	
	# if no downsampling :

	fig , ax = pl.subplots(figsize=(25, 5.5))
	pl.subplots_adjust(left=0.08, right=0.98, top=0.94, bottom=0.20)

	pl.plot(time, v1, 'm', label=('$u_{' + str(x+1) + '}(t)$'))
	pl.plot(time, v2, 'g', label=('$u_{' + str(y+1) + '}(t)$'))
	pl.setp(pl.gca().get_xticklabels(), fontsize = 30)
	pl.setp(pl.gca().get_yticklabels(), fontsize = 30)
	
	#ax.set_ylim(-v2.max()-0.05, v2.max()+0.05)
	ax.set_ylim(-0.6, 0.6)
	
	pl.legend(prop={'size':35})

	pl.xlabel('t [min]', fontsize=30)
	pl.ylabel('BOLD % change' ,fontsize=40)
	
	return	
Example #24
0
    def test_ts_plot_format_coord(self):
        def check_format_of_first_point(ax, expected_string):
            first_line = ax.get_lines()[0]
            first_x = first_line.get_xdata()[0].ordinal
            first_y = first_line.get_ydata()[0]
            try:
                self.assertEqual(expected_string,
                                 ax.format_coord(first_x, first_y))
            except (ValueError):
                raise nose.SkipTest("skipping test because issue forming "
                                    "test comparison GH7664")

        annual = Series(1, index=date_range('2014-01-01', periods=3,
                                            freq='A-DEC'))
        check_format_of_first_point(annual.plot(), 't = 2014  y = 1.000000')

        # note this is added to the annual plot already in existence, and
        # changes its freq field
        daily = Series(1, index=date_range('2014-01-01', periods=3, freq='D'))
        check_format_of_first_point(daily.plot(),
                                    't = 2014-01-01  y = 1.000000')
        tm.close()

        # tsplot
        import matplotlib.pyplot as plt
        from pandas.tseries.plotting import tsplot
        tsplot(annual, plt.Axes.plot)
        check_format_of_first_point(plt.gca(), 't = 2014  y = 1.000000')
        tsplot(daily, plt.Axes.plot)
        check_format_of_first_point(plt.gca(), 't = 2014-01-01  y = 1.000000')
Example #25
0
def groupHourly(dataGroup, names, title, timeShift, stacked=True,show=True):
    plt.gca()
    toPlot = []
    namesShown = []
    for pos in range(len(dataGroup)):
    #for dataIn in dataGroup:
        if len(dataGroup[pos]['data']) > 0:
            data = truncData(dataGroup[pos]['data'],"hour")
            dates = data['created_at']
            dates = [parser.parse(date) for date in dates]
            hour_list = [(t+timedelta(hours=timeShift)).hour for t in dates]
            toPlot.append(hour_list)
            namesShown.append(names[pos])
            numbers=[x for x in xrange(0,25)]
            labels=map(lambda x: str(x), numbers)
            plt.xticks(numbers, labels)
            plt.xlabel("Hour (GMT %s)" % timeShift)
            plt.ylabel("Tweets")
    if len(namesShown) != 0:
        plt.title(title,size = 12)
        plt.hist(toPlot,bins=numbers,stacked=stacked, alpha=0.5, label=names, align='mid')
        plt.legend(namesShown,"best")
        if show:
            plt.show()
    return plt
Example #26
0
def _plot_matplotlib(obj, mesh, kwargs):
    # Avoid importing until used
    import matplotlib.pyplot as plt

    gdim = mesh.geometry().dim()
    if gdim == 3 or kwargs.get("mode") in ("warp",):
        # Importing this toolkit has side effects enabling 3d support
        from mpl_toolkits.mplot3d import axes3d
        # Enabling the 3d toolbox requires some additional arguments
        ax = plt.gca(projection='3d')
    else:
        ax = plt.gca()
    ax.set_aspect('equal')

    title = kwargs.pop("title", None)
    if title is not None:
        ax.set_title(title)

    if isinstance(obj, cpp.Function):
        return mplot_function(ax, obj, **kwargs)
    elif isinstance(obj, cpp.Expression):
        return mplot_expression(ax, obj, mesh, **kwargs)
    elif isinstance(obj, cpp.Mesh):
        return mplot_mesh(ax, obj, **kwargs)
    elif isinstance(obj, cpp.DirichletBC):
        return mplot_dirichletbc(ax, obj, **kwargs)
    elif isinstance(obj, _meshfunction_types):
        return mplot_meshfunction(ax, obj, **kwargs)
    else:
        raise AttributeError('Failed to plot %s' % type(obj))
Example #27
0
def plot_fgmax_grid():

    fg = fgmax_tools.FGmaxGrid()
    fg.read_input_data('fgmax_grid1.txt')
    fg.read_output()

    #clines_zeta = [0.01] + list(numpy.linspace(0.05,0.3,6)) + [0.5,1.0,10.0]
    clines_zeta = [0.001] + list(numpy.linspace(0.05,0.25,10))
    colors = geoplot.discrete_cmap_1(clines_zeta)
    plt.figure(1)
    plt.clf()
    zeta = numpy.where(fg.B>0, fg.h, fg.h+fg.B)   # surface elevation in ocean
    plt.contourf(fg.X,fg.Y,zeta,clines_zeta,colors=colors)
    plt.colorbar()
    plt.contour(fg.X,fg.Y,fg.B,[0.],colors='k')  # coastline

    # plot arrival time contours and label:
    arrival_t = fg.arrival_time/3600.  # arrival time in hours
    #clines_t = numpy.linspace(0,8,17)  # hours
    clines_t = numpy.linspace(0,2,5)  # hours
    #clines_t_label = clines_t[::2]  # which ones to label 
    clines_t_label = clines_t[::1]  # which ones to label 
    clines_t_colors = ([.5,.5,.5],)
    con_t = plt.contour(fg.X,fg.Y,arrival_t, clines_t,colors=clines_t_colors) 
    plt.clabel(con_t, clines_t_label)

    # fix axes:
    plt.ticklabel_format(format='plain',useOffset=False)
    plt.xticks(rotation=20)
    plt.gca().set_aspect(1./numpy.cos(fg.Y.mean()*numpy.pi/180.))
    plt.title("Maximum amplitude / arrival times (hrs)")
Example #28
0
    def visualize(self):
        """ Show the training samples, SVS and the current decision function
        """
        dim = numpy.shape(self.samples)[1]
        if dim == 2:
            ax = plt.gca()
            ax.set_xlabel(r'$x_0$')
            ax.set_ylabel(r'$x_1$')

            self.plot_samples()
            self.plot_hyperplane()
        elif dim == 3:
            ax = plt.gca(projection='3d')
            ax.set_xlabel(r'$x_0$')
            ax.set_ylabel(r'$x_1$')
            ax.set_zlabel(r'$x_2$')

            self.plot_samples_3D()
            self.plot_hyperplane_3D()

        if dim == 2 or dim == 3:
            plt.draw()
            if self.save_plot is True:
                imagename = "%s/tmp%010d.png"\
                            % (self.plot_storage, self.m_counter_i)
                self.m_counter_i += 1
                plt.savefig(imagename)
Example #29
0
    def update_figures(self):
        plt.figure(self.figure.number)
        x = np.arange(self.data.min(), self.data.max())#, (self.data.max() - self.data.min()) / 100)  # artificial x-axis
        # self.figure.gca().cla()  # clearing the figure, just to be sure

        # plt.subplot(411)
        plt.plot(self.bins, self.hist, 'k')
        plt.hold(True)
        # if self.rv_heal is not None and self.rv_hypo is not None and self.rv_hyper is not None:
        if self.models is not None:
            healthy_y = self.rv_heal.pdf(x)
            if self.unaries_as_cdf:
                hypo_y = (1 - self.rv_hypo.cdf(x)) * self.rv_heal.pdf(self.rv_heal.mean())
                hyper_y = self.rv_hyper.cdf(x) * self.rv_heal.pdf(self.rv_heal.mean())
            else:
                hypo_y = self.rv_hypo.pdf(x)
                hyper_y = self.rv_hyper.pdf(x)
            y_max = max(healthy_y.max(), hypo_y.max(), hyper_y.max())
            fac = self.hist.max() / y_max

            plt.plot(x, fac * healthy_y, 'g', linewidth=2)
            plt.plot(x, fac * hypo_y, 'b', linewidth=2)
            plt.plot(x, fac * hyper_y, 'r', linewidth=2)
        if self.params and self.params.has_key('win_level') and self.params.has_key('win_width'):
            ax = plt.axis()
            border = 5
            xmin = self.params['win_level'] - self.params['win_width'] / 2 - border
            xmax = self.params['win_level'] + self.params['win_width'] / 2 + border
            plt.axis([xmin, xmax, ax[2], ax[3]])
        plt.gca().tick_params(direction='in', pad=1)
        plt.hold(False)
        # plt.grid(True)

        self.canvas.draw()
def dynamic_svg(x,y,smoothx, smoothy,xAxis_label,yAxis_label,chart_title):
    import StringIO
    import numpy, matplotlib.pyplot as plt
    #import seaborn as sns
    try:
        #sns.set_style('ticks')
        #plt.style.use('ggplot')
        #plt.title('T1 fitting for Look-Locker Experiment')
        #plt.scatter(x,y, s=65, color=sns.color_palette()[0],marker='o',alpha=0.8)
        #plt.plot(smoothx, fitted_y, color=sns.color_palette()[1])
        plt.figure(1)
        plt.clf()
        #pylab.rcParams.update(params)
        plt.scatter(x,y, s=65, marker='+',c= 'k',label='Original')
        plt.plot(smoothx, smoothy,c= 'k',label='Fitted data')
        plt.legend(loc='lower right')
        plt.xlabel(xAxis_label)
        plt.ylabel(yAxis_label)
        plt.xlim(xmin =-10,xmax= max(x)+100)
        plt.ylim(ymin =smoothy.min()-10)
        fig = plt.gcf()
        fig.set_size_inches(10,6)
        #plt.gca().axhline(0, color='black', lw=2)
        plt.gca().grid(True)

        #plt.gca().set_axis_bgcolor('white')
        rv = StringIO.StringIO()
        plt.savefig(rv, format="svg")
        return rv.getvalue()
    finally:
        plt.clf()
Example #31
0
list2 = []

for i, p in enumerate(player_list):
    if (i % 200 == 0): print(i)
    df_p = df[df['bat_id'] == p]
    if (df_p.shape[0] >= 500):  # first 500 games
        df_p['h_cum'] = np.cumsum(df_p.h)
        df_p = df_p.iloc[0:500:, :].reset_index()
        if (df_p.h.sum() >= 650): print(p)  # many hits
        plt.plot(df_p.h_cum, color='grey', alpha=.7, linewidth=.7)
        list1.append(list(df_p.retroID))
        list2.append(list(df_p.h_cum))

    plt.xlabel("Game of Career")
    plt.ylabel("Cumulative Hits")
    plt.gca().spines['top'].set_visible(False)
    plt.gca().spines['right'].set_visible(False)
    plt.gca().spines['bottom'].set_smart_bounds(True)
    plt.gca().spines['left'].set_smart_bounds(True)
    plt.grid(axis='y', alpha=.3)
    plt.gcf().set_size_inches(13, 5)

#bkh chart
source = ColumnDataSource(
    dict(xs=[i for i in range(0, 499)], ys=list2, nms=list1))

p = figure(title="simple line example")
p.multi_line([list(i for i in range(0, 499))] * len(list1),
             list2,
             line_width=2)
p.add_tools(HoverTool(tooltips=list1))
Example #32
0
def bland_altman_plot(m1,
                      m2,
                      sd_limit=1.96,
                      ax=None,
                      scatter_kwds=None,
                      mean_line_kwds=None,
                      limit_lines_kwds=None):
    """
    Bland-Altman Plot.

    A Bland-Altman plot is a graphical method to analyze the differences
    between two methods of measurement. The mean of the measures is plotted
    against their difference.

    Parameters
    ----------
    m1, m2: pandas Series or array-like

    sd_limit : float, default 1.96
        The limit of agreements expressed in terms of the standard deviation of
        the differences. If `md` is the mean of the differences, and `sd` is
        the standard deviation of those differences, then the limits of
        agreement that will be plotted will be
                       md - sd_limit * sd, md + sd_limit * sd
        The default of 1.96 will produce 95% confidence intervals for the means
        of the differences.
        If sd_limit = 0, no limits will be plotted, and the ylimit of the plot
        defaults to 3 standard deviatons on either side of the mean.

    ax: matplotlib.axis, optional
        matplotlib axis object to plot on.

    scatter_kwargs: keywords
        Options to to style the scatter plot. Accepts any keywords for the
        matplotlib Axes.scatter plotting method

    mean_line_kwds: keywords
        Options to to style the scatter plot. Accepts any keywords for the
        matplotlib Axes.axhline plotting method

    limit_lines_kwds: keywords
        Options to to style the scatter plot. Accepts any keywords for the
        matplotlib Axes.axhline plotting method

   Returns
    -------
    ax: matplotlib Axis object
    """

    import numpy as np
    import matplotlib.pyplot as plt

    if len(m1) != len(m2):
        raise ValueError('m1 does not have the same length as m2.')
    if sd_limit < 0:
        raise ValueError('sd_limit ({}) is less than 0.'.format(sd_limit))

    means = np.mean([m1, m2], axis=0)
    diffs = m1 - m2
    mean_diff = np.mean(diffs)
    std_diff = np.std(diffs, axis=0)

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

    scatter_kwds = scatter_kwds or {}
    if 's' not in scatter_kwds:
        scatter_kwds['s'] = 20
    mean_line_kwds = mean_line_kwds or {}
    limit_lines_kwds = limit_lines_kwds or {}
    for kwds in [mean_line_kwds, limit_lines_kwds]:
        if 'color' not in kwds:
            kwds['color'] = 'gray'
        if 'linewidth' not in kwds:
            kwds['linewidth'] = 1
    if 'linestyle' not in mean_line_kwds:
        kwds['linestyle'] = '--'
    if 'linestyle' not in limit_lines_kwds:
        kwds['linestyle'] = ':'

    ax.scatter(means, diffs, **scatter_kwds)
    ax.axhline(mean_diff, **mean_line_kwds)  # draw mean line.

    # Annotate mean line with mean difference.
    ax.annotate('mean diff:\n{}'.format(np.round(mean_diff, 2)),
                xy=(0.99, 0.5),
                horizontalalignment='right',
                verticalalignment='center',
                fontsize=14,
                xycoords='axes fraction')

    if sd_limit > 0:
        half_ylim = (1.5 * sd_limit) * std_diff
        ax.set_ylim(mean_diff - half_ylim, mean_diff + half_ylim)

        limit_of_agreement = sd_limit * std_diff
        lower = mean_diff - limit_of_agreement
        upper = mean_diff + limit_of_agreement
        for j, lim in enumerate([lower, upper]):
            ax.axhline(lim, **limit_lines_kwds)
        ax.annotate('-SD{}: {}'.format(sd_limit, np.round(lower, 2)),
                    xy=(0.99, 0.07),
                    horizontalalignment='right',
                    verticalalignment='bottom',
                    fontsize=14,
                    xycoords='axes fraction')
        ax.annotate('+SD{}: {}'.format(sd_limit, np.round(upper, 2)),
                    xy=(0.99, 0.92),
                    horizontalalignment='right',
                    fontsize=14,
                    xycoords='axes fraction')

    elif sd_limit == 0:
        half_ylim = 3 * std_diff
        ax.set_ylim(mean_diff - half_ylim, mean_diff + half_ylim)

    ax.set_ylabel('Difference', fontsize=15)
    ax.set_xlabel('Means', fontsize=15)
    ax.tick_params(labelsize=13)
    plt.tight_layout()
    return ax
Example #33
0
c = {}
with open('color.table') as f:
    for line in f:
        fields = line.split('\t')
        colorname = fields[0].lower()
        hexcode = fields[1]
        c[colorname] = hexcode

names = c.keys()
names = sorted(names)

print(names)

blues = [
    c['alice blue'], c['light blue'], c['baby blue'], c['light sky blue'],
    c['maya blue'], c['cornflower blue'], c['bleu de france'], c['azure'],
    c['blue sapphire'], c['cobalt'], c['blue'], c['egyptian blue'],
    c['duke blue']
]
ax = plt.gca()
ax.set_color_cycle(blues)

# this plots horizonial lines for each y value of m.

for i, m in enumerate(np.linspace(1, 50, 100)):
    plt.plot([0, 50], [m, m])

plt.savefig('51-2.jpg', dpi=300)
plt.show()
print('plot done')
Example #34
0
def corrfunc(x, y, **kws):
    r, _ = sp.stats.pearsonr(x, y)
    ax = plt.gca()
    ax.annotate("r = {:.2f}".format(r),
                xy=(.1, .9), xycoords=ax.transAxes)
myhist = np.zeros((bincount,1))
mindata = np.min(A)
maxdata = np.max(A)
minlevel = np.floor(mindata)
maxlevel = np.ceil(maxdata)
leveldiff = (maxlevel - minlevel) / bincount

for i in range(0, A.shape[0]):
    bin = (A[i,0] - minlevel) / leveldiff
    bin = np.ceil(bin)
    myhist[bin - 1,0] = myhist[bin - 1,0] + 1

plt.figure(1) 
bins = range(myhist.shape[0])
plt.bar(bins, myhist[:,0])
ax=plt.gca()
ax.set_xticks(np.arange(1, bincount, bincount / 10)) 
ax.set_xticklabels(np.arange(minlevel, maxlevel, leveldiff * (bincount / 10)))

# ===============================================================
# Kernel density estimation
# ===============================================================
# Here we use the tophat kernel.
#  Adjustable parameters:

kernelwidth = 0.2 # kernel width determines how smooth estimate will be

bincount = 1000
mykde = np.zeros((bincount,1))
mindata = np.min(A)
maxdata = np.max(A)
data_final['x4'].fillna(method = 'ffill', inplace = True)
data_final['x5'].fillna(method = 'ffill', inplace = True)
data_final['x6'].fillna(method = 'ffill', inplace = True)
data_final['skill'].fillna(method = 'ffill', inplace = True)
data_final['skill'].fillna(0, inplace = True)
data_final['eigen_force'].fillna(method = 'ffill', inplace = True)
data_final['eigen_force'].fillna(0, inplace = True)
data_final.to_csv('/home/deepthi/wrench_jacobian_prod22.log',index=True, sep='\t', mode='w')
dt_ = {'skill': skill, 'eig_val': eig_force}
dats = pandas.concat(dt_.values(), axis = 1, keys = dt_.keys())
dats['skill'].fillna(method = 'ffill', inplace = True)
dats['skill'].fillna(0, inplace = True)
dats['eig_val'].fillna(method = 'ffill', inplace = True)
dats = dats.reset_index()
dats.to_csv('/home/deepthi/skill_eig_ch.log', index= False, sep = '\t', mode ='w')
axes = plt.gca()
axes.set_xlim([2600, 2950])
fig,ax1 = plt.subplots()
#ax1.plot(data_final['time_x'],data_final['f_x'], 'r', label = 'force x')
#ax1.plot(data_final['time_x'],data_final['f_y'], 'b', label = 'force y')
#ax1.plot(data_final['time_x'],data_final['f_z'], 'g', label = 'force z')
ax2 = ax1.twinx()
ax2.set_xlim([2750,2950])
ax2.plot(data_final['time_x'],data_final['skill'], 'b', label = 'skill')
#plt.plot(data_final['time_x'],data_final['x5'], 'm', label = 'tau5q')
#plt.plot(data_final['time_x'],data_final['x6'], 'y', label = 'tau6q')
ax1.plot(data_final['time_x'],data_final['eigen_force'], 'k', label = 'eigen force')
plt.legend(loc = 'best')
plt.xlabel('Time')
plt.ylabel('Eigen-Force and Forces')
plt.title('Eigen-Force and Forces vs time')
Example #37
0
    def plot_gradient(self, start_point, end_point, field, fname='', display=True, title='', max_val=None, min_val=None, curve_fitting=True, n_poly=3, n_subpoints=500, legend=True):
        """Create diagram with data projected onto line on the undeformed geometry.

        Args:
            start_point [(float), (float)]: starting point of line. [x, y]
            end_point [(float), (float)]: end point of line. Example: [x, y]
            field (str): results item to plot, examples: 'ux', 'ey', 'Seqv'
            
        Kargs:
            fname (str): prefix of png file name, if writing an image
            display (bool): True = interactively show the plot
            title (str): third line in the plot title
            max_val (float or None): max value in the y-axis
                - None: max from selected data used
                - float: use the passed float
            min_val (float or None): min value in the y-axis
                - None: min from selected data used
                - float: use the passed float
            curve_fitting (bool): True = a curve is fitted to the gradient
            n_poly (int): numbers of polygons for fitting
            n_subpoints (int): numbers of points the line is subdivided into
            legend (bool): True = legend with fitted equation is shown
        """
        
        # store the selected nodes and elements
        sel = {}
        sel['nodes'] = self.__problem.fea.view.nodes

        # sort nodes low to high so index is correct
        # we have index to id below so showing subsets works
        sel['nodes'] = list(sel['nodes'])
        sel['nodes'] = sorted(sel['nodes'], key=lambda k: k.id)

        # store results at nodes
        node_position = np.zeros((len(sel['nodes']),2))
        field_values = np.zeros(len(sel['nodes']))
        
        for idx, node in enumerate(sel['nodes']):
            
            node_position[idx] = [node.x, node.y]
            field_values[idx] = self.__results[self.__time]['node'][node.id][field]
            
        
        #create subpoints on line
        subpoints = np.zeros((n_subpoints, 3))  #[x, y, line position]
        
        subpoints[:,0] = np.linspace(start_point[0], end_point[0], n_subpoints)
        subpoints[:,1] = np.linspace(start_point[1], end_point[1], n_subpoints)
        subpoints[:,2] = np.arange(n_subpoints) / n_subpoints * np.sqrt(np.sum( (np.array(start_point) - np.array(end_point))**2))
        
        #calculate weighted field value for every subpoint
        wfield = np.zeros(n_subpoints)
        
        for idx in range(n_subpoints):
            
            #calculate inverse of distance from nodes to subpoints
            dist = np.sqrt(np.sum((node_position-subpoints[idx,0:2])**2,axis=1))
            
            #calculte weighted field value
            #dist[dist < 1E-10] = 1E-10
            #inv_dist = 1. / dist**3
            #wfield[idx] = np.average(field_values, weights=inv_dist)
            
            #use nearest value
            wfield[idx] = field_values[min(range(len(dist)),key=dist.__getitem__)]
            
            
        #plot diagram
        
        fig = plt.figure(figsize=(10,6))
        ax_ = fig.add_subplot(111)
        
        plt.plot(subpoints[:,2], wfield, '-r', linewidth=2.5, label=field)
        
        if curve_fitting==True:
            #execute curve fitting if needed
            poly = np.polyfit(subpoints[:,2], wfield, n_poly)
            
            #string for equation of fitted function
            funcstring = [str(np.round(poly[i]))+u'*x^'+str(np.arange(n_poly,0,-1)[i]) for i in range(n_poly)]
            funcstring.append(str(np.round(poly[-1])))
            funcstring = '+'.join(funcstring)
            
            func = np.poly1d(poly)
            
            plt.plot(subpoints[:,2], func(subpoints[:,2]), '--k', linewidth=1.5, label=funcstring)
        
        
        # set units
        alist = self.__problem.fea.get_units(field, 'dist', 'time')
        [f_unit, d_unit, t_unit] = alist

        # set plot axes
        plot_title = ('Gradient %s%s\nTime=%f%s' %(field, f_unit, self.__time, t_unit))
        if title != '':
            plot_title += '\n%s' % title
        plt.title(plot_title)
        plt.xlabel('path position'+d_unit)
        plt.ylabel(field + ' ' +f_unit)
        
        #show legend if needed
        if legend == True:
            plt.legend()
            
        #set limits on y-axis
        if min_val!=None:
            plt.gca().set_ylim(bottom=min_val)
        if max_val!=None:
            plt.gca().set_ylim(top=max_val)
            
        plt.grid()
        base_classes.plot_finish(plt, fname, display)
def xlabel(x, color, label):
    ax = plt.gca()
    ax.set_xlabel(3.3, 0.05, label, color="black", fontsize=16)
Example #39
0
##            Ukol c. 10            ##
######################################

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

sound_1= wave.open('xstudn00.wav','r')
signal = sound_1.readframes(-1)
signal = np.fromstring(signal, 'Int16')
fs = sound_1.getframerate()
signal = signal/24576

delka_ve_vzorcich = sound_1.getnframes()

k = np.arange(-delka_ve_vzorcich+1, delka_ve_vzorcich)
Rv = np.correlate(signal[:delka_ve_vzorcich:], signal[:delka_ve_vzorcich:], 'full') / delka_ve_vzorcich

pocet_indexu = 50
pocatek = k.size // 2 - pocet_indexu
konec = k.size // 2 + pocet_indexu

x = k[pocatek:konec:]
y = Rv[pocatek:konec:]

plt.plot(x, y)
plt.gca().set_xlabel('$k$')

plt.show()

sound_1.close()
def title_function(color, label):
    ax = plt.gca()
    ax.set_title(label)
def draw(Vs, W, inputNames=None, outputNames=None, gray=False):

    def isOdd(x):
        return x % 2 != 0

    W = Vs + [W]
    nLayers = len(W)

    # calculate xlim and ylim for whole network plot
    #  Assume 4 characters fit between each wire
    #  -0.5 is to leave 0.5 spacing before first wire
    xlim = max(map(len, inputNames))/4.0 if inputNames else 1
    ylim = 0

    for li in range(nLayers):
        ni, no = W[li].shape  # no means number outputs this layer
        if not isOdd(li):
            ylim += ni + 0.5
        else:
            xlim += ni + 0.5

    ni, no = W[nLayers-1].shape
    if isOdd(nLayers):
        xlim += no + 0.5
    else:
        ylim += no + 0.5

    # Add space for output names
    if outputNames:
        if isOdd(nLayers):
            ylim += 0.25
        else:
            xlim += round(max(map(len,outputNames))/4.0)

    ax = plt.gca()

    character_width_factor = 0.07
    padding = 2
    if inputNames:
        x0 = max([1, max(map(len, inputNames)) * (character_width_factor * 3.5)])
    else:
        x0 = 1
    y0 = 0  # to allow for constant input to first layer
    # First Layer
    if inputNames:
        y = 0.55
        for n in inputNames:
            y += 1
            ax.text(x0 - (character_width_factor * padding), y, n, horizontalalignment="right", fontsize=20)

    patches = []
    for li in range(nLayers):
        thisW = W[li]
        maxW = np.max(np.abs(thisW))
        ni, no = thisW.shape
        if not isOdd(li):
            # Even layer index. Vertical layer. Origin is upper left.
            # Constant input
            ax.text(x0-0.2, y0+0.5, '1', fontsize=20)
            for i in range(ni):
                ax.plot((x0, x0+no-0.5), (y0+i+0.5, y0+i+0.5), color='gray')
            # output lines
            for i in range(no):
                ax.plot((x0+1+i-0.5, x0+1+i-0.5), (y0, y0+ni+1), color='gray')
            # cell "bodies"
            xs = x0 + np.arange(no) + 0.5
            ys = np.array([y0+ni+0.5]*no)
            for x, y in zip(xs, ys):
                patches.append(pltpatch.RegularPolygon((x, y-0.4), 3, 0.3, 0, color ='#555555'))
            # weights
            if gray:
                colors = np.array(["black", "gray"])[(thisW.flat >= 0)+0]
            else:
                colors = np.array(["red", "green"])[(thisW.flat >= 0)+0]
            xs = np.arange(no) + x0+0.5
            ys = np.arange(ni) + y0 + 0.5
            coords = np.meshgrid(xs, ys)
            for x, y, w, c in zip(coords[0].flat, coords[1].flat,
                                  np.abs(thisW/maxW).flat, colors):
                patches.append(pltpatch.Rectangle((x-w/2, y-w/2), w, w, color=c))
            y0 += ni + 1
            x0 += -1  # shift for next layer's constant input
        else:
            # Odd layer index. Horizontal layer. Origin is upper left.
            # Constant input
            ax.text(x0+0.5, y0-0.2, '1', fontsize=20)
            # input lines
            for i in range(ni):
                ax.plot((x0+i+0.5,  x0+i+0.5), (y0, y0+no-0.5), color='gray')
            # output lines
            for i in range(no):
                ax.plot((x0, x0+ni+1), (y0+i+0.5, y0+i+0.5), color='gray')
            # cell "bodies"
            xs = np.array([x0 + ni + 0.5] * no)
            ys = y0 + 0.5 + np.arange(no)
            for x, y in zip(xs, ys):
                patches.append(pltpatch.RegularPolygon((x-0.4, y), 3, 0.3, -np.pi/2, color ='#555555'))
            # weights
            if gray:
                colors = np.array(["black", "gray"])[(thisW.flat >= 0)+0]
            else:
                colors = np.array(["red", "green"])[(thisW.flat >= 0)+0]
            xs = np.arange(ni)+x0 + 0.5
            ys = np.arange(no)+y0 + 0.5
            coords = np.meshgrid(xs, ys)
            for x, y, w, c in zip(coords[0].flat, coords[1].flat,
                                  np.abs(thisW/maxW).flat, colors):
                patches.append(pltpatch.Rectangle((x-w/2, y-w/2), w, w, color=c))
            x0 += ni + 1
            y0 -= 1  # shift to allow for next layer's constant input

    collection = pltcoll.PatchCollection(patches, match_original=True)
    ax.add_collection(collection)

    # Last layer output labels
    if outputNames:
        if isOdd(nLayers):
            x = x0+1.5
            for n in outputNames:
                x += 1
                ax.text(x, y0+0.5, n, fontsize=20)
        else:
            y = y0+0.6
            for n in outputNames:
                y += 1
                ax.text(x0+0.2, y, n, fontsize=20)
    ax.axis([0, xlim, ylim, 0])
    ax.axis('off')
Example #42
0
    def vis_two(self, im_array, dets1, dets2, thresh=0.9):
        """Visualize detection results before and after calibration

        Parameters:
        ----------
        im_array: numpy.ndarray, shape(1, c, h, w)
            test image in rgb
        dets1: numpy.ndarray([[x1 y1 x2 y2 score]])
            detection results before calibration
        dets2: numpy.ndarray([[x1 y1 x2 y2 score]])
            detection results after calibration
        thresh: float
            boxes with scores > thresh will be drawn in red otherwise yellow

        Returns:
        -------
        """
        import matplotlib.pyplot as plt
        import random

        figure = plt.figure()
        plt.subplot(121)
        plt.imshow(im_array)
        color = 'yellow'

        for i in range(dets1.shape[0]):
            bbox = dets1[i, :4]
            score = dets1[i, 4]
            if score > thresh:
                rect = plt.Rectangle((bbox[0], bbox[1]),
                                     bbox[2] - bbox[0],
                                     bbox[3] - bbox[1],
                                     fill=False,
                                     edgecolor='red',
                                     linewidth=0.7)
                plt.gca().add_patch(rect)
                plt.gca().text(bbox[0],
                               bbox[1] - 2,
                               '{:.3f}'.format(score),
                               bbox=dict(facecolor='blue', alpha=0.5),
                               fontsize=12,
                               color='white')
            else:
                rect = plt.Rectangle((bbox[0], bbox[1]),
                                     bbox[2] - bbox[0],
                                     bbox[3] - bbox[1],
                                     fill=False,
                                     edgecolor=color,
                                     linewidth=0.5)
                plt.gca().add_patch(rect)

        plt.subplot(122)
        plt.imshow(im_array)
        color = 'yellow'

        for i in range(dets2.shape[0]):
            bbox = dets2[i, :4]
            score = dets2[i, 4]
            if score > thresh:
                rect = plt.Rectangle((bbox[0], bbox[1]),
                                     bbox[2] - bbox[0],
                                     bbox[3] - bbox[1],
                                     fill=False,
                                     edgecolor='red',
                                     linewidth=0.7)
                plt.gca().add_patch(rect)
                plt.gca().text(bbox[0],
                               bbox[1] - 2,
                               '{:.3f}'.format(score),
                               bbox=dict(facecolor='blue', alpha=0.5),
                               fontsize=12,
                               color='white')
            else:
                rect = plt.Rectangle((bbox[0], bbox[1]),
                                     bbox[2] - bbox[0],
                                     bbox[3] - bbox[1],
                                     fill=False,
                                     edgecolor=color,
                                     linewidth=0.5)
                plt.gca().add_patch(rect)
        plt.show()
Example #43
0
    def plotHexbin(self,fig, ax):
        # These shold be settings
        contours = 12
        ax.grid(b=True, which='major', color='Gainsboro', linestyle='-',alpha=0.7,lw=0.7)
        #ax.set_axisbelow(True)can't set the lines below as the whole data is 1 image not scatters

        if self.operation == 'ABS':
            self.data[self.geoX] == abs(self.data[self.geoX])


        x = self.data[self.geoX]#.ravel()
        y = self.data[self.geoY]#.ravel()

        extent = []
        if self.range != []:
            extent = [self.range[0], self.range[1],self.range[0],self.range[1]]
            plt.gca().set_aspect("equal")

        if self.hue.lower() == 'count':
            if self.range == []:
                hb = plt.hexbin(x, y, bins=self.bins, cmap=self.palette,gridsize=self.gridsize)
            else:
                hb = plt.hexbin(x, y, bins=self.bins, cmap=self.palette, gridsize=self.gridsize,extent=extent)

            #cb = plt.colorbar()
            #cb.set_label('Count')
        else:
            z = self.data[self.hue]  # .ravel()
            self.vmin = z.min()
            self.vmax = z.max()
            #ax = self.data.plot.hexbin(x=self.geoX,y=self.geoY,C=self.hue,gridsize=10,cmap=self.palette)
            if self.range == []:
                hb = plt.hexbin(x,y,C=z,bins=self.bins, cmap=self.palette,gridsize=self.gridsize,reduce_C_function=np.mean)
                        #,vmin = self.vmin, vmax = self.vmax)
            else:
                hb = plt.hexbin(x, y, C=z, bins=self.bins, cmap=self.palette, gridsize=self.gridsize,reduce_C_function=np.mean, extent=extent)

            cb = plt.colorbar()
            cb.set_label('Average ' + self.hue)
            #cb.set_ticks(z.min(),z.max())
            cb.set_ticks(np.linspace(hb.get_array().min(), hb.get_array().max(), 10))
            lbls = np.linspace(round(z.min(),2), round(z.max(),2), 10)
            diff = z.max()-z.min()
            lblsrounded = []
            for lbl in lbls:
                if diff < 5:
                    lblsrounded.append(round(lbl,2))
                elif diff < 10:
                    lblsrounded.append(round(lbl, 1))
                else:
                    lblsrounded.append(int(round(lbl, 0)))
            #cb.set_ticklabels(np.linspace(round(z.min(),2), round(z.max(),2), 10))
            cb.set_ticklabels(lblsrounded)

        #if self.range != []:
        #    plt.xlim(xmin=self.range[0], xmax=self.range[1])
        #    plt.gca().set_aspect("equal")
        #    ax.grid(b=True, which='major', color='Gainsboro', linestyle='-')
        #    ax.set_axisbelow(True)

        plt.axis([x.min(), x.max(), y.min(), y.max()])
        if self.range !=[]:
            bnds = np.array([self.range[0], self.range[1]])
            ax.set_xlim(bnds)
            ax.set_ylim(bnds)

        #Labelling
        ax.set_xlabel(self.geoX)
        ax.set_ylabel(self.geoY)
        count = len(self.data.index)
        title = self.title
        if title == '':
            title += 'Count=' + str(count)
        else:
            title += '\nCount=' + str(count)

        plt.title(title)
        return ''
import matplotlib.pyplot as plt
import pandas as pd

data = pd.read_csv('https://raw.githubusercontent.com/ChrisWalshaw/DataViz/master/DataNorth/001142828/DailyCustomers.csv', index_col=0)
pd.plotting.register_matplotlib_converters()
data.index = pd.to_datetime(data.index)

period = 7
rolling_average = data.rolling(window=period).mean()

selected = ['ZSD', 'MAJ', 'YYO', 'NGB']
print(data[selected].head())

plt.figure(figsize=(8, 8))
plt.plot(data[selected], linewidth=0.5)
plt.gca().set_prop_cycle(None)
plt.plot(rolling_average[selected], linewidth=2)
# plt.ylim(ymin=0)
plt.xlabel('Date', fontsize=18)
plt.ylabel('Customer visits', fontsize=18)
plt.title('Very Low Volume Customer Visits\n with 7-day Rolling Average', fontsize=20)
plt.legend(selected, loc=2)
plt.show()
Example #45
0
    def plotScatter(self,fig, ax):
        #fig, ax = plt.subplots()
        ax.grid(b=True, which='major', color='Gainsboro', linestyle='-')
        ax.set_axisbelow(True)

        if self.categorical or self.hue == 'dssp':
            #blanksdata = self.data[self.data[self.hue] == '']
            #print(blanksdata)
            # it is possible for errors in dssp assignment in which case we call them X, but it will cover any errors not just dssp
            self.data.loc[self.data[self.hue] == '', self.hue] = 'X'

            gradients = {}
            dataforgrad = self.data.copy()
            gradsorig = dataforgrad.sort_values(by=self.hue, ascending=True)[self.hue].unique()
            grads = self.getHueLists(self.hue,gradsorig)
            evenly_spaced_interval = np.linspace(0, 1, len(grads))

            try:
                sns.set_palette(sns.color_palette(self.palette, len(grads)))
                colors = [cm.get_cmap(self.palette)(x) for x in evenly_spaced_interval]
                i = 0
                for g in grads:
                    gradients[g] = colors[i]
                    i = i+1
                self.palette = gradients
            except:
                self.palette = self.palette

        if self.operation == 'ABS':
            self.data = self.data[self.data[self.geoX] == abs(self.data[self.geoX])]


        if self.sort == 'DESC':
            self.data = self.data.sort_values(by=self.hue, ascending=False)
        elif self.hue == 'resolution':
            self.data = self.data.sort_values(by=self.hue, ascending=False)
        elif self.plot == 'contact':
            self.data = self.data.sort_values(by='ridA', ascending=False)
        elif self.sort== 'ASC':
            self.data = self.data.sort_values(by=self.hue, ascending=True)
        elif self.sort == 'RAND':
            self.data = self.data.sample(frac=1)


        lw = 0.5
        alpha = 0.65#0.65
        #if the count is really low then we can have a greater alphs
        if len(self.data[self.geoX]) < 100:
            alpha = 1


        ecol = 'grey'
        if self.palette == 'gist_gray_r':
            lw = 0  # this gives a crystollagraphic image look
            ecol = 'grey'
            alpha = 0.9
        if self.title=='ghost':
            alpha = 0.4
            self.palette='Greys'

        if self.hue == 'count':
            alpha = 0.003
            self.data['count'] = 0
            self.palette = 'bone'
            lw=0.1
            self.vmin=0
            self.vmax=0


        if self.centre:
            self.data[self.hue + '2'] = self.data[self.hue] ** 2
            data = self.data.sort_values(by=self.hue + '2', ascending=True)
            maxh = max(data[self.hue].max(), -1 * data[self.hue].min())
            minh = maxh * -1
            g = ax.scatter(data[self.geoX], data[self.geoY], c=data[self.hue], cmap=self.palette,
                           vmin=minh,vmax=maxh, edgecolor=ecol, alpha=alpha,linewidth=lw,s=20)
            cb = fig.colorbar(g)
            ax.set_xlabel(self.geoX)
            ax.set_ylabel(self.geoY)
            cb.set_label(self.hue)
        elif self.vmin < self.vmax:
            #data = self.data.sort_values(by=self.hue, ascending=True)
            g = ax.scatter(self.data[self.geoX], self.data[self.geoY], c=self.data[self.hue], cmap=self.palette, vmin=self.vmin,
                           vmax=self.vmax, edgecolor=ecol, alpha=alpha,linewidth=lw,s=20)
            cb = fig.colorbar(g)
            ax.set_xlabel(self.geoX)
            ax.set_ylabel(self.geoY)
            cb.set_label(self.hue)

        elif self.plot == 'contact':
            alpha = 0.75
            self.data['distanceinv'] = 1/(self.data['distance'] ** 3)*4000
            if self.categorical == False:
                g = ax.scatter(self.data[self.geoX], self.data[self.geoY], c=self.data[self.hue],
                               cmap=self.palette,s=self.data['distanceinv'],edgecolor=ecol,alpha=alpha,linewidth=lw)
                cb = plt.colorbar(g)
                cb.set_label(self.hue)
            else:
                alpha = 0.65
                im = sns.scatterplot(x=self.geoX, y=self.geoY, hue=self.hue, data=self.data, alpha=alpha,legend='brief',
                                 palette=self.palette, size='distanceinv',edgecolor=ecol, linewidth=lw,vmax=3)
                #https://stackoverflow.com/questions/53437462/how-do-i-remove-an-attribute-from-the-legend-of-a-scatter-plot
                # EXTRACT CURRENT HANDLES AND LABELS
                h, l = ax.get_legend_handles_labels()
                # COLOR LEGEND (FIRST guess at size ITEMS) we don;t want to plot the distanceinc
                huelen = len(self.data.sort_values(by=self.hue, ascending=True)[self.hue].unique())+1
                col_lgd = plt.legend(h[:huelen], l[:huelen], loc='upper left',bbox_to_anchor=(1.05, 1), fancybox=True, shadow=True, ncol=1)
                plt.gca().add_artist(col_lgd)
                ax.set_xlabel('')
                ax.set_ylabel('')
        else:
            if self.range != []:
                plt.xlim(xmin=self.range[0], xmax=self.range[1])
                plt.ylim(ymin=self.range[0], ymax=self.range[1])
                plt.gca().set_aspect("equal")

            if self.categorical:
                legend='brief'
                try:
                    self.data[self.hue] = pd.to_numeric(self.data[self.hue])
                except:
                    legend='full'
                im = sns.scatterplot(x=self.geoX, y=self.geoY, hue=self.hue, data=self.data, alpha=alpha,palette=self.palette
                                     ,edgecolor='aliceblue', linewidth=lw,legend='brief')
                if self.title!='ghost':
                    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)  # Put the legend out of the figure
                else:
                    im.legend_.remove()
            else:
                g = ax.scatter(self.data[self.geoX], self.data[self.geoY], c=self.data[self.hue],
                               cmap=self.palette, edgecolor=ecol, alpha=alpha,linewidth=lw,s=20)
                if self.hue != 'count':
                    cb = plt.colorbar(g)
                    cb.set_label(self.hue)

        ax.set_xlabel(self.geoX)
        ax.set_ylabel(self.geoY)


        count = len(self.data.index)
        title = self.title
        if title == '':
            title += 'Count=' + str(count)
        else:
            title += '\nCount=' + str(count)

        plt.title(title)
        return ''
Example #46
0
# 设置显示数据
names = [i for i in dom.user]
names.reverse()
nums = [i for i in dom['count']]
nums.reverse()
data = pd.Series(nums, index=names)
# 设置图片显示属性,字体及大小
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['font.size'] = 10
plt.rcParams['axes.unicode_minus'] = False
# 设置图片显示属性
fig = plt.figure(figsize=(16, 8), dpi=80)
ax = plt.subplot(1, 1, 1)
ax.patch.set_color('white')
# 设置坐标轴属性
lines = plt.gca()
# 设置坐标轴颜色
lines.spines['right'].set_color('none')
lines.spines['top'].set_color('none')
lines.spines['left'].set_color((64 / 255, 64 / 255, 64 / 255))
lines.spines['bottom'].set_color((64 / 255, 64 / 255, 64 / 255))
# 设置坐标轴刻度
lines.xaxis.set_ticks_position('none')
lines.yaxis.set_ticks_position('none')
# 绘制柱状图,设置柱状图颜色
data.plot.barh(ax=ax,
               width=0.7,
               alpha=0.7,
               color=(153 / 255, 0 / 255, 102 / 255))
# 添加标题,设置字体大小
ax.set_title('歌单贡献UP主 TOP10', fontsize=18, fontweight='light')
Example #47
0
def draw_plot_func(dictionary, n_classes, window_title, plot_title, x_label, output_path, to_show, plot_color, true_p_bar):
    # sort the dictionary by decreasing value, into a list of tuples
    sorted_dic_by_value = sorted(dictionary.items(), key=operator.itemgetter(1))
    # unpacking the list of tuples into two lists
    sorted_keys, sorted_values = zip(*sorted_dic_by_value)
    # 
    if true_p_bar != "":
        """
         Special case to draw in:
            - green -> TP: True Positives (object detected and matches ground-truth)
            - red -> FP: False Positives (object detected but does not match ground-truth)
            - orange -> FN: False Negatives (object not detected but present in the ground-truth)
        """
        fp_sorted = []
        tp_sorted = []
        for key in sorted_keys:
            fp_sorted.append(dictionary[key] - true_p_bar[key])
            tp_sorted.append(true_p_bar[key])
        plt.barh(range(n_classes), fp_sorted, align='center', color='crimson', label='False Positive')
        plt.barh(range(n_classes), tp_sorted, align='center', color='forestgreen', label='True Positive', left=fp_sorted)
        # add legend
        plt.legend(loc='lower right')
        """
         Write number on side of bar
        """
        fig = plt.gcf() # gcf - get current figure
        axes = plt.gca()
        r = fig.canvas.get_renderer()
        for i, val in enumerate(sorted_values):
            fp_val = fp_sorted[i]
            tp_val = tp_sorted[i]
            fp_str_val = " " + str(fp_val)
            tp_str_val = fp_str_val + " " + str(tp_val)
            # trick to paint multicolor with offset:
            # first paint everything and then repaint the first number
            t = plt.text(val, i, tp_str_val, color='forestgreen', va='center', fontweight='bold')
            plt.text(val, i, fp_str_val, color='crimson', va='center', fontweight='bold')
            if i == (len(sorted_values)-1): # largest bar
                adjust_axes(r, t, fig, axes)
    else:
        plt.barh(range(n_classes), sorted_values, color=plot_color)
        """
         Write number on side of bar
        """
        fig = plt.gcf() # gcf - get current figure
        axes = plt.gca()
        r = fig.canvas.get_renderer()
        for i, val in enumerate(sorted_values):
            str_val = " " + str(val) # add a space before
            if val < 1.0:
                str_val = " {0:.2f}".format(val)
            t = plt.text(val, i, str_val, color=plot_color, va='center', fontweight='bold')
            # re-set axes to show number inside the figure
            if i == (len(sorted_values)-1): # largest bar
                adjust_axes(r, t, fig, axes)
    # set window title
    fig.canvas.set_window_title(window_title)
    # write classes in y axis
    tick_font_size = 12
    plt.yticks(range(n_classes), sorted_keys, fontsize=tick_font_size)
    """
     Re-scale height accordingly
    """
    init_height = fig.get_figheight()
    # comput the matrix height in points and inches
    dpi = fig.dpi
    height_pt = n_classes * (tick_font_size * 1.4) # 1.4 (some spacing)
    height_in = height_pt / dpi
    # compute the required figure height 
    top_margin = 0.15 # in percentage of the figure height
    bottom_margin = 0.05 # in percentage of the figure height
    figure_height = height_in / (1 - top_margin - bottom_margin)
    # set new height
    if figure_height > init_height:
        fig.set_figheight(figure_height)

    # set plot title
    plt.title(plot_title, fontsize=14)
    # set axis titles
    # plt.xlabel('classes')
    plt.xlabel(x_label, fontsize='large')
    # adjust size of window
    fig.tight_layout()
    # save the plot
    fig.savefig(output_path)
    # show image
    if to_show:
        plt.show()
    # close the plot
    plt.close()
Example #48
0
    def plotProbability(self,fig, ax):

        # These shold be settings
        contours = 12

        bins=50
        minX,maxX = self.axX[0],self.axX[1]
        minY,maxY = self.axY[0],self.axY[1]

        if minX == maxX:
            minX = min(self.data[self.geoX])
            maxX = max(self.data[self.geoX])
            minY = min(self.data[self.geoY])
            maxY = max(self.data[self.geoY])


        #fig, ax = plt.subplots()
        plt.axis([minX, maxX, minY, maxY])
        if self.hasMatrix:
            xgrid, ygrid, zgrid = self.numpy
        else:
            xgrid, ygrid, zgrid = self.kde2D_scipy(kde,[minX,maxX,minY,maxY], bins)

        xgrid = np.linspace(minX, maxX, bins)
        ygrid = np.linspace(minY,maxY, bins)

        # Don't allow the axis to be on top of your data

        extent = []
        if self.range != []:
            extent = [self.range[0], self.range[1],self.range[0],self.range[1]]
            plt.gca().set_aspect("equal")
            print(extent)

        ax.grid(True, which='major', axis='both', linestyle='-', color=(0.5, 0.5, 0.5), alpha=0.1)

        if self.centre:
            self.data[self.hue + '2'] = self.data[self.hue] ** 2
            self.data = self.data.sort_values(by=self.hue + '2', ascending=True)
            self.vmax = max(self.data[self.hue].max(), -1 * self.data[self.hue].min())
            self.vmin = self.vmax * -1

        alpha=1
        if self.title=='ghost':
            alpha = 0.4
            #self.palette = 'seismic'

        if self.vmin == self.vmax:
            im = plt.pcolormesh(xgrid, ygrid, zgrid, shading='gouraud', cmap=self.palette,alpha=alpha)
            if self.range == []:
                cs = plt.contour(xgrid, ygrid, zgrid, contours, colors='0.7', linewidths=0.4,alpha=alpha)
            else:
                cs = plt.contour(xgrid, ygrid, zgrid, contours, colors='0.7', linewidths=0.4, alpha=alpha,extent=extent)

        else:
            im = plt.pcolormesh(xgrid, ygrid, zgrid, shading='gouraud', cmap=self.palette, vmin=self.vmin, vmax=self.vmax,alpha=alpha)
            if self.range == []:
                cs = plt.contour(xgrid, ygrid, zgrid, contours, colors='tab:purple', linewidths=0.05,alpha=alpha)
            else:
                cs = plt.contour(xgrid, ygrid, zgrid, contours, colors='tab:purple', linewidths=0.05, alpha=alpha,extent=extent)

        ax.set_axisbelow(True)
        cbar = fig.colorbar(im, ax=ax)
        cbar.remove()


        ax.set_xlabel(self.geoX)
        ax.set_ylabel(self.geoY)

        if self.hasMatrix:
            if self.title == '':
                title = 'Difference Image'
            else:
                title = self.title + '\nDifference Image'
        else:
            count = len(self.data.index)
            title = self.title
            if title == '':
                title += 'Count=' + str(count)
            else:
                title += '\nCount=' + str(count)

        plt.title(title)
        return ''
    'Ldotmax': 5,
    'Ldotmin': -5,
    'Lmax': 1.5,
    'Lmin': 0.5,
    'g': g,
    'plot': False,
    'save_fig': False,
    'show_fig': False,
    'save_data': False,
}


# Find the trajectory (time window = 0.2, the same as finite-time d) for each point defined in the phase space

fig = plt.figure(figsize=[12, 8])
plt.gca().set_aspect('equal', adjustable='box')
plt.grid()

for i in range(x.shape[0]):
    print(f'i = {i}')
    for j in range(y.shape[1]):
        phi = x[i, j] * np.ones(1)
        dphi = y[i, j] * np.ones(1)

        wave = {
            'phi': phi,
            'dphi': dphi,
        }

        # assemble pendulum class
        vary_length_pendulum = execute_pendulum_control(wave, attributes)
def test_mirror_motion():
    '''
    Diagnostic code to call the particle pushing part of the hybrid and check
    that its solving ok. Runs with zero background E field and B field defined
    by the constant background field specified in the parameter script.
    '''
    
    for DT_multiplier in [1.0]:
        print('Doing DTx{}'.format(DT_multiplier))
        max_rev = 25000
        init_pos, init_vel, init_pitch, time, pos_history, rL_history, vel_history, mag_history, DT, max_t = do_particle_run(max_rev=max_rev)
        Np = init_pitch.shape[0]  

        # Calculate parameter timeseries using recorded values
        init_vperp = np.sqrt(init_vel[1] ** 2 + init_vel[2] ** 2)
        init_vpara = init_vel[0]
        init_KE    = 0.5 * mp * init_vel ** 2
        init_mu    = 0.5 * mp * init_vperp ** 2 / B_eq
        
        vel_perp      = np.sqrt(vel_history[:, 1] ** 2 + vel_history[:, 2] ** 2)
        vel_para      = vel_history[:, 0]
        vel_magnitude = np.sqrt(vel_history[:, 0] ** 2 + vel_history[:, 1] ** 2 + vel_history[:, 2] ** 2)
        
        B_para      = mag_history[:, 0]
        B_perp      = np.sqrt(mag_history[:, 1] ** 2 + mag_history[:, 2] ** 2)
        B_magnitude = np.sqrt(mag_history[:, 0] ** 2 + mag_history[:, 1] ** 2 + mag_history[:, 2] ** 2)
        
        KE_perp = 0.5 * mp * (vel_history[:, 1] ** 2 + vel_history[:, 2] ** 2)
        KE_para = 0.5 * mp *  vel_history[:, 0] ** 2
        KE_tot  = KE_para + KE_perp
        
        pitch_angle = np.abs(np.arctan(vel_perp/ vel_para) * 180. / np.pi)
        #pdb.set_trace()
        mu  = KE_perp / B_magnitude
        mu_normal = mu / init_mu
        
# =============================================================================
#         ## Let's check out rL variation ##
#         fig, axes = plt.subplots(5, sharex=True)
#     
#         # Basic mu plot with v_perp, |B| also plotted
#         for ii in range(Np):
#             axes[0].plot(time, mu_normal[:, ii]       , lw=0.8, label=r'DT $\times$ %5.2f' % DT_multiplier)
#             axes[1].plot(time, vel_perp[:, ii]   *1e-3, lw=0.8)
#             axes[2].plot(time, B_para[:, ii]*1e9 , lw=0.8, label='$B_\parallel$')
#             axes[2].plot(time, B_perp[:, ii]*1e11*0.5 , lw=0.8, label='$B_\perp \\times 50$')
#             axes[3].plot(time, pos_history[:, ii]*1e-3, lw=0.8)
#             axes[4].plot(time, rL_history[:, ii]*1e-3 , lw=0.8)
#         
#         axes[0].set_title(r'Particle First Invariant ($\mu$) and other Parameters with varying DT :: $\alpha_{eq}$ = %4.1f$^\circ$ :: $|v| = %.1fv_A$' % (init_pitch[0] * 180. / np.pi, v_mag/va))
#         axes[0].legend(loc='lower right', ncol=1)
#         axes[2].legend()
#         axes[0].set_ylabel('$\\frac{\mu}{\mu_0}$', rotation=0, labelpad=30, fontsize=20)
#         axes[1].set_ylabel('$v_\perp$\n(km/s)', rotation=0, labelpad=20)
#         axes[2].set_ylabel('$B$\n(nT)', rotation=0, labelpad=20)
#         axes[3].set_ylabel('$x$\n(km)', rotation=0, labelpad=20)
#         axes[4].set_ylabel('$r_L$\n(km)', rotation=0, labelpad=20)
#         
#         for ax in axes:
#             ax.set_xlim(0, time[-1])
#             ax.set_xlabel('Time (s)')
#             ax.get_yaxis().get_major_formatter().set_useOffset(False)
#         fig.align_ylabels()
# =============================================================================
    
    if True:
        fig, axes = plt.subplots(3, sharex=True)
        
        # Basic mu plot with v_perp, |B| also plotted
        for ii in range(Np):
            axes[0].plot(time, mu[:, ii]*1e10       , lw=0.8, label=r'DT $\times$ %5.2f' % DT_multiplier)
            axes[1].plot(time, vel_perp[:, ii]   *1e-3, lw=0.8)
            axes[2].plot(time, B_magnitude[:, ii]*1e9 , lw=0.8)
            #axes[3].plot(time, pos_history[:, ii]*1e-3, lw=0.8)
            #axes[4].plot(time, pitch_angle[:, ii]     , lw=0.8)
        
        axes[0].set_title(r'Particle First Invariant ($\mu$) and other Parameters with varying DT :: $\alpha_{eq}$ = %4.1f$^\circ$ :: $|v| = 10v_A$' % (init_pitch[0] * 180. / np.pi))
        axes[0].legend(loc='lower right', ncol=1)
        axes[0].set_ylabel('$\\frac{\mu}{\mu_0}$', rotation=0, labelpad=30, fontsize=20)
        axes[1].set_ylabel('$v_\perp$\n(km/s)', rotation=0, labelpad=20)
        axes[2].set_ylabel('$|B|$\n(nT)', rotation=0, labelpad=20)
        #axes[3].set_ylabel('$x$\n(km)', rotation=0, labelpad=20)
        #axes[4].set_ylabel('$\\alpha$\n(deg.)', rotation=0, labelpad=20)
        
        for ax in axes:
            ax.set_xlim(0, time[-1])
            ax.set_xlabel('Time (s)')
            ax.get_yaxis().get_major_formatter().set_useOffset(False)
        fig.align_ylabels()
            
        if False:
            ## Plots velocity/mag timeseries ##
            fig, axes = plt.subplots(2, sharex=True)
            
            axes[0].plot(time, vel_history[:, 0]* 1e-3, label='vx')
            axes[0].plot(time, vel_history[:, 1]* 1e-3, label='vy')
            axes[0].plot(time, vel_perp         * 1e-3, label='v_perp')
            axes[0].plot(time, vel_para*1e-3          , label='v_para')
            
            axes[0].set_ylabel('v (km)')
            axes[0].set_xlabel('t (s)')
            axes[0].set_title(r'Velocity/Magnetic Field at Particle, v0 = [%4.1f, %4.1f, %4.1f]km/s, $\alpha_L$=%4.1f deg, $\alpha_{p,eq}$=%4.1f deg' % (init_vel[0, 0], init_vel[1, 0], init_vel[2, 0], loss_cone, init_pitch))
            #axes[0].set_xlim(0, None)
            axes[0].legend()
            
            axes[1].plot(time, B_magnitude,       label='|B0|')
            #axes[1].plot(time, mag_history[:, 0], label='B0x')
            #axes[1].plot(time, mag_history[:, 1], label='B0y')
            #axes[1].plot(time, mag_history[:, 2], label='B0z')
            axes[1].legend()
            axes[1].set_ylabel('t (s)')
            axes[1].set_ylabel('B (nT)')
            axes[1].set_xlim(0, None)
            
            
        if False:
            # Expression for B/grad(B) to test if this ratio is much less than rL
            root   = np.sqrt((a*rL_history*pos_history) ** 2 + 2*a*pos_history**2 + a**2*pos_history**4)
            top    = 2*B_eq*rL_history*a**2*pos_history**2
            grad_B = top/root 
            rhs    = q*B_magnitude**2 / (mp * vel_perp)
        
            ## Plots position/velocity component timeseries ##
            fig, axes = plt.subplots(4, sharex=True)
            axes[0].set_title(r'Particle Positions/Velocities by initial Pitch Angle, $\alpha$ : %s' % run)
    
            for ii in range(Np):
                axes[0].plot(time, pos_history[:, ii]*1e-3, label=r'$\alpha$ = %4.1f$^\circ$' % (init_pitch[ii] * 180 / np.pi))
                axes[1].plot(time, vel_para[:, ii]/va)
                axes[2].plot(time, vel_perp[:, ii]/va)
                axes[3].plot(time, mirror_force[:, ii])
                
            axes[0].legend(loc=2, ncol=5)
    
            axes[0].axhline(xmin*1e-3, color='k', ls=':')
            axes[0].axhline(xmax*1e-3, color='k', ls=':')
    
            axes[0].set_ylabel(r'x (km)')
            axes[1].set_ylabel(r'$v_\parallel$ ($v_{A,eq}^{-1}$)')       
            axes[2].set_ylabel(r'$v_\perp$ ($v_{A,eq}^{-1}$)')
            axes[3].set_ylabel(r'$f_\parallel$)')
            
            for ax in axes:
                ax.set_xlim(0, time[-1])
                ax.set_xlabel('t (s)')
                
                
                
        if False:
            # Plot gyromotion of particle vx vs. vy
            plt.title('Particle gyromotion: {} gyroperiods ({:.1f}s)'.format(max_rev, max_t))
            plt.scatter(vel_history[:, 0], vel_history[:, 1], c=time)
            plt.colorbar().set_label('Time (s)')
            plt.ylabel('vx (km/s)')
            plt.xlabel('vy (km/s)')
            plt.axis('equal')
            
        if False:
            ## Plot parallel and perpendicular kinetic energies/velocities
            plt.figure()
            plt.title('Kinetic energy of single particle: Full Bottle')
            plt.plot(time, KE_para/q, c='b', label=r'$KE_\parallel$')
            plt.plot(time, KE_perp/q, c='r', label=r'$KE_\perp$')
            plt.plot(time, KE_tot /q, c='k', label=r'$KE_{total}$')
            plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)
            plt.gca().get_yaxis().get_major_formatter().set_scientific(False)
            plt.ylabel('Energy (eV)')
            plt.xlabel('Time (s)')
            plt.legend()
        
        if False:           
            percent = abs(KE_tot - init_KE.sum()) / init_KE.sum() * 100. 
    
            plt.figure()
            plt.title('Total kinetic energy change')
    
            plt.plot(time, percent*1e12)
            plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)
            plt.gca().get_yaxis().get_major_formatter().set_scientific(False)
            plt.xlim(0, time[-1])
            plt.ylabel(r'Percent change ($\times 10^{-12}$)')
            plt.xlabel('Time (s)')
            
        if False:
            # Plots vx, v_perp vs. x  
            fig, ax = plt.subplots(1)
            ax.set_title(r'Velocity vs. Space: v0 = [%4.1f, %4.1f, %4.1f]$v_{A,eq}^{-1}$ : %d gyroperiods (%5.2fs)' % (init_vel[0, 0], init_vel[1, 0], init_vel[2, 0], max_rev, max_t))
            ax.plot(pos_history*1e-3, vel_history[:, 2]*1e-3, c='b', label=r'$v_\parallel$')
            ax.plot(pos_history*1e-3, vel_perp,               c='r', label=r'$v_\perp$')
            ax.set_xlabel('x (km)')
            ax.set_ylabel('v (km/s)')
            ax.set_xlim(xmin*1e-3, xmax*1e-3)
            ax.legend()
    
        if False:
            # Invariant and parameters vs. x
            fig, axes = plt.subplots(3, sharex=True)
            axes[0].plot(pos_history*1e-3, mu*1e10)
            axes[0].set_title(r'First Invariant $\mu$ for single trapped particle, v0 = [%3.1f, %3.1f, %3.1f]$v_{A,eq}^{-1}$, $\alpha_L$=%4.1f deg, $\alpha_{p,eq}$=%4.1f deg, $t_{max} = %5.0fs$' % (init_vel[0, 0]/va, init_vel[1, 0]/va, init_vel[2, 0]/va, loss_cone, init_pitch, max_t))
            axes[0].set_ylabel(r'$\mu (\times 10^{-10})$', rotation=0, labelpad=20)
            axes[0].get_yaxis().get_major_formatter().set_useOffset(False)
            axes[0].axhline(init_mu*1e10, c='k', ls=':')
            
            axes[1].plot(pos_history*1e-3, KE_perp/q)
            axes[1].set_ylabel(r'$KE_\perp (eV)$', rotation=0, labelpad=20)
    
            axes[2].plot(pos_history*1e-3, B_magnitude*1e9)
            axes[2].set_ylabel(r'$|B|$ (nT)', rotation=0, labelpad=20)
            
            axes[2].set_xlabel('Position (km)')
            axes[2].set_xlim(xmin*1e-3, xmax*1e-3)
    return
Example #51
0
    def new_state(self):
        """ layout editor state machine

        Parameters
        ----------


        'l'  : select activelayer
        'i'  : back to init state
        'j'  : vertical and horizontal scaling
        'e'  : edit segment
        'b'  : edit segment keyboard
        'CTRL + t'  : translate  structure
        'h'  : add subsegment
        'd |Del'  : delete subsegment
        'r |F5'  : refresh
        'o'  : toggle overlay (<> CP mode)
               set origin (CP mode) 
        'm'  : toggle mode (point or segment)
        'n'  : toggle node label display 
        'z'  : change display parameters
        'CTRL+q'  : quit
        'x |CTRL+s'  : save .str2 and .ini file
        'w'  : display all layers
        'v'  : flip layout w.r.t y axis
        'f'  : toggle points nodes display
        'g'  : toggle segments nodes display
        '='  : increment layer 
        '$'  : decrement layer 
        """
        fig = plt.gcf()
        ax  = plt.gca()
        sl = self.L.sl
        cold = pyu.coldict()
        #print "In State ",self.state
        #print "In Event ",self.evt

                #
        # flip layout in y
        #
        if self.evt == ',':
            for k in self.ddoc.keys():
                print k,self.ddoc[k]

        if self.evt == 'v':
            for n in self.L.Gs.pos:
                self.L.Gs.pos[n]=(self.L.Gs.pos[n][0],-self.L.Gs.pos[n][1])
            self.update_state()
            return
        #
        # translation of layout (open a box)
        #
        # if self.evt == 't' :
        #     offx,offy = offsetbox()
        #     for n in self.L.Gs.pos:
        #         self.L.Gs.pos[n]=(self.L.Gs.pos[n][0]+offx,self.L.Gs.pos[n][1]+offy)
        #     self.update_state()
        #     return

        if self.evt=='escape':
            self.state='Init'
            self.update_state()
            self.fig.canvas.draw()
            return


        if self.evt=='ctrl+z':
            self.bundo=True
            print len(self.L.Gs)
            if len (self.undoGs) >2:
                oGs=self.undoGs.pop(-1)
                oGs=self.undoGs.pop(-1)
                self.L.Gs=oGs
                self.L.g2npy()
            self.update_state()
            self.bundo=False
            return

        if self.evt=='t':
            if 'SM' in self.state:
                self.update_state()
                # fig=plt.gcf()
                # ax=plt.gca()
                if self.selected == 'pt':
                    self.plotselptseg(self.selectseg,color='r')
                    PP=self.L.pt[:,self.L.tahe[:,self.L.tgs[self.selectseg]]]
                    if PP.shape[-1]!=0:
                        self.fig,self.ax=plu.displot(PP[:,0],PP[:,1],fig=self.fig,ax=self.ax,color='r',linewidth=3,alpha=0.4)
                        plt.draw()
                    self.selected='seg'
                    self.state='SMS'
                else: 
                    self.fig,self.ax= self.plotselptseg(self.selectpt)
                    self.selected='pt'
                    self.state='SMP'
                self.ax.title.set_text(self.statename[self.state])
                # self.update_state()

        if self.evt == '3':
            self.L._show3()
            return

        # Choose layers to visualized
        #
        if self.evt == 'l':
            listchoices = self.L.name.keys()
            self.L.display['layers'] = multchoicebox('message',
                                                     'titre', listchoices)
            self.state = 'Init'
            self.update_state()
            return
        #
        # 'f' toggle points nodes display
        #
        if self.evt=='f':
            self.L.display['nodes'] = not self.L.display['nodes']
            print self.L.display['nodes']
            self.update_state()
            return

        #
        # 'g' toggle segment nodes dislay
        #
        if self.evt=='g':
            self.L.display['ednodes'] = not self.L.display['ednodes']
            print self.L.display['ednodes']
            self.update_state()
            return

        #
        # '=' Increment layer
        #
        if self.evt=='=':
            N = len(self.L.display['layerset'])
            index = self.L.display['layerset'].index(self.L.display['activelayer'])
            self.L.display['activelayer'] = self.L.display['layerset'][(index+1) % N]
            self.current_layer = self.L.display['activelayer']
            print self.current_layer
            self.update_state()
            return

        #
        # '=' Decrement layer
        #
        if self.evt=='$':
            N = len(self.L.display['layerset'])
            index = self.L.display['layerset'].index(self.L.display['activelayer'])
            self.L.display['activelayer'] = self.L.display['layerset'][(index-1) % N]
            self.current_layer = self.L.display['activelayer']
            print self.current_layer
            self.update_state()
            return
        #
        # 'i' : Back to init state 
        #
        if self.evt == 'i':
            self.state = 'Init'
            self.update_state()
            return

        #
        #  'e'
        #       if state == Init
        #           egalize points coordinates
        #
        #       if state == SS
        #           edit segment properties
        #
        if self.evt == 'e':
            if (self.state == 'Init'):
                #
                # averaging one point coordinate along the smallest dimension
                #
                x1 = self.ax.get_xbound()
                y1 = self.ax.get_ybound()
                # get node list and edge list
                ndlist, edlist = self.L.get_zone([x1[0],x1[1],y1[0],y1[1]])
                for k,nd in enumerate(ndlist):
                    try:
                        tp = np.vstack((tp,np.array(self.L.Gs.pos[nd])))
                    except:
                        tp = np.array(self.L.Gs.pos[nd])
                mtp = np.sum(tp,axis=0)/(k+1)
                stp = np.sqrt(np.sum((tp-mtp)*(tp-mtp),axis=0)/(k+1))
                # if the standard deviation is lower than 10cm
                # averaging coordinates along the shortest axis
                if min(stp) < 0.10:
                    ind = np.where(stp==min(stp))[0][0]
                    for nd in ndlist:
                        x = self.L.Gs.pos[nd][0]
                        y = self.L.Gs.pos[nd][1]
                        if ind ==0:
                            self.L.Gs.pos[nd]=(mtp[0],y)
                        if ind ==1:
                            self.L.Gs.pos[nd]=(x,mtp[1])
                    plt.axis('tight')
                    self.fig,self.ax = self.show(self.fig,self.ax,clear=True)
                    self.update_state()
                return()

            if (self.state == 'SS') | (self.state =='SSS'):
                self.L.edit_segment(self.selected_edge1)
                self.state = 'Init'
                self.update_state()
                return

            if self.state == 'SP1':
                self.L.edit_point(self.selected_pt1)
                self.state = 'Init'
                self.update_state()
                return
            if self.state == 'SMS':
                outdata=self.L.edit_segment(self.selectseg[0])
                [self.L.edit_segment(s,outdata=outdata,gui=False) for s in self.selectseg]
                self.update_state()
                return


        #
        # "b" : enter a segment node value with keyboard
        #
        if self.evt == 'b':
            if self.state == 'Init':
                self.nsel = eval(raw_input("seg number :"))
                #self.L.edit_segment(nseg)
                self.state='SS'
                self.update_state()
                return

        #
        # j : vertical and horizontal scaling (Init)
        #
        if self.evt == 'j':
            if self.state == 'Init':
                vscale = eval(enterbox('enter vscale',argDefaultText='1.0'))
                hscale = eval(enterbox('enter hscale',argDefaultText='1.0'))
                for n in self.L.Gs.pos:
                    self.L.Gs.pos[n]=(self.L.Gs.pos[n][0]*hscale,self.L.Gs.pos[n][1]*vscale)
                plt.axis('tight')
                self.fig,self.ax = self.show(self.fig,self.ax,clear=True)
                self.update_state()
                return

        # Init
        # h : horizontal scaling factor
        #    add subsegment (SS)
        #
        if self.evt == 'h':
#            if self.state == 'Init':
#                hscale = eval(raw_input("horizontal scaling factor : "))
#                for n in self.L.Gs.pos:
#                    self.L.Gs.pos[n]=(self.L.Gs.pos[n][0]*hscale,self.L.Gs.pos[n][1])
#                plt.axis('tight')
#                fig,ax = self.show(fig,ax,clear=True)
#                self.update_state()
#                return()

            if self.state == 'SS':
                result = self.L.add_subseg(self.selected_edge1,self.current_layer)
                if result:
                    self.state = 'SSS'
                else :
                    self.state = 'Init'
                self.update_state()
                return
        #
        # d : delete
        #
        if self.evt == 'd' or self.evt =='delete':
            if  self.state == 'SP1':
                self.state = 'Init'
                self.L.del_points(self.selected_pt1)
                self.update_state()
                return

            if self.state == 'SS':
                self.L.del_segment(self.selected_edge1)
                self.state = 'Init'
                self.update_state()
                return

            if self.state == 'SSS':
                self.L.del_subseg(self.selected_edge1)
                self.state = 'Init'
                self.update_state()
                return

            if self.state=='SMP':
                # get boundary of the region 
                if hasattr(self,'selectpt'):

                    ptlist = self.selectpt
                    self.selectpt=[]
                    self.selectseg=[]
                    self.L.del_points(ptlist)
                    self.state = 'Init'
                    self.update_state()
                    return
                else :
                    print 'no selected region'

            if self.state=='SMS':
                seglist = self.selectseg
                self.selectpt=[]
                self.selectseg=[]
                self.L.del_segment(seglist)
                self.state = 'Init'
                self.update_state()
                return
            else :
                print 'no selected region'
        #
        # r : Refresh
        #
        if self.evt == 'r' or self.evt == 'f5':
            #plt.axis('tight')
            plt.axis(self.L.display['box'])
            self.fig,self.ax = self.show(self.fig,self.ax,clear=True)
            self.state = 'Init'
            self.update_state()
            return

        #
        # o : Toggle overlay
        #
        if self.evt == 'o' and not self.ctrl_is_held:
            self.state='Init'
            self.update_state()
            if self.L.display['overlay']:
                self.L.display['overlay'] = False
                self.update_state()
            else:
                self.L.display['overlay'] = True
                self.update_state()
            return

        if self.evt == 'o' :
            self.set_origin = True

        #
        # F2 : Create point
        #
        if self.evt == 'f2':
            self.state = "CP"
            self.update_state()
            return
        #
        # m : Toggle mode edition Point | Segment
        #
        if self.evt == 'm':
            if self.state == "Init":
                self.state = "CP"
            elif self.state == "CP":
                self.state = "Init"
            self.update_state()
            return
        #
        # 'z' : change display parameters
        #
        if self.evt == 'z':
            self.L.displaygui()
            self.fig,self.ax = self.show(fig=self.fig,ax=self.ax,clear=True)
            return
        #
        # 'q' : quit interactive mode
        #
        # if self.evt == 'q':
        #     plt.rcParams.update(self.rcconf)
        #     fig.canvas.mpl_disconnect(self.L.cid1)
        #     fig.canvas.mpl_disconnect(self.L.cid2)
        #     return

        if self.evt == 'ctrl+q':
            plt.rcParams.update(self.rcconf)
            self.fig.canvas.mpl_disconnect(self.L.cid1)
            self.fig.canvas.mpl_disconnect(self.L.cid2)
            plt.close()
            return

        #
        # 'x' save structure
        #
        if self.evt == 'x' or self.evt =='ctrl+s':
            racine, ext = os.path.splitext(self.L.filename)
            filename = racine + '.str2'
            fileini = racine + '.ini'

            # Commented because ss_ce not updated 
            #self.L.savestr2(filename)

            self.L.saveini(fileini)
            print "structure saved in ", filename
            print "structure saved in ", fileini
            return
        #
        # 'n' : toggle node label display
        #
        if self.evt == 'n':
            self.L.display['ndlabel'] = not self.L.display['ndlabel']
            self.L.display['edlabel'] = not self.L.display['edlabel']
            print self.L.display['activelayer']
            self.fig,ax = self.show(fig=self.fig,ax=self.ax,clear=True)
            self.fig.canvas.draw()
            return
        #
        # "w" : display all layers
        #
        if self.evt == 'w':
        # display all layer
            self.L.display['activelayer'] = self.L.name.keys()
            print self.L.display['activelayer']
            self.fig,self.ax = self.show(fig=self.fig,ax=self.ax,clear=True)
            return self.fig,self.ax
        #
        # Left clic and selected node is a point
        #
        if (self.evt == 'lclic') & (self.nsel < 0):

        #
        # select point 1 : Init -> SP1
        #
            if self.state=='Init':
                # yellow point 
                self.state = 'SP1'
                self.update_state()
                return
        #
        # select point 2 : SP1 --> SP2
        #

            if self.state=='SP1':
                if self.nsel != self.selected_pt1:
                    # green point 
                    self.state = 'SP2'
                    self.update_state()
                    return
                else:
                    self.state = 'Init'
                    # yellow point 
                    self.update_state()
                    return
        #
        # Create point on selected segment orthogonaly to segment starting in
        # selected point
        # 
        # Not finished 
        #
            if self.state=='SS':
                # get the connection of the selected segment
                connect = self.L.Gs.node[self.selected_edge1]['connect']
                if (self.nsel != connect[0]) & (self.nsel != connect[1]): 
                   self.L.add_nfpe(self.nsel,self.nsel,self.selected_edge1,self.selected_edge2)
                   pass

        #
        # Left clic and selected node is a segment
        #

        if (self.evt == 'lclic') & (self.nsel > 0):
            if self.state=='Init':
                self.state = 'SS'
                self.update_state()
                return

            if self.state=='SS':
                self.nsel = self.selected_edge1
                segdico = self.L.Gs.node[self.nsel]
                if 'ss_name' in segdico:
                    self.state = 'SSS'
                else:
                    self.state = 'CPS'
                self.update_state()
                return
        #
        # Right clic and selected node is a point
        #

        if (self.evt == 'rclic') & (self.nsel < 0):
            if self.state=='SP1':
                if self.nsel==self.selected_pt1:
                    self.state = 'Init'
                    self.update_state()
                    return
        #
        # Right clic and selected node is a segment
        #

        if (self.evt == 'rclic') & (self.nsel > 0):
            if self.state=='SS':
                self.state = 'Init'
                self.update_state()
                return

            if self.state=='SSS':
                self.state = 'SS'
                self.update_state()
                return

            if self.state == 'CP':
            # create point on edge
                self.state = 'CPS'
                self.update_state()
                return

            if (self.state == 'CPS') & (self.nsel!= self.selected_edge1):
            # create point on edge
                self.state = 'CPSS'
                self.update_state()
                return
        #
        # Left clic
        #
        if (self.evt == 'lclic') and not (self.shift_is_held or self.alt_is_held or self.ctrl_is_held ):
            # add free node
            # or set origin
            if self.state == 'CP':
                if self.set_origin:
                    offx = self.ptsel[0]
                    offy = self.ptsel[1]
                    print offx,offy
                    xmin,xmax,ymin,ymax = self.L.display['box']
                    self.L.display['box'] = [xmin-offx,xmax-offx,ymin-offy,ymax-offy]
                    self.set_origin=False
                    self.set_x=True
                    plt.axis('tight')
                    self.fig,self.ax = self.show(self.fig,self.ax,clear=True)
                    self.update_state()
                    return
                if self.set_x:
                    offx = self.ptsel[0]
                    val  = eval(enterbox('enter x value'))
                    ratio = val/offx
                    print ratio
                    xmin,xmax,ymin,ymax = self.L.display['box']
                    self.L.display['box'] = [ratio*xmin,ratio*xmax,ymin,ymax]
                    self.set_x=False
                    self.set_y=True
                    plt.axis('tight')
                    self.fig,self.ax = self.show(self.fig,self.ax,clear=True)
                    self.update_state()
                    return
                if self.set_y:
                    offx = self.ptsel[1]
                    val  = eval(enterbox('enter y value'))
                    ratio = val/offx
                    print ratio
                    xmin,xmax,ymin,ymax = self.L.display['box']
                    self.L.display['box'] = [xmin,xmax,ratio*ymin,ratio*ymax]
                    self.set_y=False
                    plt.axis('tight')
                    self.fig,self.ax = self.show(self.fig,self.ax,clear=True)
                    self.update_state()
                    return
                else:
                    self.L.add_fnod(tuple(self.ptsel))
                    self.pt_previous = self.ptsel
                    self.update_state()

                return

            if self.state == 'SP2':

                ta = self.selected_pt1
                he = self.selected_pt2

                segexist = self.L.isseg(ta,he)
                print segexist
                # if segment do not already exist, create it
                if not segexist: 
                    self.nsel  = self.L.add_segment(ta, he,name=self.current_layer)
                else:
                    print "segment ("+str(ta)+","+str(he)+") already exists"
                self.L.g2npy()
                self.state = 'Init'
                self.update_state()
                return

            # create point on segment
            if self.state == 'CPS':
                pt_new = geu.ptonseg(self.pta1, self.phe1, self.ptsel)
                pd1 = pt_new - self.pta1
                pd2 = self.phe1 - self.pta1
                alpha = np.sqrt(np.dot(pd1, pd1)) / np.sqrt(np.dot(pd2, pd2))
                if (pt_new != []):
                    # calculate alpha
                    self.L.add_pons(self.selected_edge1, 1. - alpha)
                    self.current_layer = self.L.Gs.node[self.selected_edge1]['name']
                    self.state = 'Init'
                self.update_state()
                return

        #
        # Right Clic event
        #
        if (self.evt == 'rclic') or (self.evt == 'lclic' and self.ctrl_is_held ):
            if self.state == 'CP':
                try:
                    self.ptsel[0] = self.pt_previous[0]
                    self.L.add_fnod(tuple(self.ptsel))
                    self.pt_previous = self.ptsel
                    self.update_state()
                    return
                except:
                    return

            if self.state=='SP2':
                if self.nsel == self.selected_pt1:
                    self.p1[0].set_visible(False)
                    self.p2[0].set_visible(False)
                    self.nsel = self.selected_pt2
                    self.state = 'SP1'
                    self.update_state()
                    return
                if self.nsel == self.selected_pt2:
                    self.p1[0].set_visible(False)
                    self.p2[0].set_visible(False)
                    self.nsel = self.selected_pt1
                    self.state = 'SP1'
                    self.update_state()
                    return
        #
        # right click : back to SS from CPS
        #
            if self.state == 'CPS':
                self.state = 'SS'
                self.update_state()
                return
        #
        # right click : back to CPS from CPSS
        #
            if self.state == 'CPSS':
                self.state = 'CPS'
                self.update_state(self.fig,self.ax)
                return
        #
        # Center Clic event
        #
        if (self.evt == 'cclic') or (self.evt == 'lclic' and self.shift_is_held ):
            if self.state == 'CP':
                try:
                    self.ptsel[1] = self.pt_previous[1]
                    self.L.add_fnod(tuple(self.ptsel))
                    self.pt_previous = self.ptsel
                    self.update_state()
                    return
                except:
                    return
        #
        # Left clic and selected node is a point
        #


        def point_select_callback(eclick, erelease):
            'eclick and erelease are the press and release events'
            self.update_state()
            if not (self.shift_is_held or self.ctrl_is_held):
                self.selectpt=[]
                self.selectseg=[]
            x1, y1 = eclick.xdata, eclick.ydata
            x2, y2 = erelease.xdata, erelease.ydata

            # print x1,x2,y1,y2
            if x1>x2:
                x1,x2=x2,x1
            if y1>y2:
                y1,y2=y2,y1
            
            
            # try:
            selectpt,selectseg = self.L.get_zone([x1,x2,y1,y2])

            if not self.ctrl_is_held:
                self.selectpt.extend(selectpt)
                self.selectseg.extend(selectseg)
                self.selectseg=filter(lambda x: self.L.Gs.node[x]['connect'][0] in self.selectpt
                                 and self.L.Gs.node[x]['connect'][1] in self.selectpt,
                                 self.selectseg)

                self.selectpt=np.unique(self.selectpt).tolist()
                self.selectseg=np.unique(self.selectseg).tolist()
            else: 
                [self.selectpt.pop(self.selectpt.index(x)) for x in selectpt if x in self.selectpt]
                [self.selectseg.pop(self.selectseg.index(x)) for x in selectseg if x in self.selectseg]
            # except:
            #     print 'empty selection'
            print self.selectpt,self.selectseg
            self.plotselptseg(self.selectpt)
            self.selected='pt'
            print self.state
            
                

        def toggle_selector(event):
            if toggle_selector.RS.active:
                toggle_selector.RS.set_active(False)
            if not toggle_selector.RS.active:
                toggle_selector.RS.set_active(True)
        
        if self.evt == 'f1':
            #avoid conflict between zoom and selection 
            # fm=plt.get_current_fig_manager()
            # if fm.toolbar._active == 'PAN':
            #     fm.toolbar.pan()
            # if fm.toolbar._active == 'ZOOM':
            #     fm.toolbar.zoom()

            self.state='SMP'
            toggle_selector.RS = RectangleSelector(self.ax, point_select_callback,
                                               drawtype='box', useblit=True,
                                               button=[1,3], # don't use middle button
                                               minspanx=5, minspany=5,
                                               spancoords='pixels')
            self.selector = toggle_selector.RS
            self.update_state()

        if self.evt == 'f9':
            print self.selectpt, self.selectseg
Example #52
0

#===============================================================================

# plot the curve for the 0 IPTG cultures
plt.figure(figsize=(7, 7))
binding_energy = df.binding_energy.unique()
for i, op in enumerate(operator):
    repressor_array = np.logspace(0, 3, 200)
    fc_theory = 1 / (1 +
                     2 * repressor_array / 5E6 * np.exp(-binding_energy[i]))

    plt.plot(repressor_array, fc_theory)

#reset color cycle to match colors
plt.gca().set_color_cycle(None)

#no_iptg = df.groupby('operator').get_group(0)
for op in operator:
    plt.plot(df[df.operator == op].repressors, df[df.operator == op].fold_change_A, \
     marker='o', linewidth=0, label = op)
plt.xscale('log')
plt.yscale('log')
plt.xlabel('repressor copy number')
plt.ylabel('fold-change')
plt.legend(loc='upper right')
plt.tight_layout()
plt.savefig('output/' + 'lacI_titration_ctrl.png')

# Produce a second plot showing the cultures on a semi-log scale.
Example #53
0
    def get_animation_nb(self, s=300., fs=20., prop_type='real', figsize=None):
        '''
        Get time evolution animation for iPython notebooks.

        :param s: Default value 300. Circle shape.
        :param fs: Default value 20. Fontsize.

        :returns:
           * **ani** -- Animation.
        '''
        '''
        Get time evolution animation.

        :param s: Default value 300. Circle size.
        :param fs: Default value 20. Fontsize.
        :param figsize: Tuple. Default value None. Figsize.
        :param prop_type: Default value None. Figsize.

        :returns:
          * **ani** -- Animation.
        '''
        error_handling.empty_ndarray(self.prop, 'get_propagation or get_pumping')
        error_handling.positive_real(s, 's')
        error_handling.positive_real(fs, 'fs')
        error_handling.prop_type(prop_type)
        error_handling.tuple_2elem(figsize, 'figsize')
        if prop_type == 'real' or prop_type == 'imag':
            color = self.prop.real
            max_val = max(np.max(color[:, -1]), -np.min(color[:, -1]))
            ticks = [-max_val, max_val]
            cmap = 'seismic'
        else:
            color = np.abs(self.prop) ** 2
            ticks = [0., np.max(color)]
            cmap = 'Reds'
        fig = plt.figure()
        ax = plt.axes(xlim=(np.min(self.lat.coor['x']-.5), np.max(self.lat.coor['x']+.5)), 
                             ylim=(np.min(self.lat.coor['y']-.5), np.max(self.lat.coor['y']+.5)))
        ax.set_aspect('equal')
        frame = plt.gca()
        frame.axes.get_xaxis().set_ticks([])
        frame.axes.get_yaxis().set_ticks([])
        scat = plt.scatter(self.lat.coor['x'], self.lat.coor['y'], c=color[:, 0],
                                    s=s, vmin=ticks[0], vmax=ticks[1],
                                    cmap=cmap)
        if prop_type == 'real' or prop_type == 'imag':
            cbar = fig.colorbar(scat, ticks=[ticks[0], 0, ticks[1]])
            cbar.ax.set_yticklabels(['min', '0','max'])
        else:
            cbar = fig.colorbar(scat, ticks=[0, ticks[1]])
            cbar.ax.set_yticklabels(['0','max'])

        def init():
            scat.set_array(color[:, 0])
            return scat,

        def animate(i):
            scat.set_array(color[:, i])    
            return scat,

        return animation.FuncAnimation(fig, animate, init_func=init,
                                   frames=self.steps, interval=120, blit=True)
Example #54
0
def cleanPlot(ax):
    removeFrames(plt.gca(),['top','right','bottom']);
    removeTicks(plt.gca(),['x','y']);
def plot_trial_measures(group_cycle,group_order,trial_measures,bracket_offset=0.5,bracket_tickheight=1,ylims=None,xticklabels=None):
    scale = 46
    offsetscale = 2
    num_sessions = len(trial_measures[0])
    ax = plt.gca()
    ax.set_color_cycle(group_cycle)
    measures = [[trial_measures[group_order[i]][s] for s in (range(num_sessions) if i != 7 else [0])] for i in range(len(trial_measures))]
    [plot_epoch_average(measures[i],label='lesion' if group_cycle[i] == 'r' else 'control',offset=i*offsetscale,scale=scale) for i in range(len(trial_measures))]
    plt.ylabel('time to cross obstacles (s)')
    plt.xlabel('x')
    
    offset1 = 3*offsetscale
    center1 = [scale*i+offset1 for i in range(num_sessions)]
    group1_times = [[np.mean(trial_measures[i][s]) for i in group_order[0:7]] for s in range(num_sessions)]
    group1_mean = [np.mean(x) for x in group1_times]
    group1_std = [np.std(x) for x in group1_times]
    plt.errorbar(center1,group1_mean,group1_std,fmt='o',color=group_cycle[0],ecolor='k',linewidth=2,capthick=2,markersize=0)
    
    offset2 = 10*offsetscale
    center2 = [scale*i+offset2 for i in range(num_sessions)]
    group2_times = [[np.mean(trial_measures[i][s]) for i in (group_order[7:14] if s < 1 else group_order[8:14])] for s in range(num_sessions)]
    group2_mean = [np.mean(x) for x in group2_times]
    group2_std = [np.std(x) for x in group2_times]
    plt.errorbar(center2,group2_mean,group2_std,fmt='o',color=group_cycle[7],ecolor='k',linewidth=2,capthick=2,markersize=0)
    
    pltutils.fix_font_size()
    #handles, labels = ax.get_legend_handles_labels()
    #plt.legend((handles[0],handles[7]),(labels[0],labels[7]))
    tickoffset = 6.5*offsetscale
    xticks = [scale*i+tickoffset for i in range(num_sessions)]
    ax.set_xticks(xticks)
    ax.set_xticklabels(xticklabels)
    
    
    ### BRACKETS (BETWEEN GROUPS) ###
    maxstd = []
    minstd = []
    significance = 0.01
    maxrange = len(measures)
    for i in range(len(xticks)):
        sigtest = stats.ttest_ind(group1_times[i],group2_times[i])[1]
        print sigtest,"groups"
        testlabel = str.format("*",sigtest) if sigtest < significance else 'n.s.'
        maxstd.append(get_bracket_y(measures,range(maxrange) if i < 1 else range(0,7)+range(8,14),i))
        minstd.append(get_negative_bracket_y(measures,range(maxrange) if i < 1 else range(0,7)+range(8,14),i))
        
    maxstd = max(maxstd)
    for i in range(len(xticks)):
        pltutils.hbracket(xticks[i],maxstd+bracket_offset,2,label=testlabel,tickheight=bracket_tickheight)
    ##################################
        
    ### BRACKETS (BETWEEN CONDITIONS) ###
    minstd = min(minstd)
    sigtest = stats.ttest_ind(group1_times[0]+group2_times[0],group1_times[-1]+group2_times[-1])[1]
    print sigtest,"conditions"
    testlabel = str.format("*",sigtest) if sigtest < significance else 'n.s.'
    #pltutils.hbracket(xticks[1],minstd-bracket_offset,5.5,label=testlabel,tickheight=-1.5*bracket_tickheight)
    pltutils.hbracket((xticks[-1]-xticks[0])/2+xticks[0],minstd-bracket_offset,9.5,label=testlabel,tickheight=-1.5*bracket_tickheight)
    #####################################
    
    ### SEPARATORS ###
    ylims = plt.ylim() if ylims is None else ylims
    for i in range(len(xticks)-1):
        separatorxi = (xticks[i]+xticks[i+1])/2
        ax.plot((separatorxi,separatorxi),ylims,'k--')
    plt.ylim(ylims)
    ##################
    
    plt.xlabel('')
    plt.draw()

############# FIGURE 3 ##############################

#### Get contact step activation ###
#def get_contact_step_activity(session,i):
#    activity = session.steps[i]
#    step_index = 3 if session.labels[i]['direction'] == 'right' else 4
#    return activity[:,step_index]
#    
#### Plot contact maximum activation distribution ###
#def plot_contact_distribution(session):
#    max_contacts = [np.max(get_contact_step_activity(session,i)) for i in range(len(session.steps))]
#    maxStContacts = [mc for state,mc in zip(session.labels,max_contacts) if state['state'] == 'stable']
#    maxUnContacts = [mc for state,mc in zip(session.labels,max_contacts) if state['state'] == 'unstable']
#    plt.plot(maxStContacts,'b.')
#    plt.plot(maxUnContacts,'r.')
#    
## Time Difference in microseconds
#def time_diff(t):
#    numTimes = np.size(t)    
#    dT = np.zeros(numTimes-1)    
#    for i in range(numTimes-1):
#        dT[i] = (t[i+1]-t[i]).microseconds
#
#    return dT
#    
#def get_randomized_speed_profiles(experiment,a,sessions,filterpath):    
#    avgSpeeds_allsess = []
#    trialTypes_allsess = []
#
#    # Select Session
#    for s in sessions:
#
#        # Load Valid Trial Filter (manually sorted)
#        validFilename = filterpath +  r'\valid_a' + str(a) + '_s' + str(s) + '.pickle'
#        valid_trials = load_data.load_pickle(validFilename)
#        numTrials = np.size(valid_trials)
#    
#        # There is some misalignment for sessions on the last 4 animals..there session 0 is other session 1
#        if a >= 10:
#            s = s-1
#        
#        # Set Trial Lables
#        labelfilter1 = {'state':'stable'}
#        labelfilter2 = {'state':'unstable'}
#        labelFilters = [labelfilter1, labelfilter2]
#        
#        # Look at all Trajectories
#        trajectories = experiment[a][s].trajectories
#        times = experiment[a][s].time    
#        slices = experiment[a][s].slices
#        labels = experiment[a][s].labels
#        steps = experiment[a][s].steps
#        speeds = experiment[a][s].speeds
#        
#        print str.format('a:s {0}:{1} {2} {3}', a, s, numTrials, len(slices))
#        
#        # Set Valid Trials (No exploration or tracking errors)
#        crossings = valid_trials
#    
#        # Set Binning and Range
#        avgSpeeds = np.zeros((numTrials, numBins))
#        trialTypes = np.zeros((numTrials, 1))
#        for t in range(0,numTrials):
#        
#            #label_indices = np.array(pt.get_labeled_indices(labels,labelFilters[l]))
#            c = crossings[t]
#            
#            # Load X Trajectories and flip all of 'Left'
#            trialX = trajectories[slices[c],0]
#            if utils.is_dict_subset({'direction':'left'},labels[c]):
#                # ALign on 2 important rails (the center of rail 3 is 550)
#                # and the centr of rail 4 is 737, therefore, the first encounter
#                # is at 550 going "right", and when flipped, (1280-737 = 543)
#                # going "left"...therefore, to correct for the shift, I subteact 1273 
#                # and align the left and right trials
#                trialX = np.abs(trialX-1273)
#                
#            # Load Y Trajectories
#            trialY = trajectories[slices[c],1]
#            
#            # Load and Parse Times
#            trialTstrings = times[slices[c]]
#            trialT = np.array([dateutil.parser.parse(timeString) for timeString in trialTstrings])
#            
#            # Measure Progression Speed
#            diffX =  np.diff(trialX)
#            diffT = time_diff(trialT)/1000000 # Time interval in seconds
#            speedX = np.concatenate((np.zeros(1) , diffX/diffT))
#        
#            # Find enter/exit and crop trials
#            indR = np.where(trialX > 1200)
#            indL = np.where(trialX < 150)
#            if (np.size(indR) > 0) and (np.size(indL) > 0):
#                exitInd = indR[0][0]+1
#                enterInd = indL[0][-1]
#                
#            trialX = trialX[enterInd:exitInd]
#            trialY = trialY[enterInd:exitInd]
#            speedX = speedX[enterInd:exitInd]
#            
#            # Bin (progrssion - X) Speed Profiles (from position 200 to 1200)
#            for b in range(0,numBins):
#                bins = np.where((trialX >= (200+(b*binSize))) & (trialX < (200+(b*binSize)+binSize)))
#                if np.size(bins) > 0:
#                    avgSpeeds[t, b] = np.mean(speedX[bins])
#                else:
#                    avgSpeeds[t, b] = np.NaN
#            
#            # Correct for starting speed - - first Third of assay
#            baseSpeed = stats.nanmean(avgSpeeds[t, 0:14])
#            avgSpeeds[t,:] = avgSpeeds[t,:]/baseSpeed
#            
#            # Get Lables
#            label = labels[c]
#            
#            if utils.is_dict_subset({'state':'stable'},label):
#                trialTypes[t] = 0
#            else:
#                trialTypes[t] = 1
#        
#        # Pool All Average Speeds/TrialTypes Across Sessions        
#        avgSpeeds_allsess.append(avgSpeeds)
#        trialTypes_allsess.append(trialTypes)
#    
#    avgSpeeds = np.concatenate(avgSpeeds_allsess)
#    trialTypes = np.concatenate(trialTypes_allsess)
#    return avgSpeeds,trialTypes
#
#def plot_randomized_speed_profiles(avgSpeeds,trialTypes):
#    # Set Plotting Attributes
#    color1 = (0.0, 0.0, 0.0, 0.1)
#    color2 = (1.0, 0.6, 0.0, 0.1)
#    color1b = (0.0, 0.0, 0.0, 1.0)
#    color2b = (1.0, 0.6, 0.0, 1.0)
#    
#    traceColors = [color1, color2]
#    boldColors = [color1b, color2b]    
#    
#    # Plot Average Speeds in bins
#    plt.figure()
#    numTrials = np.size(trialTypes)
#    for t in range(0,numTrials):
#        if trialTypes[t] == 0:
#            plt.plot(avgSpeeds[t,:], color=color1)
#        else:
#            plt.plot(avgSpeeds[t,:], color=color2)
#
#    stableTrials = np.where(trialTypes == 0)
#    unstableTrials = np.where(trialTypes == 1)
#    mSt = stats.nanmean(avgSpeeds[stableTrials, :], 1)
#    mUn = stats.nanmean(avgSpeeds[unstableTrials, :], 1)
#    eSt = stats.nanstd(avgSpeeds[stableTrials, :], 1)/np.sqrt(np.size(stableTrials)-1)
#    eUn = stats.nanstd(avgSpeeds[unstableTrials, :], 1)/np.sqrt(np.size(unstableTrials)-1)
#    
##    eSt = stats.nanstd(avgSpeeds[stableTrials, :], 1)
##    eUn = stats.nanstd(avgSpeeds[unstableTrials, :], 1)
#
#
#    mSt = mSt[0];    
#    mUn = mUn[0];    
#    eSt = eSt[0];    
#    eUn = eUn[0];
#    
#    plt.plot(mUn, color=color2b, linewidth = 7)
#    plt.plot(mSt, color=color1b, linewidth = 7)
#
##    plt.plot(mSt + eSt, color=color1b, linewidth = 0.5)
##    plt.plot(mSt - eSt, color=color1b, linewidth = 0.5)
##    plt.plot(mUn + eUn, color=color2b, linewidth = 0.5)
##    plt.plot(mUn - eUn, color=color2b, linewidth = 0.5)
#    #pltutils.fix_font_size()
#    plt.xlabel('crossing extent (cm)')
#    plt.ylabel('normalized horizontal speed')
#    pltutils.fix_font_size()
#    plt.axis([0, 39, 0, 3])
#    
#    
##### Figure 3b ####
#    
#def get_randomized_group_average_speed_profiles(profiles):        
#    stAvg = []
#    unAvg = []
#    stErr = []
#    unErr = []
#    
#    for avgSpeeds,trialTypes in profiles:
#        # Plot Average Speeds in bins
#        stableTrials = np.where(trialTypes == 0)
#        unstableTrials = np.where(trialTypes == 1)
#        
#        mSt = stats.nanmean(avgSpeeds[stableTrials, :], 1)
#        mUn = stats.nanmean(avgSpeeds[unstableTrials, :], 1)
#        eSt = stats.nanstd(avgSpeeds[stableTrials, :], 1)/np.sqrt(np.size(stableTrials)-1)
#        eUn = stats.nanstd(avgSpeeds[unstableTrials, :], 1)/np.sqrt(np.size(unstableTrials)-1)
#    
#        mSt = mSt[0]
#        mUn = mUn[0]
#        eSt = eSt[0]
#        eUn = eUn[0]
#    
#        stAvg.append(mSt)
#        unAvg.append(mUn)
#        stErr.append(eSt)
#        unErr.append(eUn)
#    return (stAvg,stErr),(unAvg,unErr)
#    
#def get_randomized_group_speed_profile_difference(avgProfiles):    
#    diffs = []
#    errors = []
#
#    # Unpack average profile structure
#    (stAvg,stErr),(unAvg,unErr) = avgProfiles
#    
#    for mSt,eSt,mUn,eUn in zip(stAvg,stErr,unAvg,unErr):
#        # Compute Difference Speed between Stable and Unstable Trials
#        mDiff = mUn-mSt
#        eDiff = np.sqrt((eSt*eSt) + (eUn*eUn))
#        diffs.append(mDiff)
#        errors.append(eDiff)
#        
#    diffs = np.array(diffs)
#    errors = np.array(errors)
#    return diffs,errors,np.mean(diffs[:, 20:], 1)
#    
#def plot_randomized_group_average_speed_profiles(avgProfiles,labelx=True,labely=True,legend=True,title=None):
#    # Set Plotting Attributes
#    color1b = (0.0, 0.0, 0.0, 1.0)
#    color2b = (1.0, 0.6, 0.0, 1.0)
#    
#    # Unpack average profile structure
#    (stAvg,stErr),(unAvg,unErr) = avgProfiles
#    
#    # Prepare Bulk Arrays
#    stAvg = np.array(stAvg)
#    unAvg = np.array(unAvg)
#    stErr = np.array(stErr)
#    unErr = np.array(unErr)
#    
#    # Plot Averge Speed Profiles
#    a1 = plt.plot(np.mean(unAvg,0), color = color2b, linewidth = 3,label='unstable')
#    a2 = plt.plot(np.mean(stAvg,0), color = color1b, linewidth = 3,label='stable')
#    if labelx:
#        plt.xlabel('crossing extent (cm)')
#    if labely:
#        plt.ylabel('normalized horizontal speed')
#    pltutils.fix_font_size()
#    plt.axis([0, numBins, 0.5, 2.0])
#    plt.yticks([0.75,1.0,1.25,1.5,1.75])
#    if legend:
#        plt.legend((a2[0],a1[0]),('stable','unstable'),loc='upper left')
#        
#    if title is not None:
#        ax = plt.gca()
#        ax.text(0.5,0.9,title,horizontalalignment='center',transform=ax.transAxes)
#    
#def plot_randomized_speed_profile_difference_comparison(controls,lesions):
#    controlMeans = np.mean(controls, 0)
#    controlMeanAll = np.mean(controlMeans)
#    controlError = np.std(controlMeans)/np.sqrt(7-1)
#    
#    lesionMeans = np.mean(lesions, 0)
#    lesionMeanAll = np.mean(lesionMeans)
#    lesionlError = np.std(lesionMeans)/np.sqrt(6-1)
#    
#    significance = 0.05
#    sigtest = stats.ttest_ind(controlMeans, lesionMeans)[1]
#    testlabel = str.format("*",sigtest) if sigtest < significance else 'n.s.'
#    print sigtest
#    
#    cX = [1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1]
#    lX = [1.9, 1.9, 1.9, 1.9, 1.9, 1.9]
#    
#    plt.plot([0,3], [0,0], color=[0.25,0.25,0.25,1], linewidth = 1)
#    plt.plot(cX, controlMeans, 'bo')
#    plt.plot(lX, lesionMeans, 'ro')
#    plt.plot(1.9, lesionMeans[5], 'o', color = [1.0, 0.75, 0.75, 1.0])
#    
#    #plt.bar(1.2, controlMeanAll, 0.2, color=[1.0,1.0,1.0,0.0])
#    plt.errorbar(1.3, controlMeanAll, controlError, marker='s', mfc='blue', ecolor = 'black', mec='black', ms=1, mew=1, capsize=5, elinewidth=2)
#    plt.plot([1.0,1.4], [controlMeanAll,controlMeanAll], color=[0.25,0.25,1.0,1], linewidth = 2)
#    
#    #plt.bar(1.6, lesionMeanAll, 0.2, color=[1.0,1.0,1.0,0.0])
#    plt.errorbar(1.7, lesionMeanAll, lesionlError, marker='s', mfc='red', ecolor = 'black', mec='black', ms=1, mew=1, capsize=5, elinewidth=2)
#    plt.plot([1.6,2.0], [lesionMeanAll,lesionMeanAll], color=[1.00,0.25,0.25,1], linewidth = 2)
#    pltutils.hbracket(1.5,0.17,4.5,label=testlabel,tickheight=0.01)
#    
#    ax = plt.gca()
#    ax.set_xticks([1.1,1.9])
#    ax.set_xticklabels(['controls','lesions'])
#    plt.ylabel('normalized speed difference')
#    
#    pltutils.fix_font_size()
#    plt.axis([0.75,2.25,-0.2,0.2])
Example #56
0
import geopandas as gpd
#change the file here
crimes = pd.read_csv('data/la_crimes/4/burglaryByNeighborhood.csv')
la = gpd.read_file('data/la-county-neighborhoods-v2/l.a. county neighborhood (v2).shp')
crimes['Neighborhood'] = crimes['Neighborhood'].astype(str)
la['slug'] = la['slug'].astype(str)
#fix a different name
la[la['slug'] == 'chatsworth']['slug'] = 'chatsworth-reservoir'
merged = la.merge(crimes, left_on = 'slug', right_on = 'Neighborhood', how='left')
merged = merged.to_crs(epsg=3857)
import contextily as ctx
# la['coords'] = la['geometry'].apply(lambda x: x.representative_point().coords[:])
# la['coords'] = [coords[0] for coords in la['coords']]
ax = merged.plot(column='Crime Amount', cmap = 'YlGn', figsize=(10,10), edgecolor = "none", linewidth = 1, legend= True);
#emphasised block
encino = merged[merged.slug == 'encino']
encino.boundary.plot(ax = ax, edgecolor='red', linewidth = 3)
hyde_park = merged[merged.slug == 'hyde-park']
hyde_park.boundary.plot(ax = ax, edgecolor='purple', linewidth = 3)
# for idx, row in la.iterrows():
#     plt.annotate(s=row['slug'], xy=row['coords'], horizontalalignment='center', fontsize=5, fontweight="bold" )
ax.set_axis_off()
ctx.add_basemap(ax)
plt.gca().set_axis_off()
#plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
plt.margins(0,0, tight=True)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
#change the same of saved file here
plt.savefig("/Users/bobyang/Desktop/crime_prediction/final_graphs/4.png")
#plt.show()
Example #57
0
def plot_one_cohort_churn(cc,args,var_to_plot,plot_score):
    '''
    Makes a plot of churn rates in behavioral cohorts for the dataset contained in the churn calculator.
    The function ChurnCalculator.behavioral_cohort_analysis actually calculates the cohorts, churn ratesa and
    average values and this function is concerned with presentation.

    Command line arguments control other features:
    1. Plot the grouped behavioral metrics or plain metrics,
    2. Always plot scored metrics, or the default of plotting scores only for skewed metrics
    3. Hide the axes scales (for use on case study data)
    4. Number of bins to suggest for cohorts (defaults to 10)

    There is also a plot scaling configuration in the schema_churnalyze.json - this will give a uniform maximum to
    all of the cohort plots, by scaling the churn rate. That way the different cohort plots are easier to compare.
    Usually scaling it to 2x the maximum churn rate is good, but this parameter allows adjustment. The parameter is
    given as an integer where 200 means set the maximum to 2x the churn rate, 300 means 3x the churn rate, etc.
    The code here also ensures that the chosen maximum is a whole number of percents (as a decimal) i.e. 0.10 or 0.11
     but not 0.1085 or some odd number of decimal places.

    :param cc: ChurnCalculator object created from schema given on the command line
    :param args: Command line arguments from argparse (defined at the top of this file)
    :param var_to_plot: string name of the metric to plot the cohorts of
    :param plot_score: boolean indicates scored version of metric should be plotted as well
    :return:
    '''

    print('Plotting churn vs %s' % var_to_plot)
    renames = cc.get_renames()
    if var_to_plot not in renames:
        renames[var_to_plot] = var_to_plot
    # First plot should always be the unscored version
    plot_frame = cc.behavioral_cohort_analysis(var_to_plot, nbin=args.nbin,bins=args.bins,
                                               use_score=False,use_group=args.group)
    ax_scale=cc.get_conf('ax_scale',default=200)
    churn_plot_max = ceil(cc.churn_rate() * ax_scale) / 100.0

    if args.group or not plot_score:
        plt.figure(figsize=(6, 4))
        plt.plot(var_to_plot, 'churn_rate', data=plot_frame,
                 marker='o', color='red', linewidth=2, label=var_to_plot)
        plt.gcf().subplots_adjust(bottom=0.2)
        plt.xlabel('Cohort Average of  "%s"' % renames[var_to_plot])
        plt.ylim(0, churn_plot_max)
        if args.noax:
            plt.gca().get_yaxis().set_ticks(
                [0.25 * churn_plot_max, 0.5 * churn_plot_max, 0.75 * churn_plot_max, 1.0 * churn_plot_max])
            plt.gca().get_yaxis().set_ticklabels([])  # Hiding y axis labels on the count
            plt.ylabel('Cohort Churn (Relative)')
        else:
            plt.ylabel('Cohort Churn Rate (%)')
        plt.grid()

    else:
        score_frame = cc.behavioral_cohort_analysis(var_to_plot, use_score=True, nbin=args.nbin,bins=args.bins)
        plt.figure(figsize=(10, 10))
        plt.subplot(2, 1, 1)
        plt.plot(var_to_plot, 'churn_rate', data=plot_frame,
                 marker='o', color='red', linewidth=2, label=var_to_plot)
        plt.ylabel('Cohort Churn Rate (%)')
        plt.xlabel('Cohort Average of  "%s"' % renames[var_to_plot])
        plt.grid()
        plt.ylim(0, churn_plot_max)
        if args.noax:
            plt.gca().get_yaxis().set_ticks(
                [0.25 * churn_plot_max, 0.5 * churn_plot_max, 0.75 * churn_plot_max, 1.0 * churn_plot_max])
            plt.gca().get_yaxis().set_ticklabels([])  # Hiding y axis labels on the count
            plt.ylabel('Cohort Churn (Relative)')
        else:
            plt.ylabel('Cohort Churn Rate (%)')

        plt.subplot(2, 1, 2)
        plt.plot(var_to_plot, 'churn_rate', data=score_frame,
                 marker='o', color='blue', linewidth=2, label='score(%s)' % var_to_plot)
        plt.xlabel('Cohort Average of  "%s" (SCORE)' % renames[var_to_plot])
        plt.grid()
        plt.ylim(0, churn_plot_max)
        if args.noax:
            plt.gca().get_yaxis().set_ticks(
                [0.25 * churn_plot_max, 0.5 * churn_plot_max, 0.75 * churn_plot_max, 1.0 * churn_plot_max])
            plt.gca().get_yaxis().set_ticklabels([])  # Hiding y axis labels on the count
            plt.ylabel('Cohort Churn (Relative)')
        else:
            plt.ylabel('Cohort Churn Rate (%)')

    save_name = 'churn_vs_' + var_to_plot
    if args.noax:
        save_name+='noax'

    plt.tight_layout()
    plt.savefig(cc.save_path(save_name, ext=args.format, subdir=cc.grouping_correlation_subdir(args.group)))
    plt.close()
            linestyles=['--', '-', '--'],
            levels=[-1, 0, 1])
plt.savefig('Pro3-(a)-clf.png', dpi=1200)

# Pro3-(d)
weights, bias = train_weights(gen_R4(X), y)
G = grid.reshape(2, -1)
G = np.concatenate([(-G[0] * G[1])[:, None], (G[0] * G[0])[:, None],
                    (G[0] * G[1])[:, None], (G[1] * G[1])[:, None]],
                   axis=1)
Z = weights @ G.T + bias
Z = Z.reshape(grid.shape[1:])

#3D
from mpl_toolkits.mplot3d import Axes3D
ax = plt.gca(projection='3d')
ax.plot_surface(grid[0], grid[1], Z, cmap=plt.cm.rainbow, alpha=0.2)
#ax.plot_wireframe(grid[0], grid[1], Z, alpha=0.2, rstride=20, cstride=20)
ax.scatter(X[:, 0], X[:, 1], y, c=y, cmap=plt.cm.rainbow, s=30)
plt.savefig('Pro3-(d)-3D.png', dpi=1200)

#2D
plt.figure()
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.rainbow, zorder=10, s=50)
xx = np.random.uniform(-2.7, 2.7, size=(2, 2000))
xx_after = np.concatenate([(-xx[0] * xx[1])[:, None], (xx[0] * xx[0])[:, None],
                           (xx[0] * xx[1])[:, None], (xx[1] * xx[1])[:, None]],
                          axis=1)
y_after = weights @ xx_after.T + bias
Z = weights @ G.T + bias
Z = Z.reshape(grid.shape[1:])
Example #59
0
def abline(slope, intercept):
    """Plot a line from slope and intercept"""
    axes = plt.gca()
    x_vals = np.array([2.0, 5, 7])
    y_vals = intercept + slope * x_vals
    plt.plot(x_vals, y_vals, '--')
def draw_court(ax=None, color='white', lw=2, outer_lines=False):
    from matplotlib.patches import Circle, Rectangle, Arc
    if ax is None:
        ax = plt.gca()
    hoop = Circle((0, 0), radius=7.5, linewidth=lw, color=color, fill=False)
    backboard = Rectangle((-30, -7.5), 60, -1, linewidth=lw, color=color)
    outer_box = Rectangle((-80, -47.5),
                          160,
                          190,
                          linewidth=lw,
                          color=color,
                          fill=False)
    inner_box = Rectangle((-60, -47.5),
                          120,
                          190,
                          linewidth=lw,
                          color=color,
                          fill=False)
    top_free_throw = Arc((0, 142.5),
                         120,
                         120,
                         theta1=0,
                         theta2=180,
                         linewidth=lw,
                         color=color,
                         fill=False)
    bottom_free_throw = Arc((0, 142.5),
                            120,
                            120,
                            theta1=180,
                            theta2=0,
                            linewidth=lw,
                            color=color,
                            linestyle='dashed')
    restricted = Arc((0, 0),
                     80,
                     80,
                     theta1=0,
                     theta2=180,
                     linewidth=lw,
                     color=color)
    corner_three_a = Rectangle((-220, -50.0),
                               0,
                               140,
                               linewidth=lw,
                               color=color)
    corner_three_b = Rectangle((219.75, -50.0),
                               0,
                               140,
                               linewidth=lw,
                               color=color)
    three_arc = Arc((0, 0),
                    475,
                    475,
                    theta1=22,
                    theta2=158,
                    linewidth=lw,
                    color=color)
    center_outer_arc = Arc((0, 422.5),
                           120,
                           120,
                           theta1=180,
                           theta2=0,
                           linewidth=lw,
                           color=color)
    center_inner_arc = Arc((0, 422.5),
                           40,
                           40,
                           theta1=180,
                           theta2=0,
                           linewidth=lw,
                           color=color)
    court_elements = [
        hoop, backboard, outer_box, inner_box, top_free_throw,
        bottom_free_throw, restricted, corner_three_a, corner_three_b,
        three_arc, center_outer_arc, center_inner_arc
    ]
    if outer_lines:
        outer_lines = Rectangle((-250, -47.5),
                                500,
                                470,
                                linewidth=lw,
                                color=color,
                                fill=False)
        court_elements.append(outer_lines)

    for element in court_elements:
        ax.add_patch(element)

    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.set_xticks([])
    ax.set_yticks([])
    return ax