Пример #1
0
    def plot_field(self,x,y,u=None,v=None,F=None,contour=False,outdir=None,plot='quiver',figname='_field',format='eps'):
        outdir = self.set_dir(outdir)
        p = 64
        if F is None: F=self.calc_F(u,v)

        plt.close('all')
        plt.figure()
        #fig, axes = plt.subplots(nrows=1)
        if contour:
            plt.hold(True)
            plt.contourf(x,y,F)
        if plot=='quiver':
            plt.quiver(x[::p],y[::p],u[::p],v[::p],scale=0.1)
        
        if plot=='pcolor':
            plt.pcolormesh(x[::4],y[::4],F[::4],cmap=plt.cm.Pastel1)
            plt.colorbar()

        if plot=='stream':
            speed = F[::16]
            plt.streamplot(x[::16], y[::16], u[::16], v[::16], density=(1,1),color='k')

        plt.xlabel('$x$ (a.u.)')
        plt.ylabel('$y$ (a.u.)')
        
        plt.savefig(os.path.join(outdir,figname+'.'+format),format=format,dpi=320,bbox_inches='tight')
        plt.close()
Пример #2
0
def plot_mesh(mesh, result_path):
    plt.figure()
    plt.hold(True)

    # change the font
    matplotlib.rcParams.update({'font.size': 10, 'font.family': 'serif'})

    n_vert = mesh.num_vertices()
    n_cells = mesh.num_cells()
    d = mesh.geometry().dim()

    plotting.plot(mesh)
    # Create the triangulation
    # mesh_coordinates = mesh.coordinates().reshape((n_vert, d))
    # triangles = np.asarray([cell.entities(0) for cell in cells(mesh)])
    # triangulation = tri.Triangulation(mesh_coordinates[:, 0],
    #                                  mesh_coordinates[:, 1],
    #                                  triangles)

    # Plot the mesh
    # plt.triplot(triangulation)
    plt.xlabel("x")
    plt.ylabel("y")

    # Saving the mesh into the file
    fig = plt.gcf()
    fig.savefig(result_path + '-cells-%d-vertices-%d' % (n_cells, n_vert) +
                ".eps")
    plt.close('all')
Пример #3
0
def plot_waveforms(time,voltage,APTimes,titlestr):
    """
    plot_waveforms takes four arguments - the recording time array, the voltage
    array, the time of the detected action potentials, and the title of your
    plot.  The function creates a labeled plot showing the waveforms for each
    detected action potential
    """
   
    plt.figure()
   
    ## Your Code Here 
    indices = []
    
    for x in range(len(APTimes)):
        for i in range(len(time)):
            if(time[i]==APTimes[x]):
                indices.append(i)
            

    ##print indices
    Xval = np.linspace(-.003,.003,200)
    print len(Xval)
    for x in range(len(APTimes)):
        plt.plot(Xval, voltage[indices[x]-100:indices[x]+100])
        plt.title(titlestr)
        plt.xlabel('Time (s)')
        plt.ylabel('Voltage (uV)')
        plt.hold(True)

    
    
    plt.show()
Пример #4
0
def plot_svc(X, y, mysvc, bounds=None, grid=50):
    if bounds is None:
        xmin = np.min(X[:, 0], 0)
        xmax = np.max(X[:, 0], 0)
        ymin = np.min(X[:, 1], 0)
        ymax = np.max(X[:, 1], 0)
    else:
        xmin, ymin = bounds[0], bounds[0]
        xmax, ymax = bounds[1], bounds[1]
    aspect_ratio = (xmax - xmin) / (ymax - ymin)
    xgrid, ygrid = np.meshgrid(np.linspace(xmin, xmax, grid),
                              np.linspace(ymin, ymax, grid))
    plt.gca(aspect=aspect_ratio)
    plt.xlim(xmin, xmax)
    plt.ylim(ymin, ymax)
    plt.xticks([])
    plt.yticks([])
    plt.hold(True)
    plt.plot(X[y == 1, 0], X[y == 1, 1], 'bo')
    plt.plot(X[y == -1, 0], X[y == -1, 1], 'ro')
    
    box_xy = np.append(xgrid.reshape(xgrid.size, 1), ygrid.reshape(ygrid.size, 1), 1)
    if mysvc is not None:
        scores = mysvc.decision_function(box_xy)
    else:
        print 'You must have a valid SVC object.'
        return None;
    
    CS=plt.contourf(xgrid, ygrid, scores.reshape(xgrid.shape), alpha=0.5, cmap='jet_r')
    plt.contour(xgrid, ygrid, scores.reshape(xgrid.shape), levels=[0], colors='k', linestyles='solid', linewidths=1.5)
    plt.contour(xgrid, ygrid, scores.reshape(xgrid.shape), levels=[-1,1], colors='k', linestyles='dashed', linewidths=1)
    plt.plot(mysvc.support_vectors_[:,0], mysvc.support_vectors_[:,1], 'ko', markerfacecolor='none', markersize=10)
    CB = plt.colorbar(CS)
def plot_completion_graph_complete_vs_failed(result_list,
                                             colors=['b', 'm'],
                                             figure=1,
                                             labels=['complete', 'failed']):
    n = len(result_list)  # number of trials
    times = []
    percents = []
    for rl in ['complete', 'failed']:
        t = [i.time for i in result_list if i.tag == rl]
        t.sort()
        times.append(np.array(t))
        p = np.array(range(1, len(t) + 1))
        p = 100 * p / n
        percents.append(p)
    # the last data points of each type should sum to 1.0 if all trajectories either fail or complete (rather than time out)

    plt.figure(figure)
    plt.hold(False)

    for t, p, c, label in zip(times, percents, colors, labels):
        plt.plot(t, p, color=c, linewidth=2.0, label=label)
        plt.hold(True)

    plt.xlabel("Simulation Time (s)", fontsize='larger')
    plt.ylabel("% of Trajectories Complete", fontsize='larger')
    plt.yticks([0, 20, 40, 60, 80, 100],
               ("0%", "20%", "40%", "60%", "80%", "100%"),
               fontsize='larger',
               va='bottom')
    plt.xticks(fontsize='larger')
    plt.title(
        "Percentage of Total Trajectories Complete by a Given Time, Design A")
    plt.legend(loc=0)
    plt.show()
Пример #6
0
def plotConn():
    # Create plot
    figh = figure(figsize=(8,6))
    figh.subplots_adjust(left=0.02) # Less space on left
    figh.subplots_adjust(right=0.98) # Less space on right
    figh.subplots_adjust(top=0.96) # Less space on bottom
    figh.subplots_adjust(bottom=0.02) # Less space on bottom
    figh.subplots_adjust(wspace=0) # More space between
    figh.subplots_adjust(hspace=0) # More space between
    h = axes()
    totalconns = zeros(shape(f.connprobs))
    for c1 in range(size(f.connprobs,0)):
        for c2 in range(size(f.connprobs,1)):
            for w in range(f.nreceptors):
                totalconns[c1,c2] += f.connprobs[c1,c2]*f.connweights[c1,c2,w]*(-1 if w>=2 else 1)
    imshow(totalconns,interpolation='nearest',cmap=bicolormap(gap=0))

    # Plot grid lines
    hold(True)
    for pop in range(f.npops):
        plot(array([0,f.npops])-0.5,array([pop,pop])-0.5,'-',c=(0.7,0.7,0.7))
        plot(array([pop,pop])-0.5,array([0,f.npops])-0.5,'-',c=(0.7,0.7,0.7))

    # Make pretty
    h.set_xticks(range(f.npops))
    h.set_yticks(range(f.npops))
    h.set_xticklabels(f.popnames)
    h.set_yticklabels(f.popnames)
    h.xaxis.set_ticks_position('top')
    xlim(-0.5,f.npops-0.5)
    ylim(f.npops-0.5,-0.5)
    clim(-abs(totalconns).max(),abs(totalconns).max())
    colorbar()
Пример #7
0
def startAnim(x, m, th, Tsim, inter=1, Tstart=0, h=0.002):
#    fig, axM = subplo1ts()
#    axX = axM.twinx()
    fig = figure()
    axM = subplot(211)
    axX = subplot(212, sharex=axM)
    anim = MyAnim(x, m, th, Tsim, inter, Tstart/h, h)

    anim.line1, = axM.plot([], [], 'b')
    anim.line2, = axX.plot([], [], 'g')
    setp(axM.get_xticklabels(), visible=False)
    axM.set_xlim([-pi, pi])
    axX.set_xlim([-pi, pi])
#    axM.set_ylim([0., 3])
#    axX.set_ylim([0., 1.])
    axM.set_ylim([amin(m), amax(m)])
    axX.set_ylim([amin(x), amax(x)])

    axM.set_ylabel(r"$m$")
    axX.set_ylabel(r"$x$")
    axX.set_xlabel(r"$\theta$")
    hold(False)
    for tl in axM.get_yticklabels():
        tl.set_color('b')
    for tl in axX.get_yticklabels():
        tl.set_color('g')
    anim.axM = axM
    anim.axX = axX
    fig.canvas.mpl_connect('button_press_event', anim.onClick)
    a = FuncAnimation(fig, anim, frames=anim.dataGen, init_func=anim.init,
                 interval=0, blit=True, repeat=True)
    show()
    return a
Пример #8
0
def mark_cross(center, **kwargs):
    """Mark a cross. Correct for matplotlib imshow funny coordinate system.
    """
    N = 20
    plt.hold(1)
    plt.axhline(y=center[1]-0.5, **kwargs)
    plt.axvline(x=center[0]-0.5, **kwargs)
Пример #9
0
def plot_waveforms(time,voltage,APTimes,titlestr):
    """
    plot_waveforms takes four arguments - the recording time array, the voltage
    array, the time of the detected action potentials, and the title of your
    plot.  The function creates a labeled plot showing the waveforms for each
    detected action potential
    """

    plt.figure()

    ## Your Code Here
    for n in range(0,APTimes.size):
        ind = time[(time>(APTimes[n] - 0.003)) & (time<(APTimes[n] + 0.003))]
        sp = np.zeros(ind.size)
    
        for i in range(0,ind.size):
            sp[i] = plt.find(time == ind[i])
        sp=sp.astype(np.int64)
        x = np.linspace(-3.0e-3, 3.0e-3, sp.size)
        plt.plot(x,voltage[sp])
        plt.hold(True)
        
    plt.xlabel('Time (s)')
    plt.ylabel('Voltages (s)')
    plt.title(titlestr)    
    plt.show()
Пример #10
0
def plot_histograms(result_lists, figure=1, labels=None):
    times = []
    for n in range(len(result_lists)):
        times.append(
            1e6 * np.array([i.time for i in result_lists[n]
                            ]))  # convert from seconds to microseconds units.

    min_time = np.min([np.min(times[n]) for n in range(len(result_lists))])
    max_time = np.max([np.max(times[n]) for n in range(len(result_lists))])

    plt.figure(figure)
    plt.hold(False)
    for n in range(len(result_lists)):
        plt.hist(times[n],
                 50,
                 range=(min_time, max_time),
                 color=colors[n],
                 label=labels[n],
                 rwidth=(1 - n * 1.0 / len(result_lists)))
        plt.hold(True)

    plt.title("Migration time for different sequences")
    plt.xlabel("First Passage Time (us)", fontsize='larger')
    plt.ylabel("# of Trajectories", fontsize='larger')
    plt.yticks(fontsize='larger', va='bottom')
    plt.xticks(fontsize='larger')
    plt.legend(loc=0)
    plt.show()
Пример #11
0
def mark_cross(center, **kwargs):
    """Mark a cross. Correct for matplotlib imshow funny coordinate system.
    """
    N = 20
    plt.hold(1)
    plt.axhline(y=center[1] - 0.5, **kwargs)
    plt.axvline(x=center[0] - 0.5, **kwargs)
Пример #12
0
def question1():
    """
    Function compute the runing times of the functions slow_closest_pairs
    and fast_closest_pair for lists of clusters of size 2 to 200.
    """
    slow_time_list = []
    fast_time_list = []
    for cluster_size in xrange(2, 201):
        random_cluster = gen_random_clusters(cluster_size)
        #For the slow_time_list
        start_time = time.time()
        slow_closest_pairs(random_cluster)
        slow_time_list.append(time.time() - start_time)
        #For the fast_time_list
        start_time = time.time()
        fast_closest_pair(random_cluster)
        fast_time_list.append(time.time() - start_time)
    plt.figure()
    plt.hold(True)
    plt.plot(range(2, 201), slow_time_list, 'r', label='Slow Closest Pairs')
    plt.plot(range(2, 201), fast_time_list, 'b', label='Fast Closest Pair')
    plt.legend(loc='upper right')
    plt.title('Running Time Comparision')
    plt.xlabel('The size of clusters')
    plt.ylabel('Runing Time(s)')
    plt.hold(False)
    plt.show()
Пример #13
0
def plot_completion_graph(result_lists, figure=1, labels=None):
    times = []
    percents = []
    if labels == None:
        labels = [str(n) for n in range(1, 1 + len(result_lists))]
    # if len(labels) < len(colors):
    #    colors = colors[:len(labels)]

    for rl in result_lists:
        n = len(rl)
        t = [i.time for i in rl]
        t.sort()
        times.append(np.array(t))

        p = np.array(range(1, len(t) + 1))
        p = 100 * p / n  # percentage of all trials
        percents.append(p)

    plt.figure(figure)
    plt.hold(False)

    for t, p, c, label in zip(times, percents, colors, labels):
        plt.plot(1e6 * t, p, color=c, linewidth=2.0, label=label)
        plt.hold(True)

    plt.xlabel("Simulation Time (us)", fontsize='larger')
    plt.ylabel("% of Trajectories Complete", fontsize='larger')
    plt.yticks([0, 20, 40, 60, 80, 100],
               ("0%", "20%", "40%", "60%", "80%", "100%"),
               fontsize='larger',
               va='bottom')
    plt.xticks(fontsize='larger')
    plt.title("Percentage of Total Trajectories Complete by a Given Time")
    plt.legend(loc=0)
    plt.show()
Пример #14
0
def ensemble_demo():
    utc = Calendar()
    t_start = utc.time(YMDhms(2011, 9, 1))
    t_fc_ens_start = utc.time(YMDhms(2015, 7, 26))
    disp_start = utc.time(YMDhms(2015, 7, 20))
    dt = deltahours(1)
    n_obs = int(round((t_fc_ens_start - t_start) / dt))
    n_fc_ens = 30
    n_disp = int(round(t_fc_ens_start - disp_start) / dt) + n_fc_ens + 24 * 7

    obs_time_axis = Timeaxis(t_start, dt, n_obs + 1)
    fc_ens_time_axis = Timeaxis(t_fc_ens_start, dt, n_fc_ens)
    display_time_axis = Timeaxis(disp_start, dt, n_disp)

    q_obs_m3s_ts = observed_tistel_discharge(obs_time_axis.total_period())
    ptgsk = create_tistel_simulator(
        PTGSKOptModel, tistel.geo_ts_repository(tistel.grid_spec.epsg()))
    initial_state = burn_in_state(ptgsk, t_start, utc.time(YMDhms(2012, 9, 1)),
                                  q_obs_m3s_ts)

    ptgsk.run(obs_time_axis, initial_state)
    current_state = adjust_simulator_state(ptgsk, t_fc_ens_start, q_obs_m3s_ts)
    q_obs_m3s_ts = observed_tistel_discharge(display_time_axis.total_period())
    ens_repos = tistel.arome_ensemble_repository(tistel.grid_spec)
    ptgsk_fc_ens = create_tistel_simulator(PTGSKModel, ens_repos)
    sims = ptgsk_fc_ens.create_ensembles(fc_ens_time_axis, t_fc_ens_start,
                                         current_state)
    for sim in sims:
        sim.simulate()
    plt.hold(1)
    percentiles = [10, 25, 50, 75, 90]
    plot_percentiles(sims, percentiles, obs=q_obs_m3s_ts)
    #plt.interactive(1)
    plt.show()
Пример #15
0
def plot_fits(direction_rates,fit_curve,title):
    """
    This function takes the x-values and the y-values  in units of spikes/s 
    (found in the two columns of direction_rates and fit_curve) and plots the 
    actual values with circles, and the curves as lines in both linear and 
    polar plots.
    """
    curve_xs = np.arange(direction_rates[0,0], direction_rates[-1,0])
    fit_ys2 = normal_fit(curve_xs,fit_curve[0],fit_curve[1],fit_curve[2])
    
    
    plt.subplot(2,2,3)
    plt.plot(direction_rates[:,0],direction_rates[:,1],'o',hold=True)
    plt.plot(curve_xs,fit_ys2,'-')
    plt.xlabel('Direction of Motions (Degrees)')
    plt.ylabel('Firing Rates (Spikes/sec)')
    plt.title(title)
    plt.axis([0, 360, 0, 40])
    plt.xticks(direction_rates[:,0])
    
    fit_ys = normal_fit(direction_rates[:,0],fit_curve[0],fit_curve[1],fit_curve[2])
    plt.subplot(2,2,4,polar=True)
    spkiecount = np.append(direction_rates[:,1],direction_rates[0,1])
    plt.polar(np.arange(0,361,45)*np.pi/180,spkiecount,'o',label='Firing Rate (spike/s)')
    plt.hold(True)
    spkiecount_y = np.append(fit_ys,fit_ys[0])
    plt.plot(np.arange(0,361,45)*np.pi/180,spkiecount_y,'-')    
    plt.legend(loc=8)
    plt.title(title)
    
    fit_ys2 = np.transpose(np.vstack((curve_xs,fit_ys2)))    
    
    return(fit_ys2)
    def plot(self):
        Ns = 1
        h = 0.1
        m = []
        for i in range(len(self.l)):
            for s in range(Ns):
                m.append(ml_to_xy((i, float(s)/Ns, 0), self.kappa, self.l, self.x0, self.theta0))
        m.append(ml_to_xy((len(self.l)-1, 1., 0), self.kappa, self.l, self.x0, self.theta0))

        plt.clf()
        plt.hold(True)
        x=[p[0] for p in m]
        y=[p[1] for p in m]
        
        bp, angles, tangents= breakpoints(self.kappa, self.l, self.x0, self.theta0)
        x=[p[0] for p in bp]
        y=[p[1] for p in bp]
        plt.plot(x[::10],y[::10],'k-')
#        xm = [p[0] for i, p in enumerate(bp) if self.markers[i]==1]
#        ym = [p[1] for i, p in enumerate(bp) if self.markers[i]==1]


#        plt.plot(xm,ym,'kx')

        plt.xlim((-100, 3000))
        plt.ylim((-3000, 100))
        plt.draw()
Пример #17
0
    def plotVWavelet(self, width=30):
        plt.close()
        fig, figInds = plt.subplots(nrows=self.nCell, sharex=True)

        # 周波数
        widths = np.arange(1, width + 1)

        for figInd in np.arange(len(figInds)):
            # continuous waveletをかけて、係数マップと周波数を出力
            cwtmatr, freqs = pywt.cwt(self.yV[:, figInd], widths, 'mexh')

            # 係数マップのプロット
            figInds[figInd].imshow(
                cwtmatr,
                extent=[1, self.nYear, widths[-1], widths[0]],
                cmap='gray',
                aspect='auto',
                vmax=abs(cwtmatr).max(),
                vmin=-abs(cwtmatr).max())

        plt.hold(True)

        fullPath = os.path.join(self.visualPath,
                                "{}_cwt.png".format(self.logName))
        plt.savefig(fullPath)

        fig.show()
        plt.show()
def plot_completion_graph(result_lists,
                          colors=['b', 'r'],
                          figure=1,
                          labels=['Design A', 'Design B']):
    times = []
    percents = []
    for rl in result_lists:
        n = len(rl)
        t = [i.time for i in rl if i.tag == 'complete']
        t.sort()
        times.append(np.array(t))

        p = np.array(range(1, len(t) + 1))
        p = 100 * p / n  # percentage of all trials, including ones that don't complete
        percents.append(p)

    plt.figure(figure)
    plt.hold(False)

    for t, p, c, label in zip(times, percents, colors, labels):
        plt.plot(t, p, color=c, linewidth=2.0, label=label)
        plt.hold(True)

    plt.xlabel("Simulation Time (s)", fontsize='larger')
    plt.ylabel("% of Trajectories Complete", fontsize='larger')
    plt.yticks([0, 20, 40, 60, 80, 100],
               ("0%", "20%", "40%", "60%", "80%", "100%"),
               fontsize='larger',
               va='bottom')
    plt.xticks(fontsize='larger')
    plt.title("Percentage of Total Trajectories Complete by a Given Time")
    plt.legend(loc=0)
    plt.show()
def plot_histograms_two_designs(result_lists,
                                colors=['magenta', 'b'],
                                figure=1):
    times = []
    times.append(
        np.array([i.time for i in result_lists[0] if i.tag == 'complete']))
    times.append(
        np.array([i.time for i in result_lists[1] if i.tag == 'complete']))

    min_time = np.min([np.min(times[0]), np.min(times[1])])
    max_time = np.max([np.max(times[0]), np.max(times[1])])
    # the above might fail if any list is empty; min, max of empty is undefined

    plt.figure(figure)
    plt.hold(False)
    plt.hist(times[1],
             50,
             range=(min_time, max_time),
             color=colors[1],
             label="Design B")
    plt.hold(True)
    plt.hist(times[0],
             50,
             range=(min_time, max_time),
             color=colors[0],
             label="Design A",
             rwidth=.5)

    plt.title("Successful trajectories in two designs")
    plt.xlabel("First Passage Time (s)", fontsize='larger')
    plt.ylabel("# of Trajectories", fontsize='larger')
    plt.yticks(fontsize='larger', va='bottom')
    plt.xticks(fontsize='larger')
    plt.legend(loc=0)
    plt.show()
Пример #20
0
def ensemble_demo():
    utc = Calendar()
    t_start = utc.time(YMDhms(2011, 9, 1))
    t_fc_ens_start = utc.time(YMDhms(2015, 7, 26))
    disp_start = utc.time(YMDhms(2015, 7, 20))
    dt = deltahours(1)
    n_obs = int(round((t_fc_ens_start - t_start)/dt))
    n_fc_ens = 30
    n_disp = int(round(t_fc_ens_start - disp_start)/dt) + n_fc_ens + 24*7

    obs_time_axis = Timeaxis(t_start, dt, n_obs + 1)
    fc_ens_time_axis = Timeaxis(t_fc_ens_start, dt, n_fc_ens)
    display_time_axis = Timeaxis(disp_start, dt, n_disp)

    q_obs_m3s_ts = observed_tistel_discharge(obs_time_axis.total_period())
    ptgsk = create_tistel_simulator(PTGSKOptModel, tistel.geo_ts_repository(tistel.grid_spec.epsg()))
    initial_state = burn_in_state(ptgsk, t_start, utc.time(YMDhms(2012, 9, 1)), q_obs_m3s_ts)

    ptgsk.run(obs_time_axis, initial_state)
    current_state = adjust_simulator_state(ptgsk, t_fc_ens_start, q_obs_m3s_ts)
    q_obs_m3s_ts = observed_tistel_discharge(display_time_axis.total_period())
    ens_repos = tistel.arome_ensemble_repository(tistel.grid_spec)
    ptgsk_fc_ens = create_tistel_simulator(PTGSKModel, ens_repos)
    sims = ptgsk_fc_ens.create_ensembles(fc_ens_time_axis, t_fc_ens_start, current_state)
    for sim in sims:
        sim.simulate()
    plt.hold(1)
    percentiles = [10, 25, 50, 75, 90]
    plot_percentiles(sims, percentiles, obs=q_obs_m3s_ts)
    #plt.interactive(1)
    plt.show()
Пример #21
0
def waterfall_plot(q,x,sampling=10,cmap=None,num_colors=100,outdir='./',outname='waterfall',format='eps',cbar_label='$|q| (a.u.)$'):
    plt.figure()
    plt.hold(True)
    colorVal = 'b'
    vmax = q[:,:].max()
    print vmax,len(q)
    for n in range(0,len(q),sampling):
        if cmap is not None:
            print q[n,:].max()
            colorVal = get_color(value=q[n,:].max(),cmap=cmap,vmax=vmax+.1,num_colors=num_colors)

        plt.plot(x,q[n,:]+n/10.0,label=str(n),color=colorVal,alpha=0.7)
    ax = plt.gca()
    for tic in ax.yaxis.get_major_ticks():
        tic.tick1On = tic.tick2On = False
        tic.label1On = tic.label2On = False

    if cmap is not None:
        scalar = get_smap(vmax=q[:,:].max()+.1,num_colors=sampling)
        cbar = plt.colorbar(scalar)

    plt.xlabel('$x\quad (a.u.)$')
    cbar.set_label(cbar_label)
    plt.draw()

    plt.savefig(os.path.join(outdir,outname+'.'+format),format=format,dpi=320,bbox_inches='tight')
    plt.close()
    return
Пример #22
0
def saveCMDataFig(CMdata, trialDuration, trialReps, saveDir, plotName, timeStr):
    plt.figure(1, figsize=(14, 11), dpi=80)
    plt.clf()
    
    numFreq = len(CMdata.freqArray)
    numAmp = len(CMdata.ampArray)
    nGraphs = numFreq + 1
    numRows = int(np.ceil(nGraphs ** 0.5))
    numCols = int(np.ceil(nGraphs / numRows))
    numSD = 2.5
    for n in range(0, numFreq):
        CMresp = CMdata.CMResp[n, :]
        noise_mean = CMdata.noise_mean[n, :]
        noise_std = CMdata.noise_std[n, :]
        noise = noise_mean + (numSD * noise_std)
        
        plt.subplot(numRows, numCols, n+1)
        plt.plot(CMdata.ampArray, 1e6*CMresp,'-bo', label='Response (uV)')
        plt.hold('on')
        plt.plot(CMdata.ampArray,  1e6*(noise_mean + 3*noise_std), '-ro', label='Noise')   
        plt.plot(CMdata.ampArray, noise_mean, ':r', label='Noise mean')
        # plt.plot(CMdata.ampArray, noise, '-rs', label='+ %g SD' % numSD)
        
        plt.xlabel('Amplitude (dB)', fontsize=10)
        if n == (numFreq-1):
            plt.legend(loc='upper left', fontsize=10)
        #plt.pcolormesh(t, f, Sxx)
        plt.ylabel('dB SPL', fontsize=10)
        plt.title('%0.2f kHz' % (CMdata.freqArray[n]/1e3), x=0.15, fontsize=10)
        
    plt.show()
    fname = os.path.join(saveDir, plotName)
    plt.savefig(fname)
Пример #23
0
def saveABRDataFig(ABRdata, ABRparams, saveDir, plotName, timeStr):
    plt.figure(1, figsize=(14, 11), dpi=80) 
    plt.clf()
    
    numFreq = len(ABRdata.freqArray)
    numAmp = len(ABRdata.ampArray)
    numSD = 5
    # clr_lbls = ['b', 'g', 'r', 'c', 'm',  'y', 'k']
    nGraphs = numFreq + 1
    numRows = int(np.ceil(nGraphs ** 0.5))
    numCols = int(np.ceil(nGraphs / numRows))
    for n in range(0, numFreq):
        plt.subplot(numRows, numCols, n+1)
        ABRresp = 1e6*ABRdata.ABRResp[n, :]
        noise = 1e6*numSD*ABRdata.noise_std[n, :]
        plt.plot(ABRdata.ampArray, ABRresp, '-bo', label='Signal')
        plt.hold('on')
        plt.plot(ABRdata.ampArray, noise, '-r', label='Noise (%0.1f SD)' % numSD)
        if n == (0):
            plt.ylabel('Resp PP (uV)', fontsize=10)
        if n == (numFreq-1):
            plt.legend(loc='upper left', fontsize=10)
            plt.xlabel('Amplitude (dB)', fontsize=10)
        #plt.pcolormesh(t, f, Sxx)
        
        plt.title('%0.2f kHz' % (ABRdata.freqArray[n]/1e3), x=0.15, fontsize=10)

    plt.show()
    fname = os.path.join(saveDir, plotName)
    plt.savefig(fname)
    
    plt.figure(2, figsize=(14, 11), dpi=80)
    plt.clf()
    
    # clr_lbls = ['b', 'g', 'r', 'c', 'm',  'y', 'k']
    t = ABRdata.t
    for n in range(0, numFreq):
        plt.subplot(numRows, numCols, n+1)
        offset = 0
        for a in range(numAmp):
            tr = 1e6*ABRdata.tracings[n, a, :]
            if a > 0:
                offset = offset + np.abs(np.min(tr))

            plt.plot(t*1e3, tr+offset, '-b', label='Signal')
            plt.hold('on')
            offset = offset + np.max(tr)
            
        if n == (0):
            plt.ylabel('Resp (uV)', fontsize=10)
        if n == (numFreq-1):
            plt.xlabel('Time (ms)', fontsize=10)
        #plt.pcolormesh(t, f, Sxx)
        
        plt.title('%0.2f kHz' % (ABRdata.freqArray[n]/1e3), x=0.15, fontsize=10)
    
    plt.show()
    fname = os.path.join(saveDir, plotName + ' tracings')
    plt.savefig(fname)
Пример #24
0
def gasket(pa, pb, pc, level, col):
    if level == 0:
        plt.fill([pa[0], pb[0], pc[0]], [pa[1], pb[1], pc[1]], col) 
        plt.hold(True)
    else:
        gasket(pa, (pa + pb) / 2., (pa + pc) / 2., level - 1, col) 
        gasket(pb, (pb + pa) / 2., (pb + pc) / 2., level - 1, col) 
        gasket(pc, (pc + pa) / 2., (pc + pb) / 2., level - 1, col)
def gasket(pa, pb, pc, level, color):
    if level == 0:
        plt.fill([pa[0], pb[0], pc[0]], [pa[1], pb[1], pc[1]], color)
        plt.hold(True)
    else:
        gasket(pa, (pa + pb) / 2., (pa + pc) / 2., level - 1, color)
        gasket(pb, (pb + pa) / 2., (pb + pc) / 2., level - 1, color)
        gasket(pc, (pc + pa) / 2., (pc + pb) / 2., level - 1, color)
def Sierpinski(a, b, c, k, iteration):
    if iteration == 0:
        plt.fill([a[0], b[0], c[0]], [a[1], b[1], c[1]], 'b')
        plt.hold(True)
    else:
        Sierpinski(a, bis(a, b, k), bis(a, c, k), k, iteration - 1)
        Sierpinski(b, bis(a, b, k), bis(b, c, k), k, iteration - 1)
        Sierpinski(c, bis(a, c, k), bis(b, c, k), k, iteration - 1)
        plt.hold(True)
Пример #27
0
def Sierpinski(a,b,c,k,iteration): 
    if iteration==0:
        plt.fill([a[0], b[0], c[0]], [a[1], b[1], c[1]],'b') 
        plt.hold(True)
    else:
        Sierpinski(a,bis(a,b,k),bis(a,c,k),k,iteration-1)
        Sierpinski(b,bis(a,b,k),bis(b,c,k),k,iteration-1)
        Sierpinski(c,bis(a,c,k),bis(b,c,k),k,iteration-1)
        plt.hold(True)
Пример #28
0
    def run(self):

        plt.figure()
        plt.ion()
        plt.hold(True)

        while not rospy.is_shutdown():
            self.plotTrajectory()
            time.sleep(0.5 / self.update_rate)
Пример #29
0
 def display_multiple_egg_carton(u0,s0,s1,ds,C,s):
     X = solve_multiple(C,u0,s0,s1,ds,s)
     plt.hold('on')
     # plot the parametrized data on to the egg carton
     u,v = X[:,0], X[:,2]
     x = u
     y = v
     z = np.sin(u)*np.cos(v)
     ax.plot(x,y,z,'--r')
     return plt
Пример #30
0
 def display_multiple_torus(u0,s0,s1,ds,C,s):
     X = solve_multiple(C,u0,s0,s1,ds,s)
     plt.hold('on')
     # plot the parametrized data on to the sphere
     u,v = X[:,0], X[:,2]
     x = (2 + 1*np.cos(v))*np.cos(u)
     y = (2 + 1*np.cos(v))*np.sin(u)
     z = np.sin(v)
     ax.plot(x,y,z,'--r')
     return plt
Пример #31
0
 def display_multiple_egg_carton(u0, s0, s1, ds, C, s):
     X = solve_multiple(C, u0, s0, s1, ds, s)
     plt.hold('on')
     # plot the parametrized data on to the egg carton
     u, v = X[:, 0], X[:, 2]
     x = u
     y = v
     z = np.sin(u) * np.cos(v)
     ax.plot(x, y, z, '--r')
     return plt
Пример #32
0
 def display_multiple_catenoid(u0, s0, s1, ds, C, s):
     X = solve_multiple(C, u0, s0, s1, ds, s)
     plt.hold('on')
     # plot the parametrized data on to the catenoid
     u, v = X[:, 0], X[:, 2]
     x = np.cos(u) - v * np.sin(u)
     y = np.sin(u) + v * np.cos(u)
     z = v
     ax.plot(x, y, z, '--r')
     return plt
Пример #33
0
 def display_multiple_torus(u0, s0, s1, ds, C, s):
     X = solve_multiple(C, u0, s0, s1, ds, s)
     plt.hold('on')
     # plot the parametrized data on to the sphere
     u, v = X[:, 0], X[:, 2]
     x = (2 + 1 * np.cos(v)) * np.cos(u)
     y = (2 + 1 * np.cos(v)) * np.sin(u)
     z = np.sin(v)
     ax.plot(x, y, z, '--r')
     return plt
Пример #34
0
 def display_multiple_catenoid(u0,s0,s1,ds,C,s):
     X = solve_multiple(C,u0,s0,s1,ds,s)
     plt.hold('on')
     # plot the parametrized data on to the catenoid
     u,v = X[:,0], X[:,2]
     x = np.cos(u) - v*np.sin(u)
     y = np.sin(u) + v*np.cos(u)
     z = v
     ax.plot(x,y,z,'--r')
     return plt
Пример #35
0
def plotPolygon(lat,lon,poly,regnum,plotFile):
    fig = plt.figure(figsize=(6,6))
    px = [pol[0] for pol in poly]
    py = [pol[1] for pol in poly]
    plt.plot(px,py,'b')
    plt.hold(True)
    plt.plot(lon,lat,'rx')
    plt.title('%.4f,%.4f in Region %i' % (lat,lon,regnum))
    plt.savefig(plotFile)
    plt.close()    
Пример #36
0
def plotPolygon(lat,lon,poly,regnum,plotFile):
    fig = plt.figure(figsize=(6,6))
    px = [pol[0] for pol in poly]
    py = [pol[1] for pol in poly]
    plt.plot(px,py,'b')
    plt.hold(True)
    plt.plot(lon,lat,'rx')
    plt.title('%.4f,%.4f in Region %i' % (lat,lon,regnum))
    plt.savefig(plotFile)
    plt.close()    
Пример #37
0
def sierpinski(a, b, c, iterations):
    x=(random.random(),random.random(),random.random())
    if iterations  == 0:
        plt.fill([a[0], b[0], c[0]], [a[1], b[1], c[1]], color=x,alpha=0.9) 
        plt.hold(True)
    else:
        sierpinski(a, (a + b) / 2., (a + c) / 2., iterations  - 1) 
        sierpinski(b, (b + a) / 2., (b + c) / 2., iterations  - 1) 
        sierpinski(c, (c + a) / 2., (c + b) / 2., iterations  - 1)
        plt.fill([(a[0] + b[0]) / 2., (a[0] + c[0]) / 2., (b[0] + c[0]) / 2.], [(a[1] + b[1]) / 2., (a[1] + c[1]) / 2., (b[1] + c[1]) / 2.], color=x,alpha=0.9)
Пример #38
0
def display_toroid(u0,
                   s0,
                   s1,
                   ds,
                   u_val=1,
                   v_val=None,
                   a=1,
                   solver=None,
                   show=False):
    C = toroid(u_val, v_val, a)  # Find the Christoffel tensor for toroid
    X = solve(C, u0, s0, s1, ds, solver)

    import matplotlib.pylab as plt
    from mpl_toolkits.mplot3d import Axes3D
    from math import pi
    if v_val is None:
        u = u_val  # toroids
        v, w = plt.meshgrid(np.linspace(-pi, pi, 250),
                            np.linspace(0, 2 * pi, 250))
    else:
        v = v_val  # spherical bowls
        u, w = plt.meshgrid(np.linspace(0, 2, 250),
                            np.linspace(0, 2 * pi, 250))

    x = (a * np.sinh(u) * np.cos(w)) / (np.cosh(u) - np.cos(v))
    y = (a * np.sinh(u) * np.sin(w)) / (np.cosh(u) - np.cos(v))
    z = (a * np.sin(v)) / (np.cosh(u) - np.cos(v))

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.view_init(elev=90., azim=0)
    # use transparent colormap
    import matplotlib.cm as cm
    theCM = cm.get_cmap()
    theCM._init()
    alphas = -.5 * np.ones(theCM.N)
    theCM._lut[:-3, -1] = alphas
    ax.plot_surface(x, y, z, linewidth=0, cmap=theCM)
    plt.hold('on')

    # plot the parametrized data on to the toroid
    if v_val is None:
        w, v = X[:, 0], X[:, 2]
    else:
        w, u = X[:, 0], X[:, 2]
    x = (a * np.sinh(u) * np.cos(w)) / (np.cosh(u) - np.cos(v))
    y = (a * np.sinh(u) * np.sin(w)) / (np.cosh(u) - np.cos(v))
    z = (a * np.sin(v)) / (np.cosh(u) - np.cos(v))

    s1_ = s1 / pi
    ax.plot(x, y, z, '--r')
    fig.suptitle('$s\in[%.1f\pi \, , \,%2.1f\pi]$' % (s0, s1_))
    if show == True:
        plt.show()
    return X, plt
def plot_histograms_complete_vs_failed(result_list,
                                       colors=['b', 'm'],
                                       figure=1):
    # separate based on which stop condition ended the simulation   ((( what if simulation ran out of time? )))
    times_complete = np.array(
        [i.time for i in result_list if i.tag == 'complete'])
    times_failed = np.array([i.time for i in result_list if i.tag == 'failed'])
    neither = [
        i for i in result_list
        if not i.tag == 'complete' and not i.tag == 'failed'
    ]
    if len(neither) > 0:
        print "some trajectories did not finish, one way nor the other..."
        for i in neither:
            assert (i.type_name == 'Time')
            assert (i.tag == None)

    if len(times_complete) > 0 and len(times_failed) > 0:
        min_time = np.min([np.min(times_complete), np.min(times_failed)])
        max_time = np.max([np.max(times_complete), np.max(times_failed)])
    else:
        if len(times_complete) > 0:
            min_time = np.min(times_complete)
            max_time = np.max(times_complete)
        if len(times_failed) > 0:
            min_time = np.min(times_failed)
            max_time = np.max(times_failed)

    plt.figure(figure)
    plt.hold(False)

    if len(times_complete) > 0:
        plt.hist(times_complete,
                 50,
                 range=(min_time, max_time),
                 color=colors[0],
                 label="complete")
        plt.hold(True)

    if len(times_failed) > 0:
        plt.hist(times_failed,
                 50,
                 range=(min_time, max_time),
                 color=colors[1],
                 rwidth=.5,
                 label="failed")

    plt.title(
        "Completion times for successful and failed trajectories, Design A")
    plt.xlabel("First Passage Time (s)", fontsize='larger')
    plt.ylabel("# of Trajectories", fontsize='larger')
    plt.yticks(fontsize='larger', va='bottom')
    plt.xticks(fontsize='larger')
    plt.legend(loc=0)
    plt.show()
Пример #40
0
def plot_rect_mesh(p,tri):
    plt.figure()
    tx = p[:,0]; ty = p[:,1]
    for t in tri:
        t_i = [t[0],t[1],t[2],t[0]]
        plt.plot(tx[t_i],ty[t_i],'k')
        plt.hold('on')
    plt.title('TRIANGULAR MESH')
    plt.axis('equal')
    plt.hold('off')
    plt.show()
Пример #41
0
def plot_learning_curves(clf, X, y):
  
    train_sizes, train_scores, valid_scores = learning_curve.learning_curve(clf, X, np.ravel(y), scoring = roc_auc_scorer, 
                                 cv = 6, train_sizes = np.linspace(.5, 1, 10), n_jobs = -1)
    
    plt.figure()
    plt.plot(train_sizes, np.mean(train_scores, axis = 1))
    plt.hold(True)
    plt.plot(train_sizes, np.mean(valid_scores, axis = 1))
    plt.grid(True)
    plt.show()
def Sierpinski(a,b,c,k,iteration):    
    x=(random.random(),random.random(),random.random())
    if iteration==0:
        plt.fill([a[0], b[0], c[0]], [a[1], b[1], c[1]], color=x,alpha=0.9)
        plt.hold(True)
    else:
        Sierpinski(a,bis(a,b,k),bis(a,c,k),k,iteration-1)
        Sierpinski(b,bis(a,b,k),bis(b,c,k),k,iteration-1)
        Sierpinski(c,bis(a,c,k),bis(b,c,k),k,iteration-1)
        plt.hold(True)
        plt.fill([bis(a,b,k)[0], bis(a,c,k)[0], bis(b,c,k)[0]], [bis(a,b,k)[1], bis(a,c,k)[1], bis(b,c,k)[1]], color=x,alpha=0.9)
Пример #43
0
def plotPORVelocity(velocity, POR, time, xtitle, ytitle, title):
    plt.figure()
    plt.plot(time, velocity)
    plt.hold(True)    
    plt.plot(time, POR, 'r.')
    
    plt.xlabel(xtitle)
    plt.ylabel(ytitle)
    plt.title(title)
    plt.grid(True)
    plt.show()
Пример #44
0
 def update_iq_power_plot_all(self, iq_power_1, iq_power_2):
     plt.cla()
     plt.plot(np.arange(0, len(iq_power_1), 1), iq_power_1, 'd-', color='b')
     plt.hold(True)
     plt.plot(np.arange(0, len(iq_power_2), 1), iq_power_2, 'o-', color='r')
     plt.hold(False)
     plt.grid(True)
     plt.ylim([-100, -30])
     plt.tight_layout()
     plt.show()
     plt.pause(0.00001)
Пример #45
0
def plot_svc(X, y, mysvc, bounds=None, grid=50):
    if bounds is None:
        xmin = np.min(X[:, 0], 0)
        xmax = np.max(X[:, 0], 0)
        ymin = np.min(X[:, 1], 0)
        ymax = np.max(X[:, 1], 0)
    else:
        xmin, ymin = bounds[0], bounds[0]
        xmax, ymax = bounds[1], bounds[1]
    aspect_ratio = (xmax - xmin) / (ymax - ymin)
    xgrid, ygrid = np.meshgrid(np.linspace(xmin, xmax, grid),
                               np.linspace(ymin, ymax, grid))
    plt.gca(aspect=aspect_ratio)
    plt.xlim(xmin, xmax)
    plt.ylim(ymin, ymax)
    plt.xticks([])
    plt.yticks([])
    plt.hold(True)
    plt.plot(X[y == 1, 0], X[y == 1, 1], 'bo')
    plt.plot(X[y == -1, 0], X[y == -1, 1], 'ro')

    box_xy = np.append(xgrid.reshape(xgrid.size, 1),
                       ygrid.reshape(ygrid.size, 1), 1)
    if mysvc is not None:
        scores = mysvc.decision_function(box_xy)
    else:
        print 'You must have a valid SVC object.'
        return None

    CS = plt.contourf(xgrid,
                      ygrid,
                      scores.reshape(xgrid.shape),
                      alpha=0.5,
                      cmap='jet_r')
    plt.contour(xgrid,
                ygrid,
                scores.reshape(xgrid.shape),
                levels=[0],
                colors='k',
                linestyles='solid',
                linewidths=1.5)
    plt.contour(xgrid,
                ygrid,
                scores.reshape(xgrid.shape),
                levels=[-1, 1],
                colors='k',
                linestyles='dashed',
                linewidths=1)
    plt.plot(mysvc.support_vectors_[:, 0],
             mysvc.support_vectors_[:, 1],
             'ko',
             markerfacecolor='none',
             markersize=10)
    CB = plt.colorbar(CS)
Пример #46
0
 def plotPoints(self, TITLE, saveName, xlab, ylab):
     plot(self.points[0, :], self.points[1, :], '.')
     hold('on')
     plot(self.points[0, :], self.evaluated, '-')
     hold('off')
     title(TITLE)
     xlabel(xlab)
     ylabel(ylab)
     legend(('datapunkter', 'polynomtilnærming',), loc=1)
     savefig(saveName)
     show()
Пример #47
0
def runAllBenchmarks(X, JobQ, ResultQ,
                     nRepeat=1, methods='all', **kwargs):
    methodNames = getMethodNames(methods=methods)

    print '======================= ', makeTitle(**kwargs)
    print '%16s %15s %15s %15s %10s' % (
        ' ',  'slice size', 'slice time', 'wallclock time', 'speedup')
    Tinfo = defaultdict(dict)
    for rep in xrange(nRepeat):
        for method in methodNames:
            tstart = time.time()
            ts = runBenchmark(X, JobQ, ResultQ, method=method, **kwargs)
            telapsed = time.time() - tstart

            Tinfo[method][rep] = dict()
            Tinfo[method][rep]['telapsed'] = telapsed
            Tinfo[method][rep]['ts'] = ts

    # PRINT RESULTS
    if 'monolithic' in Tinfo:
        telasped_monolithic = np.median([Tinfo['monolithic'][r]['telapsed']
                                         for r in xrange(nRepeat)])

    for rep in xrange(nRepeat):
        for method in methodNames:
            start, stop = [x for x in sliceGenerator(**kwargs)][0]
            msg = "%16s" % (method)
            if method == 'monolithic':
                msg += " %8d x %2d" % (X.shape[0], 1)
            else:
                msg += " %8d x %2d" % (stop - start, kwargs['nWorker'])
            msg += " %11.3f sec" % (np.median(Tinfo[method][rep]['ts']))

            telapsed = Tinfo[method][rep]['telapsed']
            msg += " %11.3f sec" % (telapsed)
            if 'monolithic' in Tinfo:
                msg += " %11.2f" % (telasped_monolithic / telapsed)
            print msg

    # PLOT RESULTS
    pylab.figure(1)
    pylab.hold('on')
    for method in methodNames:
        xs = kwargs['nWorker'] * np.ones(nRepeat)
        ys = [Tinfo[method][r]['telapsed'] for r in xrange(nRepeat)]
        if kwargs['nWorker'] == 1:
            label = method
        else:
            label = None
        pylab.plot(xs, ys, '.',
                   color=ColorMap[method],
                   markeredgecolor=ColorMap[method],
                   label=label)
    return Tinfo
Пример #48
0
def plot_generic(x_values, y_values, plot_func = pyp.plot, hold = True,
					figure_number = None, *args, **kargs):
	"""
	Actual plotting function that passes arguments to the correct plot method.
	"""

	if figure_number:
		pyp.figure(figure_number)

	pyp.hold(hold) # keeps existing plots on the graph if true

	plot_func(x_values, y_values, *args, **kargs)
Пример #49
0
 def draw_grid_plot():
     if not has_plt:
         return
     plt.imshow(z_sample, cmap=plt.cm.binary, origin='lower',
                interpolation='nearest',
                extent=(grid_min, grid_max, grid_min, grid_max))
     plt.hold(True)  # XXX: restore plt state
     plt.contour(np.linspace(grid_min, grid_max, grid_n),
                 np.linspace(grid_min, grid_max, grid_n),
                 z_actual)
     plt.savefig(grid_filename)
     plt.close()
def gasket(pa, pb, pc, level):
    x=(random.random(),random.random(),random.random())
    if level == 0:
        plt.fill([pa[0], pb[0], pc[0]], [pa[1], pb[1], pc[1]], color=x,alpha=0.9) 
        plt.hold(True)
    else:
        gasket(pa, (pa + pb) / 2., (pa + pc) / 2., level - 1) 
        gasket(pb, (pb + pa) / 2., (pb + pc) / 2., level - 1) 
        gasket(pc, (pc + pa) / 2., (pc + pb) / 2., level - 1)
        plt.hold(True)
        plt.fill([(pa[0] + pb[0]) / 2.,(pb[0] + pc[0]) / 2.,(pa[0] + pc[0]) / 2.],
                 [(pa[1] + pb[1]) / 2.,(pb[1] + pc[1]) / 2.,(pa[1] + pc[1]) / 2.],color=x,alpha=0.9)
Пример #51
0
def plot_comparison(template,
                    haps,
                    snps=None,
                    title=None,
                    xlabel=None,
                    x=None,
                    y=None,
                    template_y='TEMP',
                    colors=DEFAULT_COLORS):
    '''Generate a recombination coloring plot of the difference between template
    and each element in the list haps..'''
    # Read or re-generate differences data
    num_snps = len(template)
    if np.size(haps.shape) == 1:
        haps = np.transpose(np.array([haps]))
    num_haps = haps.shape[1]
    # d = (haps != np.transpose(np.tile(template, (num_haps,1)))).astype('int8')
    d = np.transpose(
        np.array([
            diff.hap_diff(haps[:, j], template).astype('int8')
            for j in xrange(0, num_haps)
        ]))

    # Restrict view to snps, if specified
    x = x if x is not None else np.arange(0, num_snps)
    if snps is not None:
        (x, d) = (x[snps], d[snps, :])

    # Generate haplotype plots
    P.clf()
    P.hold(True)
    hap_ticks = range(0, num_haps)
    for j in hap_ticks:
        difference = d[:, j]
        for (value, color) in colors.iteritems():
            hap = np.where(difference == value)
            if hap:
                P.plot(x[hap[0]],
                       np.zeros((np.size(hap), )) + j,
                       color,
                       markeredgecolor='gray'
                       if value == INDETERMINATE else color[0])

    if title is not None:
        P.title(title)
    P.xlim([min(x) - 1, max(x) + 1])
    P.ylim([-0.5, num_haps - 0.5])
    P.xlabel(xlabel if xlabel else 'SNP #')
    P.ylabel('Sample')
    if y is not None:
        P.yticks(hap_ticks, [template_y] + list(y))
    return d
Пример #52
0
def optimize_char_ngram():
    
    log_reg_clf = LogisticRegression(C = 10)
    #svm_clf = svm.SVC(C = 10)
    
    #classifiers = [log_reg_clf, svm_clf]

    tfidf_vect = TfidfVectorizer()
    
    estimators = [('vect', tfidf_vect), ('clf', log_reg_clf)]
    clf = Pipeline(estimators)
    
    clf.set_params(vect__analyzer = 'char')
    n_gram_range = np.array(range(1, 5))
    scores_train_vec = np.zeros(n_gram_range.shape)
    scores_test_vec = np.zeros(n_gram_range.shape)
    for n_gram_ind in range(len(n_gram_range)):
        print("%d n_gram:" % n_gram_range[n_gram_ind])
        clf.set_params(vect__ngram_range=(1, n_gram_range[n_gram_ind]))
        #cv = cross_validation.ShuffleSplit(X_train.shape[0], n_iter = 20, test_size = 0.2)
        cv = cross_validation.KFold(X_train.shape[0], n_folds = 6)
        scores_train = []
        scores_test = []
        for train_index, test_index in cv:
            clf.fit(X_train[train_index], np.ravel(y_train[train_index]))

            y_train_pred = clf.predict(X_train[train_index])
            train_score = roc_auc_score_(y_train_pred, np.ravel(y_train[train_index]))
            print train_score
            scores_train.append(train_score)

            y_test_pred = clf.predict(X_train[test_index])
            test_score = roc_auc_score_(y_test_pred, np.ravel(y_train[test_index]))
            print test_score
            scores_test.append(test_score)

        scores_train_vec[n_gram_ind] = np.mean(scores_train)
        scores_test_vec[n_gram_ind] = np.mean(scores_test)
            
        
    
    
    print(scores_train_vec)
    print(scores_test_vec)
    
    
    plt.figure()
    plt.plot(n_gram_range, scores_train_vec)
    plt.hold(True)
    plt.plot(n_gram_range, scores_test_vec)
    plt.grid(True)
    plt.show()
def show_image(img_dir, img_name, label_dict):

    img_path = os.path.join(img_dir, img_name)

    img = scipy.misc.imread(img_path)

    plt.figure()
    plt.imshow(img)
    if len(label_dict[img_name]):
        points = np.array(label_dict[img_name]) / 100. * [640., 480.]
        plt.hold('on')
        plt.scatter(points[:, 0], points[:, 1])
    plt.show()
Пример #54
0
 def draw_grid_plot():
     if not has_plt:
         return
     plt.imshow(z_sample,
                cmap=plt.cm.binary,
                origin='lower',
                interpolation='nearest',
                extent=(grid_min, grid_max, grid_min, grid_max))
     plt.hold(True)  # XXX: restore plt state
     plt.contour(np.linspace(grid_min, grid_max, grid_n),
                 np.linspace(grid_min, grid_max, grid_n), z_actual)
     plt.savefig(grid_filename)
     plt.close()
Пример #55
0
def plot_data_and_model(x, y, f, knee, title):
    '''Generate a plot of the data y(x), fitted curve f, and knee point (knee is the index of that
    point into the x-array).'''
    P.figure(1)
    P.clf()
    P.hold(True)
    P.plot(x, y, 'x', label='Data')
    P.plot(x, f, 'r-', label='Fit')
    P.title(title)
    P.xlabel(r'$\beta$')
    P.ylabel('Frequency')
    P.legend(loc=0)
    P.plot(x[knee], y[knee], 'ko', markersize=8)
Пример #56
0
def SierpinskiTriangle(a, b, c, iterations):
    '''
    Recursively generated Sierpinski Triangle. 
    '''
    if iterations == 0:
        # Fill the triangle with vertices a, b, c. 
        plt.fill([a[0], b[0], c[0]], [a[1], b[1], c[1]], 'g') 
        plt.hold(True)
    else:
        # Recursive calls for the three subtriangles. 
        SierpinskiTriangle(a, (a + b) / 2., (a + c) / 2., iterations - 1) 
        SierpinskiTriangle(b, (b + a) / 2., (b + c) / 2., iterations - 1) 
        SierpinskiTriangle(c, (c + a) / 2., (c + b) / 2., iterations - 1)
def sierpinski(a, b, c, iterations):
    x = (random.random(), random.random(), random.random())
    if iterations == 0:
        plt.fill([a[0], b[0], c[0]], [a[1], b[1], c[1]], color=x, alpha=0.9)
        plt.hold(True)
    else:
        sierpinski(a, (a + b) / 2., (a + c) / 2., iterations - 1)
        sierpinski(b, (b + a) / 2., (b + c) / 2., iterations - 1)
        sierpinski(c, (c + a) / 2., (c + b) / 2., iterations - 1)
        plt.fill([(a[0] + b[0]) / 2., (a[0] + c[0]) / 2., (b[0] + c[0]) / 2.],
                 [(a[1] + b[1]) / 2., (a[1] + c[1]) / 2., (b[1] + c[1]) / 2.],
                 color=x,
                 alpha=0.9)
Пример #58
0
def SierpinskiTriangle(a, b, c, iterations):
    """
    Recursively generated Sierpinski Triangle. 
    """
    if iterations == 0:
        # Fill the triangle with vertices a, b, c.
        plt.fill([a[0], b[0], c[0]], [a[1], b[1], c[1]], "g")
        plt.hold(True)
    else:
        # Recursive calls for the three subtriangles.
        SierpinskiTriangle(a, (a + b) / 2.0, (a + c) / 2.0, iterations - 1)
        SierpinskiTriangle(b, (b + a) / 2.0, (b + c) / 2.0, iterations - 1)
        SierpinskiTriangle(c, (c + a) / 2.0, (c + b) / 2.0, iterations - 1)
Пример #59
0
def show_trajectories(positions,LM_traj,intensities,LM_traj2=None,legend=True):
    fig = plt.figure()
    if LM_traj2!=None:
        plt.subplot(121)
    plt.hold(True)
    x,y = list(itertools.chain(*[v[0,:] for v in positions])), list(itertools.chain(*[v[1,:] for v in positions]))
    plt.scatter(x,y,marker='o',edgecolor='b',linestyle='dashed',alpha=0.3)
    for i,idx in enumerate(LM_traj):
        pos = [positions[t,:,int(ix)] for t,ix in enumerate(idx) if ix==ix]
        x, y = [v[0] for v in pos], [v[1] for v in pos]
        plt.plot(x,y,'-',linewidth=2.,alpha=0.4,label=str(i))
    plt.hold(False)
    if legend: plt.legend(loc=0)
    if LM_traj2!=None:
        plt.title('traj1')
    
    if LM_traj2!=None:
        
        plt.subplot(122)
        plt.hold(True)
        x,y = list(itertools.chain(*[v[0,:] for v in positions])), list(itertools.chain(*[v[1,:] for v in positions]))
        plt.scatter(x,y,marker='o',edgecolor='b',linestyle='dashed',alpha=0.3)
        for i,idx in enumerate(LM_traj2):
            pos = [positions[t,:,int(ix)] for t,ix in enumerate(idx) if ix==ix]
            x, y = [v[0] for v in pos], [v[1] for v in pos]
            plt.plot(x,y,'-',linewidth=2.,alpha=0.4,label=str(i))
        plt.hold(False)
        if legend: plt.legend(loc=0)
        plt.title('traj2')
    plt.show() 
Пример #60
0
def watch_sim():
    G = nx.complete_graph(40)
    G.name = 'K%d'%G.number_of_nodes()
    #G = nx.erdos_renyi_graph(20, 0.1)
    #G.name = 'ER%d'%G.number_of_nodes()
    
    #lam = 16.
    #lam = 10
    #lam = 1.
    lam = 3
    tau = 0.2

    Kvals = dict([(node,npr.poisson(lam)) for node in G])
    
    extentDummy,statuses = resMetrics.extentKFleeSIRSim_helper(G=G, startN=0, vaccinated=[], weighted=False, verbose=True,
                                             params={'tau':tau, 'K':Kvals,})

    pos = nx.drawing.layout.spring_layout(G, iterations=90)
    uninfected_color = 'green' #'black'
    infected_color   = 'red'
    contrarian_color = 'blue'

    uninfected_nodes = []
    infected_nodes = []
    contrarian_nodes = []
    for node in G:
        status = statuses[node]
        if 'UIF' in status:
            uninfected_nodes.append(node)
        elif 'INF' in status:
            infected_nodes.append(node)
        elif 'CON' in status:
            contrarian_nodes.append(node)
        else:
            raise ValueError, 'unknown status'


    reg_node_size = 200
    pylab.figure()
    pylab.hold(True)
    nx.draw_networkx_nodes(G, pos=pos, nodelist=uninfected_nodes, node_color=uninfected_color, node_size=reg_node_size, alpha=0.4)
    nx.draw_networkx_nodes(G, pos=pos, nodelist=infected_nodes,   node_color=infected_color,   node_size=reg_node_size, alpha=0.4)
    nx.draw_networkx_nodes(G, pos=pos, nodelist=contrarian_nodes, node_color=contrarian_color, node_size=reg_node_size, alpha=0.4)
    #nx.draw_networkx_edges(G, pos=pos, alpha=0.1)
    nx.draw_networkx_labels(G, pos=pos, labels=statuses)
    #pylab.grid(b=False)
    pylab.axis('off')
    #pylab.axes(frameon=False)
    pylab.text(-0.2, -0.2, 'nn=%d, tau=%.2f, lam=%.1f'%(G.number_of_nodes(),tau,lam))
    pylab.savefig('output/epidemic_final_tau=%.2f_lam=%.1f'%(tau,lam)+timeNow()+'.pdf')