Esempio n. 1
0
def map_along_line(x, y, q, ax=None, cmap=None, norm=None,
            time=None, max_step=1., missing=np.nan,
            new_timebase=None,
            **kwargs):
    """Map some quantity q along x,y as a coloured line.
With time set, perform linear interpolation of x,y,q onto new_timebase
filling with missing, and with max_step."""

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

    if x.shape != y.shape:
        raise ValueError('Shape mismatch')
    if x.shape != q.shape:
        raise ValueError('Shape mismatch')

    if time is not None:
        if new_timebase is None:
            new_timebase = np.arange(time[0], time[-1], np.min(np.diff(time)))

        # Bit redundant
        x = interp_safe(new_timebase, time, x, max_step=max_step, missing=missing)
        y = interp_safe(new_timebase, time, y, max_step=max_step, missing=missing)
        q = interp_safe(new_timebase, time, q, max_step=max_step, missing=missing)

    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lc = LineCollection(segments, cmap=cmap, norm=norm, **kwargs)

    lc.set_array(q)
    plt.gca().add_collection(lc)

    return lc
Esempio n. 2
0
def hello():

    rtimes, rt, rp = np.loadtxt("data/data.txt").T
    rtimes = map(datetime.datetime.fromtimestamp, rtimes)
    rtimes = matplotlib.dates.date2num(rtimes)
    fig = Figure()
    axis = fig.add_subplot(1, 1, 1)
    axis.xaxis_date()
    fig.autofmt_xdate()

    forecast_list = []
    for fname in glob.glob("data/forecast.*.txt"):
        stamp = fname.split(".")[1]
        times, tempa = np.loadtxt(fname).T
        times = map(datetime.datetime.fromtimestamp, times)
        times = matplotlib.dates.date2num(times)

        points = np.array([times, tempa]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        lc = LineCollection(segments, cmap=plt.get_cmap("jet"),
                            norm=plt.Normalize(0, 1))
        lc.set_array(np.linspace(0,1,len(times)))
        lc.set_linewidth(1)
        axis.add_collection(lc)

        axis.plot_date(times, tempa, "-", linewidth=0)

    axis.plot_date(rtimes, rt, "-",linewidth=1, color="black")

    canvas = FigureCanvas(fig)
    output = StringIO.StringIO()
    canvas.print_png(output)
    response = make_response(output.getvalue())
    response.mimetype = 'image/png'
    return response
def plot_Kiel_diagram(starl):
    """
    Plot Kiel diagram.
    """
    x = starl['temperature']
    y = starl['g']
    age = starl['age']/1e6
    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    
    cmap = pl.cm.spectral
    norm = pl.Normalize(age.min(), age.max())
    lc = LineCollection(segments, cmap=cmap,norm=norm)
    lc.set_array(age)
    lc.set_linewidth(3)
    pl.gca().add_collection(lc)
    pl.xlim(x.max(), x.min())
    pl.ylim(y.max(), y.min())
    pl.xlabel('Effective temperature [K]')
    pl.ylabel('log(surface gravity [cm s$^{-2}$]) [dex]')
    
    ax0 = pl.gca()
    ax1 = pl.mpl.colorbar.make_axes(ax0)[0]
    norm = pl.mpl.colors.Normalize(age.min(), age.max())
    cb1 = pl.mpl.colorbar.ColorbarBase(ax1, cmap=cmap,
                                   norm=norm,orientation='vertical')
    cb1.set_label('Age [Myr]')
    pl.axes(ax0)
Esempio n. 4
0
def d3():
    rtimes, rt, rp = np.loadtxt("data/data.txt").T
    mask = np.logical_and(rtimes>1391000000, rtimes<1393000000)
    rtimes = rtimes[mask]
    rt = rt[mask]
    rtimes = map(datetime.datetime.fromtimestamp, rtimes)
    rtimes = matplotlib.dates.date2num(rtimes)
    fig, axis = plt.subplots()

    axis.xaxis_date()
    fig.autofmt_xdate()
    axis.plot_date(rtimes, rt, "-",linewidth=3, color="black")

    forecast_list = []
    for fname in glob.glob("data/forecast.1391*.txt"):
        stamp = fname.split(".")[1]
        times, tempa = np.loadtxt(fname).T
        times = map(datetime.datetime.fromtimestamp, times)
        times = matplotlib.dates.date2num(times)

        points = np.array([times, tempa]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        lc = LineCollection(segments, cmap=plt.get_cmap("jet"),
                            norm=plt.Normalize(0, 1))
        lc.set_array(np.linspace(0,1,len(times)))
        lc.set_linewidth(1)
        axis.add_collection(lc)

        axis.plot_date(times, tempa, "-", linewidth=2)



    return fig_to_html(fig)
Esempio n. 5
0
def colorbar_legend(ax, values, cmap, vis=True):
    """
    Add a vertical colorbar legend to a plot
    """
    x_range = ax.get_xlim()[1]-ax.get_xlim()[0]
    y_range = ax.get_ylim()[1]-ax.get_ylim()[0]

    x = [ax.get_xlim()[0]+x_range*0.05]
    y = [ax.get_ylim()[1]-(y_range * 0.25), ax.get_ylim()[1]-(y_range*0.05)]

    segs = []
    vals=[]
    p = (x[0], y[0]+((y[1]-y[0])/256.0))
    for i in range(2, 257):
        n = (x[0], y[0]+((y[1]-y[0])/256.0)*i)
        segs.append((p, n))
        p = segs[-1][-1]
        vals.append(min(values)+((max(values)-min(values))/256.0)*(i-1))
    lcbar =  LineCollection(segs, cmap=cmap, lw=15)
    lcbar.set_visible(vis)
    lcbar.set_array(np.array(vals))
    ax.add_collection(lcbar)
    lcbar.set_zorder(1)


    minlab = str(min(values))[:6]
    maxlab = str(max(values))[:6]

    ax.text(x[0]+x_range*.02, y[0], minlab, verticalalignment="bottom", visible=vis)
    ax.text(x[0]+x_range*.02, y[1], maxlab, verticalalignment="top", visible=vis)
Esempio n. 6
0
def plot_grid(x, y, colormap=None, plaincolor=None,
              varname=None, var=None, minvar=None, maxvar=None):

# colormap and plaincolor are optional - set defaults
  if colormap == None:
    colormap = 'jet'
  if plaincolor == None:
    plaincolor = 'black'

# Last four parameters optional: if not supplied, plain grid is plotted
  if varname == None:
    print 'Plotting plain grid ...\n'
    colorplot = False
  else:
    print 'Plotting grid colored by ' + varname + ' ...\n'
    colorplot = True

# Determine grid dimensions
  imax = x.shape[0]
  jmax = x.shape[1]

# Initialize plot
  fig = plt.figure()
  ax = fig.add_subplot(111)

# See http://wiki.scipy.org/Cookbook/Matplotlib/MulticoloredLine
# LineCollection type allows color to vary along the line according
#   to a parameter.
  for j in range(0, jmax):
    segments = line_to_segments(x[:,j], y[:,j])
    if colorplot:
      lc = LineCollection(segments, cmap=plt.get_cmap(colormap),
           norm=plt.Normalize(minvar, maxvar))
      lc.set_array(var[:,j])
    else:
      lc = LineCollection(segments, colors=plaincolor)
    ax.add_collection(lc)
  for i in range(0, imax):
    segments = line_to_segments(x[i,:], y[i,:])
    if colorplot:
      lc = LineCollection(segments, cmap=plt.get_cmap(colormap),
           norm=plt.Normalize(minvar, maxvar))
      lc.set_array(var[i,:])
    else:
      lc = LineCollection(segments, colors=plaincolor)
    ax.add_collection(lc)

# Create colorbar and title
  if colorplot:
    faux_colorbar(minvar, maxvar, varname, colormap)
    title = 'Grid geometry colored by ' + varname
  else:
    title = 'Grid geometry'

# Show plot
  plt.title(title)
  plt.xlabel('x')
  plt.ylabel('y')
  plt.axis('equal')
  plt.show(block=False)
Esempio n. 7
0
def plot_multi_line(x, y, z, bins, colors, ax):
    """
    Plot a multi-color line.
    See: http://matplotlib.sourceforge.net/examples/
               pylab_examples/multicolored_line.html
    """

    from matplotlib.collections import LineCollection
    from matplotlib.colors import ListedColormap, BoundaryNorm

    # Allow specifying bin centers, not edges
    if len(bins) == len(colors):
        bins = np.array(bins, dtype=np.float)
        bins = np.concatenate([[z.min() - 1],
                               (bins[1:] + bins[:-1]) / 2.0,
                               [z.max() + 1]])

    cmap = ListedColormap(colors)
    norm = BoundaryNorm(bins, cmap.N)

    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)

    lc = LineCollection(segments, cmap=cmap, norm=norm)
    lc.set_array(z)
    lc.set_linewidth(3)
    ax.add_collection(lc)
 def get_figures(self):
     from matplotlib.collections import LineCollection
     figs = []
     ys = [(1.0/self.PROCS_PER_WINDOW.value)*(i+1) for i in range(self.PROCS_PER_WINDOW.value)]
     all_xs = []
     for rad1, procs in self.rad1_to_procs.iteritems():
         windows = get_procedure_windows(procs, self.PROCS_PER_WINDOW.value,
                                self.STEP_SIZE.value)
         all_xs = []
         for window in windows:
             all_xs.append([p.fluoro for p in window])
         #the matplotlib part
         fig = plt.figure()
         ax = plt.gca()
         ax.set_xlim(0,10)
         ax.set_ylim(0,1)
         line_segments= LineCollection([zip(xs,ys) for xs in all_xs])
         line_segments.set_array(np.array(range(len(all_xs))))
         ax.add_collection(line_segments)
         plt.title(rad1)
         plt.xlabel("Fluoro Time")
         plt.ylabel("Fraction of Procedures Below Fluoro Time")
         colorbar = fig.colorbar(line_segments, ticks = range(len(windows)))#ticks = ?
         colorbar.set_ticklabels([str(window[0].dos_start) for window in windows])
         colorbar.set_label("Window Start Date")
         figs.append(fig)
     return figs
Esempio n. 9
0
def _draw_segments(ax, x, y, state, cmap, norm, lc_kwargs):
    """
    helper function to turn boundary edges into the input LineCollection
    expects.

    Parameters
    ----------
    ax : Axes
       The axes to draw to

    x, y, state : array
       The x edges, the y values and the state of each region

    cmap : matplotlib.colors.Colormap
       The color map to use

    norm : matplotlib.ticker.Norm
       The norm to use with the color map

    lc_kwargs : dict
       kwargs to pass through to LineCollection
    """

    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lc = LineCollection(segments, cmap=cmap, norm=norm, **lc_kwargs)
    lc.set_array(state)

    ax.add_collection(lc)
    return lc
Esempio n. 10
0
def draw_edges(tree, steiner_pos, diams=None, fig=None, ax=None, lim=None,
               colorbar=True):
    '''Draw edges with given positions.'''
    if fig is None:
        fig, ax = new_fig()
    if lim is None:
        lim = diam_min, diam_max

    pos = merge_pos(tree, steiner_pos)
    nodes = tree.get_nodes()
    arcs = tree.get_arcs()
    x = np.array([pos[n][0] for n in nodes])
    y = np.array([pos[n][1] for n in nodes])

    segments = [(pos[u], pos[v]) for (u,v) in arcs]

    if diams is None:
        lines = LineCollection(segments, colors='k', zorder=1)
    else:
        diams = np.array([diams[a] for a in arcs])
        lw = 7*diams + 1
        lines = LineCollection(segments, linewidths=lw, zorder=1)
        # set colors
        lines.set_array(diams)
        lines.set_cmap(_diam_cmap)
        lines.set_clim(*lim)
        if colorbar:
            plt.colorbar(lines, orientation='horizontal')
    ax.add_collection(lines)
Esempio n. 11
0
class Visualize:
    def __init__(self, v, t, e, fig, win, axesLimit=[-3,3.5,-2,2]):
        self.e = e.copy()
        self.p = [Polygon(v[ti]) for ti in t]
        self.p = PatchCollection(self.p, edgecolors='none')
        self.l = LineCollection(v[e[:,:2]])

        win = win or fig.canvas.manager.window
        if fig is None: fig = gcf()
        fig.clf()
        ax = fig.add_axes([0.02,0.02,.98,.98])
        ax.axis('scaled')
        ax.axis(axesLimit)
        ax.set_autoscale_on(False)
        self.axis, self.fig, self.win = ax, fig, win

        ax.add_collection(self.p)
        ax.add_collection(self.l)
        # ax.add_collection(self.l1)
        # ax.add_collection(self.l2)

    def update(self, title, phi):
        norm = Normalize(phi.min(), phi.max())
        self.p.set_norm(norm)
        self.l.set_norm(norm)
        self.p.set_array(phi)
        self.l.set_array(phi[self.e[:,2:]].mean(1))
        if not self.__dict__.has_key('colorbar'):
            self.colorbar = self.fig.colorbar(self.p)
        self.win.set_title(title)
        #self.fig.canvas.set_window_title(title)
        self.fig.canvas.draw()
Esempio n. 12
0
    def __plot_all(self):
        total = len(self.data)
        count = 0.0
        for timeStamp in self.data:
            if len(self.data[timeStamp]) < 2:
                self.parent.threadPlot = None
                return None, None

            if self.fade:
                alpha = (total - count) / total
            else:
                alpha = 1

            data = self.data[timeStamp].items()
            peakF, peakL = self.extent.get_peak_fl()

            segments, levels = self.__create_segments(data)
            lc = LineCollection(segments)
            lc.set_array(numpy.array(levels))
            lc.set_norm(self.__get_norm(self.autoL, self.extent))
            lc.set_cmap(self.colourMap)
            lc.set_linewidth(self.lineWidth)
            lc.set_gid('plot')
            lc.set_alpha(alpha)
            self.axes.add_collection(lc)
            count += 1

        return peakF, peakL
Esempio n. 13
0
    def __plot_all(self, spectrum):
        total = len(spectrum)
        count = 0.0
        for timeStamp in spectrum:
            if self.settings.fadeScans:
                alpha = (total - count) / total
            else:
                alpha = 1

            data = spectrum[timeStamp].items()
            peakF, peakL = self.extent.get_peak_fl()

            segments, levels = self.__create_segments(data)
            if segments is not None:
                lc = LineCollection(segments)
                lc.set_array(numpy.array(levels))
                lc.set_norm(self.__get_norm(self.settings.autoL, self.extent))
                lc.set_cmap(self.colourMap)
                lc.set_linewidth(self.lineWidth)
                lc.set_gid('plot')
                lc.set_alpha(alpha)
                self.axes.add_collection(lc)
                count += 1

        return peakF, peakL
Esempio n. 14
0
def colorline(ax, x,y,z,linewidth=1, colormap='jet', norm=None, zorder=1, alpha=1, linestyle='solid'):
        cmap = plt.get_cmap(colormap)
        
        if type(linewidth) is list or type(linewidth) is np.array or type(linewidth) is np.ndarray:
            linewidths = linewidth
        else:
            linewidths = np.ones_like(z)*linewidth
        
        if norm is None:
            norm = plt.Normalize(np.min(z), np.max(z))
        else:
            norm = plt.Normalize(norm[0], norm[1])
        
        '''
        if self.hide_colorbar is False:
            if self.cb is None:
                self.cb = matplotlib.colorbar.ColorbarBase(self.ax1, cmap=cmap, norm=norm, orientation='vertical', boundaries=None)
        '''
            
        # Create a set of line segments so that we can color them individually
        # This creates the points as a N x 1 x 2 array so that we can stack points
        # together easily to get the segments. The segments array for line collection
        # needs to be numlines x points per line x 2 (x and y)
        points = np.array([x, y]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        
        # Create the line collection object, setting the colormapping parameters.
        # Have to set the actual values used for colormapping separately.
        lc = LineCollection(segments, linewidths=linewidths, cmap=cmap, norm=norm, zorder=zorder, alpha=alpha, linestyles=linestyle )
        lc.set_array(z)
        lc.set_linewidth(linewidth)
        
        ax.add_collection(lc)
Esempio n. 15
0
def update_line(num, print_loss, data, axes, epochsInds, test_error, test_data, epochs_bins, loss_train_data, loss_test_data, colors,
                font_size = 18, axis_font=16, x_lim = [0,12.2], y_lim=[0, 1.08], x_ticks = [], y_ticks = []):
    """Update the figure of the infomration plane for the movie"""
    #Print the line between the points
    cmap = ListedColormap(LAYERS_COLORS)
    segs = []
    for i in range(0, data.shape[1]):
        x = data[0, i, num, :]
        y = data[1, i, num, :]
        points = np.array([x, y]).T.reshape(-1, 1, 2)
        segs.append(np.concatenate([points[:-1], points[1:]], axis=1))
    segs = np.array(segs).reshape(-1, 2, 2)
    axes[0].clear()
    if len(axes)>1:
        axes[1].clear()
    lc = LineCollection(segs, cmap=cmap, linestyles='solid',linewidths = 0.3, alpha = 0.6)
    lc.set_array(np.arange(0,5))
    #Print the points
    for layer_num in range(data.shape[3]):
        axes[0].scatter(data[0, :, num, layer_num], data[1, :, num, layer_num], color = colors[layer_num], s = 35,edgecolors = 'black',alpha = 0.85)
    axes[1].plot(epochsInds[:num], 1 - np.mean(test_error[:, :num], axis=0), color ='r')

    title_str = 'Information Plane - Epoch number - ' + str(epochsInds[num])
    utils.adjustAxes(axes[0], axis_font, title_str, x_ticks, y_ticks, x_lim, y_lim, set_xlabel=True, set_ylabel=True,
                     x_label='$I(X;T)$', y_label='$I(T;Y)$')
    title_str = 'Precision as function of the epochs'
    utils.adjustAxes(axes[1], axis_font, title_str, x_ticks, y_ticks, x_lim, y_lim, set_xlabel=True, set_ylabel=True,
                     x_label='# Epochs', y_label='Precision')
Esempio n. 16
0
def plot_file_color(base, thin=True, start=0, size=14, save=False):
    conf, track, pegs = load(base)

    fig = pl.figure(figsize=(size,size*conf['top']/conf['wall']))

    track = track[start:]
    x = track[:,0];   y = track[:,1]
    t = np.linspace(0,1,x.shape[0])
    points = np.array([x,y]).transpose().reshape(-1,1,2)
    segs = np.concatenate([points[:-1],points[1:]],axis=1)
    lc = LineCollection(segs, linewidths=0.25, cmap=pl.cm.coolwarm)
    lc.set_array(t)
    pl.gca().add_collection(lc)

    #pl.scatter(x, y, c=np.arange(len(x)),linestyle='-',cmap=pl.cm.coolwarm)
    #pl.plot(track[-1000000:,0], track[-1000000:,1], '-', linewidth=0.0125, alpha=0.8)
    for peg in pegs:
        pl.gca().add_artist(pl.Circle(peg, conf['radius'], color='k', alpha=0.3))
    pl.xlim(0, conf['wall'])
    pl.ylim(0, conf['top'])
    pl.xticks([])
    pl.yticks([])
    pl.tight_layout()
    pl.show()
    if save:
        pl.savefig(base+".png", dpi=200)
	def main(self):
		x_field = self.fields_by_key('x')[0]
		y_field = self.fields_by_key('y')[0]	
		x = np.array(self.slice_data(x_field,int))
		y = np.array(self.slice_data(y_field,int))
		n = len(x)
		render = StringIO.StringIO()
		
		###############################################################################
		# Fit IsotonicRegression and LinearRegression models

		ir = IsotonicRegression()

		y_ = ir.fit_transform(x, y)

		lr = LinearRegression()
		lr.fit(x[:, np.newaxis], y)  # x needs to be 2d for LinearRegression

		###############################################################################
		# plot result

		segments = [[[i, y[i]], [i, y_[i]]] for i in range(n)]
		lc = LineCollection(segments, zorder=0)
		lc.set_array(np.ones(len(y)))
		lc.set_linewidths(0.5 * np.ones(n))

		fig = plt.figure()
		plt.plot(x, y, 'r.', markersize=12)
		plt.plot(x, y_, 'g.-', markersize=12)
		plt.plot(x, lr.predict(x[:, np.newaxis]), 'b-')
		plt.gca().add_collection(lc)
		plt.legend(('Data', 'Isotonic Fit', 'Linear Fit'), loc='lower right')
		plt.title('Isotonic regression')
		plt.savefig(render,format='png')
		return render
Esempio n. 18
0
    def gradient(figure_object, axis_object, xs, ys, start_year, TWP_length, cmap, key_count):
        """Based on http://matplotlib.org/examples/pylab_examples/multicolored_line.html
        and http://stackoverflow.com/questions/19132402/set-a-colormap-under-a-graph
        """
        from matplotlib.collections import LineCollection

        # plot a color_map line fading to white
        points = np.array([xs, ys]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        lc = LineCollection(segments, cmap=plt.get_cmap('gray'), norm=plt.Normalize(start_year, start_year+TWP_length),
                            linewidth=0.2, zorder=1)   # norm sets the color min:max range
        lc.set_array(np.array(xs))
        axis_object.add_collection(lc)

        # add fading color_map fill as well
        xs.append(max(xs))
        xs.append(min(xs))
        ys.append(0)
        ys.append(0)
        poly, = axis_object.fill(xs, ys, facecolor='none', edgecolor='none')
        img_data = np.arange(0, 100, 1)
        img_data = img_data.reshape(1, img_data.size)
        im = axis_object.imshow(img_data, aspect='auto', origin='lower', cmap=plt.get_cmap(cmap),
                                extent=[start_year+TWP_length, start_year, 1000, -1000], vmin=0., vmax=100., zorder=-(start_year+1)*key_count)
        im.set_clip_path(poly)
Esempio n. 19
0
def plot_colored_line(x,y, color, cmap = 'spectral_r', line_width = 2):
  """Plot a line with color code"""
  segments = np.array([x, y]).T.reshape(-1, 1, 2);
  segments = np.concatenate([segments[:-1], segments[1:]], axis=1);
  lc = LineCollection(segments, cmap=cmap);
  lc.set_array(np.array(color));
  #lc.set_linewidth(line_width);
  plt.gca().add_collection(lc)
Esempio n. 20
0
def fading_line(x, y, color='black', alpha_initial=1., alpha_final=0., glow=False, **kwargs):
    """
    Returns a matplotlib LineCollection connecting the points in the x and y lists, with a single color and alpha varying from alpha_initial to alpha_final along the line.
    Can pass any kwargs you can pass to LineCollection, like linewidgth.

    Parameters
    ----------
    x       : list or array of floats for the positions on the (plot's) x axis
    y       : list or array of floats for the positions on the (plot's) y axis
    color   : matplotlib color for the line. Can also pass a 3-tuple of RGB values (default: 'black')
    alpha_initial:  Limiting value of alpha to use at the beginning of the arrays.
    alpha_final:    Limiting value of alpha to use at the end of the arrays.
    """
    try:
        from matplotlib.collections import LineCollection
        from matplotlib.colors import LinearSegmentedColormap
        import numpy as np
    except:
        raise ImportError("Error importing matplotlib and/or numpy. Plotting functions not available. If running from within a jupyter notebook, try calling '%matplotlib inline' beforehand.")


    if glow:
        glow = False
        kwargs["lw"] = 1
        fl1 = fading_line(x, y, color, alpha_initial, alpha_final, glow=False, **kwargs)
        kwargs["lw"] = 2
        alpha_initial *= 0.5
        alpha_final *= 0.5
        fl2 = fading_line(x, y, color, alpha_initial, alpha_final, glow=False, **kwargs)
        kwargs["lw"] = 6
        alpha_initial *= 0.5
        alpha_final *= 0.5
        fl3 = fading_line(x, y, color, alpha_initial, alpha_final, glow=False, **kwargs)
        return [fl3,fl2,fl1]

    color = get_color(color)
    cdict = {'red': ((0.,color[0],color[0]),(1.,color[0],color[0])),
             'green': ((0.,color[1],color[1]),(1.,color[1],color[1])),
             'blue': ((0.,color[2],color[2]),(1.,color[2],color[2])),
             'alpha': ((0.,alpha_initial, alpha_initial), (1., alpha_final, alpha_final))}
    
    Npts = len(x)
    if len(y) != Npts:
        raise AttributeError("x and y must have same dimension.")
   
    segments = np.zeros((Npts-1,2,2))
    segments[0][0] = [x[0], y[0]]
    for i in range(1,Npts-1):
        pt = [x[i], y[i]]
        segments[i-1][1] = pt
        segments[i][0] = pt 
    segments[-1][1] = [x[-1], y[-1]]

    individual_cm = LinearSegmentedColormap('indv1', cdict)
    lc = LineCollection(segments, cmap=individual_cm, **kwargs)
    lc.set_array(np.linspace(0.,1.,len(segments)))
    return lc
Esempio n. 21
0
def _plotpartial(ax, partial, downsample=1, cmap='inferno', exp=1, linewidth=1, avg=True):
    # columns: time, freq, amp, phase, bw
    segments, Z = _segmentsZ(partial, downsample=downsample, exp=exp, avg=avg)
    lc = LineCollection(segments, cmap=cmap)
    # Set the values used for colormapping
    lc.set_array(Z)
    lc.set_linewidth(linewidth)
    lc.set_alpha(None)
    ax.add_collection(lc, autolim=True)
Esempio n. 22
0
def faux_colorbar(minvar, maxvar, varname, colormap):

  colorx = np.linspace(0.0, 1.0, 10)
  colory = np.linspace(minvar, maxvar, 10)
  segments = line_to_segments(colorx, colory)
  colors = LineCollection(segments, cmap=plt.get_cmap(colormap),
           norm=plt.Normalize(minvar, maxvar))
  colors.set_array(colory)
  cbar=plt.colorbar(colors)
  cbar.set_label(varname, rotation=270)
def show_q():
    # show all the valid/used transitions
    coords = np.array([[2, 2],
                       [4, 2],
                       [5, 3],
                       [4, 4],
                       [2, 4],
                       [5, 2]])
    # invert y axis for display
    coords[:, 1] = max(coords[:, 1]) - coords[:, 1]

    plt.figure(1, facecolor='w', figsize=(10, 8))
    plt.clf()
    ax = plt.axes([0., 0., 1., 1.])
    plt.axis('off')

    plt.scatter(coords[:, 0], coords[:, 1], c='r')

    start_idx, end_idx = np.where(q > 0)
    segments = [[coords[start], coords[stop]]
                for start, stop in zip(start_idx, end_idx)]
    values = np.array(q[q > 0])
    # bump up values for viz
    values = values
    lc = LineCollection(segments,
                        zorder=0, cmap=plt.cm.hot_r)
    lc.set_array(values)
    ax.add_collection(lc)

    verticalalignment = 'top'
    horizontalalignment = 'left'
    for i in range(len(coords)):
        x = coords[i][0]
        y = coords[i][1]
        name = str(i)
        if i == 1:
            y = y - .05
            x = x + .05
        elif i == 3:
            y = y - .05
            x = x + .05
        elif i == 4:
            y = y - .05
            x = x + .05
        else:
            y = y + .05
            x = x + .05

        plt.text(x, y, name, size=10,
                 horizontalalignment=horizontalalignment,
                 verticalalignment=verticalalignment,
                 bbox=dict(facecolor='w',
                           edgecolor=plt.cm.spectral(float(len(coords))),
                           alpha=.6))
    plt.show()
Esempio n. 24
0
def plotElevationMap(trk, smoothed=True):
    from cmap_parula import cmap_parula
    import datetime
    from matplotlib.collections import LineCollection
    from matplotlib.colors import ListedColormap
    import matplotlib.image as mpimg

    x = np.array([t['lon'] for t in trk])
    y = np.array([t['lat'] for t in trk])
    z = np.array([t['ele'] for t in trk])
    f = butter_lowpass_filtfilt(z, 5000, 50000)
    pts = np.array([x, y]).T.reshape(-1,1,2)
    segments = np.hstack([pts[:-1], pts[1:]])

    cmap = cmap_parula().parula
    coll = LineCollection(segments, cmap=cmap, linewidth=2)
    coll.set_array(f)

    # Get extents based on the track.
    xmin = min(x); xmax = max(x)
    ymin = min(y); ymax = max(y)
    xdel = xmax - xmin
    ydel = ymax - ymin
    xmin = xmin - 0.05 * xdel; xmax = xmax + 0.05 * xdel
    ymin = ymin - 0.05 * ydel; ymax = ymax + 0.05 * ydel

    # Get new extents based on OSM's tiling, to ensure alignment.
    xmin, xmax, ymin, ymax, mapname, ar = getOSM(xmin, xmax, ymin, ymax)

    fig, ax = plt.subplots()

    ax = plt.gca()
    ax.set_aspect(ar)

    img = mpimg.imread(mapname)

    implt = plt.imshow(img, zorder=0, extent=[xmin, xmax, ymin, ymax], aspect=ar, alpha=0.4)
    cs = ax.add_collection(coll)

    add_colorbar(cs, ax=ax, label='Elevation [feet]')

    # Final reset of the extents to focus on the track despite OSM's tiling.
    xmin = min(x); xmax = max(x)
    ymin = min(y); ymax = max(y)
    xdel = xmax - xmin
    ydel = ymax - ymin
    xmin = xmin - 0.05 * xdel; xmax = xmax + 0.05 * xdel
    ymin = ymin - 0.05 * ydel; ymax = ymax + 0.05 * ydel

    plt.xlim([xmin, xmax])
    plt.ylim([ymin, ymax])

    ax.set_xticks([])
    ax.set_yticks([])
    return(plt)
def plot_MDS():
    """Plots the difference matrix with Multi-Dimensional Scaling"""
    diff_matrix = fast_generate_diff_matrix()
    X_true = diff_matrix
    similarities = euclidean_distances(diff_matrix)
    seed = 1
    

    mds = manifold.MDS(n_components=1, max_iter=3000, eps=1e-9, random_state=seed,
                       dissimilarity="precomputed", n_jobs=1)
    pos = mds.fit(similarities).embedding_
    
#    nmds = manifold.MDS(n_components=2, metric=False, max_iter=3000, eps=1e-12,
#                        dissimilarity="precomputed", random_state=2, n_jobs=1,
#                        n_init=1)
#    npos = nmds.fit_transform(similarities, init=pos)
    
    # Rescale the data
    pos *= np.sqrt((X_true ** 2).sum()) / np.sqrt((pos ** 2).sum())
#    npos *= np.sqrt((X_true ** 2).sum()) / np.sqrt((npos ** 2).sum())
    
    # Rotate the data
    clf = PCA(n_components=2)
    X_true = clf.fit_transform(X_true)
    
    pos = clf.fit_transform(pos)
#    
#    npos = clf.fit_transform(npos)
    
    fig = plt.figure(1)
    ax = plt.axes([0., 0., 1., 1.])
    
    plt.scatter(X_true[:, 0], X_true[:, 1], c='r', s=20)
#    plt.scatter(pos[:, 0], pos[:, 1], s=20, c='g')
#    plt.scatter(npos[:, 0], npos[:, 1], s=20, c='b')
    plt.legend(('True position'), loc='best')
    
    similarities = similarities.max() / similarities * 100
    similarities[np.isinf(similarities)] = 0
    
    # Plot the edges
    start_idx, end_idx = np.where(pos)
    #a sequence of (*line0*, *line1*, *line2*), where::
    #            linen = (x0, y0), (x1, y1), ... (xm, ym)
    segments = [[X_true[i, :], X_true[j, :]]
                for i in range(len(pos)) for j in range(len(pos))]
    values = np.abs(similarities)
    lc = LineCollection(segments,
                        zorder=0, cmap=plt.cm.hot_r,
                        norm=plt.Normalize(0, values.max()))
    lc.set_array(similarities.flatten())
    lc.set_linewidths(0.5 * np.ones(len(segments)))
    ax.add_collection(lc)
    
    plt.show()
Esempio n. 26
0
def nts_line_data(nts_data, keys=None, path=None, save=True, show=False, 
                  ext='.png'): 
    """
    Plot the non timeseries data in ``data`` with ``points`` as the x axis. To
    plot only a subset of this data list which ADCIRC Output types to plot in
    keys.

    .. note:: This only applies to 1D nts data (``irtype`` = 1)

    :type nts_data: :class:`dict`
    :param nts_data: ``nts_data`` from
        :class:`~polyadcirc.run_framework.random_manningsn.runSet`
    :param list() keys: list of types of ADCIRC output data to plot 
    :type path: string or None
    :param path: directory to store plots
    :type save: boolean
    :param save: flag for whether or not to save plots
    :type show: boolean
    :param show: flag for whether or not to show plots
    :param string ext: file extension
    
    """
    if path == None:
        path = os.getcwd()

    if keys == None:
        keys = nts_data.keys()
    s_keys = list()
    for k in keys:
        if not(f15.filetype[k][0]) and f15.filetype[k][1] == 1:
            s_keys.append(k)
    keys = s_keys

    fm.mkdir(path+'/figs/nts')

    for k in keys:
        fig = plt.figure()

        x = np.arange(nts_data[k].shape[0])
        ax = fig.add_subplot(111)
        ax.set_xlim((np.min(x),np.max(x)))
        ax.set_ylim((np.min(nts_data[k]),np.max(nts_data[k])))

        segs = list()

        for j in xrange(nts_data[k].shape[1]):
            segs.append(zip(x, nts_data[k][...,j]))

        line_segs = LineCollection(segs, linestyles = 'solid')
        line_segs.set_array(np.arange(nts_data[k].shape[1]))
        ax.add_collection(line_segs)
        colorbar(line_segs, fig)
        fig.title(k)
        fig.xlabel('node number')
        save_show(path+'/figs/nts/'+k, save, show, ext)
Esempio n. 27
0
def visualize(reader, visualization_method, value_column, segment_column):
    labels, data = organize_data(reader, visualization_method, value_column, segment_column)

    if visualization_method == 'hc':
        link = linkage(data)
        dendrogram(link, leaf_label_func=lambda i: labels[i])
        plt.gcf()
        plt.show()

    if visualization_method == 'mds':
        n = len(labels)
        data -= data.mean()
        clf = PCA(n_components=2)
        data = clf.fit_transform(data)

        similarities = euclidean_distances(data)

        # Add noise to the similarities
        noise = np.random.rand(n, n)
        noise = noise + noise.T
        noise[np.arange(noise.shape[0]), np.arange(noise.shape[0])] = 0
        similarities += noise


        fig = plt.figure(1)
        ax = plt.axes([0., 0., 1., 1.])

        similarities = similarities.max() / similarities * 100
        similarities[np.isinf(similarities)] = 0

        plt.scatter(data[:, 0], data[:, 1], c='r', s=20)
        plt.legend('Position', loc='best')
        start_idx, end_idx = np.where(data)
        segments = [[data[i, :], data[j, :]]
                    for i in range(len(data)) for j in range(len(data))]
        values = np.abs(similarities)
        lc = LineCollection(segments,
                            zorder=0, cmap=plt.cm.hot_r,
                            norm=plt.Normalize(0, values.max()))
        lc.set_array(similarities.flatten())
        lc.set_linewidths(0.5 * np.ones(len(segments)))
        ax.add_collection(lc)

        for label, x, y in zip(labels, data[:, 0], data[:, 1]):
            plt.annotate(
                label, 
                xy = (x, y), xytext = (-20, 20),
                textcoords = 'offset points', ha = 'right', va = 'bottom',
                bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
                arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))



        plt.show()
Esempio n. 28
0
def plot_trajectory(trajectories, name='trajectory', pos='left'):
    print "Plotting trajectory: %s" % name
    plt.figure(1, figsize=(4, 4))

    ax = plt.subplot(111)
    trajx = np.concatenate([t[0] for t in trajectories])
    trajy = np.concatenate([t[1] for t in trajectories])
    annote = set()
    for t in trajectories:
        for a in t[2]:
            annote.add(a)

    cmap = plt.get_cmap('Greys')

    t = np.arange(trajx.shape[0]) * 0.001
    points = np.array([trajy, trajx]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lc = LineCollection(segments, cmap=cmap,
                        norm=plt.Normalize(-t[-1] * 0.5, t[-1] * 0.75))
    lc.set_array(t)
    lc.set_linewidth(3)
    lc.set_rasterized(True)
    ax.add_collection(lc)

    for (a_t, l) in annote:
        ix = int(a_t / 0.001) - 1
        xy = (trajy[ix], trajx[ix])
        xytext = (-30 if xy[0] > 0 else 30, -30 if xy[1] > 0 else 30)
        if l == 'Start of next trial' and xy[1] > 0:
            l = 'Start of\nnext trial'
            xytext = (-50, 5)
        if l == 'Release\n(premature)':
            xytext = (-10, -35)
        plt.annotate(l, xy, xycoords='data', xytext=xytext, ha='center',
                     va='center', textcoords='offset points',
                     arrowprops={'arrowstyle': '->',
                                 'connectionstyle': 'arc3, rad=0.2'})

    plt.axhline(0.0, color='k', ls=":")
    plt.axvline(0.0, color='k', ls=":")
    if 'left' in pos:
        plt.ylabel("Task state (arbitrary units)")
        ax.get_yaxis().tick_left()
    else:
        plt.yticks(())
    ax.get_xaxis().tick_bottom()
    plt.xlabel("Relative time in task state (arbitrary units)")


    plt.axis((-1.5, 1.5, -2.0, 1.5))
    plt.subplots_adjust(bottom=0.12, top=0.97, left=0.17, right=0.97)

    save_or_show('plots/' + name + '_traj')
Esempio n. 29
0
def plot_colored_line(ax, x, y, c=None, s=2, **kwargs):
    """ Draws a linegraph with the line color coded.
    """
    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lc = LineCollection(segments, **kwargs)
    if c is not None:
        lc.set_array(c)
    lc.set_linewidth(s)
    ax.add_collection(lc)
    ax.set_xlim([x.min(), x.max()])
    ax.set_ylim([y.min(), y.max()])
Esempio n. 30
0
def plot_linestring_collection(ax, geoms, values=None, color=None,
                               cmap=None, vmin=None, vmax=None, **kwargs):
    """
    Plots a collection of LineString and MultiLineString geometries to `ax`

    Parameters
    ----------

    ax : matplotlib.axes.Axes
        where shapes will be plotted

    geoms : a sequence of `N` LineStrings and/or MultiLineStrings (can be
            mixed)

    values : a sequence of `N` values, optional
        Values will be mapped to colors using vmin/vmax/cmap. They should
        have 1:1 correspondence with the geometries (not their components).

    color : single color or sequence of `N` colors
        Cannot be used together with `values`.

    Returns
    -------

    collection : matplotlib.collections.Collection that was plotted

    """
    from matplotlib.collections import LineCollection

    geoms, values = _flatten_multi_geoms(geoms, values)
    if None in values:
        values = None

    # LineCollection does not accept some kwargs.
    if 'markersize' in kwargs:
        del kwargs['markersize']

    # color=None gives black instead of default color cycle
    if color is not None:
        kwargs['color'] = color

    segments = [np.array(linestring)[:, :2] for linestring in geoms]
    collection = LineCollection(segments, **kwargs)

    if values is not None:
        collection.set_array(np.asarray(values))
        collection.set_cmap(cmap)
        collection.set_clim(vmin, vmax)

    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    return collection
Esempio n. 31
0
    non_zero)  # 只有条件non_zero,所以返回non_zero.nonzero(),即返回有两个元素的元组,
# 第一个元素为非零的数在O轴即竖轴的下标,第二个元素为非零的数在1轴即横轴的下标

# a sequence of (*line0*, *line1*, *line2*), where::linen = (x0, y0), (x1, y1), ... (xm, ym)
segments = [[embedding[:, start], embedding[:, stop]]
            for start, stop in zip(start_idx, end_idx)]
#embedding为二维数组

values = np.abs(partial_correlations[non_zero])  # 用non_zero遮罩后的15个元素的数组
lc = LineCollection(segments,
                    zorder=0,
                    cmap=plt.cm.hot_r,
                    norm=plt.Normalize(
                        0, .7 * values.max()))  # zorder:调整层次,cmap:colormap

lc.set_array(values)
lc.set_linewidths(6 * values)
ax.add_collection(lc)

# Add a label to each node. The challenge here is that we want to
# position the labels to avoid overlap with other labels
for index, (name, label, (x, y)) in enumerate(zip(names, labels, embedding.T)):
    dx = x - embedding[0]
    dx[index] = 1
    dy = y - embedding[1]
    dy[index] = 1
    this_dx = dx[np.argmin(np.abs(dy))]
    this_dy = dy[np.argmin(np.abs(dx))]
    if this_dx > 0:
        horizontalalignment = 'left'
        x = x + .002
Esempio n. 32
0
def show_rag(labels, rag, image, border_color='black', edge_width=1.5,
             edge_cmap='magma', img_cmap='bone', in_place=True, ax=None):
    """Show a Region Adjacency Graph on an image.

    Given a labelled image and its corresponding RAG, show the nodes and edges
    of the RAG on the image with the specified colors. Edges are displayed between
    the centroid of the 2 adjacent regions in the image.

    Parameters
    ----------
    labels : ndarray, shape (M, N)
        The labelled image.
    rag : RAG
        The Region Adjacency Graph.
    image : ndarray, shape (M, N[, 3])
        Input image. If `colormap` is `None`, the image should be in RGB
        format.
    border_color : color spec, optional
        Color with which the borders between regions are drawn.
    edge_width : float, optional
        The thickness with which the RAG edges are drawn.
    edge_cmap : :py:class:`matplotlib.colors.Colormap`, optional
        Any matplotlib colormap with which the edges are drawn.
    img_cmap : :py:class:`matplotlib.colors.Colormap`, optional
        Any matplotlib colormap with which the image is draw. If set to `None`
        the image is drawn as it is.
    in_place : bool, optional
        If set, the RAG is modified in place. For each node `n` the function
        will set a new attribute ``rag.node[n]['centroid']``.
    ax : :py:class:`matplotlib.axes.Axes`, optional
        The axes to draw on. If not specified, new axes are created and drawn
        on.

    Returns
    -------
    lc : :py:class:`matplotlib.collections.LineCollection`
         A colection of lines that represent the edges of the graph. It can be
         passed to the :meth:`matplotlib.figure.Figure.colorbar` function.

    Examples
    --------
    >>> from skimage import data, segmentation
    >>> from skimage.future import graph
    >>> import matplotlib.pyplot as plt
    >>>
    >>> img = data.coffee()
    >>> labels = segmentation.slic(img)
    >>> g =  graph.rag_mean_color(img, labels)
    >>> lc = graph.show_rag(labels, g, img)
    >>> cbar = plt.colorbar(lc)
    """
    from matplotlib import colors, cm
    from matplotlib import pyplot as plt
    from matplotlib.collections import LineCollection

    if not in_place:
        rag = rag.copy()

    if ax is None:
        fig, ax = plt.subplots()
    out = util.img_as_float(image, force_copy=True)

    if img_cmap is None:
        if image.ndim < 3 or image.shape[2] not in [3, 4]:
            msg = 'If colormap is `None`, an RGB or RGBA image should be given'
            raise ValueError(msg)
        # Ignore the alpha channel
        out = image[:, :, :3]
    else:
        img_cmap = cm.get_cmap(img_cmap)
        out = color.rgb2gray(image)
        # Ignore the alpha channel
        out = img_cmap(out)[:, :, :3]

    edge_cmap = cm.get_cmap(edge_cmap)

    # Handling the case where one node has multiple labels
    # offset is 1 so that regionprops does not ignore 0
    offset = 1
    map_array = np.arange(labels.max() + 1)
    for n, d in rag.nodes(data=True):
        for label in d['labels']:
            map_array[label] = offset
        offset += 1

    rag_labels = map_array[labels]
    regions = measure.regionprops(rag_labels)

    for (n, data), region in zip(rag.nodes(data=True), regions):
        data['centroid'] = tuple(map(int, region['centroid']))

    cc = colors.ColorConverter()
    if border_color is not None:
        border_color = cc.to_rgb(border_color)
        out = segmentation.mark_boundaries(out, rag_labels, color=border_color)

    ax.imshow(out)

    # Defining the end points of the edges
    # The tuple[::-1] syntax reverses a tuple as matplotlib uses (x,y)
    # convention while skimage uses (row, column)
    lines = [[rag.node[n1]['centroid'][::-1], rag.node[n2]['centroid'][::-1]]
             for (n1, n2) in rag.edges()]

    lc = LineCollection(lines, linewidths=edge_width, cmap=edge_cmap)
    edge_weights = [d['weight'] for x, y, d in rag.edges(data=True)]
    lc.set_array(np.array(edge_weights))
    ax.add_collection(lc)

    return lc
Esempio n. 33
0
ax = plt.axes([0., 0., 1., 1.])



similarities[np.isinf(similarities)] = 0
# similarities[similarities<1]=0
print np.max(similarities)
# Plot the edges
start_idx, end_idx = np.where(pos)
# a sequence of (*line0*, *line1*, *line2*), where::
#            linen = (x0, y0), (x1, y1), ... (xm, ym)
segments = [[pca_data[i, :], pca_data[j, :]]
            for i in range(len(pos)) for j in range(len(pos))]
values = np.abs(similarities)
lc = LineCollection(segments,
                    zorder=2, cmap=plt.cm.Greys,
                    norm=plt.Normalize(0, values.max()))
lc.set_array(similarities.flatten())
lc.set_linewidths(0.5 * np.ones(len(segments)))
ax.add_collection(lc)

s = 100
plt.scatter(pca_data[:, 0], pca_data[:, 1], color='red', s=s, lw=0,
            label='True Position')
# plt.scatter(pos[:, 0], pos[:, 1], color='turquoise', s=s, lw=0, label='MDS')
# plt.scatter(npos[:, 0], npos[:, 1], color='darkorange', s=s, lw=0, label='NMDS')
plt.legend(scatterpoints=1, loc='best', shadow=False)
plt.show()


Esempio n. 34
0
def _h_path_curvature(skeletons,
                      body_length=None,
                      partition_str='body',
                      path_step=DFLT_ARGS['path_step'],
                      path_grad_window=DFLT_ARGS['path_grad_window'],
                      _is_debug=False):

    if body_length is None:
        #caculate the length if it is not given
        body_length = np.nanmedian(get_length(skeletons))
    #clip_val = clip_val_body_lengths/body_length

    p_obj = DataPartition(n_segments=skeletons.shape[1])
    body_coords = p_obj.apply(skeletons, partition_str, func=np.mean)

    xx = body_coords[:, 0]
    yy = body_coords[:, 1]
    tt = np.arange(body_coords.shape[0])

    #empty array return
    if body_coords.size == 0 or np.all(np.isnan(body_coords)):
        return np.full_like(tt, np.nan), body_coords

    #interpolate nan values
    good = ~np.isnan(xx)

    x_i = xx[good]
    y_i = yy[good]
    t_i = tt[good]

    t_i = np.hstack([-1, t_i, body_coords.shape[0]])
    x_i = np.hstack([x_i[0], x_i, x_i[-1]])
    y_i = np.hstack([y_i[0], y_i, y_i[-1]])

    fx = interp1d(t_i, x_i)
    fy = interp1d(t_i, y_i)

    xx_i = fx(tt)
    yy_i = fy(tt)

    # calculate the cumulative length for each segment in the curve
    dx = np.diff(xx_i)
    dy = np.diff(yy_i)
    dr = np.sqrt(dx * dx + dy * dy)

    lengths = np.cumsum(dr)
    lengths = np.hstack((0, lengths))

    fx = interp1d(lengths, xx_i)
    fy = interp1d(lengths, yy_i)
    ft = interp1d(lengths, tt)

    sub_lengths = np.arange(lengths[0], lengths[-1], path_step)

    #there is not enough data to calculate the curvature
    if len(sub_lengths) <= 4 * path_grad_window:
        return np.full(skeletons.shape[0], np.nan), body_coords

    xs = fx(sub_lengths)
    ys = fy(sub_lengths)
    ts = ft(sub_lengths)

    curve = np.vstack((xs, ys)).T
    curvature_r = curvature_grad(curve,
                                 points_window=path_grad_window,
                                 axis=0,
                                 is_nan_border=False)

    #clip values to remove regions with extremely large curvatures (typically short reversars)
    #curvature_r = np.clip(curvature_r, -clip_val,clip_val)

    ts_i = np.hstack((-1, ts, tt[-1] + 1))
    c_i = np.hstack((curvature_r[0], curvature_r, curvature_r[-1]))
    curvature_t = interp1d(ts_i, c_i)(tt)

    if _is_debug:
        import matplotlib.pylab as plt
        from matplotlib.collections import LineCollection
        #path_curvature[np.isnan(worm_features['speed'])] = np.nan
        #path_curvature = np.clip(curvature_t, -0.02, 0.02)
        path_curvature = curvature_t

        curv_range = (np.nanmin(path_curvature), np.nanmax(path_curvature))

        points = body_coords.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        lc = LineCollection(segments,
                            cmap=plt.get_cmap('plasma'),
                            norm=plt.Normalize(*curv_range))
        lc.set_array(path_curvature)
        lc.set_linewidth(2)

        plt.figure(figsize=(20, 5))

        plt.subplot(1, 2, 1)
        plt.gca().add_collection(lc)

        plt.xlim(3000, 11000)
        plt.ylim(3000, 11000)
        plt.axis('equal')

        plt.subplot(1, 2, 2)
        plt.plot(path_curvature)

    return curvature_t, body_coords
Esempio n. 35
0
    def colorplotMD(self,
                    xvals,
                    yvals,
                    cvals,
                    title="",
                    xlabel="",
                    ylabel="",
                    label="",
                    cmap="hsv",
                    config=None,
                    color="black",
                    marker=None,
                    zoom="box",
                    nopaint=False,
                    test_kda=False,
                    integerticks=False,
                    **kwargs):
        self._axes = [0.11, 0.1, 0.64, 0.8]
        self.clear_plot("nopaint")
        self.xlabel = xlabel
        self.ylabel = ylabel
        self.zoomtype = zoom
        if "nticks" in kwargs:
            nticks = kwargs["nticks"]
            del kwargs['nticks']
        else:
            nticks = None

        if test_kda:
            self.kda_test(xvals)

        pubflag = 0
        if config is not None:
            if config.publicationmode is not 0:
                pubflag = 1

        self.subplot1 = self.figure.add_axes(self._axes)

        points = np.array([xvals, yvals]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        # print segments
        t = cvals  # np.linspace(0, 1, len(xvals), endpoint=True)
        lc = LineCollection(segments, cmap=cmap)
        lc.set_array(t)
        lc.set_clim(0, 1)
        self.subplot1.add_collection(lc)

        if pubflag == 0:
            self.subplot1.set_ylabel(self.ylabel)
            self.subplot1.set_title(title)
        else:

            self.subplot1.spines['top'].set_visible(False)
            self.subplot1.spines['right'].set_visible(False)
            self.subplot1.get_xaxis().tick_bottom()
            self.subplot1.get_yaxis().tick_left()
            self.subplot1.get_yaxis().set_tick_params(direction='out')
            self.subplot1.get_xaxis().set_tick_params(direction='out')
            if config.peaknorm is not 2:
                self.subplot1.get_yaxis().set_ticks(
                    [0, np.amax(yvals) / 2,
                     np.amax(yvals)])
                self.subplot1.get_yaxis().set_ticklabels(["0", '%', "100"])
            else:
                self.subplot1.set_ylabel("Relative Intensity")

        if nticks is not None:
            self.subplot1.xaxis.set_major_locator(MaxNLocator(nbins=nticks))
        if integerticks:
            self.subplot1.xaxis.set_major_locator(MaxNLocator(integer=True))

        self.subplot1.set_xlabel(self.xlabel)
        cax = self.figure.add_axes([0.77, 0.1, 0.04, 0.8])
        self.cbar = colorbar.ColorbarBase(cax,
                                          cmap=cmap,
                                          orientation="vertical",
                                          ticks=np.linspace(0.,
                                                            1.,
                                                            11,
                                                            endpoint=True))
        self.cbar.set_label("Normalized Mass Defect")

        self.setup_zoom([self.subplot1],
                        self.zoomtype,
                        data_lims=[
                            np.amin(xvals),
                            np.amin(yvals),
                            np.max(xvals),
                            np.amax(yvals)
                        ])

        if not nopaint:
            self.repaint()
        self.flag = True
        self.mlist = []
        self.x1, self.x2 = None, None
        self.colors = []
Esempio n. 36
0
def add_phylorate(treeplot, rates, nodeidx, vis=True):
    """
    Add phylorate plot generated from data analyzed with BAMM
    (http://bamm-project.org/introduction.html)

    Args:
        rates (array): Array of rates along branches
          created by r_funcs.phylorate
        nodeidx (array): Array of node indices matching rates (also created
          by r_funcs.phylorate)

    WARNING:
        Ladderizing the tree can cause incorrect assignment of Ape node index
        numbers. To prevent this, call this function or root.ape_node_idx()
        before ladderizing the tree to assign correct Ape node index numbers.
    """
    if not treeplot.root.apeidx:
        treeplot.root.ape_node_idx()
    segments = []
    values = []

    if treeplot.plottype == "radial":
        radpatches = [] # For use in drawing arcs for radial plots

        for n in treeplot.root.descendants():
            n.rates = rates[nodeidx==n.apeidx]
            c = treeplot.n2c[n]
            pc = treeplot._path_to_parent(n)[0][1]
            xd = c.x - pc[0]
            yd = c.y - pc[1]
            xseg = xd/len(n.rates)
            yseg = yd/len(n.rates)
            for i, rate in enumerate(n.rates):
                x0 = pc[0] + i*xseg
                y0 = pc[1] + i*yseg
                x1 = x0 + xseg
                y1 = y0 + yseg

                segments.append(((x0, y0), (x1, y1)))
                values.append(rate)

            curverts = treeplot._path_to_parent(n)[0][2:]
            curcodes = treeplot._path_to_parent(n)[1][2:]
            curcol = RdYlBu(n.rates[0])

            radpatches.append(PathPatch(
                       Path(curverts, curcodes), lw=2, edgecolor = curcol,
                            fill=False))
    else:
        for n in treeplot.root.descendants():
            n.rates = rates[nodeidx==n.apeidx]
            c = treeplot.n2c[n]
            pc = treeplot.n2c[n.parent]
            seglen = (c.x-pc.x)/len(n.rates)
            for i, rate in enumerate(n.rates):
                x0 = pc.x + i*seglen
                x1 = x0 + seglen
                segments.append(((x0, c.y), (x1, c.y)))
                values.append(rate)
            segments.append(((pc.x, pc.y), (pc.x, c.y)))
            values.append(n.rates[0])

    lc = LineCollection(segments, cmap=RdYlBu, lw=2)
    lc.set_array(np.array(values))
    treeplot.add_collection(lc)
    lc.set_zorder(1)
    if treeplot.plottype == "radial":
        arccol = matplotlib.collections.PatchCollection(radpatches,
                                                        match_original=True)
        treeplot.add_collection(arccol)
        arccol.set_visible(vis)
        arccol.set_zorder(1)
    lc.set_visible(vis)
    colorbar_legend(treeplot, values, RdYlBu, vis=vis)

    treeplot.figure.canvas.draw_idle()
def plot_tracks_2D_colorcode(trackDF,
                             output_fig_path=None,
                             colorcode='z',
                             color_map='jet',
                             color_bar=True,
                             norm_min=None,
                             norm_max=None,
                             track_list=None,
                             tracks_highlight=None,
                             plot_xy_outlines=False,
                             polyline_df_xy=None,
                             z_range=15,
                             x_ticks=None,
                             y_ticks=None,
                             draw_spot_start=False,
                             draw_spot_end=False):

    assert colorcode in ['z', 'speed', 'time']

    fig = plt.figure(figsize=(2, 2), dpi=300)
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

    x_min, y_min = trackDF.x.min(), trackDF.y.min()
    #     df = trackDF # alias
    if track_list is None:
        track_list = trackDF.track_id.unique()
    for i, track in enumerate(track_list):
        df_temp = trackDF[trackDF.track_id == track]
        df_temp.sort_values('t', ascending=True, inplace=True)
        df_temp.reset_index(inplace=True, drop=True)

        # Extract the x, y coordinates of the points
        x, y = df_temp.x.values - x_min, df_temp.y.values - y_min

        # Create a set of line segments so that we can color them individually
        # This creates the points as a N x 1 x 2 array so that we can stack points
        # together easily to get the segments. The segments array for line collection
        # needs to be (numlines) x (points per line) x 2 (for x and y)
        points = np.array([x, y]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)

        if colorcode == 'z':
            color_code_values = df_temp.z.values[:-1]
            if norm_min is None:
                norm_min = 0
            if norm_max is None:
                norm_max = 100

        elif colorcode == 'speed':
            # Calculate the mean track speed (drop last point to match segment number)
            color_code_values = get_mean_speed_track(df_temp,
                                                     n_rolling=12)[:-1]
            if norm_min is None:
                norm_min = 10
            if norm_max is None:
                norm_max = 40

        elif colorcode == 'time':
            # Calculte time from anaphase onset
            # Convert frames to minutes (5 min per frame)
            if 't_normed' in df_temp.columns:
                color_code_values = df_temp.t_normed.values[1:]
            else:
                n_pre = df_temp.pre_anaphase_onset_n_frames.values[0]
                frames = df_temp.t.values[1:]
                start_frame = df_temp.t.min()
                color_code_values = [
                    5 * (i - n_pre - start_frame) for i in frames
                ]
            if norm_min is None:
                norm_min = 0
            if norm_max is None:
                norm_max = 240

        # make color code values into a numpy array
        color_code_values = np.array(color_code_values)

        # Create a continuous norm to map from data points to colors
        norm = plt.Normalize(
            norm_min, norm_max)  # empirically determined speed normalization
        lc = LineCollection(segments, cmap=color_map, norm=norm)
        # Set the values used for colormapping
        lc.set_array(color_code_values)
        lc.set_linewidth(.6)
        line = ax.add_collection(lc)

        if draw_spot_start == True:
            ax.plot(x[0],
                    y[0],
                    'ob',
                    alpha=.4,
                    markersize=2,
                    markeredgewidth=0)
        if draw_spot_end == True:
            ax.plot(x[-1],
                    y[-1],
                    'or',
                    alpha=.4,
                    markersize=2,
                    markeredgewidth=0)

    if plot_xy_outlines:
        plot_2D_outlines_xy(polyline_df_xy,
                            t=1,
                            z_range=z_range,
                            shift_x=x_min,
                            shift_y=y_min,
                            ax=ax,
                            line_color='#1A6A82',
                            line_alpha=.02,
                            line_width=.6)
        plot_2D_outlines_xy(polyline_df_xy,
                            t=192,
                            z_range=z_range,
                            shift_x=x_min,
                            shift_y=y_min,
                            ax=ax,
                            line_color='#A05B22',
                            line_alpha=.02,
                            line_width=.6)

    # *** add color bar ***
    if color_bar:
        fig.colorbar(line, ax=ax)

    # *** add axis labels ***
    ax.set_xlabel('x')
    ax.set_ylabel('y')

    # *** set axis ticks if provided ***
    if x_ticks is not None:
        ax.set_xticks(x_ticks)
    if y_ticks is not None:
        ax.set_yticks(y_ticks)

    # *** Make the x and y axes equal in dimension to mimic image display ***
    ax.axis('equal')

    # *** Flip the y-axis to match the image coordinates ***
    plt.gca().invert_yaxis()

    for o in fig.findobj():
        o.set_clip_on(False)
    for o in ax.findobj():
        o.set_clip_on(False)

    if output_fig_path is not None:
        plt.savefig(output_fig_path)

    return ax
Esempio n. 38
0
ax.plot([0, 1], [0, 1], color='lightgray')
ax.axvline(0, lw=0.5, color='lightgray')
ax.axhline(1, lw=0.5, color='lightgray')

fpr, tpr, t = roc_curve(df['label'],
                        df['probabilities'],
                        drop_intermediate=False)

nth = 5000
fpr, tpr, t = fpr[::nth], tpr[::nth], t[::nth]

points = np.array([fpr, tpr]).T.reshape((-1, 1, 2))
segments = np.concatenate([points[:-1], points[1:]], axis=1)
col = LineCollection(segments, zorder=3)
col.set_array(t)
col.set_clim(0, 1)
col.set_cmap('inferno')
ax.add_collection(col)

rocs = np.array([
    roc_auc_score(fold['label'], fold['probabilities'])
    for _, fold in df.groupby('cv_fold')
])

ax.set_title(f'ROC-AUC: {rocs.mean():.4f} ± {rocs.std():.4f}')

ax.set_ylim(0, 1.025)
ax.set_xlim(-0.025, 1)
ax.set_aspect(1)
ax.set_xlabel('False Positive Rate')
Esempio n. 39
0
def station_data(ts_data,
                 time_obs,
                 keys=None,
                 stations=None,
                 path=None,
                 save=True,
                 show=False,
                 ext='.png'):
    """
    Plot the station data in ``ts_data`` with ``time_obs`` as the x axis. To
    plot only a subset of this data list which ADCIRC Output types to plot in
    keys.

    :type ts_data: :class:`dict`
    :param ts_data: ``ts_data`` from
        :class:`~polyadcirc.run_framework.random_manningsn.runSet`
    :type time_obs: :class:`dict`
    :param time_obs: ``time_obs`` from
        :class:`~polyadcirc.run_framework.random_manningsn.runSet`
    :param list() keys: list of types of ADCIRC output data to plot 
    :param dict stations: dictonary of lists of stations to plot
    :type path: string or None
    :param path: directory to store plots
    :type save: boolean
    :param save: flag for whether or not to save plots
    :type show: boolean
    :param show: flag for whether or not to show plots
    :param string ext: file extension
    
    """
    if path == None:
        path = os.getcwd()

    if keys == None:
        keys = ts_data.keys()
    s_keys = list()
    for k in keys:
        if f15.filetype[k][0]:
            s_keys.append(k)
    keys = s_keys

    for k in keys:
        fm.mkdir(path + '/figs/' + k)
        if stations[k] == None:
            stations = xrange(ts_data[k].shape[0])
        for i in stations:
            fig = plt.figure()
            x = time_obs[k]

            num_plts = f15.filetype[k][1]

            if num_plts == 1:
                ax = fig.add_subplot(111)
                ax.set_xlim((np.min(x), np.max(x)))
                ax.set_ylim((np.min(ts_data[k]), np.max(ts_data[k])))

                segs = list()
                for j in xrange(ts_data[k].shape[2]):
                    segs.append(zip(x, ts_data[k][i, ..., j]))

                line_segs = LineCollection(segs, linestyles='solid')
                line_segs.set_array(np.arange(ts_data[k].shape[2]))
                ax.add_collection(line_segs)
                ax.set_xlabel('time')
                colorbar(line_segs, fig)

            elif num_plts == 2:
                ax1 = fig.add_subplot(121)
                ax2 = fig.add_subplot(122)

                ax1.set_xlim((np.min(x), np.max(x)))
                ax1.set_ylim(
                    (np.min(ts_data[k][:, :,
                                       0, :]), np.max(ts_data[k][:, :, 0, :])))
                ax2.set_xlim((np.min(x), np.max(x)))
                ax2.set_ylim(
                    (np.min(ts_data[k][:, :,
                                       1, :]), np.max(ts_data[k][:, :, 1, :])))
                segs1 = list()
                segs2 = list()
                for j in xrange(ts_data[k].shape[-1]):
                    segs1.append(zip(x, ts_data[k][i, :, 0, j]))
                    segs2.append(zip(x, ts_data[k][i, :, 1, j]))

                line_segs1 = LineCollection(segs1, linestyles='solid')
                line_segs1.set_array(np.arange(ts_data[k].shape[-1]))
                ax1.add_collection(line_segs1)
                ax1.set_ylabel('u (m/s)')
                ax1.set_xlabel('time')
                line_segs2 = LineCollection(segs2, linestyles='solid')
                line_segs2.set_array(np.arange(ts_data[k].shape[-1]))
                ax2.add_collection(line_segs2)
                ax2.set_xlabel('time')
                ax2.set_ylabel('v (m/s)')
                colorbar(line_segs2, fig)

            save_show(path + '/figs/' + k + '/station' + str(i), save, show,
                      ext)
Esempio n. 40
0
def plot_curvature():
    """
    This function computes analytically the curvature 
    at various points on the attractor and compares against 
    the numerical values obtained from the algorithm in 
    dclv_clv, for the directional derivative of the 1st 
    CLV along itself.
    """
    s = [1., Inf]
    u = rand(3, 1)
    n = 10000
    u0 = step(u, s, n)[0, :, -1]
    u0 = u0.reshape(3, 1)
    u_trj = step(u0, s, n)[0]

    d, n = u_trj.shape
    x, y, z = u_trj
    t_trj = arctan2(y, x)[1:]
    t_trj = t_trj % (2 * pi)
    du_trj = dstep(u_trj, s)
    clv_trj = clvs(u_trj, du_trj, 1)
    V1 = clv_trj[:, :, 0]
    ddu_trj = d2step(u_trj, s)
    W1 = dclv_clv(clv_trj, du_trj, ddu_trj)
    W1 = W1[:, :, 0]
    W1_ana = analytical_W1(u_trj).T[:-1]
    W1 = W1[1:]
    eps = array([-1E-2, 1E-2]).reshape([1, 2, 1])
    segments = u_trj[:2].T.reshape([-1,1,2]) + \
            eps * V1[:,:2].reshape([-1,1,2])
    curvature_num = norm(W1, axis=1)
    curvature = norm(W1_ana, axis=1)
    assert (allclose(curvature, curvature_num, rtol=0.05))

    lc = LineCollection(segments, cmap=plt.get_cmap('RdBu'), \
            norm=plt.Normalize(min(curvature), max(curvature)))
    lc.set_array(curvature)
    lc.set_linewidth(1)
    lc1 = LineCollection(segments, cmap=plt.get_cmap('RdBu'), \
            norm=plt.Normalize(min(curvature_num), max(curvature_num)))
    lc1.set_array(curvature_num)
    lc1.set_linewidth(1)

    fig, ax = subplots(1, 2)
    ax[0].add_collection(lc)
    ax[1].add_collection(lc1)
    '''
    rad1 = 1.5
    xx = linspace(-rad1,rad1,10000)
    yy = sqrt(rad1*rad1 - xx*xx)
    ax[0].plot(xx, yy,'-',color='gray',alpha=0.2)
    ax[0].plot(xx, -yy,'-',color='gray',alpha=0.2)
    
    ax[1].plot(xx, yy,'-',color='gray',alpha=0.2)
    ax[1].plot(xx, -yy,'-',color='gray',alpha=0.2)
    rad2 = 0.5
    xx = linspace(-rad2,rad2,10000)
    yy = sqrt(rad2*rad2 - xx*xx)
    ax[0].plot(xx, yy,'-',color='gray',alpha=0.2)
    ax[0].plot(xx, -yy,'-',color='gray',alpha=0.2)
    
    ax[1].plot(xx, yy,'-',color='gray',alpha=0.2)
    ax[1].plot(xx, -yy,'-',color='gray',alpha=0.2)
    '''
    ax[0].axis('scaled')
    ax[1].axis('scaled')

    ax[0].set_title('Analytical curvature', fontsize=30)
    ax[1].set_title('Numerical curvature', fontsize=30)
    ax[0].xaxis.set_tick_params(labelsize=30)
    ax[0].yaxis.set_tick_params(labelsize=30)
    ax[0].set_xlabel('$x_1$', fontsize=30)
    ax[0].set_ylabel('$x_2$', fontsize=30)
    ax[1].set_xlabel('$x_1$', fontsize=30)
    ax[1].set_ylabel('$x_2$', fontsize=30)

    ax[1].xaxis.set_tick_params(labelsize=30)
    ax[1].yaxis.set_tick_params(labelsize=30)
    ax[0].grid(True)
    ax[1].grid(True)
    cbar = fig.colorbar(lc,
                        cmap=get_cmap('RdBu'),
                        norm=Normalize(min(curvature), max(curvature)),
                        ax=ax[0])
    cbar.ax.tick_params(labelsize=30)
    cbar1 = fig.colorbar(lc1,
                         cmap=get_cmap('RdBu'),
                         norm=Normalize(min(curvature), max(curvature)),
                         ax=ax[1])
    cbar1.ax.tick_params(labelsize=30)
                                                 N=256)

    fig, axs = plt.subplots(1, 1, figsize=(7, 7))

    axs.margins(y=0, x=0)
    x = np.linspace(0.1, 0.9, num=9)
    y = np.mean(environmentLacunarities, axis=0)
    yq75, yq25 = np.percentile(environmentLacunarities, [75, 25], axis=0)

    colors = cmap(y / np.max(y))
    axs.scatter(x, y, c=colors, edgecolor='none')
    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)

    lc = LineCollection(segments, cmap=cmap)
    lc.set_array(y)
    lc.set_linewidth(1.5)
    axs.add_collection(lc)

    axs.errorbar(x[:3],
                 y[:3],
                 yerr=[(y[:3] - yq25[:3]).tolist(),
                       (yq75[:3] - y[:3]).tolist()],
                 fmt='none',
                 ecolor='#1C76BC')
    axs.errorbar(x[3:7],
                 y[3:7],
                 yerr=[(y[3:7] - yq25[3:7]).tolist(),
                       (yq75[3:7] - y[3:7]).tolist()],
                 fmt='none',
                 ecolor='#6A8055')
Esempio n. 42
0
def create_line_collection(net,
                           lines=None,
                           line_geodata=None,
                           use_bus_geodata=False,
                           infofunc=None,
                           cmap=None,
                           norm=None,
                           picker=False,
                           z=None,
                           cbar_title="Line Loading [%]",
                           clim=None,
                           **kwargs):
    """
    Creates a matplotlib line collection of pandapower lines.

    Input:
        **net** (pandapowerNet) - The pandapower network

    OPTIONAL:
        **lines** (list, None) - The lines for which the collections are created. If None, all lines
        in the network are considered.

        **line_geodata** (DataFrame, None) - coordinates to use for plotting If None,
        net["line_geodata"] is used

         **infofunc** (function, None) - infofunction for the patch element

        **kwargs - key word arguments are passed to the patch function

    """
    lines = net.line.index.tolist() if lines is None else list(lines)
    if len(lines) == 0:
        return None
    if line_geodata is None:
        line_geodata = net["line_geodata"]
    if len(lines) == 0:
        return None

    if use_bus_geodata:
        data = [
            ([(net.bus_geodata.at[a, "x"], net.bus_geodata.at[a, "y"]),
              (net.bus_geodata.at[b, "x"], net.bus_geodata.at[b, "y"])],
             infofunc(line) if infofunc else [])
            for line, (a,
                       b) in net.line.loc[lines,
                                          ["from_bus", "to_bus"]].iterrows()
            if a in net.bus_geodata.index.values
            and b in net.bus_geodata.index.values
        ]
    else:
        data = [(line_geodata.loc[line, "coords"],
                 infofunc(line) if infofunc else []) for line in lines
                if line in line_geodata.index.values]

    if len(data) == 0:
        return None

    data, info = list(zip(*data))

    # This would be done anyways by matplotlib - doing it explicitly makes it a) clear and
    # b) prevents unexpected behavior when observing colors being "none"
    lc = LineCollection(data, picker=picker, **kwargs)
    lc.line_indices = np.array(lines)
    if cmap:
        if z is None:
            z = net.res_line.loading_percent.loc[lines]
        lc.set_cmap(cmap)
        lc.set_norm(norm)
        if clim is not None:
            lc.set_clim(clim)
        lc.set_array(np.array(z))
        lc.has_colormap = True
        lc.cbar_title = cbar_title
    lc.info = info
    return lc
Esempio n. 43
0
def draw_networkx_edges(G,
                        pos,
                        edgelist=None,
                        width=1.0,
                        edge_color='k',
                        style='solid',
                        alpha=None,
                        edge_cmap=None,
                        edge_vmin=None,
                        edge_vmax=None,
                        ax=None,
                        arrows=True,
                        **kwds):
    """Draw the edges of the graph G.

    This draws only the edges of the graph G.

    Parameters
    ----------
    G : graph
       A networkx graph 

    pos : dictionary
       A dictionary with nodes as keys and positions as values.
       If not specified a spring layout positioning will be computed.
       See networkx.layout for functions that compute node positions.
       
    ax : Matplotlib Axes object, optional
       Draw the graph in the specified Matplotlib axes.  

    alpha: float
       The edge transparency (default=1.0) 

    width`: float
       Line width of edges (default =1.0)

    edge_color: color string, or array of floats
       Edge color. Can be a single color format string (default='r'),
       or a sequence of colors with the same length as edgelist.
       If numeric values are specified they will be mapped to
       colors using the edge_cmap and edge_vmin,edge_vmax parameters.

    edge_ cmap: Matplotlib colormap
       Colormap for mapping intensities of edges (default=None)

    edge_vmin,edge_vmax: floats
       Minimum and maximum for edge colormap scaling (default=None)

    style: string
       Edge line style (default='solid') (solid|dashed|dotted,dashdot)

    Notes
    -----
    For directed graphs, "arrows" (actually just thicker stubs) are drawn
    at the head end.  Arrows can be turned off with keyword arrows=False.
    Yes, it is ugly but drawing proper arrows with Matplotlib this
    way is tricky.

    Examples
    --------
    >>> G=nx.dodecahedral_graph()
    >>> edges=nx.draw_networkx_edges(G,pos=nx.spring_layout(G)) 

    Also see the NetworkX drawing examples at
    http://networkx.lanl.gov/gallery.html

    See Also
    --------
    draw()
    draw_networkx()
    draw_networkx_nodes()
    draw_networkx_labels()
    draw_networkx_edge_labels()

    """
    try:
        import matplotlib
        import matplotlib.pylab as pylab
        import matplotlib.cbook as cb
        from matplotlib.colors import colorConverter, Colormap
        from matplotlib.collections import LineCollection
        import numpy
    except ImportError:
        raise ImportError("Matplotlib required for draw()")
    except RuntimeError:
        print("Matplotlib unable to open display")
        raise

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

    if edgelist is None:
        edgelist = G.edges()

    if not edgelist or len(edgelist) == 0:  # no edges!
        return None

    # set edge positions
    edge_pos = numpy.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])

    if not cb.iterable(width):
        lw = (width, )
    else:
        lw = width

    if not cb.is_string_like(edge_color) \
           and cb.iterable(edge_color) \
           and len(edge_color)==len(edge_pos):
        if numpy.alltrue([cb.is_string_like(c) for c in edge_color]):
            # (should check ALL elements)
            # list of color letters such as ['k','r','k',...]
            edge_colors = tuple(
                [colorConverter.to_rgba(c, alpha) for c in edge_color])
        elif numpy.alltrue([not cb.is_string_like(c) for c in edge_color]):
            # If color specs are given as (rgb) or (rgba) tuples, we're OK
            if numpy.alltrue(
                [cb.iterable(c) and len(c) in (3, 4) for c in edge_color]):
                edge_colors = tuple(edge_color)
            else:
                # numbers (which are going to be mapped with a colormap)
                edge_colors = None
        else:
            raise ValueError(
                'edge_color must consist of either color names or numbers')
    else:
        if cb.is_string_like(edge_color) or len(edge_color) == 1:
            edge_colors = (colorConverter.to_rgba(edge_color, alpha), )
        else:
            raise ValueError(
                'edge_color must be a single color or list of exactly m colors where m is the number or edges'
            )

    edge_collection = LineCollection(
        edge_pos,
        colors=edge_colors,
        linewidths=lw,
        antialiaseds=(1, ),
        linestyle=style,
        transOffset=ax.transData,
    )

    edge_collection.set_zorder(1)  # edges go behind nodes
    ax.add_collection(edge_collection)

    # Note: there was a bug in mpl regarding the handling of alpha values for
    # each line in a LineCollection.  It was fixed in matplotlib in r7184 and
    # r7189 (June 6 2009).  We should then not set the alpha value globally,
    # since the user can instead provide per-edge alphas now.  Only set it
    # globally if provided as a scalar.
    if cb.is_numlike(alpha):
        edge_collection.set_alpha(alpha)

    # need 0.87.7 or greater for edge colormaps
    mpl_version = matplotlib.__version__
    if mpl_version.endswith('.svn'):
        mpl_version = matplotlib.__version__[0:-4]
    elif mpl_version.endswith('svn'):
        mpl_version = matplotlib.__version__[0:-3]
    elif mpl_version.endswith('pre'):
        mpl_version = matplotlib.__version__[0:-3]
    if list(map(int, mpl_version.split('.'))) >= [0, 87, 7]:
        if edge_colors is None:
            if edge_cmap is not None: assert (isinstance(edge_cmap, Colormap))
            edge_collection.set_array(numpy.asarray(edge_color))
            edge_collection.set_cmap(edge_cmap)
            if edge_vmin is not None or edge_vmax is not None:
                edge_collection.set_clim(edge_vmin, edge_vmax)
            else:
                edge_collection.autoscale()
#            pylab.axes(ax)
            pylab.sci(edge_collection)


#    else:
#        sys.stderr.write(\
#            """matplotlib version >= 0.87.7 required for colormapped edges.
#        (version %s detected)."""%matplotlib.__version__)
#        raise UserWarning(\
#            """matplotlib version >= 0.87.7 required for colormapped edges.
#        (version %s detected)."""%matplotlib.__version__)

    arrow_collection = None

    if G.is_directed() and arrows:

        # a directed graph hack
        # draw thick line segments at head end of edge
        # waiting for someone else to implement arrows that will work
        arrow_colors = edge_colors
        a_pos = []
        p = 1.0 - 0.25  # make head segment 25 percent of edge length
        for src, dst in edge_pos:
            x1, y1 = src
            x2, y2 = dst
            dx = x2 - x1  # x offset
            dy = y2 - y1  # y offset
            d = numpy.sqrt(float(dx**2 + dy**2))  # length of edge
            if d == 0:  # source and target at same position
                continue
            if dx == 0:  # vertical edge
                xa = x2
                ya = dy * p + y1
            if dy == 0:  # horizontal edge
                ya = y2
                xa = dx * p + x1
            else:
                theta = numpy.arctan2(dy, dx)
                xa = p * d * numpy.cos(theta) + x1
                ya = p * d * numpy.sin(theta) + y1

            a_pos.append(((xa, ya), (x2, y2)))

        arrow_collection = LineCollection(
            a_pos,
            colors=arrow_colors,
            linewidths=[4 * ww for ww in lw],
            antialiaseds=(1, ),
            transOffset=ax.transData,
        )

        arrow_collection.set_zorder(1)  # edges go behind nodes
        ax.add_collection(arrow_collection)

    # update view
    minx = numpy.amin(numpy.ravel(edge_pos[:, :, 0]))
    maxx = numpy.amax(numpy.ravel(edge_pos[:, :, 0]))
    miny = numpy.amin(numpy.ravel(edge_pos[:, :, 1]))
    maxy = numpy.amax(numpy.ravel(edge_pos[:, :, 1]))

    w = maxx - minx
    h = maxy - miny
    padx, pady = 0.05 * w, 0.05 * h
    corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady)
    ax.update_datalim(corners)
    ax.autoscale_view()

    #    if arrow_collection:

    return edge_collection
def plot_cluster(X, labels, model):
    # We use a dense eigen_solver to achieve reproducibility (arpack is
    # initiated with random vectors that we don't control). In addition, we
    # use a large number of neighbors to capture the large-scale structure.
    node_position_model = manifold.LocallyLinearEmbedding(n_components=2,
                                                          eigen_solver='dense',
                                                          n_neighbors=6)
    embedding = node_position_model.fit_transform(X.T).T

    plt.figure(1, facecolor='w', figsize=(10, 8))
    plt.clf()
    ax = plt.axes([0., 0., 1., 1.])
    plt.axis('off')

    # Display a graph of the partial correlations
    partial_correlations = model.precision_.copy()
    d = 1 / np.sqrt(np.diag(partial_correlations))
    partial_correlations *= d
    partial_correlations *= d[:, np.newaxis]
    non_zero = (np.abs(np.triu(partial_correlations, k=1)) > 0.02)

    # Plot the nodes using the coordinates of our embedding
    plt.scatter(embedding[0],
                embedding[1],
                s=100 * d**2,
                c=labels,
                cmap=plt.cm.spectral)

    # Plot the edges
    start_idx, end_idx = np.where(non_zero)
    # a sequence of (*line0*, *line1*, *line2*), where::
    #            linen = (x0, y0), (x1, y1), ... (xm, ym)
    segments = [[embedding[:, start], embedding[:, stop]]
                for start, stop in zip(start_idx, end_idx)]
    values = np.abs(partial_correlations[non_zero])
    lc = LineCollection(segments,
                        zorder=0,
                        cmap=plt.cm.hot_r,
                        norm=plt.Normalize(0, .7 * values.max()))
    lc.set_array(values)
    lc.set_linewidths(15 * values)
    ax.add_collection(lc)

    # Add a label to each node. The challenge here is that we want to
    # position the labels to avoid overlap with other labels
    for index, (name, label,
                (x, y)) in enumerate(zip(names, labels, embedding.T)):

        dx = x - embedding[0]
        dx[index] = 1
        dy = y - embedding[1]
        dy[index] = 1
        this_dx = dx[np.argmin(np.abs(dy))]
        this_dy = dy[np.argmin(np.abs(dx))]
        if this_dx > 0:
            horizontalalignment = 'left'
            x = x + .002
        else:
            horizontalalignment = 'right'
            x = x - .002
        if this_dy > 0:
            verticalalignment = 'bottom'
            y = y + .002
        else:
            verticalalignment = 'top'
            y = y - .002
        plt.text(x,
                 y,
                 name,
                 size=10,
                 horizontalalignment=horizontalalignment,
                 verticalalignment=verticalalignment,
                 bbox=dict(facecolor='w',
                           edgecolor=plt.cm.spectral(label / float(n_labels)),
                           alpha=.6))

    plt.xlim(
        embedding[0].min() - .15 * embedding[0].ptp(),
        embedding[0].max() + .10 * embedding[0].ptp(),
    )
    plt.ylim(embedding[1].min() - .03 * embedding[1].ptp(),
             embedding[1].max() + .03 * embedding[1].ptp())

    plt.show()
    def make_plot(self, z1, z2, stack, collection, plot):
        cmap = plt.cm.plasma_r
        x1, y1, id1 = self.specs(z1, stack)
        x2, y2, id2 = self.specs(z2, stack)
        dbconnection = make_dbconnection(collection)

        #use mongo to get the point matches
        self.pm = get_matches(z1, z2, collection, dbconnection)
        print('%d tile pairs for z1,z2=%d,%d in collection %s__%s' %
              (len(self.pm), z1, z2, collection['owner'], collection['name']))
        if not plot:
            return

        lclist = [
        ]  #will hold coordinates of line segments (between tile pairs)
        clist = []  #will hold number of point match pairs, used as color

        #tiny line to make sure zero is in there for consistent color range
        tmp = []
        tmp.append((0, 0))
        tmp.append((0, 0.1))
        lclist.append(tmp)
        clist.append(0)
        #tiny line to make sure max is in there for consistent color range
        tmp = []
        tmp.append((0.1, 0.1))
        tmp.append((0, 0.1))
        lclist.append(tmp)
        clist.append(self.args['threshold'])
        #if z1!=z2:
        #   clist.append(500) #limit was set at 500 for cross-section matches
        #else:
        #   clist.append(200) #limit was set at 200 for within section matches

        ntp = 0
        if len(self.pm) != 0:  #only plot if there are matches
            xmin = 1e9
            xmax = -1e9
            ymin = 1e9
            ymax = -1e9
            for k in np.arange(len(self.pm)):
                #find the tilespecs
                k1 = np.argwhere(id1 == self.pm[k]['pId']).flatten()
                k2 = np.argwhere(id2 == self.pm[k]['qId']).flatten()
                if (k1.size != 0) & (k2.size != 0):
                    ntp += 1
                    k1 = k1[0]
                    k2 = k2[0]
                    tmp = []
                    tmp.append((x1[k1], y1[k1]))
                    tmp.append((x2[k2], y2[k2]))
                    lclist.append(tmp)
                    clist.append(len(self.pm[k]['matches']['q'][0]))
                    for ix in [x1[k1], x2[k2]]:
                        if ix.min() < xmin:
                            xmin = ix.min()
                        if ix.max() > xmax:
                            xmax = ix.max()
                    for iy in [y1[k1], y2[k2]]:
                        if iy.min() < ymin:
                            ymin = iy.min()
                        if iy.max() > ymax:
                            ymax = iy.max()
            print('%d tile pairs match stack %s__%s__%s' %
                  (ntp, stack['owner'], stack['project'], stack['name']))

            #plot the line segments all at once for speed:
            # https://matplotlib.org/examples/pylab_examples/line_collection2.html
            fig = plt.figure(1, figsize=(11.69, 8.27))
            fig.clf()
            ax = fig.add_subplot(111)
            border = 4000
            ax.set_xlim(xmin - border, xmax + border)
            ax.set_ylim(ymin - border, ymax + border)

            LC = LineCollection(lclist, cmap=cmap)
            LC.set_array(np.array(clist))
            ax.add_collection(LC)
            fig = plt.gcf()
            ax.set_aspect('equal')
            ax.patch.set_color([0.5, 0.5,
                                0.5])  #gray background, easier to see yellow
            ax.set_title('%s %s\n%d tile pairs %d point pairs' %
                         (z1, z2, len(self.pm), sum(clist[2:])))
            ax.invert_yaxis()
            fig.colorbar(LC)
            plt.draw()
            fname = '%s/%s_%d_%d.pdf' % (self.args['plot_dir'],
                                         collection['name'], z1, z2)
            pdf = PdfPages(fname)
            pdf.savefig(fig)  #save the figure as a pdf page
            pdf.close()
            plt.ion()
            plt.show()
            print('wrote %s' % fname)
            self.outputname = fname
Esempio n. 46
0
        PD_DOWN = probdens[int(probdens.shape[0] / 2):]
        for k in range(N):
            if V[k, k] != 0:
                wt[i, j] += PD_UP[k] + PD_DOWN[k]

fig = plt.figure()
norm = plt.Normalize(0, 1)
ax = fig.add_subplot(1, 1, 1)
for i in range(0, bands.shape[1]):
    ax.plot(qx, bands[:, i], linewidth=1.25, c='w', zorder=-10)
for i in range(0, bands.shape[1]):
    print(bands.shape[1] - i)
    points = np.array([qx, bands[:, i]]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lc = LineCollection(segments, cmap='seismic', norm=norm)
    lc.set_array(wt[:, i])
    lc.set_linewidth(1.0)
    line = ax.add_collection(lc)

ax.patch.set_facecolor('black')
axcb = fig.colorbar(lc)
ax.set_xlim(qx[0], qx[-1])
ax.set_xlabel('kx (1/A)')
ax.set_ylabel('Energy (meV)')
plt.savefig('weighted_bands.png')
plt.show()
sys.exit()

#####################################

VV = sparse.bmat([[None, V], [-V, None]], format='csc', dtype='complex')
Esempio n. 47
0
def draw_networkx_edges(G,
                        pos,
                        edgelist=None,
                        width=1.0,
                        edge_color='k',
                        style='solid',
                        alpha=None,
                        edge_cmap=None,
                        edge_vmin=None,
                        edge_vmax=None,
                        ax=None,
                        arrows=True,
                        **kwds):
    """Draw the edges of the graph G

    This draws only the edges of the graph G.

    pos is a dictionary keyed by vertex with a two-tuple
    of x-y positions as the value.
    See networkx.layout for functions that compute node positions.

    edgelist is an optional list of the edges in G to be drawn.
    If provided, only the edges in edgelist will be drawn.

    edgecolor can be a list of matplotlib color letters such as 'k' or
    'b' that lists the color of each edge; the list must be ordered in
    the same way as the edge list. Alternatively, this list can contain
    numbers and those number are mapped to a color scale using the color
    map edge_cmap.  Finally, it can also be a list of (r,g,b) or (r,g,b,a)
    tuples, in which case these will be used directly to color the edges.  If
    the latter mode is used, you should not provide a value for alpha, as it
    would be applied globally to all lines.

    For directed graphs, 'arrows' (actually just thicker stubs) are drawn
    at the head end.  Arrows can be turned off with keyword arrows=False.

    See draw_networkx for the list of other optional parameters.

    """
    try:
        import matplotlib.pylab as pylab
        import matplotlib.cbook as cb
        from matplotlib.colors import colorConverter, Colormap
        from matplotlib.collections import LineCollection
    except ImportError:
        raise ImportError("Matplotlib required for draw()")
    except RuntimeError:
        pass  # unable to open display

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

    if edgelist is None:
        edgelist = G.edges()

    if not edgelist or len(edgelist) == 0:  # no edges!
        return None

    # set edge positions
    edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])

    if not cb.iterable(width):
        lw = (width, )
    else:
        lw = width

    if not cb.is_string_like(edge_color) \
           and cb.iterable(edge_color) \
           and len(edge_color) == len(edge_pos):
        if np.alltrue([cb.is_string_like(c) for c in edge_color]):
            # (should check ALL elements)
            # list of color letters such as ['k','r','k',...]
            edge_colors = tuple(
                [colorConverter.to_rgba(c, alpha) for c in edge_color])
        elif np.alltrue([not cb.is_string_like(c) for c in edge_color]):
            # If color specs are given as (rgb) or (rgba) tuples, we're OK
            if np.alltrue(
                [cb.iterable(c) and len(c) in (3, 4) for c in edge_color]):
                edge_colors = tuple(edge_color)
                alpha = None
            else:
                # numbers (which are going to be mapped with a colormap)
                edge_colors = None
        else:
            e_s = 'edge_color must consist of either color names or numbers'
            raise ValueError(e_s)
    else:
        if len(edge_color) == 1:
            edge_colors = (colorConverter.to_rgba(edge_color, alpha), )
        else:
            e_s = 'edge_color must be a single color or list of exactly'
            e_s += 'm colors where m is the number or edges'
            raise ValueError(e_s)
    edge_collection = LineCollection(
        edge_pos,
        colors=edge_colors,
        linewidths=lw,
        antialiaseds=(1, ),
        linestyle=style,
        transOffset=ax.transData,
    )

    # Note: there was a bug in mpl regarding the handling of alpha values for
    # each line in a LineCollection.  It was fixed in matplotlib in r7184 and
    # r7189 (June 6 2009).  We should then not set the alpha value globally,
    # since the user can instead provide per-edge alphas now.  Only set it
    # globally if provided as a scalar.
    if cb.is_numlike(alpha):
        edge_collection.set_alpha(alpha)

    # need 0.87.7 or greater for edge colormaps
    if edge_colors is None:
        if edge_cmap is not None:
            assert (isinstance(edge_cmap, Colormap))
        edge_collection.set_array(np.asarray(edge_color))
        edge_collection.set_cmap(edge_cmap)
        if edge_vmin is not None or edge_vmax is not None:
            edge_collection.set_clim(edge_vmin, edge_vmax)
        else:
            edge_collection.autoscale()
        pylab.sci(edge_collection)


#    else:
#        sys.stderr.write(\
#            """matplotlib version >= 0.87.7 required for colormapped edges.
#        (version %s detected)."""%matplotlib.__version__)
#        raise UserWarning(\
#            """matplotlib version >= 0.87.7 required for colormapped edges.
#        (version %s detected)."""%matplotlib.__version__)

    arrow_collection = None

    if G.is_directed() and arrows:

        # a directed graph hack
        # draw thick line segments at head end of edge
        # waiting for someone else to implement arrows that will work
        arrow_colors = (colorConverter.to_rgba('k', alpha), )
        a_pos = []
        p = 1.0 - 0.25  # make head segment 25 percent of edge length
        for src, dst in edge_pos:
            x1, y1 = src
            x2, y2 = dst
            dx = x2 - x1  # x offset
            dy = y2 - y1  # y offset
            d = np.sqrt(float(dx**2 + dy**2))  # length of edge
            if d == 0:  # source and target at same position
                continue
            if dx == 0:  # vertical edge
                xa = x2
                ya = dy * p + y1
            if dy == 0:  # horizontal edge
                ya = y2
                xa = dx * p + x1
            else:
                theta = np.arctan2(dy, dx)
                xa = p * d * np.cos(theta) + x1
                ya = p * d * np.sin(theta) + y1

            a_pos.append(((xa, ya), (x2, y2)))

        arrow_collection = LineCollection(
            a_pos,
            colors=arrow_colors,
            linewidths=[4 * ww for ww in lw],
            antialiaseds=(1, ),
            transOffset=ax.transData,
        )

    # update view
    minx = np.amin(np.ravel(edge_pos[:, :, 0]))
    maxx = np.amax(np.ravel(edge_pos[:, :, 0]))
    miny = np.amin(np.ravel(edge_pos[:, :, 1]))
    maxy = np.amax(np.ravel(edge_pos[:, :, 1]))

    w = maxx - minx
    h = maxy - miny
    padx, pady = 0.05 * w, 0.05 * h
    corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady)
    ax.update_datalim(corners)
    ax.autoscale_view()

    edge_collection.set_zorder(1)  # edges go behind nodes
    ax.add_collection(edge_collection)
    if arrow_collection:
        arrow_collection.set_zorder(1)  # edges go behind nodes
        ax.add_collection(arrow_collection)

    return ax
Esempio n. 48
0
def plot(network,
         margin=0.05,
         ax=None,
         geomap=True,
         projection=None,
         bus_colors='b',
         line_colors={
             'Line': 'g',
             'Link': 'cyan'
         },
         bus_sizes=10,
         line_widths={
             'Line': 2,
             'Link': 2
         },
         flow=None,
         layouter=None,
         title="",
         line_cmap=None,
         bus_cmap=None,
         boundaries=None,
         geometry=False,
         branch_components=['Line', 'Link'],
         jitter=None,
         basemap=None,
         basemap_parameters=None,
         color_geomap=None):
    """
    Plot the network buses and lines using matplotlib and cartopy/basemap.

    Parameters
    ----------
    margin : float
        Margin at the sides as proportion of distance between max/min x,y
    ax : matplotlib ax, defaults to plt.gca()
        Axis to which to plot the network
    geomap: bool/str, default True
        Switch to use Basemap or Cartopy (depends on what is installed).
        If string is passed, it will be used as a resolution argument.
        For Basemap users 'c' (crude), 'l' (low), 'i' (intermediate),
        'h' (high), 'f' (full) are valid resolutions options.
        For Cartopy users '10m', '50m', '110m' are valid resolutions options.
    projection: cartopy.crs.Projection, defaults to None
        Define the projection of your geomap, only valid if cartopy is
        installed. If None (default) is passed the projection for cartopy
        is set to cartopy.crs.PlateCarree
    bus_colors : dict/pandas.Series
        Colors for the buses, defaults to "b"
    bus_sizes : dict/pandas.Series
        Sizes of bus points, defaults to 10
    line_colors : dict/pandas.Series
        Colors for the lines, defaults to "g" for Lines and "cyan" for
        Links. Colors for branches other than Lines can be
        specified using a pandas Series with a MultiIndex.
    line_widths : dict/pandas.Series
        Widths of lines, defaults to 2. Widths for branches other
        than Lines can be specified using a pandas Series with a
        MultiIndex.
    flow : snapshot/pandas.Series/function/string
        Flow to be displayed in the plot, defaults to None. If an element of
        network.snapshots is given, the flow at this timestamp will be
        displayed. If an aggregation function is given, is will be applied
        to the total network flow via pandas.DataFrame.agg (accepts also
        function names). Otherwise flows can be specified by passing a pandas
        Series with MultiIndex including all necessary branch components.
        Use the line_widths argument to additionally adjust the size of the
        flow arrows.
    layouter : networkx.drawing.layout function, default None
        Layouting function from `networkx <https://networkx.github.io/>`_ which
        overrules coordinates given in ``network.buses[['x','y']]``. See
        `list <https://networkx.github.io/documentation/stable/reference/drawing.html#module-networkx.drawing.layout>`_
        of available options.
    title : string
        Graph title
    line_cmap : plt.cm.ColorMap/str|dict
        If line_colors are floats, this color map will assign the colors.
        Use a dict to specify colormaps for more than one branch type.
    bus_cmap : plt.cm.ColorMap/str
        If bus_colors are floats, this color map will assign the colors
    boundaries : list of four floats
        Boundaries of the plot in format [x1,x2,y1,y2]
    branch_components : list of str
        Branch components to be plotted, defaults to Line and Link.
    jitter : None|float
        Amount of random noise to add to bus positions to distinguish
        overlapping buses
    basemap_parameters : dict
        Specify a dict with additional constructor parameters for the
        Basemap. Will disable Cartopy.
        Use this feature to set a custom projection.
        (e.g. `{'projection': 'tmerc', 'lon_0':10.0, 'lat_0':50.0}`)
    color_geomap : dict or bool
        Specify colors to paint land and sea areas in.
        If True, it defaults to `{'ocean': 'lightblue', 'land': 'whitesmoke'}`.
        If no dictionary is provided, colors are white.

    Returns
    -------
    bus_collection, branch_collection1, ... : tuple of Collections
        Collections for buses and branches.
    """
    defaults_for_branches = pd.Series({
        'Link':
        dict(color="cyan", width=2),
        'Line':
        dict(color="b", width=2),
        'Transformer':
        dict(color='green', width=2)
    }).rename_axis('component')

    if not plt_present:
        logger.error("Matplotlib is not present, so plotting won't work.")
        return

    if basemap is not None:
        logger.warning("argument `basemap` is deprecated, "
                       "use `geomap` instead.")
        geomap = basemap

    if geomap:
        if not (cartopy_present or basemap_present):
            # Not suggesting Basemap since it is being deprecated
            logger.warning(
                "Cartopy needs to be installed to use `geomap=True`.")
            geomap = False

        # Use cartopy by default, fall back on basemap
        use_basemap = False
        use_cartopy = cartopy_present
        if not use_cartopy:
            use_basemap = basemap_present

        # If the user specifies basemap parameters, they prefer
        # basemap over cartopy.
        # (This means that you can force the use of basemap by
        # setting `basemap_parameters={}`)
        if basemap_present:
            if basemap_parameters is not None:
                logger.warning("Basemap is being deprecated, consider "
                               "switching to Cartopy.")
                use_basemap = True
                use_cartopy = False

        if use_cartopy:
            if projection is None:
                projection = get_projection_from_crs(network.srid)

            if ax is None:
                ax = plt.gca(projection=projection)
            else:
                assert isinstance(ax, cartopy.mpl.geoaxes.GeoAxesSubplot), (
                    'The passed axis is not a GeoAxesSubplot. You can '
                    'create one with: \nimport cartopy.crs as ccrs \n'
                    'fig, ax = plt.subplots('
                    'subplot_kw={"projection":ccrs.PlateCarree()})')
    elif ax is None:
        ax = plt.gca()

    x, y = _get_coordinates(network, layouter=layouter)

    axis_transform = ax.transData

    if geomap:
        if use_cartopy:
            axis_transform = draw_map_cartopy(network, x, y, ax, boundaries,
                                              margin, geomap, color_geomap)
            new_coords = pd.DataFrame(ax.projection.transform_points(
                axis_transform, x.values, y.values),
                                      index=network.buses.index,
                                      columns=['x', 'y', 'z'])
            x, y = new_coords['x'], new_coords['y']
        elif use_basemap:
            basemap_transform = draw_map_basemap(network, x, y, ax, boundaries,
                                                 margin, geomap,
                                                 basemap_parameters,
                                                 color_geomap)

            # A non-standard projection might be used; the easiest way to
            # support this is to tranform the bus coordinates.
            x, y = basemap_transform(x.values, y.values)
            x = pd.Series(x, network.buses.index)
            y = pd.Series(y, network.buses.index)

    if jitter is not None:
        x = x + np.random.uniform(low=-jitter, high=jitter, size=len(x))
        y = y + np.random.uniform(low=-jitter, high=jitter, size=len(y))

    if isinstance(bus_sizes, pd.Series) and isinstance(bus_sizes.index,
                                                       pd.MultiIndex):
        # We are drawing pies to show all the different shares
        assert len(bus_sizes.index.levels[0].difference(network.buses.index)) == 0, \
            "The first MultiIndex level of bus_sizes must contain buses"
        assert (isinstance(bus_colors, dict) and
                set(bus_colors).issuperset(bus_sizes.index.levels[1])), \
            "bus_colors must be a dictionary defining a color for each element " \
            "in the second MultiIndex level of bus_sizes"

        bus_sizes = bus_sizes.sort_index(level=0, sort_remaining=False)
        if geomap:
            bus_sizes *= projected_area_factor(ax, network.srid)**2

        patches = []
        for b_i in bus_sizes.index.levels[0]:
            s = bus_sizes.loc[b_i]
            radius = s.sum()**0.5
            if radius == 0.0:
                ratios = s
            else:
                ratios = s / s.sum()

            start = 0.25
            for i, ratio in ratios.iteritems():
                patches.append(
                    Wedge((x.at[b_i], y.at[b_i]),
                          radius,
                          360 * start,
                          360 * (start + ratio),
                          facecolor=bus_colors[i]))
                start += ratio
        bus_collection = PatchCollection(patches, match_original=True)
        ax.add_collection(bus_collection)
    else:
        c = pd.Series(bus_colors, index=network.buses.index)
        s = pd.Series(bus_sizes, index=network.buses.index,
                      dtype="float").fillna(10)
        bus_collection = ax.scatter(x,
                                    y,
                                    c=c,
                                    s=s,
                                    cmap=bus_cmap,
                                    edgecolor='face')

    def as_branch_series(ser):
        # ensure that this function always return a multiindexed series
        if isinstance(ser, dict) and set(ser).issubset(branch_components):
            return pd.concat(
                {
                    c.name: pd.Series(s, index=c.df.index)
                    for c, s in zip(network.iterate_components(ser.keys()),
                                    ser.values())
                },
                names=['component', 'name'])
        elif isinstance(ser, pd.Series) and isinstance(ser.index,
                                                       pd.MultiIndex):
            return ser.rename_axis(index=['component', 'name'])
        else:
            ser = pd.Series(ser, network.lines.index)
            return pd.concat([ser],
                             axis=0,
                             keys=['Line'],
                             names=['component', 'name']).fillna(0)

    line_colors = as_branch_series(line_colors)
    line_widths = as_branch_series(line_widths)

    if not isinstance(line_cmap, dict):
        line_cmap = {'Line': line_cmap}

    branch_collections = []

    if flow is not None:
        flow = (_flow_ds_from_arg(
            flow, network, branch_components).pipe(as_branch_series).div(
                sum(
                    len(t.df)
                    for t in network.iterate_components(branch_components)) +
                100))
        flow = flow.mul(line_widths[flow.index], fill_value=1)
        # update the line width, allows to set line widths separately from flows
        line_widths.update((5 * flow.abs()).pipe(np.sqrt))
        arrows = directed_flow(network,
                               flow,
                               x=x,
                               y=y,
                               ax=ax,
                               geomap=geomap,
                               branch_colors=line_colors,
                               branch_comps=branch_components,
                               cmap=line_cmap['Line'])
        branch_collections.append(arrows)

    for c in network.iterate_components(branch_components):
        l_defaults = defaults_for_branches[c.name]
        l_widths = line_widths.get(c.name, l_defaults['width'])
        l_nums = None
        l_colors = line_colors.get(c.name, l_defaults['color'])

        if isinstance(l_colors, pd.Series):
            if issubclass(l_colors.dtype.type, np.number):
                l_nums = l_colors
                l_colors = None
            else:
                l_colors.fillna(l_defaults['color'], inplace=True)

        if not geometry:
            segments = (np.asarray(
                ((c.df.bus0.map(x), c.df.bus0.map(y)),
                 (c.df.bus1.map(x), c.df.bus1.map(y)))).transpose(2, 0, 1))
        else:
            from shapely.wkt import loads
            from shapely.geometry import LineString
            linestrings = c.df.geometry[lambda ds: ds != ''].map(loads)
            assert all(isinstance(ls, LineString) for ls in linestrings), (
                "The WKT-encoded geometry in the 'geometry' column must be "
                "composed of LineStrings")
            segments = np.asarray(list(linestrings.map(np.asarray)))

        l_collection = LineCollection(segments,
                                      linewidths=l_widths,
                                      antialiaseds=(1, ),
                                      colors=l_colors,
                                      transOffset=ax.transData)

        if l_nums is not None:
            l_collection.set_array(np.asarray(l_nums))
            l_collection.set_cmap(line_cmap.get(c.name, None))
            l_collection.autoscale()

        ax.add_collection(l_collection)
        l_collection.set_zorder(3)

        branch_collections.append(l_collection)

    bus_collection.set_zorder(4)

    ax.update_datalim(compute_bbox_with_margins(margin, x, y))
    ax.autoscale_view()

    if geomap:
        if use_cartopy:
            ax.outline_patch.set_visible(False)
        ax.axis('off')

    ax.set_title(title)

    return (bus_collection, ) + tuple(branch_collections)
Esempio n. 49
0
def area_series_plot(northern=True):

    all_area = pd.read_pickle('/Users/mskirk/data/PCH_Project/all_area.pkl')

    if northern:
        north = pd.concat([
            all_area.Area[all_area.Center_lat > 0],
            all_area.Area_max[all_area.Center_lat > 0],
            all_area.Area_min[all_area.Center_lat > 0]
        ]).sort_index()
    else:
        north = pd.concat([
            all_area.Area[all_area.Center_lat < 0],
            all_area.Area_max[all_area.Center_lat < 0],
            all_area.Area_min[all_area.Center_lat < 0]
        ]).sort_index()

    north_ci = PCH_series.series_bootstrap(north,
                                           interval='360D',
                                           delta=True,
                                           confidence=0.997).fillna(0)

    n_div = (north_ci.upper - north_ci.lower) / 2

    wso = PCH_series.read_wso_data(
        '/Users/mskirk/data/PCH_Project/WSO_PolarField.txt')

    sns.set(style="darkgrid")

    fig = plt.figure(figsize=(8, 4))
    outer_grid = gridspec.GridSpec(2,
                                   1,
                                   wspace=0.0,
                                   hspace=0.0,
                                   height_ratios=[20, 1])
    ax = fig.add_subplot(outer_grid[0])
    plt.plot(north.resample('11D').median())
    plt.tight_layout()
    plt.fill_between(north_ci.resample('11D').median().index,
                     (north - n_div).resample('11D').median(),
                     (north + n_div).resample('11D').median(),
                     alpha=0.5)
    if northern:
        ax.set_title('Northern Polar Coronal Hole')
    else:
        ax.set_title('Southern Polar Coronal Hole')
    ax.set_ylabel('Fractional Area')
    ax.set_ylim(0, 0.08)
    ax.set_xlim(all_area.index[0] - timedelta(days=180),
                all_area.index[-1] + timedelta(days=180))
    ax.set_xlabel('')
    ax.set_xticklabels([])

    ax1 = fig.add_subplot(outer_grid[1])
    inxval = mdates.date2num(wso.index.to_pydatetime())
    y = np.zeros_like(inxval)
    points = np.array([inxval, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    cmap = ListedColormap(['r', 'y'])

    if northern:
        norm = BoundaryNorm([wso.NorthFilter.min(), 0,
                             wso.NorthFilter.max()], cmap.N)
        lc = LineCollection(segments, cmap=cmap, norm=norm)
        lc.set_array(wso.NorthFilter)
    else:
        norm = BoundaryNorm([wso.SouthFilter.min(), 0,
                             wso.SouthFilter.max()], cmap.N)
        lc = LineCollection(segments, cmap=cmap, norm=norm)
        lc.set_array(wso.SouthFilter)

    lc.set_linewidth(4)
    line = ax1.add_collection(lc)
    ax1.xaxis.set_major_locator(mdates.AutoDateLocator())
    monthFmt = mdates.DateFormatter("%Y")
    ax1.xaxis.set_major_formatter(monthFmt)
    ax1.autoscale_view()
    ax1.set_ylim(-0.1, 0.1)
    ax1.axes.get_yaxis().set_visible(False)
    ax1.set_aspect(1000)
    t_min = np.floor(Time(all_area.index[0]).jd - 1721424.5 - 180)
    t_max = np.floor(Time(all_area.index[-1]).jd - 1721424.5 + 180)
    ax1.set_xlim(t_min, t_max)
Esempio n. 50
0
def graph_smile_formula_bond_pairs(s, xs, ys, position):
    cm = plt.get_cmap("RdYlGn")
    mkdir('graphs')
    label = ''.join(['Smile Formula Graph: ', s])
    zeros = [0.0 for x in xs]
    complete_set = [xs[0]]
    complete_set.extend(ys)
    complete_position = [0]
    complete_position.extend(position)
    complete_zeros = [0.0]
    complete_zeros.extend(zeros)
    for graph_type in ['scatter', 'line']:  #line
        if graph_type == 'line':
            # convert to ndarray
            xs = array(xs)
            ys = array(ys)
            position = array(position)
            points = np.array([xs, ys]).T.reshape(-1, 1, 2)
            segments = np.concatenate([points[:-1], points[1:]], axis=1)
            #print('segments', segments.shape)
            fig, axs = plt.subplots(2, 1, sharex=True, sharey=True)
            norm = plt.Normalize(0, position.max())
            lc = LineCollection(segments, cmap='viridis', norm=norm)
            lc.set_array(position)
            lc.set_linewidth(2)
            line = axs[0].add_collection(lc)
            fig.colorbar(line, ax=axs[0])
            axs[0].set_xlim(0, xs.max())
            axs[0].set_ylim(0, ys.max())
            fig.delaxes(axs[1])
            #plt.show()
            image_path = ''.join(['graphs/', s, '_', graph_type, '.png'])
            plt.savefig(image_path)
            plt.close()
        elif graph_type == 'scatter':
            colors = [cm(float(i) / len(zeros)) for i in range(len(zeros))]
            complete_colors = [
                cm(float(i) / len(complete_zeros))
                for i in range(len(complete_zeros))
            ]
            image_path = ''.join(['graphs/', s, '_', graph_type, '.png'])
            scatters = {
                'default': {
                    'xs':
                    xs,
                    'ys':
                    ys,
                    'zs':
                    zeros,
                    'colors':
                    colors,
                    'xlabel':
                    '1st electron count',
                    'ylabel':
                    '2nd electron count',
                    'zlabel':
                    'N/A',
                    'title':
                    'Bond Pair Electron Counts',
                    'path':
                    ''.join(['graphs/', s, '_default_', graph_type, '.png'])
                },
                'position': {
                    'xs':
                    complete_position,
                    'ys':
                    complete_set,
                    'zs':
                    complete_zeros,
                    'colors':
                    complete_colors,
                    'xlabel':
                    'Position of element',
                    'ylabel':
                    'Electron count',
                    'zlabel':
                    'N/A',
                    'title':
                    'Electron counts by position in smile formula',
                    'path':
                    ''.join(['graphs/', s, '_position_', graph_type, '.png'])
                },
                'all': {
                    'xs': xs,
                    'ys': ys,
                    'zs': position,
                    'colors': colors,
                    'xlabel': '',
                    'ylabel': '',
                    'zlabel': '',
                    'title': '',
                    'path':
                    ''.join(['graphs/', s, '_all_', graph_type, '.png'])
                }
            }
            for scatter, value in scatters.items():
                make_plot(value, cm)
            plt.close()
        '''
        # comment in one of the following sections if you want to use plotly which has a nice browser UI
        default = go.Scatter3d(x=xs, y=ys, z=zeros) if graph_type == 'scatter' else px.line_3d(x=xs, y=ys, z=zeros)
        change = go.Scatter3d(x=complete_position, y=complete_set, z=zeros) if graph_type == 'scatter' else px.line_3d(x=complete_position, y=complete_set, z=zeros)
        all_changes = go.Scatter3d(x=xs, y=ys, z=position) if graph_type == 'scatter' else px.line_3d(x=xs, y=ys, z=position)
        fig = go.Figure()
        fig.add_trace(default)
        fig.add_trace(change) 
        fig.add_trace(all_changes)
        fig.update_layout(title = label)
        fig.show()
        # comment in the following section if youre using plotly & working offline to view graph in the browser
        plotly.offline.plot(
            {
                "data": traces,
                "layout": go.Layout(title=label)
            },
            image='jpeg',
            image_filename=image_path
        )
        traces = [default, change, all_changes]
        py.image.save_as({'data':traces}, image_path, format='png')
        '''

    return True
Esempio n. 51
0
def create_ngram_plot(term_or_topic_list: list,
                      use_log_scale: bool = False,
                      subplot_ax: Subplot = None,
                      plot_title: str = None,
                      plot_filename: str = None,
                      show_plot: bool = False,
                      show_male_female_bar: bool = None,
                      scale_factor: int = 1,
                      master_viz_data: dict = None):

    print(f'Drawing ngram plot for {term_or_topic_list}')

    if subplot_ax and plot_filename:
        raise ValueError(
            "Cannot save a plot that will be stored in a subplot.")
    if show_male_female_bar not in [None, 'horizontal', 'vertical']:
        raise ValueError(
            "show_male_female_bar has to be None, horizontal, or vertical.")

    if term_or_topic_list[0].startswith(
            'topic.') or term_or_topic_list[0].startswith('gen_approach_'):
        mode = 'topics'
    else:
        mode = 'terms'

    if not master_viz_data:
        master_viz_data = load_master_viz_data(mode)

    data = {term: master_viz_data[term] for term in term_or_topic_list}

    start_year = next(iter(data.values()))['year'][0]
    end_year = next(iter(data.values()))['year'][0]

    # 2: Set up the plot
    # if an ax is passed, we're creating a subplot for that axes. otherwise, we're creating a
    # complete plot here.
    if subplot_ax is None:
        fig = plt.figure(figsize=(12, 12))
        gs = gridspec.GridSpec(nrows=1,
                               ncols=1,
                               figure=fig,
                               width_ratios=[1],
                               height_ratios=[1],
                               wspace=0.2,
                               hspace=0.05)
        ax = fig.add_subplot(gs[0, 0])
    else:
        ax = subplot_ax

    ax.set_ylim(0, 1)
    ax.set_xlim(start_year + 2, end_year - 2)
    ax.set_axisbelow(True)
    ax.grid(which='major', axis='both')

    # add all passed terms to chart
    for t in term_or_topic_list:
        x = data[t]['year']
        y = data[t]['freq']

        freq_scores = data[t]['freq_score']
        x_lin = np.linspace(min(data[t]['year']), max(data[t]['year']), 1000)
        spl = make_interp_spline(x, y, k=2)
        y_lin = spl(x_lin)
        spl_freq_score = make_interp_spline(x, freq_scores, k=1)
        freq_score_lin = spl_freq_score(x_lin)

        points = np.array([x_lin, y_lin]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        norm = plt.Normalize(0.0, 1.0)

        lc = LineCollection(segments, cmap='coolwarm', norm=norm)
        # Set the values used for colormapping
        lc.set_array(freq_score_lin)
        lc.set_linewidth(4 * scale_factor)
        line = ax.add_collection(lc)

        # Line below can be used to add a label to the right of the frequency line
        # ax.text(x=max(x)+1, y=y[-1], s=t, fontsize=14)

    # Set x axis (years)
    ax.set_xlim(x_lin.min(), x_lin.max())
    ax.tick_params(axis='x', labelsize=14 * scale_factor)

    # Set y axis (frequencies or topic weights)
    y_max = max([max(data[t]['freq']) for t in term_or_topic_list]) * 1.2
    ax.set_ylim(0, y_max)

    ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1.0))
    if use_log_scale:
        y_min = min([min(data[t]['freq']) for t in term_or_topic_list]) * 1.2
        ax.set_yscale('log')
    ax.tick_params(axis='y', labelsize=14 * scale_factor)

    # Set title
    if plot_title:
        ax.set_title(label=plot_title,
                     weight='bold',
                     fontsize=24 * scale_factor,
                     pad=20 * scale_factor)

    # Set color bar with male female indicator
    if show_male_female_bar:
        fig.colorbar(line,
                     ax=ax,
                     orientation=show_male_female_bar,
                     fraction=0.1)

    if plot_filename:
        plt.savefig(
            Path(BASE_PATH, 'visualizations', 'ngram_plots', plot_filename))
    if show_plot:
        plt.show()
    if subplot_ax:
        return ax
Esempio n. 52
0
    def _create_xvy_trajectory_fig(self, filter_index, week_index, x_index,
                                   y_index, feature_name):

        ### Generate features
        subject_generator = self.subject.get_full_generator()
        features, labels = next(subject_generator)

        ### Create figure
        fig, axs = plt.subplots(1)
        fig.set_figwidth(self.save_config.Callback.figwidth)
        fig.set_figheight(self.save_config.Callback.figheight)
        fig.tight_layout()
        fig.suptitle("Week " + str(week_index + 1) +
                     " Trajectory Response: X vs Y")

        ### Get individual points
        x_points = features[0, week_index, :, x_index]
        y_points = features[0, week_index, :, y_index]

        ### Create combined points and segments
        points = np.array([x_points, y_points]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)

        ### Get convolutional output from logs
        conv_output = self.recent_epoch_logs["convolutional_output"]

        ### Define colormap function
        norm = plt.Normalize(conv_output[0, week_index, :, filter_index].min(),
                             conv_output[0, week_index, :, filter_index].max())
        lc = LineCollection(segments, cmap='viridis', norm=norm)
        # Set the values used for colormapping
        lc.set_array(conv_output[0, week_index, :, filter_index])
        lc.set_linewidth(2)
        line = axs.add_collection(lc)
        fig.colorbar(line, ax=axs)

        ### Set margins
        margin = .3
        half_x_points = x_points.max() - (x_points.min() + x_points.max()) / 2
        axs.set_xlim(x_points.min() - half_x_points * margin,
                     x_points.max() + half_x_points * margin)
        half_y_points = y_points.max() - (y_points.min() + y_points.max()) / 2
        axs.set_ylim(y_points.min() - half_y_points * margin,
                     y_points.max() + half_y_points * margin)

        ### Set labels
        axs.set_xlabel("Y Position")
        axs.set_ylabel("X Position")

        ### Save filter response fig as png and eps
        filter_response_folder_path = "results/" + self.save_config.Output.batch_name + "/" + self.child_name + "/trajectory-responses/"
        if not os.path.exists(filter_response_folder_path):
            os.mkdir(filter_response_folder_path)

        filter_response_folder_path += "{}/".format(feature_name)
        if not os.path.exists(filter_response_folder_path):
            os.mkdir(filter_response_folder_path)

        filter_response_folder_path += "x-vs-y/".format(filter_index)
        if not os.path.exists(filter_response_folder_path):
            os.mkdir(filter_response_folder_path)

        filter_response_folder_path += "filter-{}/".format(filter_index)
        if not os.path.exists(filter_response_folder_path):
            os.mkdir(filter_response_folder_path)

        filter_response_folder_path += "week-{}/".format(week_index + 1)
        if not os.path.exists(filter_response_folder_path):
            os.mkdir(filter_response_folder_path)

        single_response_png_path = filter_response_folder_path + "week-{}.png".format(
            week_index + 1)
        fig.savefig(single_response_png_path,
                    dpi=200,
                    format="png",
                    bbox_inches="tight")
        single_response_eps_path = filter_response_folder_path + "week-{}.eps".format(
            week_index + 1)
        fig.savefig(single_response_eps_path,
                    dpi=200,
                    format="eps",
                    bbox_inches="tight")

        plt.close(fig)
def plotter(flight_id):
    flight_datestr = SCI_FLIGHTS[flight_id]
    flight_date = datetime.strptime(flight_datestr, "%Y%m%d")
    save_sat_dir = EXTRACTDIR  # / f'{flight_date:%Y%m%d}'
    masin_data_path = (
        mypaths.masin_dir / f"flight{flight_id}" /
        MASIN_FILE_MASK.format(flight_date=flight_date, flight_id=flight_id))
    ds = xr.open_dataset(masin_data_path, decode_times=False)
    ref_date = flight_date.replace(hour=0, minute=0, second=0, microsecond=0)
    # TODO: decode from ds.Time.units
    ds.coords["data_point"] = np.array([
        np.datetime64(ref_date) +
        np.timedelta64(timedelta(seconds=int(i)))  # NOQA
        for i in ds.Time.values
    ])
    ds = ds.drop("Time")
    ds = ds.rename({"data_point": "Time"})
    masin_x = ds.LON_OXTS[~ds.ALT_OXTS.isnull()][::flt_stride]
    masin_y = ds.LAT_OXTS[~ds.ALT_OXTS.isnull()][::flt_stride]
    masin_z = ds.ALT_OXTS[~ds.ALT_OXTS.isnull()][::flt_stride]
    masin_t = ds.Time[~ds.ALT_OXTS.isnull()]

    flight_hours = sorted(set(masin_t.dt.hour.values))

    seaice_str = ""
    if add_sea_ice.lower() == "amsr2":
        (sic_lons, sic_lats, sic_data) = sat_tools.get_amsr2(dt=flight_date,
                                                             save_dir=SICDIR)
        seaice_str = "_amsr2"

    print(flight_date)
    for sat_opt in sat_opts:
        print(sat_opt)
        prev_tstamp = ref_date
        for hour in flight_hours:
            dt = ref_date + timedelta(hours=int(hour))
            # Get satellite image with given options closest to the flight time
            arch_file = ARCH_DIR / f"{dt:%Y%m%d}.zip"
            with ZipFile(arch_file) as z:
                zfile, tstamp = sat_tools.get_nearest_zfile(z, dt, **sat_opt)

            if tstamp == prev_tstamp:
                continue

            sat_image_name = save_sat_dir / zfile
            if not sat_image_name.is_file():
                # er = sat_tools.download_file(url=url, save_dir=save_sat_dir)
                # assert err == 0, 'Downloading the image failed'
                with ZipFile(arch_file) as z:
                    z.extract(zfile, save_sat_dir)

            # Open the satellite image and get data, image extent, and CRS
            im, extent, crs = sat_tools.read_raster_stereo(str(sat_image_name))

            fig = plt.figure(figsize=(12, 8))
            ax = ukmo_igp_map(fig, coast=COAST, **igp_map_kw, **gridline_kw)
            ax.tick_params(labelsize="x-large", length=0)

            ax.imshow(
                im[::sat_stride, ::sat_stride],
                origin="upper",
                extent=extent,
                transform=crs,
                cmap="gray",
                interpolation="nearest",
            )
            if SICDIR:
                # Add contours of sea-ice concentration
                cntr = ax.contour(sic_lons, sic_lats, sic_data, **sic_kw,
                                  **mapkw)
                clbls = ax.clabel(cntr, **sic_clab_kw)
                plt.setp(cntr.collections + clbls, path_effects=path_effects)

            ax.plot(masin_x,
                    masin_y,
                    linewidth=5,
                    color="k",
                    alpha=0.25,
                    **mapkw)
            points = np.array([masin_x, masin_y]).T.reshape(-1, 1, 2)
            segments = np.concatenate([points[:-1], points[1:]], axis=1)
            lc = LineCollection(segments,
                                cmap=cmap,
                                linewidth=3,
                                zorder=10,
                                norm=norm,
                                **mapkw)
            lc.set_array(masin_z)
            h = ax.add_collection(lc)

            cb = fig.colorbar(h, ax=ax, extend="max", pad=0.01, aspect=40)
            cb.ax.tick_params(labelsize="large")
            cb.ax.set_ylabel(
                f"Altitude [{masin_z.units.strip()}]",
                fontsize="large",
                rotation=270,
                labelpad=15,
            )

            txt = f"Flight {flight_id} | {tstamp:%d %b}"
            txt += (f"\nFlight time: {str(masin_t.min().values)[11:16]}"
                    f"-{str(masin_t.max().values)[11:16]}")
            txt += f'\n{" | ".join(sat_opt.values())}'
            txt += f"\nSat image time: {tstamp:%H:%M}"
            if SICDIR:
                txt += f"\n{add_sea_ice.upper()} sea ice"
            # ax.set_title(txt, loc='left', fontsize='large')
            ax.add_artist(AnchoredText(txt, prop=dict(size="large"), loc=4))

            sat_opt_str = "_".join(sat_opt.values())
            outdir = PLOTDIR / f"flight{flight_id}"
            outdir.mkdir(exist_ok=True)
            fig.savefig(
                outdir / (f"flight_{flight_id}_{tstamp:%Y%m%d%H%M}"
                          f"_{sat_opt_str}{seaice_str}{zoom_str}.png"),
                **svfigkw,
            )
            prev_tstamp = tstamp
            plt.close(fig)
Esempio n. 54
0
def martin_plot_frame(well_data, time, vrange=(-100, 100),
                      autocad_path=None, strike=120., hydro_path=None,
                      origin=np.array([2579332., 1247600., 514.]),
                      title=None):
    """
    Plot single frame of wells colored by strain. Take map and cross
    section from Vero and my presentation to MT partners

    :param well_data: Output from extract_wells
    :param time: Time plot signals for

    :return:
    """
    fig = plt.figure(figsize=(15, 8))
    spec = GridSpec(ncols=8, nrows=8, figure=fig)
    ax3d = fig.add_subplot(spec[:6, :4], projection='3d')
    ax_x = fig.add_subplot(spec[:7, 4:])
    ax_hydro = fig.add_subplot(spec[7:, :])
    if title:
        fig.suptitle(title, fontsize=20)
    # Cross section plane (strike 320)
    r = np.deg2rad(360 - strike)
    normal = np.array([-np.sin(r), -np.cos(r), 0.])
    normal /= linalg.norm(normal)
    new_strk = np.array([np.sin(r), -np.cos(r), 0.])
    new_strk /= linalg.norm(new_strk)
    change_b_mat = np.array([new_strk, [0, 0, 1], normal])
    for afile in glob('{}/*.csv'.format(autocad_path)):
        df_cad = pd.read_csv(afile)
        lines = df_cad.loc[df_cad['Name'] == 'Line']
        arcs = df_cad.loc[df_cad['Name'] == 'Arc']
        for i, line in lines.iterrows():
            xs = np.array([line['Start X'], line['End X']])
            ys = np.array([line['Start Y'], line['End Y']])
            zs = np.array([line['Start Z'], line['End Z']])
            # Proj
            pts = np.column_stack([xs, ys, zs])
            proj_pts = np.dot(pts - origin, normal)[:, None] * normal
            proj_pts = pts - origin - proj_pts
            proj_pts = np.matmul(change_b_mat, proj_pts.T)
            ax3d.plot(xs, ys, zs, color='lightgray', zorder=210,
                      linewidth=0.5)
            ax_x.plot(proj_pts[0, :], proj_pts[1, :], color='lightgray',
                      zorder=110, alpha=0.5, linewidth=0.5)
        for i, arc in arcs.iterrows():
            # Stolen math from Melchior
            if not np.isnan(arc['Extrusion Direction X']):
                rotaxang = [arc['Extrusion Direction X'],
                            arc['Extrusion Direction Y'],
                            arc['Extrusion Direction Z'],
                            arc['Total Angle']]
                rad = np.linspace(arc['Start Angle'], arc['Start Angle'] +
                                  arc['Total Angle'])
                dx = np.sin(np.deg2rad(rad)) * arc['Radius']
                dy = np.cos(np.deg2rad(rad)) * arc['Radius']
                dz = np.zeros(dx.shape[0])
                phi1 = -np.arctan2(
                    linalg.norm(
                        np.cross(np.array([rotaxang[0], rotaxang[1], rotaxang[2]]),
                        np.array([0, 0, 1]))),
                    np.dot(np.array([rotaxang[0], rotaxang[1], rotaxang[2]]),
                           np.array([0, 0, 1])))
                DX = dx * np.cos(phi1) + dz * np.sin(phi1)
                DY = dy
                DZ = dz * np.cos(phi1) - dx * np.sin(phi1)
                # ax.plot(DX, DY, DZ, color='r')
                phi2 = np.arctan(rotaxang[1] / rotaxang[0])
                fdx = (DX * np.cos(phi2)) - (DY * np.sin(phi2))
                fdy = (DX * np.sin(phi2)) + (DY * np.cos(phi2))
                fdz = DZ
                x = fdx + arc['Center X']
                y = fdy + arc['Center Y']
                z = fdz + arc['Center Z']
                # projected pts
                pts = np.column_stack([x, y, z])
                proj_pts = np.dot(pts - origin, normal)[:, None] * normal
                proj_pts = pts - origin - proj_pts
                proj_pts = np.matmul(change_b_mat, proj_pts.T)
                ax3d.plot(x, y, z, color='lightgray', zorder=210,
                          linewidth=0.5)
                ax_x.plot(proj_pts[0, :], proj_pts[1, :], color='lightgray',
                          zorder=110, alpha=0.5, linewidth=0.5)
            elif not np.isnan(arc['Start X']):
                v1 = -1. * np.array([arc['Center X'] - arc['Start X'],
                                     arc['Center Y'] - arc['Start Y'],
                                     arc['Center Z'] - arc['Start Z']])
                v2 = -1. * np.array([arc['Center X'] - arc['End X'],
                                     arc['Center Y'] - arc['End Y'],
                                     arc['Center Z'] - arc['End Z']])
                rad = np.linspace(0, np.deg2rad(arc['Total Angle']), 50)
                # get rotation vector (norm is rotation angle)
                rotvec = np.cross(v2, v1)
                rotvec /= linalg.norm(rotvec)
                rotvec = rotvec[:, np.newaxis] * rad[np.newaxis, :]
                Rs = R.from_rotvec(rotvec.T)
                pt = np.matmul(v1, Rs.as_matrix())
                # Projected pts
                x = arc['Center X'] + pt[:, 0]
                y = arc['Center Y'] + pt[:, 1]
                z = arc['Center Z'] + pt[:, 2]
                pts = np.column_stack([x, y, z])
                proj_pts = np.dot(pts - origin, normal)[:, None] * normal
                proj_pts = pts - origin - proj_pts
                proj_pts = np.matmul(change_b_mat, proj_pts.T)
                ax3d.plot(x, y, z, color='lightgray', zorder=210,
                          linewidth=0.5)
                ax_x.plot(proj_pts[0, :], proj_pts[1, :], color='lightgray',
                          zorder=210, alpha=0.5, linewidth=0.5)
    well_dict = create_FSB_boreholes()
    # cmap = ListedColormap(sns.color_palette('icefire', 21).as_hex())
    cmap = ListedColormap(sns.color_palette('coolwarm', 21).as_hex())
    for well, w_dict in well_data.items():
        pts = []
        if well == 'B4':
            continue
        for feature_dep in w_dict['depth']:
            feature_dep -= w_dict['depth'][0]
            pts.append(depth_to_xyz(well_dict, well, feature_dep))
        strains = w_dict['data'][:, np.argmin(np.abs(time - w_dict['times']))]
        # Project well points and fault intersection points onto cross section
        pts = np.array(pts)
        proj_pts = np.dot(pts - origin, normal)[:, None] * normal
        proj_pts = pts - origin - proj_pts
        proj_pts = np.matmul(change_b_mat, proj_pts.T)
        proj_pts = proj_pts[:2, :]
        proj_pts = proj_pts.T.reshape([-1, 1, 2])
        ax3d.scatter(pts[0, 0], pts[0, 1], pts[0, 2], color='darkgray',
                     linewidth=1.5, s=15., zorder=110)
        pts = pts.reshape([-1, 1, 3])
        try:
            fault_pts = [depth_to_xyz(well_dict, well, fault_depths[well][i])
                         for i in (0, 1)]
            fault_pts = np.array(fault_pts)
            p_fault_pts = np.dot(fault_pts - origin, normal)[:, None] * normal
            p_fault_pts = fault_pts - origin - p_fault_pts
            p_fault_pts = np.matmul(change_b_mat, p_fault_pts.T)
            p_fault_pts = p_fault_pts[:2, :].T
            # Plot fault intersection points
            ax_x.scatter(p_fault_pts[:, 0], p_fault_pts[:, 1], c='purple',
                         marker='x', s=15., zorder=105)
        except KeyError as e:
            # Borehole doesn't intersect fault
            pass
        # Make segments
        proj_seggies = np.concatenate([proj_pts[:-1], proj_pts[1:]], axis=1)
        seggies = np.concatenate([pts[:-1], pts[1:]], axis=1)
        col_norm = plt.Normalize(vrange[0], vrange[1])
        lc = Line3DCollection(seggies, cmap=cmap, norm=col_norm)
        lc_proj = LineCollection(proj_seggies, cmap=cmap, norm=col_norm)
        # Set the values used for colormapping
        lc.set_array(strains)
        lc.set_linewidth(3.)
        lc_proj.set_array(strains)
        lc_proj.set_linewidth(3.)
        line = ax3d.add_collection3d(lc)
        line_x = ax_x.add_collection(lc_proj)
    fig.colorbar(line_x, ax=ax3d, label=r'$\mu\epsilon$')
    # Formatting
    ax3d.set_xlim([2579310, 2579355])
    ax3d.set_ylim([1247555, 1247600])
    ax3d.set_zlim([485, 530])
    # ax3d.view_init(elev=30., azim=-112)
    ax3d.view_init(elev=75, azim=-120.)
    ax3d.margins(0.)
    ax3d.set_xticks([])
    ax3d.set_xticklabels([])
    ax3d.set_yticks([])
    ax3d.set_yticklabels([])
    ax3d.set_zticks([])
    ax3d.set_zticklabels([])
    # Cross section
    ax_x.set_xlim([-30, 5])
    ax_x.axis('equal')
    ax_x.spines['top'].set_visible(False)
    ax_x.spines['bottom'].set_visible(False)
    ax_x.spines['left'].set_visible(False)
    ax_x.yaxis.set_ticks_position('right')
    ax_x.tick_params(direction='in', bottom=False, labelbottom=False)
    ax_x.set_yticks([-30, -20, -10, 0])
    ax_x.set_yticklabels(['30', '20', '10', '0'])
    ax_x.set_ylabel('                                      Meters', labelpad=15)
    ax_x.yaxis.set_label_position("right")
    ax_x.spines['right'].set_bounds(0, -30)
    # Plot the hydro
    df_hydro = read_fsb_hydro(hydro_path)
    pq_axes = plot_fsb_hydro(df_hydro, axes=ax_hydro)
    # Add 1 hour to Swiss local winter time
    pq_axes[0].axvline(x=time, linestyle=':', color='k', linewidth=2.)
    pq_axes[0].set_xlabel('Time', fontsize=14)
    return fig
Esempio n. 55
0
    ax1.plot([u[0] - eps*W1[0], u[0] + eps*W1[0]],\
            [u[1] - eps*W1[1], u[1] + eps*W1[1]],\
            lw=1.0,color="blue")
    ax1.axis("equal")
    ax.xaxis.set_tick_params(labelsize=30)
    ax.yaxis.set_tick_params(labelsize=30)
    ax1.xaxis.set_tick_params(labelsize=30)
    ax1.yaxis.set_tick_params(labelsize=30)
    '''
    eps=array([-1E-2, 1E-2]).reshape([1,2,1])
    segments = u.T.reshape([-1,1,2]) + eps * v1.T.reshape([-1,1,2])
    cross_prod = W1[0]*v1[1] - W1[1]*v1[0]
    lc = LineCollection(segments, cmap=plt.get_cmap('RdBu'), \
            norm=plt.Normalize(min(cross_prod), max(cross_prod)))
    #lc.set_array(ones(u.shape[1]))
    lc.set_array(cross_prod)
    #lc.set_array(norm(W1,axis=0))
    lc.set_linewidth(1)

    fig2, ax2 = subplots(1,1) 
    ax2.add_collection(lc)
    cbar = fig2.colorbar(cm.ScalarMappable(norm=plt.Normalize(min(cross_prod),max(cross_prod)), cmap=plt.get_cmap('RdBu')), ax=ax2)
    cbar.ax.tick_params(labelsize=30)
    ax2.xaxis.set_tick_params(labelsize=30)
    ax2.yaxis.set_tick_params(labelsize=30)
    ax2.axis('scaled')
    ax2.set_xlabel("$x_1$",fontsize=30)
    ax2.set_ylabel("$x_2$",fontsize=30)

    
def clv_along_clv():
Esempio n. 56
0
def plot_multicolored_line(*,
                           ax=None,
                           x,
                           y,
                           other_y,
                           cmap="viridis",
                           vmin=None,
                           vmax=None,
                           linewidth=2,
                           alpha=1):
    r"""Plots a line colored based on the values of another array.

    Plots the curve ``y(x)``, colored based on the values in ``other_y``.

    Parameters
    ----------
    ax : :py:class:`~matplotlib.axes.Axes`, optional
        Axes instance, for plotting, defaults to ``None``.
        If ``None``, a new :py:class:`~matplotlib.figure.Figure` will be created.

    y : 1d array_like
        The dependent variable.
    x : 1d array_like
        The independent variable.
    other_y: 1d array_like
        The values whose magnitude will be converted to colors.

    cmap : str, optional
        The used colormap (defaults to "viridis").
    vmin : float, optional
        Lower normalization limit
    vmax : float, optional
        Upper normalization limit
    linewidth : float, optional (default 2)
        Width of the plotted line
    alpha : float, optional (default 1)
        Line transparency, between 0 and 1

    Returns
    -------
    ax, line : Axes, LineCollection
        Main Axes and plotted line

    Raises
    ------
    AssertionError
        If the length of `y` and `other_y` do not match.

    References
    ----------
    ``matplotlib`` `example <https://matplotlib.org/gallery/lines_bars_and_markers/multicolored_line.html>`_.

    Examples
    --------
    We plot a curve and color it based on the value of its first derivative.

    .. plot::
       :include-source:

        import numpy as np
        from matplotlib import pyplot

        from sliceplots import plot_multicolored_line

        x = np.linspace(0, 3 * np.pi, 500)
        y = np.sin(x)
        dydx = np.gradient(y) * 100  # first derivative

        _, ax = pyplot.subplots()

        plot_multicolored_line(ax=ax, x=x, y=y, other_y=dydx, label="dydx")

        ax.set(ylabel="y", xlabel="x")
    """
    if not (len(y) == len(other_y)):
        raise AssertionError("The two 'y' arrays must have the same size!")

    ax = ax or _make_ax()

    # Create a set of line segments so that we can color them individually
    # This creates the points as a N x 1 x 2 array so that we can stack points
    # together easily to get the segments. The segments array for line collection
    # needs to be (numlines) x (points per line) x 2 (for x and y)
    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)

    if vmin is None:
        vmin = np.min(other_y)
    if vmax is None:
        vmax = np.max(other_y)

    # Create a continuous norm to map from data points to colors
    norm = Normalize(vmin, vmax)
    lc = LineCollection(segments, cmap=cmap, norm=norm)
    # Set the values used for colormapping
    lc.set_array(other_y)
    lc.set_linewidth(linewidth)
    lc.set_alpha(alpha)
    line = ax.add_collection(lc)

    return ax, line
Esempio n. 57
0
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm

x = np.linspace(0, 3 * np.pi, 500)
y = np.sin(x)
z = np.cos(0.5 * (x[:-1] + x[1:]))  # first derivative

# Create a colormap for red, green and blue and a norm to color
# f' < -0.5 red, f' > 0.5 blue, and the rest green
cmap = ListedColormap(['r', 'g', 'b'])
norm = BoundaryNorm([-1, -0.5, 0.5, 1], cmap.N)

# Create a set of line segments so that we can color them individually
# This creates the points as a N x 1 x 2 array so that we can stack points
# together easily to get the segments. The segments array for line collection
# needs to be numlines x points per line x 2 (x and y)
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

# Create the line collection object, setting the colormapping parameters.
# Have to set the actual values used for colormapping separately.
lc = LineCollection(segments, cmap=cmap, norm=norm)
lc.set_array(z)
lc.set_linewidth(3)

fig1 = plt.figure()
plt.gca().add_collection(lc)
plt.xlim(x.min(), x.max())
plt.ylim(-1.1, 1.1)

plt.show()
Esempio n. 58
0
def file_plotter(logname):
    """Plots a single timing log file.

    Arguments:
    logname -- the log file (str)
    """

    summary_stats = np.zeros((NUM_STATS,workers))
    offset = 0

    for i in range(0,workers):
        (segments, colors, offset) = worker_parser(logname, offset, summary_stats)

        if do_plot or save_eps:
            cmap = ListedColormap(colors)
            lc = LineCollection(segments, cmap=cmap)
            # this (probably?) sets which of cmap's colors to use
            lc.set_array(np.arange(0, len(colors)))
            lc.set_linewidth(line_width)

            plt.gca().add_collection(lc)

            # min()/max() finds single digit (i.e., flattens and then finds)
            # this makes sure there aren't messed up/"reversed" timestamps
            if np.array(segments).min() < 0:
                print 'WARNING: encountered negative value in ' + logname + '!'

            #plt.axis('auto')    # to get auto max-lims

            # ensure we modify global var (rather than create local one)
            global max_xlim
            max_xlim = max(max_xlim, np.array(segments).max()+0.5)


    ## pretty plot
    if do_plot or save_eps:
        # gca() returns actual Axes object
        plt.gca().set_xlim(left=0)
        plt.gca().minorticks_on()
        plt.xlabel('Time (s)', fontsize=FONTSIZE)   # or plt.gca().set_xlabel(...)
        plt.tick_params(axis='x', which='major', labelsize=XLABELSIZE)

        plt.ylim(0.25, workers+0.75)
        plt.yticks(range(1, workers+1))
        #plt.gca().set_yticklabels([r'W$_{' + str(i) + '}$' for i in range(workers,0,-1)])
        plt.gca().set_yticklabels([str(i) for i in range(workers,0,-1)])
        plt.gca().tick_params(axis='y',which='both',right='off',left='off')
        plt.ylabel('Workers', fontsize=FONTSIZE)
        plt.tick_params(axis='y', which='major', labelsize=YLABELSIZE)

        plt.title(logname, fontsize=FONTSIZE)

    ## print statistics
    for w in range(0,workers):
        for s in range(1, NUM_STATS):
            summary_stats[s, w] /= float(summary_stats[T_TOTAL, w])
    stats = summary_stats[1:NUM_STATS]

    avg_stats = tuple([s.mean()*100 for s in stats])
    min_stats = tuple([s.min()*100 for s in stats])
    max_stats = tuple([s.max()*100 for s in stats])

    print '===================================================================================='
    print '   ' + logname
    print '===================================================================================='
    print '    |  compute  | ss comm |   comm   | local barrier | ltw barrier | global barrier'
    print '----+-----------+---------+----------+---------------+-------------+----------------'
    print 'avg |  %6.3f%%  | %6.3f%% |  %6.3f%% |    %6.3f%%    |   %6.3f%%   |     %6.3f%%' % avg_stats
    print 'min |  %6.3f%%  | %6.3f%% |  %6.3f%% |    %6.3f%%    |   %6.3f%%   |     %6.3f%%' % min_stats
    print 'max |  %6.3f%%  | %6.3f%% |  %6.3f%% |    %6.3f%%    |   %6.3f%%   |     %6.3f%%' % max_stats
    print ''
def plot_run(instructions, channel_labels=None, tmin=None, tmax=None):

    if channel_labels is None:
        channel_labels = [f'ch{chan}' for chan in range(24)]

    #Takes the raw instructions in bytes and them back decoded into a dictionary format
    decoded_instructions = decode_instructions(instructions)

    # Simulates what the pulse generator actually does. The output of this may be very large if there are many transitions.
    durations, states, address, goto_counter, goto_counter_original, stop_and_wait, hard_trig_out, notify_computer, powerline_sync = simulate_output_coordinator(
        decoded_instructions)

    instruction_spacing_tn = durations.cumsum()
    instruction_spacing_tn = np.insert(instruction_spacing_tn, 0, 0)
    instruction_spacing = np.zeros(instruction_spacing_tn.size) + 1.1
    instruction_text_center_pos = instruction_spacing_tn[:-1] + 0.5 * durations

    # Calculates where the tags should be
    stop_and_wait_tn = instruction_spacing_tn[1:][stop_and_wait] - 0.1
    stop_and_wait = np.zeros(stop_and_wait_tn.size) + 1.08
    hard_trig_out_tn = instruction_spacing_tn[:-1][hard_trig_out] + 0.1
    hard_trig_out = np.zeros(hard_trig_out_tn.size) + 1.06
    notify_computer_tn = instruction_spacing_tn[:-1][notify_computer] + 0.1
    notify_computer = np.zeros(notify_computer_tn.size) + 1.04
    powerline_sync_tn = instruction_spacing_tn[:-1][powerline_sync] + 0.1
    powerline_sync = np.zeros(powerline_sync_tn.size) + 1.02

    fig, ax = plt.subplots(figsize=(10, 5))

    # Adds the main information about the state of the channels
    norm = colors.Normalize(0, 1)
    y_tick_pos = []
    indicator_positions = []
    for chan in range(24):
        indicator_pos = 1 - chan / 24
        indicator_positions.append(indicator_pos)
        state_segments, seg_colors = construct_state_line_segments(
            instruction_spacing_tn, states[:, chan], indicator_pos)
        coll = LineCollection(state_segments,
                              linewidths=8,
                              cmap='nipy_spectral',
                              norm=norm)
        coll.set_array(seg_colors)
        ax.add_collection(coll)
        y_tick_pos.append(indicator_pos)

    # Add the instruction tag circles
    ax.plot(stop_and_wait_tn,
            stop_and_wait,
            'oC1',
            markersize=3,
            label='stop and wait')
    ax.plot(hard_trig_out_tn,
            hard_trig_out,
            'oC2',
            markersize=3,
            label='hardware trig out')
    ax.plot(notify_computer_tn,
            notify_computer,
            'oC3',
            markersize=3,
            label='notification')
    ax.plot(powerline_sync_tn,
            powerline_sync,
            'oC4',
            markersize=3,
            label='powerline sync')

    # Add the white lines between the indicator bars
    indicator_spacing_segments = construct_indicator_spacing_line_segments(
        instruction_spacing_tn, indicator_positions)
    coll = LineCollection(indicator_spacing_segments,
                          linewidths=0.5,
                          colors='white',
                          norm=norm)
    ax.add_collection(coll)

    # Add the black instruction edge indicators
    spacing_segments = construct_instruction_spacing_line_segments(
        instruction_spacing_tn, ymin=-5, ymax=1.1)
    coll = LineCollection(spacing_segments,
                          linewidths=0.5,
                          colors='k',
                          norm=norm)
    ax.add_collection(coll)

    # Add the black bar with stars indicating the instruction spacing
    ax.plot(instruction_spacing_tn, instruction_spacing, '-Dk', markersize=3)

    ax.set_xlabel('time (clock cycles)')
    ax.set_yticks(y_tick_pos)
    ax.set_yticklabels(channel_labels)

    # This makes the cursor display meaningful values
    def y_pos_to_tick_label(y):
        val = int(np.round(-(y - 1) * 24))
        if val < 0:
            val = 0
        elif val > 23:
            val = 23
        return channel_labels[val]

    def sec_to_prefex_sec(t):
        if t < 1E-6:
            t = t * 1E9
            return f'{t:.0f}ns'
        elif t < 1E-3:
            t = t * 1E6
            return f'{t:.3f}μs'
        elif t < 1:
            t = t * 1E3
            return f'{t:.6f}ms'
        else:
            return f'{t:.9f}s'

    ax.format_coord = lambda x, y: '{}  {}'.format(
        sec_to_prefex_sec(x * 10E-9), y_pos_to_tick_label(y))

    # Sets the limits to be plotted
    if tmin is not None:
        ax.set_xlim(left=tmin * 1E8)
    if tmax is not None:
        ax.set_xlim(right=tmax * 1E8)
    ax.set_ylim(0.01, 1.4)

    ax.legend()

    secax = ax.secondary_xaxis('top', functions=(n2t, t2n))
    secax.set_xlabel('time (s)')

    # Add the text that give information about the instructions
    td = Text_Drawer(instruction_text_center_pos, address, durations,
                     goto_counter, goto_counter_original)
    td.on_xlims_change(ax)
    ax.callbacks.connect('xlim_changed', td.on_xlims_change)
    ax.callbacks.connect('ylim_changed', on_ylims_change)
    plt.show()
Esempio n. 60
0
n = 100
x = np.arange(n)
rs = check_random_state(0)
y = rs.randint(-50, 50, size=(n, )) + 50. * np.log(1 + np.arange(n))

ir = IsotonicRegression()

y_ = ir.fit_transform(x, y)

lr = LinearRegression()
lr.fit(x[:, np.newaxis], y)  # 线性回归的 x 需要为 2d

segments = [[[i, y[i]], [i, y_[i]]] for i in range(n)]
lc = LineCollection(segments, zorder=0)
lc.set_array(np.ones(len(y)))
lc.set_linewidths(0.5 * np.ones(n))

fig = plt.figure()
plt.plot(x, y, 'r.', markersize=12)
plt.plot(x, y_, 'g.-', markersize=12)
plt.plot(x, lr.predict(x[:, np.newaxis]), 'b-')
plt.gca().add_collection(lc)
# loc(设置图例显示的位置)
# ncol(设置列的数量,使显示扁平化,当要表示的线段特别多的时候会有用)
# 按照加图的顺序把图放在一个图里面
plt.legend(('Data', 'Isotonic Fit', 'Linear Fit'), loc='lower right')
plt.title('Isotonic regression')
plt.show()

# Kernel ridge regression ( 内核岭回归 )