Beispiel #1
0
def plot_funnel(pi_true, delta_str):
    delta = float(delta_str)
    n = pl.exp(mc.rnormal(10, 2**-2, size=10000))
    p = pi_true*pl.ones_like(n)

    # old way:
    #delta = delta * p * n

    nb = rate_model.neg_binom_model('funnel', pi_true, delta, p, n)
    r = nb['p_pred'].value

    pl.vlines([pi_true], .1*n.min(), 10*n.max(),
              linewidth=5, linestyle='--', color='black', zorder=10)
    pl.plot(r, n, 'o', color=colors[0], ms=10,
            mew=0, alpha=.25)

    pl.semilogy(schiz['r'], schiz['n'], 's', mew=1, mec='white', ms=15,
                color=colors[1],
                label='Observed Values')

    pl.xlabel('Rate (Per 1000 PY)', size=32)
    pl.ylabel('Study Size (PY)', size=32)
    pl.axis([-.0001, .0101, 50., 15000000])
    pl.title(r'$\delta = %s$'%delta_str, size=48)
    pl.xticks([0, .005, .01], [0, 5, 10], size=30)
    pl.yticks(size=30)
Beispiel #2
0
def simulation(recipe, curvNo, noIndicators):
    worker = recipe.getWorker("ThicknessModeller")
    simulation = worker.plugCalcAbsorption.getResult()
    worker = recipe.getWorker("AddColumn")
    table = worker.plugCompute.getResult(
        subscriber=TextSubscriber("Add Column"))
    thickness = table[u"thickness"]
    index = curvNo2Index(table[u"pixel"], curvNo)
    worker = recipe.getWorker("MRA Exp")
    minimaPos = worker.plugMra.getResult()[r'\lambda_{min}'].inUnitsOf(
        simulation.dimensions[1])
    maximaPos = worker.plugMra.getResult()[r'\lambda_{max}'].inUnitsOf(
        simulation.dimensions[1])
    visualizer = ImageVisualizer(simulation, False)
    ordinate = simulation.dimensions[1].data
    if not noIndicators:
        pylab.hlines(thickness.data[index],
                     ordinate.min(),
                     ordinate.max(),
                     label="$%s$" % minimaPos.shortname)
        abscissae = simulation.dimensions[0].data
        pylab.vlines(minimaPos.data[:, index],
                     abscissae.min(),
                     abscissae.max(),
                     label="$%s$" % minimaPos.shortname)
        pylab.vlines(maximaPos.data[:, index],
                     abscissae.min(),
                     abscissae.max(),
                     label="$%s$" % maximaPos.shortname)
Beispiel #3
0
def plotT(x, y, plt):
    plt.scatter(x, y)
    plt.vlines(x, [0], y)
    plt.ylim((min(y)-abs(min(y)*0.1)),max(y)+max(y)*0.1)
    plt.hlines(0, x[0]-1, x[x.shape[0]-1]+1)
    plt.xlim(x[0]-1,x[x.shape[0]-1]+1)
    plt.grid()
Beispiel #4
0
def plot_x_and_psd_with_estimated_omega(x, sample_step=1, dt=1.0):
    y = x[::sample_step]
    F = freq(x, sample_step, dt)
    T = 1.0 / F

    pylab.clf()

    # plot PSD
    pylab.subplot(211)
    pylab.psd(y, Fs=1.0 / sample_step / dt)
    ylim = pylab.ylim()
    pylab.vlines(F, *ylim)
    pylab.ylim(ylim)

    # plot time series
    pylab.subplot(223)
    pylab.plot(x)

    # plot time series (three cycles)
    n = int(T / dt) * 3
    m = n // sample_step
    pylab.subplot(224)
    pylab.plot(x[:n])
    pylab.plot(numpy.arange(0, n, sample_step)[:m], y[:m], 'o')

    pylab.suptitle('F = %s' % F)
Beispiel #5
0
    def __init__(self, n, handicap=0):

        self.welcome()

        self.n = n
        self.handicap = handicap
        self.board = [np.zeros((self.n, self.n))]

        self.f, self.ax = pylab.subplots(figsize=(8, 9))
        self.ax._label = 'main'
        pylab.subplots_adjust(bottom=0.2)
        self.f.set_facecolor('tan')
        pylab.axes(axisbg='tan')

        #pylab.grid(ls='-', zorder=0)
        pylab.vlines(np.arange(self.n - 1), 0, self.n - 1, zorder=-1)
        pylab.hlines(np.arange(self.n - 1), 0, self.n - 1, zorder=-1)
        pylab.xticks(np.arange(self.n))
        pylab.yticks(np.arange(self.n))
        pylab.xlim(-0.5, self.n - 0.5)
        pylab.ylim(-0.5, self.n - 0.5)

        self.turn = 0
        self.marker = 1  # 1 = black, -1 = white
        self.score = [[0, 0]]  # Captured stones (negative is bad)
        self.territory = [0, 0]  # Enclosed territory (positive is good)
    def plot(self):
        import pylab as pl
        ax = pl.gca()

        pl.hlines(self.tops,
                  self.left,
                  self.right,
                  linestyles='dashed',
                  colors='blue')
        pl.hlines(self.tops + self.heights,
                  self.left,
                  self.right,
                  linestyles='dashed',
                  colors='green')
        pl.vlines(self.lefts,
                  self.top,
                  self.bottom,
                  linestyles='dashed',
                  colors='blue')
        pl.vlines(self.lefts + self.widths,
                  self.top,
                  self.bottom,
                  linestyles='dashed',
                  colors='green')

        for box in self.rectangles:
            t, l, b, r = box
            patch = pl.Rectangle((l, t),
                                 r - l,
                                 b - t,
                                 color='blue',
                                 fill=True,
                                 alpha=0.5)
            ax.add_patch(patch)
        pass
Beispiel #7
0
def plot_profile(experiment, step, out_file):
    from pylab import figure, subplot, hold, plot, xlabel, ylabel, text, title, axis, vlines, savefig

    if out_file is None:
        out_file = "MISMIP_%s_A%d.pdf" % (experiment, step)

    xg = x_g(experiment, step)

    x = np.linspace(0, L(), N(2) + 1)
    thk = thickness(experiment, step, x)
    x_grounded, thk_grounded = x[x < xg],  thk[x < xg]
    x_floating, thk_floating = x[x >= xg], thk[x >= xg]

    figure(1)
    ax = subplot(111)
    hold(True)
    plot(x / 1e3, np.zeros_like(x), ls='dotted', color='red')
    plot(x / 1e3, -b(experiment, x), color='black')
    plot(x / 1e3, np.r_[thk_grounded - b(experiment, x_grounded),
                        thk_floating * (1 - rho_i() / rho_w())],
         color='blue')
    plot(x_floating / 1e3, -thk_floating * (rho_i() / rho_w()), color='blue')
    _, _, ymin, ymax = axis(xmin=0, xmax=x.max() / 1e3)
    vlines(xg / 1e3, ymin, ymax, linestyles='dashed', color='black')

    xlabel('distance from the summit, km')
    ylabel('elevation, m')
    text(0.6, 0.9, "$x_g$ (theory) = %4.0f km" % (xg / 1e3),
         color='black', transform=ax.transAxes)
    title("MISMIP experiment %s, step %d" % (experiment, step))
    savefig(out_file)
Beispiel #8
0
def check_interface(series: Series, debug=False) -> (bool, list):
    interval = series.index[1] - series.index[0]

    result, peaks = Ptre.test_data(series, interval, debug=debug)

    if debug:
        try:
            import pylab
        except:
            print('matplotlib not found, cannot debug')
        else:
            t = np.array(series.index) - series.index[0]
            pylab.plot(t, series)
            if result in [Ptre._PATTERN_A, Ptre._PATTERN_D]:
                pylab.vlines([p[0] for p in peaks], 0, 1, colors='red')
            pylab.show()

            for i in range(0, len(peaks)):
                if peaks[i][1] < 0:
                    state = 'INCREASING'
                else:
                    state = 'DECREASING'
                print(state, peaks[i][0])

    if result == Ptre._PATTERN_A:
        return True, peaks
    else:
        return False, peaks
Beispiel #9
0
def plot_profile(experiment, step, out_file):
    from pylab import figure, subplot, hold, plot, xlabel, ylabel, text, title, axis, vlines, savefig

    if out_file is None:
        out_file = "MISMIP_%s_A%d.pdf" % (experiment, step)

    xg = x_g(experiment, step)

    x = np.linspace(0, L(), N(2) + 1)
    thk = thickness(experiment, step, x)
    x_grounded, thk_grounded = x[x < xg], thk[x < xg]
    x_floating, thk_floating = x[x >= xg], thk[x >= xg]

    figure(1)
    ax = subplot(111)
    hold(True)
    plot(x / 1e3, np.zeros_like(x), ls='dotted', color='red')
    plot(x / 1e3, -b(experiment, x), color='black')
    plot(x / 1e3,
         np.r_[thk_grounded - b(experiment, x_grounded),
               thk_floating * (1 - rho_i() / rho_w())],
         color='blue')
    plot(x_floating / 1e3, -thk_floating * (rho_i() / rho_w()), color='blue')
    _, _, ymin, ymax = axis(xmin=0, xmax=x.max() / 1e3)
    vlines(xg / 1e3, ymin, ymax, linestyles='dashed', color='black')

    xlabel('distance from the summit, km')
    ylabel('elevation, m')
    text(0.6,
         0.9,
         "$x_g$ (theory) = %4.0f km" % (xg / 1e3),
         color='black',
         transform=ax.transAxes)
    title("MISMIP experiment %s, step %d" % (experiment, step))
    savefig(out_file)
Beispiel #10
0
def plot_funnel(pi_true, delta_str):
    delta = float(delta_str)
    n = pl.exp(mc.rnormal(10, 2**-2, size=10000))
    p = pi_true * pl.ones_like(n)

    # old way:
    #delta = delta * p * n

    nb = rate_model.neg_binom_model('funnel', pi_true, delta, p, n)
    r = nb['p_pred'].value

    pl.vlines([pi_true],
              .1 * n.min(),
              10 * n.max(),
              linewidth=5,
              linestyle='--',
              color='black',
              zorder=10)
    pl.plot(r, n, 'o', color=colors[0], ms=10, mew=0, alpha=.25)

    pl.semilogy(schiz['r'],
                schiz['n'],
                's',
                mew=1,
                mec='white',
                ms=15,
                color=colors[1],
                label='Observed Values')

    pl.xlabel('Rate (Per 1000 PY)', size=32)
    pl.ylabel('Study Size (PY)', size=32)
    pl.axis([-.0001, .0101, 50., 15000000])
    pl.title(r'$\delta = %s$' % delta_str, size=48)
    pl.xticks([0, .005, .01], [0, 5, 10], size=30)
    pl.yticks(size=30)
Beispiel #11
0
    def OnCalcShift(self, event):
        if (len(self.PSFLocs) > 0):
            import pylab
            
            x,y,z = self.PSFLocs[0]
            
            z_ = numpy.arange(self.image.data.shape[2])*self.image.mdh['voxelsize.z']*1.e3
            z_ -= z_.mean()
            
            pylab.figure()
            p_0 = 1.0*self.image.data[x,y,:,0].squeeze()
            p_0  -= p_0.min()
            p_0 /= p_0.max()

            #print (p_0*z_).sum()/p_0.sum()
            
            p0b = numpy.maximum(p_0 - 0.5, 0)
            z0 = (p0b*z_).sum()/p0b.sum()
            
            p_1 = 1.0*self.image.data[x,y,:,1].squeeze()
            p_1 -= p_1.min()
            p_1 /= p_1.max()
            
            p1b = numpy.maximum(p_1 - 0.5, 0)
            z1 = (p1b*z_).sum()/p1b.sum()
            
            dz = z1 - z0

            print(('z0: %f, z1: %f, dz: %f' % (z0,z1,dz)))
            
            pylab.plot(z_, p_0)
            pylab.plot(z_, p_1)
            pylab.vlines(z0, 0, 1)
            pylab.vlines(z1, 0, 1)
            pylab.figtext(.7,.7, 'dz = %3.2f' % dz)
def plot_matrices(cov, prec, title, subject_n=0):
    """Plot covariance and precision matrices, for a given processing. """

    # Put zeros on the diagonal, for graph clarity.
    size = prec.shape[0]
    prec[range(size), range(size)] = 0

    span = max(abs(prec.min()), abs(prec.max()))
    title = "{0:d} {1}".format(subject_n, title)

    # Display covariance matrix
    pl.figure()
    pl.imshow(cov,
              interpolation="nearest",
              vmin=-1,
              vmax=1,
              cmap=pl.cm.get_cmap("bwr"))
    pl.hlines([(pl.ylim()[0] + pl.ylim()[1]) / 2], pl.xlim()[0], pl.xlim()[1])
    pl.vlines([(pl.xlim()[0] + pl.xlim()[1]) / 2], pl.ylim()[0], pl.ylim()[1])
    pl.colorbar()
    pl.title(title + " / covariance")

    # Display precision matrix
    pl.figure()
    pl.imshow(prec,
              interpolation="nearest",
              vmin=-span,
              vmax=span,
              cmap=pl.cm.get_cmap("bwr"))
    pl.hlines([(pl.ylim()[0] + pl.ylim()[1]) / 2], pl.xlim()[0], pl.xlim()[1])
    pl.vlines([(pl.xlim()[0] + pl.xlim()[1]) / 2], pl.ylim()[0], pl.ylim()[1])
    pl.colorbar()
    pl.title(title + " / precision")
Beispiel #13
0
    def view_results(self, states_object, burnin=1):
        # plotting params
        nbins = 20
        alpha = 0.5
        label_size = 8
        linewidth = 3
        linecolor = "r"

        # extract from states
        thetas = states_object.get_thetas()[burnin:, :]
        stats = states_object.get_statistics()[burnin:, :]
        nsims = states_object.get_sim_calls()[burnin:]

        f = pp.figure()
        for i in range(6):
            sp = f.add_subplot(2, 10, i + 1)
            pp.hist(thetas[:, i], 10, normed=True, alpha=0.5)
            pp.title(self.theta_names[i])
            set_label_fonsize(sp, 6)
            set_tick_fonsize(sp, 6)
            set_title_fonsize(sp, 8)
        for i in range(10):
            sp = f.add_subplot(2, 10, 10 + i + 1)
            pp.hist(stats[:, i], 10, normed=True, alpha=0.5)
            ax = pp.axis()
            pp.vlines(self.obs_statistics[i],
                      0,
                      ax[3],
                      color="r",
                      linewidths=2)
            # if self.obs_statistics[i] < ax[0]:
            #   ax[0] = self.obs_statistics[i]
            # elif self.obs_statistics[i] > ax[1]:
            #   ax[1] = self.obs_statistics[i]
            pp.axis([
                min(ax[0], self.obs_statistics[i]),
                max(ax[1], self.obs_statistics[i]), ax[2], ax[3]
            ])
            pp.title(self.stats_names[i])
            set_label_fonsize(sp, 6)
            set_tick_fonsize(sp, 6)
            set_title_fonsize(sp, 8)
        pp.suptitle("top: posterior, bottom: post pred with true")

        f = pp.figure()
        I = np.random.permutation(len(thetas))
        for i in range(16):
            sp = pp.subplot(4, 4, i + 1)
            theta = thetas[I[i], :]
            test_obs = self.simulation_function(theta)
            test_stats = self.statistics_function(test_obs)
            err = np.sum(np.abs(self.obs_statistics - test_stats))
            pp.title("%0.2f" % (err))
            pp.plot(self.observations / 1000.0)
            pp.plot(test_obs / 1000.0)
            pp.axis("off")
            set_label_fonsize(sp, 6)
            set_tick_fonsize(sp, 6)
            set_title_fonsize(sp, 8)
        pp.suptitle("time-series from random draws of posterior")
def PlotTemp2(md_list, th=2):
    """ Second function (and main) to analyze the results of the activation threshold"""
    hold = {}  #empty dictionary
    for md in md_list:
        hold[md.experiment] = [[0], [0]] + color[md.experiment]
    for md in md_list:
        p = md.CalcProb(th=th)
        hold[md.experiment][0] += [md.data_other['Time']]
        hold[md.experiment][1] += [p]

    ### This 'plot' is only to get the label right for room temp.
    plot(0, 0, '-', marker='.', markersize=1, color='blue', linewidth=2)
    for experiment in hold:
        plot( hold[experiment][0], hold[experiment][1], '-',\
             marker=hold[experiment][3], markersize=5,\
                color=hold[experiment][2], linewidth=2, label=hold[experiment][4])

    ylabel(r"$P( E <= %d | Y)$" % (th))
    xlabel(r"$min$")
    hlines(0, -1, 91)
    vlines(0, -0.1, 1.1)

    xlim((-1, 91))
    ylim((-0.1, 1.1))
    axis([-1, 20, -0.1, 1.1])
    legend()
    return hold
Beispiel #15
0
def decoderDiagnostics(waveform=None):
    if waveform is None:
        waveform = badPacketWaveforms[-1]
    Fs_eff = Fs / upsample_factor
    ac = wifi.autocorrelate(waveform)
    ac_t = np.arange(ac.size) * 16 / Fs_eff
    synch = wifi.synchronize(waveform) / float(Fs_eff)
    pl.figure(2)
    pl.clf()
    pl.subplot(211)
    pl.specgram(waveform,
                NFFT=64,
                noverlap=64 - 1,
                Fc=Fc,
                Fs=Fs_eff,
                interpolation='nearest',
                window=lambda x: x)
    pl.xlim(0, waveform.size / Fs_eff)
    yl = pl.ylim()
    pl.vlines(synch, *yl)
    pl.ylim(*yl)
    pl.subplot(212)
    pl.plot(ac_t, ac)
    yl = pl.ylim()
    pl.vlines(synch, *yl)
    pl.ylim(*yl)
    pl.xlim(0, waveform.size / Fs_eff)
 def _plot_optimization (self, x_pars, y_pars):
            
     def _gaussian(x, A0, A, x0, sigma):
         return np.abs(A0) + np.abs(A)*np.exp(-(x-x0)**2 / (2*sigma**2))
     
     print ('Optimization result: x0 = ', self._xm, ' y0 = ', self._ym)
  
     Vx = np.linspace (self.xPositions[0], self.xPositions[-1], 1000)
     x_fit = _gaussian (x=Vx, A0=x_pars[0], A=x_pars[1], x0=x_pars[2], sigma=x_pars[3] )
     Vy = np.linspace (self.yPositions[0], self.yPositions[-1], 1000)
     y_fit = _gaussian (x=Vy, A0=y_pars[0], A=y_pars[1], x0=y_pars[2], sigma=y_pars[3] )
         
     pl.figure (figsize = (8,5))
     pl.subplot(121)
     pl.plot (self.xPositions, self._xCounts, color='RoyalBlue', marker='o')
     pl.plot (Vx, x_fit, color='crimson')
     pl.vlines (self._xm, 0.9*min (self._xCounts), 1.1*max(self._xCounts), color='crimson', linewidth=2, linestyles='--')
     pl.xlabel ('voltage (V)', fontsize= 15)       
     pl.ylabel ('counts', fontsize=15)
     pl.subplot(122)
     pl.plot (self.yPositions, self._yCounts, color='RoyalBlue', marker='o')
     pl.plot (Vy, y_fit, color='crimson')
     pl.vlines (self._ym, 0.9*min (self._xCounts), 1.1*max(self._xCounts), color='crimson', linewidth=2, linestyles='--')
     pl.xlabel ('voltage (V)', fontsize= 15)       
     pl.show()
Beispiel #17
0
def noisyAbsorption(recipe, curvNo, noIndicators):
    worker = recipe.getWorker("Slicing")
    noisyAbsorption = worker.plugExtract.getResult()
    worker = recipe.getWorker("ThicknessModeller")[0]
    simulation = worker.plugCalcAbsorption.getResult()
    worker = recipe.getWorker("MRA Exp")
    minimaPos = worker.plugMra.getResult()[r'\lambda_{min}'].inUnitsOf(simulation.dimensions[1])
    maximaPos = worker.plugMra.getResult()[r'\lambda_{max}'].inUnitsOf(simulation.dimensions[1])
    worker = recipe.getWorker("AddColumn")
    table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column"))
    xPos = table[u"x-position"]
    yPos = table[u"y-position"]
    thickness = table[u"thickness"]
    index = curvNo2Index(table[u"pixel"], curvNo)
    result = "$%s_{%s}$(%s %s,%s %s)=%s %s" % (thickness[index].shortname,curvNo,
                                               xPos.data[index],xPos.unit.unit.name(),
                                               yPos.data[index],yPos.unit.unit.name(),
                                               thickness.data[index],
                                               thickness.unit.unit.name())
    pylab.plot(noisyAbsorption.dimensions[1].inUnitsOf(simulation.dimensions[1]).data,
               noisyAbsorption.data[index,:],label="$%s$"%noisyAbsorption.shortname)
    if not noIndicators:
        pylab.vlines(minimaPos.data[:,index],0.1,1.0,
                     label ="$%s$"%minimaPos.shortname)
        pylab.vlines(maximaPos.data[:,index],0.1,1.0,
                     label ="$%s$"%maximaPos.shortname)
    pylab.title(result)
    pylab.xlabel(simulation.dimensions[1].label)
    pylab.ylabel(simulation.label)
def plotVowelProportionHistogram(wordList, numBins=15):
    """
    Plots a histogram of the proportion of vowels in each word in wordList
    using the specified number of bins in numBins
    """
    vowels = 'aeiou'
    vowelProportions = []

    for word in wordList:
        vowelsCount = 0.0

        for letter in word:
            if letter in vowels:
                vowelsCount += 1

        vowelProportions.append(vowelsCount / len(word))

    meanProportions = sum(vowelProportions) / len(vowelProportions)
    print "Mean proportions: ", meanProportions

    pylab.figure(1)
    pylab.hist(vowelProportions, bins=15)
    pylab.title("Histogram of Proportions of Vowels in Each Word")
    pylab.ylabel("Count of Words in Each Bucket")
    pylab.xlabel("Proportions of Vowels in Each Word")

    ymin, ymax = pylab.ylim()
    ymid = (ymax - ymin) / 2
    pylab.text(0.03, ymid, "Mean = {0}".format(
        str(round(meanProportions, 4))))
    pylab.vlines(0.5, 0, ymax)
    pylab.text(0.51, ymax - 0.01 * ymax, "0.5", verticalalignment = 'top')

    pylab.show()
Beispiel #19
0
def decorate(mean):
    pl.legend(loc='upper center', bbox_to_anchor=(.5, -.3))
    xmin, xmax, ymin, ymax = pl.axis()
    pl.vlines([mean], -ymax, ymax * 10, linestyle='dashed', zorder=20)
    pl.xticks([0, .5, 1])
    pl.yticks([])
    pl.axis([-.01, 1.01, -ymax * .05, ymax * 1.01])
Beispiel #20
0
    def plotcdf(self, x=None, xmin=None, alpha=None, **kwargs):
        """
        Plots CDF and powerlaw
        """
        if not (x): x = self.data
        if not (xmin): xmin = self._xmin
        if not (alpha): alpha = self._alpha

        x = numpy.sort(x)
        n = len(x)
        xcdf = numpy.arange(n, 0, -1, dtype='float') / float(n)

        q = x[x >= xmin]
        fcdf = (q / xmin)**(1 - alpha)
        nc = xcdf[argmax(x >= xmin)]
        fcdf_norm = nc * fcdf

        D_location = argmax(xcdf[x >= xmin] - fcdf_norm)
        pylab.vlines(q[D_location],
                     xcdf[x >= xmin][D_location],
                     fcdf_norm[D_location],
                     color='m',
                     linewidth=2)

        #plotx = pylab.linspace(q.min(),q.max(),1000)
        #ploty = (plotx/xmin)**(1-alpha) * nc

        pylab.loglog(x, xcdf, marker='+', color='k', **kwargs)
        #pylab.loglog(plotx,ploty,'r',**kwargs)
        pylab.loglog(q, fcdf_norm, 'r', **kwargs)
Beispiel #21
0
def plot_hist_rmsRho_Levs012(rho_L0, rho_L1, rho_L2, tSim, fname):
    ''''''
    import pylab as py
    #make 6 hists
    rms = rho_L0
    lab = r"$\rho$, Lev 0"
    rms1d = np.reshape(rms, np.product(rms.shape))
    logrms= np.log10(rms1d)
    cnt,bins,patches = py.hist(logrms, bins=100, color="blue", alpha=0.5, label=lab)
    rms = rho_L1
    lab = r"$\rho$, Lev 1"
    rms1d = np.reshape(rms, np.product(rms.shape))
    logrms= np.log10(rms1d)
    cnt,bins,patches = py.hist(logrms, bins=100, color="red", alpha=0.5, label=lab)
    rms = rho_L2
    lab = r"$\rho$, Lev 2"
    rms1d = np.reshape(rms, np.product(rms.shape))
    logrms= np.log10(rms1d)
    #plot quantities
    Tratio = tSim / ic.tCr
    #plot
    cnt,bins,patches = py.hist(logrms, bins=100, color="green", alpha=0.5,label=lab)
    py.vlines(np.log10( ic.rho0 ), 0, cnt.max(), colors="black", linestyles='dashed',label=r"$\rho_{0}$ = %2.2g [g/cm^3]" % ic.rho0)
    #py.xlim([-13.,-9.])
    py.xlabel("Log10 Density [g/cm^3]")
    py.ylabel("count")
    py.title(r"$T/T_{\rmCross}$ = %g" % Tratio)
    py.legend(loc=0, fontsize="small")
    py.savefig(fname,format="pdf")
    py.close()
Beispiel #22
0
    def update_loop(self):
        import pylab
        import numpy
        pylab.ion()
        self.fig = pylab.figure()
        vmin, vmax = -1, 1
        self.img = pylab.imshow(self.retina.image,
                                vmin=vmin,
                                vmax=vmax,
                                cmap='gray',
                                interpolation='none')
        self.line_y = pylab.vlines(self.retina.p_y, 0, 128)
        self.line_x = pylab.vlines(self.retina.p_x, 0, 128)
        while True:
            #self.fig.clear()
            #pylab.imshow(self.retina.image, vmin=vmin, vmax=vmax,
            #                   cmap='gray', interpolation='none')
            self.img.set_data(self.retina.image)
            #self.scatter[0].set_data([self.retina.p_x], [self.retina.p_y])
            #if len(self.retina.deltas) > 0:
            #    pylab.hist(self.retina.deltas, 20, range=(0.0, 0.1))
            #pylab.ylim(0, 100)
            #pylab.vlines(self.retina.p_y, 0, 128)
            #pylab.hlines(self.retina.p_x, 0, 128)

            y = self.retina.p_y
            self.line_y.set_segments(numpy.array([[(y, 0), (y, 128)]]))
            x = self.retina.p_x
            self.line_x.set_segments(numpy.array([[(0, x), (128, x)]]))

            self.retina.clear_image()
            pylab.draw()
            time.sleep(0.04)
def plot_conjunction_stats(target_n_planets = 2, acc_vec = [0], t_vec = [0, 1],\
			 acc_time_per = 1.0, pattern = '*', color = 'b', stack = False, bottom = [], verbose = False):
	"""
	"""
	if verbose:
		print 'Dimension of t_vec :', size(t_vec)
		print 'Dimension of acc_vec :', size(acc_vec)

	x_ind = []
	for i in range(0, size(acc_vec)):
		x_ind_tmp = 0.5*(t_vec[i+1]+t_vec[i])-t_vec[0]
		x_ind.append(x_ind_tmp)

	if pattern == 'bar':
		if stack:
			plot_obj = pylab.bar(t_vec[0:-1]-t_vec[0], acc_vec, width = acc_time_per*0.3,\
					 bottom = bottom, color = color, align = 'center')
		else:
			plot_obj = pylab.bar(t_vec[0:-1]-t_vec[0], acc_vec, width = acc_time_per*0.3, \
					 color = color, align = 'center')
	else:
		if stack:
			plot_obj = pylab.plot(x_ind, acc_vec+bottom, pattern, color = color)
			for i in range(0, size(acc_vec)):
				pylab.vlines(x = x_ind[i], ymin = bottom[i], ymax = acc_vec[i]+bottom[i], \
						lw = 2, color = color)
		else:
			plot_obj = pylab.plot(x_ind, acc_vec, pattern, color = color)
			for i in range(0, size(acc_vec)):
				pylab.vlines(x = x_ind[i], ymin = 0, ymax = acc_vec[i], lw = 2, color = color)

	plot_legend = 'Number of conjunctions of '+str(target_n_planets)+' planets per '+str(acc_time_per)+' days'

	return plot_obj, plot_legend
Beispiel #24
0
def plot_T1_Hct(par_dict, Hct_sol, sO2=0.5, T1=1.5):

    R1ery0 = par_dict['R1ery0']
    R1plas = par_dict['R1plas']
    r1dHb = par_dict['r1_prime_dHb']

    Hct_axis = np.arange(0, 1.001, 0.001)
    xtemp = np.zeros([2, len(Hct_axis)])
    xtemp[0, :] = Hct_axis
    xtemp[1, :] = sO2

    T1s = 1000 / calc_R1(xtemp, R1plas, R1ery0, r1dHb)

    plt.xlabel('hematocrit (Hct)', fontsize=16)
    plt.ylabel('$T_1$ relaxation time (ms)', fontsize=16)

    plt.plot(Hct_axis, T1s, lw=2)

    plt.ylim([0.95 * np.min(T1s), 1.05 * np.max(T1s)])
    plt.xlim([0, 1])

    plt.hlines(1000 * T1, 0, 1, linestyle='dashed')
    plt.vlines(Hct_sol,
               0.95 * np.min(T1s),
               1.05 * np.max(T1s),
               linestyle='dashed')

    return
Beispiel #25
0
    def update_loop(self):
        import pylab
        import numpy
        pylab.ion()
        self.fig = pylab.figure()
        vmin, vmax = -1, 1
        self.img = pylab.imshow(self.retina.image, vmin=vmin, vmax=vmax,
                               cmap='gray', interpolation='none')
        self.line_y = pylab.vlines(self.retina.p_y, 0, 128)
        self.line_x = pylab.vlines(self.retina.p_x, 0, 128)
        while True:
            #self.fig.clear()
            #pylab.imshow(self.retina.image, vmin=vmin, vmax=vmax,
            #                   cmap='gray', interpolation='none')
            self.img.set_data(self.retina.image)
            #self.scatter[0].set_data([self.retina.p_x], [self.retina.p_y])
            #if len(self.retina.deltas) > 0:
            #    pylab.hist(self.retina.deltas, 20, range=(0.0, 0.1))
            #pylab.ylim(0, 100)
            #pylab.vlines(self.retina.p_y, 0, 128)
            #pylab.hlines(self.retina.p_x, 0, 128)

            y = self.retina.p_y
            self.line_y.set_segments(numpy.array([[(y,0), (y,128)]]))
            x = self.retina.p_x
            self.line_x.set_segments(numpy.array([[(0,x), (128,x)]]))

            self.retina.clear_image()
            pylab.draw()
            time.sleep(0.04)
Beispiel #26
0
 def view_simple( self, stats, thetas ):
   # plotting params
   nbins       = 20
   alpha       = 0.5
   label_size  = 8
   linewidth   = 3
   linecolor   = "r"
   
   # extract from states
   #thetas = states_object.get_thetas()[burnin:,:]
   #stats  = states_object.get_statistics()[burnin:,:]
   #nsims  = states_object.get_sim_calls()[burnin:]
   
   # plot sample distribution of thetas, add vertical line for true theta, theta_star
   f = pp.figure()
   sp = f.add_subplot(111)
   pp.plot( self.fine_theta_range, self.posterior, linecolor+"-", lw = 1)
   ax = pp.axis()
   pp.hist( thetas, self.nbins_coarse, range=self.range,normed = True, alpha = alpha )
   
   pp.fill_between( self.fine_theta_range, self.posterior, color="m", alpha=0.5)
   
   pp.plot( self.posterior_bars_range, self.posterior_bars, 'ro')
   pp.vlines( thetas.mean(), ax[2], ax[3], color="b", linewidths=linewidth)
   #pp.vlines( self.theta_star, ax[2], ax[3], color=linecolor, linewidths=linewidth )
   pp.vlines( self.posterior_mode, ax[2], ax[3], color=linecolor, linewidths=linewidth )
   
   pp.xlabel( "theta" )
   pp.ylabel( "P(theta)" )
   pp.axis([self.range[0],self.range[1],ax[2],ax[3]])
   set_label_fonsize( sp, label_size )
   pp.show()
Beispiel #27
0
def decorate(mean):
    pl.legend(loc='upper center', bbox_to_anchor=(.5,-.3))
    xmin, xmax, ymin, ymax = pl.axis()
    pl.vlines([mean], -ymax, ymax*10, linestyle='dashed', zorder=20)
    pl.xticks([0, .5, 1])
    pl.yticks([])
    pl.axis([-.01, 1.01, -ymax*.05, ymax*1.01])
Beispiel #28
0
def verifySpikes(data,group=1,dataFilePattern=None):
    """
    Overlay the spikes found with the highpass data files
    """
    #TODO: only shows the first file for now
    dataFiles = glob.glob(dataFilePattern)
    descriptorFile,_,_ = dataFiles[0].partition('.')
    descriptorFile = '%s.txt' % (descriptorFile.replace('highpass','descriptor'),)
    #get the descriptor
    descriptor = fr.readDescriptor(descriptorFile)
    #get the relevant channels for this group
    nchannels = sum(descriptor['gr_nr']>0)
    channels = np.where(descriptor['gr_nr']==group)[0]
    hdata = np.memmap(dataFiles[0],mode='r',offset=73,dtype=np.int16) 
    hdata = hdata.reshape(hdata.size/nchannels,nchannels)[:,channels]
    #calculate offset 
    offset = np.append([0],np.cumsum(hdata.max(0))[:-1])
    x = np.arange(hdata.shape[0])
                       
    plt.plot(x[:,None].repeat(len(channels),1),hdata+offset[None,:].repeat(hdata.shape[0],0))
    yl = plt.ylim()
    timepoints = data['unitTimePoints']
    for k in timepoints.keys():
        T = timepoints[k]
        plt.vlines(T[(T>=x[0])*(T<x[-1])],yl[0],yl[1])
Beispiel #29
0
def plot_channel(ax, c, clusters, cluster_p_values, plot_type, full=False):
    for i_c, (start, stop) in enumerate(clusters):
        if start / n_times == c:
            start -= c * n_times
            stop -= c * n_times
            if cluster_p_values[i_c] <= 0.05:
                h = ax.axvspan(times[start],
                               times[stop - 1],
                               color='r',
                               alpha=0.3)
            else:
                ax.axvspan(times[start],
                           times[stop - 1],
                           color=(0.3, 0.3, 0.3),
                           alpha=0.3)
    pl.axhline(y=0, linewidth=1, color="black")
    if plot_type == "data":
        hf = ax.plot(times, -1 * means0[c], "r", times, -1 * means1[c], "g")
        if not full:
            pl.text(-0.035, ydata_scale * .9, ydata_scale_txt)
            pl.legend(hf, (cond_names[0], cond_names[1]), loc="upper right")
    elif plot_type == "f":
        hf = ax.plot(times, T_obs[c], 'g')
    pl.vlines(x=xt, ymin=ymarks * -1, ymax=ymarks)
    pl.vlines(x=xt2, ymin=np.array([0]), ymax=ymarks2, linewidth=1)
    pl.hlines(ydata_scale, xmark * -1, xmark)
    pl.xlim([0, times[lent - 1]])
    return hf
Beispiel #30
0
def draw_fit(rl, pct):
    """Draw sigmoid for psychometric

    rl: x values
    pct: y values

    Fxn draws the curve
    """
    def sig(x, A, x0, k, y0):
        return A / (1 + np.exp(-k*(x-x0))) + y0
    def sig2(x, x0, k):
        return 1. / (1+np.exp(-k*(x-x0)))

    pl.xlabel('R-L stimuli')
    pl.ylabel('p(choose R)')
    pl.xlim([rl.min()-1, rl.max()+1])
    pl.ylim([-0.05, 1.05])

    popt,pcov = curve_fit(sig, rl, pct) # stretch and yshift are free params
    popt2,pcov2 = curve_fit(sig2, rl, pct) # stretch and yshift are fixed
    x = np.linspace(rl.min(), rl.max(), 200)
    y = sig(x, *popt)
    y2 = sig2(x, *popt2)
    pl.vlines(0,0,1,linestyles='--')
    pl.hlines(0.5,rl.min(),rl.max(),linestyles='--')
    pl.plot(x,y)
    #pl.plot(x,y2)
    return popt
Beispiel #31
0
def plot_x_and_psd_with_estimated_omega(x, sample_step=1, dt=1.0):
    y = x[::sample_step]
    F = freq(x, sample_step, dt)
    T = 1.0 / F

    pylab.clf()

    # plot PSD
    pylab.subplot(211)
    pylab.psd(y, Fs=1.0 / sample_step / dt)
    ylim = pylab.ylim()
    pylab.vlines(F, *ylim)
    pylab.ylim(ylim)

    # plot time series
    pylab.subplot(223)
    pylab.plot(x)

    # plot time series (three cycles)
    n = int(T / dt) * 3
    m = n // sample_step
    pylab.subplot(224)
    pylab.plot(x[:n])
    pylab.plot(numpy.arange(0, n, sample_step)[:m], y[:m], 'o')

    pylab.suptitle('F = %s' % F)
    def plot_importances(self, lower_bound=10, upper_bound=90):
        """
        Plots the relative importance of each parameter
        
        :param name: Lower bound of credible intervals (default: 10%)
        :type name: int
        :param name: Upper bound of credible intervals (default 90%)
        :type name: int
        """
        import pylab as plt

        median, lower, upper = self.parameter_importances(
            lower_bound, upper_bound)

        width = 1.0
        for i, key in enumerate(median.keys()):
            plt.bar(i, median[key], width=width)
            plt.vlines(i + width / 2.0, lower[key], upper[key])
        plt.xticks(width / 2.0 + np.arange(len(median.keys())), median.keys())
        plt.ylabel("Parameter importance")
        plt.ylim(0, 1.2)
        l, u = plt.xlim()
        l = l - width / 4.0
        u = u + width / 4.0
        plt.xlim(l, u)
def plot_matrices(cov, prec, title, subject_n=0):
    """Plot covariance and precision matrices, for a given processing. """

    # Put zeros on the diagonal, for graph clarity.
    size = prec.shape[0]
    prec[range(size), range(size)] = 0

    span = max(abs(prec.min()), abs(prec.max()))
    title = "{0:d} {1}".format(subject_n, title)

    # Display covariance matrix
    pl.figure()
    pl.imshow(cov, interpolation="nearest",
              vmin=-1, vmax=1, cmap=pl.cm.get_cmap("bwr"))
    pl.hlines([(pl.ylim()[0] + pl.ylim()[1]) / 2],
              pl.xlim()[0], pl.xlim()[1])
    pl.vlines([(pl.xlim()[0] + pl.xlim()[1]) / 2],
              pl.ylim()[0], pl.ylim()[1])
    pl.colorbar()
    pl.title(title + " / covariance")

    # Display precision matrix
    pl.figure()
    pl.imshow(prec, interpolation="nearest",
              vmin=-span, vmax=span,
              cmap=pl.cm.get_cmap("bwr"))
    pl.hlines([(pl.ylim()[0] + pl.ylim()[1]) / 2],
              pl.xlim()[0], pl.xlim()[1])
    pl.vlines([(pl.xlim()[0] + pl.xlim()[1]) / 2],
              pl.ylim()[0], pl.ylim()[1])
    pl.colorbar()
    pl.title(title + " / precision")
def plot_samples(S, axis_list=None):
    pl.scatter(S[:, 0], S[:, 1], s=2, marker='o', linewidths=0, zorder=10)
    if axis_list is not None:
        colors = [(0, 0.6, 0), (0.6, 0, 0)]
        for color, axis in zip(colors, axis_list):
            axis /= axis.std()
            x_axis, y_axis = axis
            # Trick to get legend to work
            pl.plot(0.1 * x_axis, 0.1 * y_axis, linewidth=2, color=color)
            # pl.quiver(x_axis, y_axis, x_axis, y_axis, zorder=11, width=0.01,
            pl.quiver(0,
                      0,
                      x_axis,
                      y_axis,
                      zorder=11,
                      width=0.01,
                      scale=6,
                      color=color)

    pl.hlines(0, -3, 3)
    pl.vlines(0, -3, 3)
    pl.xlim(-3, 3)
    pl.ylim(-3, 3)
    pl.xlabel('x')
    pl.ylabel('y')
Beispiel #35
0
    def draw_plot(plotxrange):
        xmin, xmax = plotxrange
        ixmin = np.argmin(np.abs(tx - xmin))
        ixmax = np.argmin(np.abs(tx - xmax))
        plt.figure(figsize=figsize)

        plt.plot(tx[ixmin:ixmax], sy[ixmin:ixmax], label="signal")
        if overlays is not None:
            if type(overlays) is np.ndarray:
                plt.plot(tx[ixmin:ixmax],
                         overlays[ixmin:ixmax],
                         label=overlay_labels)
            else:
                for i, overlay in enumerate(overlays):
                    lab = overlay_labels[
                        i] if overlay_labels is not None else None
                    plt.plot(tx[ixmin:ixmax], overlay[ixmin:ixmax], label=lab)
        for istart, iend in interpolated:
            plt.gca().axvspan(tx[istart], tx[iend], color="green", alpha=0.1)
        for istart, iend in blinks:
            plt.gca().axvspan(tx[istart], tx[iend], color="red", alpha=0.1)

        plt.vlines(event_onsets, *plt.ylim(), color="grey", alpha=0.5)
        plt.xlim(xmin, xmax)
        plt.xlabel(xlab)
        if overlay_labels is not None:
            plt.legend()
def y_randomization(rf_best, X_train, y_train, descritor, algoritimo):    
    permutations = 20
    score, permutation_scores, pvalue = permutation_test_score(rf_best, X_train, y_train,
                                                               cv=5, scoring='balanced_accuracy',
                                                               n_permutations=permutations,
                                                               n_jobs=-1,
                                                               verbose=1,
                                                               random_state=24)
    print('True score = ', score.round(2),
          '\n Média per. = ', np.mean(permutation_scores).round(2),
          '\np-value = ', pvalue.round(4))

    ###############################################################################
    # View histogram of permutation scores
    pl.subplots(figsize=(10,6))
    pl.hist(permutation_scores.round(2), label='Permutation scores')
    ylim = pl.ylim()
    pl.vlines(score, ylim[0], ylim[1], linestyle='--',
              color='g', linewidth=3, label='Classification Score'
              ' (pvalue %s)' % pvalue.round(4))
    pl.vlines(1.0 / 2, ylim[0], ylim[1], linestyle='--',
              color='k', linewidth=3, label='Luck')
    pl.ylim(ylim)
    pl.legend()
    pl.xlabel('Score')
    pl.title('Aleatoriarização da variável Y '+algoritimo+'X'+descritor, fontsize=12)
    pl.savefig('figures/y_randomization-'+descritor+'X'+algoritimo+'.png', bbox_inches='tight', transparent=False, format='png', dpi=300)
    pl.show()
Beispiel #37
0
    def plotcdf(self, x=None, xmin=None, alpha=None, pointcolor='k',
            pointmarker='+', **kwargs):
        """
        Plots CDF and powerlaw
        """
        if x is None: x=self.data
        if xmin is None: xmin=self._xmin
        if alpha is None: alpha=self._alpha

        x=numpy.sort(x)
        n=len(x)
        xcdf = numpy.arange(n,0,-1,dtype='float')/float(n)

        q = x[x>=xmin]
        fcdf = (q/xmin)**(1-alpha)
        nc = xcdf[argmax(x>=xmin)]
        fcdf_norm = nc*fcdf

        D_location = argmax(xcdf[x>=xmin]-fcdf_norm)
        pylab.vlines(q[D_location],xcdf[x>=xmin][D_location],fcdf_norm[D_location],color='m',linewidth=2)

        #plotx = pylab.linspace(q.min(),q.max(),1000)
        #ploty = (plotx/xmin)**(1-alpha) * nc

        pylab.loglog(x,xcdf,marker=pointmarker,color=pointcolor,**kwargs)
        #pylab.loglog(plotx,ploty,'r',**kwargs)
        pylab.loglog(q,fcdf_norm,'r',**kwargs)
def ExamplePlotFrozenDist():
    """Example of PlotFrozenDist."""

    from pylab import figure, subplot
    from scipy.stats import norm, gamma, poisson, skellam

    print("Example: Norm, Norm, Gamma, Gamma, Poisson, Poisson, Skellam, Skellam.")

    figure()
    subplot(421)
    PlotFrozenDist( norm() )
    subplot(422)
    PlotFrozenDist( norm( loc=10, scale=0.5) )
    subplot(423)
    PlotFrozenDist( gamma(3) )
    subplot(424)
    ga = gamma( 3, loc=5)
    PlotFrozenDist( ga, q=1e-6, color='g')
    mn = float(ga.stats()[0]) ### add a red vline at the mean
    vlines( mn, 0, ga.pdf(mn),  colors='r', linestyles='-')
    subplot(425)
    PlotFrozenDist(poisson(5.3))
    subplot(426)
    PlotFrozenDist( poisson(10), color='r', ms=3) ## Pass other plotting arguments 
    subplot(427)
    PlotFrozenDist( skellam( 5.3, 10), marker='*')
    subplot(428)
    PlotFrozenDist( skellam( 100, 10), marker='+', no_vlines=True)
def plot_histogram():
    import numpy as np
    import pylab as P

    # The hist() function now has a lot more options
    #

    #
    # first create a single histogram
    #
    P.figure()
    mu, sigma = 40, 35


    x = abs(np.random.normal(mu, sigma, 1000000))

    # the histogram of the data with histtype='step'
    n, bins, patches = P.hist(x, 100, normed=1, histtype='stepfilled')
    P.setp(patches, 'facecolor', 'g', 'alpha', 0.50)
    P.vlines(np.mean(x), 0, max(n))
    P.vlines(np.median(x), 0, max(n))
    # add a line showing the expected distribution
    y = np.abs(P.normpdf( bins, mu, sigma))
    l = P.plot(bins, y, 'k--', linewidth=1.5)

    P.show()
Beispiel #40
0
def fit_peaks(data, args, params_dict):
    """
    Returns
    """
    logging.info('Performing Gaussian fit...')

    half_window = int(params_dict['window'] / 2) + 1
    hist = np.histogram(data[params_dict['mass_shifts_column']],
                        bins=params_dict['bins'])
    hist_y = smooth(hist[0], window_size=params_dict['window'], power=5)
    hist_x = 1 / 2 * (hist[1][:-1] + hist[1][1:])
    loc_max_candidates_ind = argrelextrema(hist_y, np.greater_equal)[0]
    # smoothing and finding local maxima
    min_height = 2 * np.median(
        [x for x in hist[0] if (x > 1)]
    )  # minimum bin height expected to be peak approximate noise level as median of all non-negative
    loc_max_candidates_ind = loc_max_candidates_ind[
        hist_y[loc_max_candidates_ind] >= min_height]

    poptpvar = []
    shape = int(np.sqrt(len(loc_max_candidates_ind))) + 1
    plt.figure(figsize=(shape * 3, shape * 4))
    plt.tight_layout()
    for index, center in enumerate(loc_max_candidates_ind, 1):

        x = hist_x[center - half_window:center + half_window + 1]
        y = hist[0][center - half_window:center + half_window +
                    1]  #take non-smoothed data
        #        y_= hist_y[center - half_window: center + half_window + 1]
        popt, perr = gauss_fitting(hist[0][center], x, y)
        plt.subplot(shape, shape, index)
        if popt is None:
            label = 'NO FIT'
        else:

            if x[0] <= popt[1] and popt[1] <= x[-1] and(perr[0]/popt[0] < params_dict['max_deviation_height']) \
            and (perr[2]/popt[2] < params_dict['max_deviation_sigma']):
                label = 'PASSED'
                poptpvar.append(np.concatenate([popt, perr]))
                plt.vlines(popt[1] - 3 * popt[2],
                           0,
                           hist[0][center],
                           label='3sigma interval')
                plt.vlines(popt[1] + 3 * popt[2], 0, hist[0][center])
            else:
                label = 'FAILED'
        plt.plot(x, y, 'b+:', label=label)
        if label != 'NO FIT':
            plt.scatter(x,
                        gauss(x, *popt),
                        label='Gaussian fit\n $\sigma$ = ' +
                        "{0:.4f}".format(popt[2]))

        plt.legend()
        plt.title("{0:.3f}".format(hist[1][center]))
        plt.grid(True)
    plt.savefig(os.path.join(args.dir, 'gauss_fit.pdf'))
    plt.close()
    return hist, np.array(poptpvar)
Beispiel #41
0
    def plotcdf(self,
                x=None,
                xmin=None,
                alpha=None,
                pointcolor='k',
                dolog=True,
                zoom=True,
                pointmarker='+',
                **kwargs):
        """
        Plots CDF and powerlaw
        """
        if x is None: x = self.data
        if xmin is None: xmin = self._xmin
        if alpha is None: alpha = self._alpha

        x = np.sort(x)
        n = len(x)
        xcdf = np.arange(n, 0, -1, dtype='float') / float(n)

        q = x[x >= xmin]
        fcdf = (q / xmin)**(1 - alpha)
        nc = xcdf[argmax(x >= xmin)]
        fcdf_norm = nc * fcdf

        D_location = argmax(xcdf[x >= xmin] - fcdf_norm)
        pylab.vlines(q[D_location],
                     xcdf[x >= xmin][D_location],
                     fcdf_norm[D_location],
                     color='m',
                     linewidth=2,
                     zorder=2)
        pylab.plot([q[D_location]] * 2,
                   [xcdf[x >= xmin][D_location], fcdf_norm[D_location]],
                   color='m',
                   marker='s',
                   zorder=3)

        #plotx = pylab.linspace(q.min(),q.max(),1000)
        #ploty = (plotx/xmin)**(1-alpha) * nc

        if dolog:
            pylab.loglog(x,
                         xcdf,
                         marker=pointmarker,
                         color=pointcolor,
                         **kwargs)
            pylab.loglog(q, fcdf_norm, 'r', **kwargs)
        else:
            pylab.semilogx(x,
                           xcdf,
                           marker=pointmarker,
                           color=pointcolor,
                           **kwargs)
            pylab.semilogx(q, fcdf_norm, 'r', **kwargs)

        if zoom:
            pylab.axis([xmin, x.max(), xcdf.min(), nc])
Beispiel #42
0
def plot_profile(in_file, out_file):
    print(
        "Reading %s to plot geometry profile for model %s, experiment %s, grid mode %s, step %s"
        % (in_file, model, experiment, mode, step))

    if out_file is None:
        out_file = os.path.splitext(in_file)[0] + "-profile.pdf"

    mask = read(in_file, 'mask')
    usurf = read(in_file, 'usurf')
    topg = read(in_file, 'topg')
    thk = read(in_file, 'thk')
    x = read(in_file, 'x')

    # theoretical grounding line position
    xg = MISMIP.x_g(experiment, step)
    # modeled grounding line position
    xg_PISM = find_grounding_line(x, topg, thk, mask)

    # mask out ice-free areas
    usurf = np.ma.array(usurf, mask=mask == 4)

    # compute the lower surface elevation
    lsrf = topg.copy()
    lsrf[mask == 3] = -MISMIP.rho_i() / MISMIP.rho_w() * thk[mask == 3]
    lsrf = np.ma.array(lsrf, mask=mask == 4)

    # convert x to kilometers
    x /= 1e3

    figure(1)
    ax = subplot(111)
    hold(True)
    plot(x, np.zeros_like(x), ls='dotted', color='red')
    plot(x, topg, color='black')
    plot(x, usurf, 'o', color='blue', markersize=4)
    plot(x, lsrf, 'o', color='blue', markersize=4)
    xlabel('distance from the divide, km')
    ylabel('elevation, m')
    title("MISMIP experiment %s, step %d" % (experiment, step))
    text(0.6,
         0.9,
         "$x_g$ (model) = %4.0f km" % (xg_PISM / 1e3),
         color='r',
         transform=ax.transAxes)
    text(0.6,
         0.85,
         "$x_g$ (theory) = %4.0f km" % (xg / 1e3),
         color='black',
         transform=ax.transAxes)

    _, _, ymin, ymax = axis(xmin=0, xmax=x.max())
    vlines(xg / 1e3, ymin, ymax, linestyles='dashed', color='black')
    vlines(xg_PISM / 1e3, ymin, ymax, linestyles='dashed', color='red')

    print("Saving '%s'...\n" % out_file)
    savefig(out_file)
Beispiel #43
0
def oneRoundDelay(step = 10000):
    injectRate = 0.9
    factory = GridNetworkFactory(makeSimpleNode(),Queues)
    factory.constructNetwork(6,6)\
        .setFlow(Flow((0,0),(0,5),injectRate))\
        .setFlow(Flow((5,0),(5,5),injectRate))\
        .setFlow(Flow((2,0),(3,5),injectRate))

    network = factory.getNetwork()

    packetFactory = PacketFactory()
    simulator = \
        Simulator(network,step,ConstLinkRateGenerator(1),packetFactory)
    simulator.run()
    #simulator.printNetwork()
    stat = simulator.getStaticsInfo()
    print stat['aveDelay']
    packetPool = sorted(stat['packetPool'],key=lambda p: p.getID)


    
    py.subplot(211)
    py.vlines([p.getCreateTime() for p in packetPool],[1],[p.getDelay() for p in packetPool],'r')
    py.xlabel('Packet create time(bp with $\lambda$ = 0.9)')
    py.ylabel('delay')
    py.grid(True)




    injectRate = 0.9
    factory = GridNetworkFactory(makeMNode(2),Queues)
    factory.constructNetwork(6,6)\
        .setFlow(Flow((0,0),(0,5),injectRate))\
        .setFlow(Flow((5,0),(5,5),injectRate))\
        .setFlow(Flow((2,0),(3,5),injectRate))

    network = factory.getNetwork()

    packetFactory = PacketFactory()
    simulator = \
        Simulator(network,step,ConstLinkRateGenerator(1),packetFactory)
    simulator.run()
    #simulator.printNetwork()

    stat = simulator.getStaticsInfo()
    print stat['aveDelay']
    packetPool = sorted(stat['packetPool'],key=lambda p: p.getID)

    py.subplot(212)
    py.vlines([p.getCreateTime() for p in packetPool],[1],[p.getDelay() for p in packetPool],'b')
    py.xlabel('Packet create time (m=2 with $\lambda$ = 0.9)')
    py.ylabel('delay')
    py.grid(True)
    py.savefig('packetDelayInOneRound_09')
    py.show()
Beispiel #44
0
def periodogram_scipy(data, frequencies, plot=False):
    freqs, pgram = lombscargle_scipy(data, frequencies)
    periods = map(lambda x: (2 * math.pi) / x, freqs)

    if plot:
        pylab.vlines(periods, 0, np.array(pgram), color='k', linestyles='solid')
        pylab.xlabel("period, days")
        pylab.ylabel("power")
        pylab.title("CenX-3 18-60 KeV Periodogram")
        pylab.show()
Beispiel #45
0
def myPlot(X,fun,X0,funp,c1,c2):
    p.figure(figsize=(10,6))
    F=do(f,X)
    p.plot(X0,funp,c1+'o-',lw=2,)
    p.vlines(X0,0,funp,linestyle='dotted')
    p.hlines(0,0,1)
    p.xticks(X0,['$x_{%s}$'%i for i in range(len(X0))],fontsize='large')
    p.yticks([])
    p.ylabel('$f(x)$',fontsize='large')
    p.axis([X0[0],X0[-1],0,F.max()+0.1])
Beispiel #46
0
    def plotpdf(self,x=None,xmin=None,alpha=None,nbins=50,dolog=True,dnds=False,
            drawstyle='steps-post', histcolor='k', plcolor='r', **kwargs):
        """
        Plots PDF and powerlaw.

        kwargs is passed to pylab.hist and pylab.plot
        """
        if not(x): x=self.data
        if not(xmin): xmin=self._xmin
        if not(alpha): alpha=self._alpha

        x=numpy.sort(x)
        n=len(x)

        pylab.gca().set_xscale('log')
        pylab.gca().set_yscale('log')

        if dnds:
            hb = pylab.histogram(x,bins=numpy.logspace(log10(min(x)),log10(max(x)),nbins))
            h = hb[0]
            b = hb[1]
            db = hb[1][1:]-hb[1][:-1]
            h = h/db
            pylab.plot(b[:-1],h,drawstyle=drawstyle,color=histcolor,**kwargs)
            #alpha -= 1
        elif dolog:
            hb = pylab.hist(x,bins=numpy.logspace(log10(min(x)),log10(max(x)),nbins),log=True,fill=False,edgecolor=histcolor,**kwargs)
            alpha -= 1
            h,b=hb[0],hb[1]
        else:
            hb = pylab.hist(x,bins=numpy.linspace((min(x)),(max(x)),nbins),fill=False,edgecolor=histcolor,**kwargs)
            h,b=hb[0],hb[1]
        # plotting points are at the center of each bin
        b = (b[1:]+b[:-1])/2.0

        q = x[x>=xmin]
        px = (alpha-1)/xmin * (q/xmin)**(-alpha)

        # Normalize by the median ratio between the histogram and the power-law
        # The normalization is semi-arbitrary; an average is probably just as valid
        plotloc = (b>xmin)*(h>0)
        norm = numpy.median( h[plotloc] / ((alpha-1)/xmin * (b[plotloc]/xmin)**(-alpha))  )
        px = px*norm

        plotx = pylab.linspace(q.min(),q.max(),1000)
        ploty = (alpha-1)/xmin * (plotx/xmin)**(-alpha) * norm

        #pylab.loglog(q,px,'r',**kwargs)
        pylab.loglog(plotx,ploty,color=plcolor,**kwargs)

        axlims = pylab.axis()
        pylab.vlines(xmin,axlims[2],max(px),colors=plcolor,linestyle='dashed')

        pylab.gca().set_xlim(min(x),max(x))
Beispiel #47
0
def GMRrichness(ra=None,dec=None,photoz=None,cat=None,plot=True,err=True,rw=True,bcg=True,radius=1.):
    fra=cat.field('ra')
    fdec=cat.field('dec')
    imag=cat.field('model_counts')[:,3]
    gmr=cat.field('gmr')
    gmrerr=cat.field('gmr_err')
    depth=12
    h=es.htm.HTM(depth)
    srad=np.rad2deg(radius/Da(0,photoz))
    m1,m2,d12 = h.match(ra,dec,fra,fdec,srad,maxmatch=5000)
    cimag=imag[m2[0]]
    cgmr=gmr[m2[0]]
    r12=np.deg2rad(d12)*Da(0,photoz)
    if bcg is True:
        indices=(imag[m2]<=limi(photoz))*(imag[m2]>cimag)
    else:
        indices=(imag[m2]<=limi(photoz))
    ntot=len(m2[indices])
    if ntot <= 10:
        return 0, 0, 0
    alpha=np.array([0.5,0.5])
    mu=np.array([sts.scoreatpercentile(gmr[m2[indices]],per=70),sts.scoreatpercentile(gmr[m2[indices]],per=40)])
    sigma=np.array([0.04,0.3])
    if err is True:
        if rw is False:
            aic2=gmm.aic_ecgmm(gmr[m2[indices]],gmrerr[m2[indices]],alpha,mu,sigma)
            aic1=gmm.wstat(gmr[m2[indices]],gmrerr[m2[indices]])[3] 
        else:
            aic2,alpha,mu,sigma=rwgmm.aic2EM(gmr[m2[indices]],gmrerr[m2[indices]],r12[indices],alpha,mu,sigma)
            aic1=rwgmm.aic1EM(gmr[m2[indices]],gmrerr[m2[indices]],r12[indices])[0]
    else:
        aic2=gmm.aic_ecgmm(gmr[m2[indices]],aalpha=alpha,mmu=mu,ssigma=sigma)
        aic1=gmm.wstat(gmr[m2[indices]])[3] 
    if plot==True:
        pl.hist(gmr[m2[indices]],bins=30,normed=True,facecolor='green',alpha=0.3)
        pl.vlines(cgmr,0,3,color='green')
        x=np.arange(-1,5,0.01)
        srt=np.argsort(sigma)
        alpha=alpha[srt]
        mu=mu[srt]
        sigma=sigma[srt]
        z = gmrz(mu[0])
        t=gmm.ecgmmplot(x,alpha,mu,sigma)
        pl.xlabel('g - r')
        pl.figtext(0.61,0.85,r'$\alpha$: '+str(np.round(alpha,4)))
        pl.figtext(0.61,0.8,r'$\mu$: '+str(np.round(mu,4)))
        pl.figtext(0.61,0.75,r'$\sigma$: '+str(np.round(sigma,4)))
        pl.figtext(0.61,0.68,r'$Amplitude$: '+str(np.round(ntot*alpha[0],2)))
        pl.figtext(0.61,0.61,r'$AIC_1$: '+str(aic1))
        pl.figtext(0.61,0.54,r'$AIC_2$: '+str(aic2))
        pl.figtext(0.61,0.47,'Photoz: '+str(photoz))
        pl.figtext(0.61,0.4,'ridgeline Z: '+str(z))
        pl.title('Total # of galaxies: '+str(ntot))
    return ntot*alpha[0],aic1,aic2,cgmr,alpha,mu,sigma,z
Beispiel #48
0
def oneRoundDelay(step=10000):
    injectRate = 0.9
    factory = GridNetworkFactory(makeSimpleNode(), Queues)
    factory.constructNetwork(6,6)\
        .setFlow(Flow((0,0),(0,5),injectRate))\
        .setFlow(Flow((5,0),(5,5),injectRate))\
        .setFlow(Flow((2,0),(3,5),injectRate))

    network = factory.getNetwork()

    packetFactory = PacketFactory()
    simulator = \
        Simulator(network,step,ConstLinkRateGenerator(1),packetFactory)
    simulator.run()
    #simulator.printNetwork()
    stat = simulator.getStaticsInfo()
    print stat['aveDelay']
    packetPool = sorted(stat['packetPool'], key=lambda p: p.getID)

    py.subplot(211)
    py.vlines([p.getCreateTime() for p in packetPool], [1],
              [p.getDelay() for p in packetPool], 'r')
    py.xlabel('Packet create time(bp with $\lambda$ = 0.9)')
    py.ylabel('delay')
    py.grid(True)

    injectRate = 0.9
    factory = GridNetworkFactory(makeMNode(2), Queues)
    factory.constructNetwork(6,6)\
        .setFlow(Flow((0,0),(0,5),injectRate))\
        .setFlow(Flow((5,0),(5,5),injectRate))\
        .setFlow(Flow((2,0),(3,5),injectRate))

    network = factory.getNetwork()

    packetFactory = PacketFactory()
    simulator = \
        Simulator(network,step,ConstLinkRateGenerator(1),packetFactory)
    simulator.run()
    #simulator.printNetwork()

    stat = simulator.getStaticsInfo()
    print stat['aveDelay']
    packetPool = sorted(stat['packetPool'], key=lambda p: p.getID)

    py.subplot(212)
    py.vlines([p.getCreateTime() for p in packetPool], [1],
              [p.getDelay() for p in packetPool], 'b')
    py.xlabel('Packet create time (m=2 with $\lambda$ = 0.9)')
    py.ylabel('delay')
    py.grid(True)
    py.savefig('packetDelayInOneRound_09')
    py.show()
Beispiel #49
0
 def view_results( self, states_object, burnin = 1 ):
   # plotting params
   nbins       = 20
   alpha       = 0.5
   label_size  = 8
   linewidth   = 3
   linecolor   = "r"
   
   # extract from states
   thetas = states_object.get_thetas()[burnin:,:]
   stats  = states_object.get_statistics()[burnin:,:]
   nsims  = states_object.get_sim_calls()[burnin:]
   
   f=pp.figure()
   for i in range(6):
     sp=f.add_subplot(2,10,i+1)
     pp.hist( thetas[:,i], 10, normed=True, alpha = 0.5)
     pp.title( self.theta_names[i])
     set_label_fonsize( sp, 6 )
     set_tick_fonsize( sp, 6 )
     set_title_fonsize( sp, 8 )
   for i in range(10):
     sp=f.add_subplot(2,10,10+i+1)
     pp.hist( stats[:,i], 10, normed=True, alpha = 0.5)
     ax=pp.axis()
     pp.vlines( self.obs_statistics[i], 0, ax[3], color="r", linewidths=2)
     # if self.obs_statistics[i] < ax[0]:
     #   ax[0] = self.obs_statistics[i]
     # elif self.obs_statistics[i] > ax[1]:
     #   ax[1] = self.obs_statistics[i]
     pp.axis( [ min(ax[0],self.obs_statistics[i]), max(ax[1],self.obs_statistics[i]), ax[2],ax[3]] )
     pp.title( self.stats_names[i])
     set_label_fonsize( sp, 6 )
     set_tick_fonsize( sp, 6 )
     set_title_fonsize( sp, 8 )
   pp.suptitle( "top: posterior, bottom: post pred with true")
   
   f = pp.figure()  
   I = np.random.permutation( len(thetas) )
   for i in range(16):
     sp=pp.subplot(4,4,i+1)
     theta = thetas[ I[i],:]
     test_obs = self.simulation_function( theta )
     test_stats = self.statistics_function( test_obs )
     err = np.sum( np.abs( self.obs_statistics - test_stats ) )
     pp.title( "%0.2f"%( err ))
     pp.plot( self.observations/1000.0 )
     pp.plot(test_obs/1000.0)
     pp.axis("off")
     set_label_fonsize( sp, 6 )
     set_tick_fonsize( sp, 6 )
     set_title_fonsize( sp, 8 )
   pp.suptitle( "time-series from random draws of posterior")
Beispiel #50
0
 def plot_peak(self, x, peaks, properties):
     plt.plot(x)
     plt.plot(peaks, x[peaks], "x")
     plt.vlines(x=peaks,
                ymin=x[peaks] - properties["prominences"],
                ymax=x[peaks],
                color="C1")
     plt.hlines(y=properties["width_heights"],
                xmin=properties["left_ips"],
                xmax=properties["right_ips"],
                color="C1")
     plt.show()
def Test1():
    cluster_result_filename = 'cluster_test.txt'
    
    from optics import *
    from numpy import random
    import scipy as S
    testX = random.rand(100, 2)
    x1 = S.rand(30,2)*2
    x2 = (S.rand(40,2)+1)*2
    x3 = (S.rand(40,2)*0.2+1)*2.5
    testX= np.concatenate((x1,x2,x3))
    
    #P.plot(testX[:,0], testX[:,1], 'ro')
    #RD, CD, order = optics(testX, 4)
    k =4 
    Eps = epsilon(testX,k)
    print Eps
    RD,CD,order = loptics(testX, Eps,k) 
    testXOrdered = testX[order]
   
    P.plot(testXOrdered[:,0], testXOrdered[:,1], 'b-')
    x = [float(i)/10.0 for i in range(110)]
    y = [-RD[i] for i in order]
    P.vlines(x,[0],y)
    print order
    P.savefig('D:\\Desktop\\test.png',dpi=300,format='png')

    ##############################################################
    _RD = [RD[i] for i in order]
    clusters = extractCluster(_RD,0.1,k,cluster_result_filename)
    
    hierarchy = 1
    starts,ends,counts = extractRangeCollection(cluster_result_filename)
    root = Node(0,0,0)
    extractHierarchicalStructure(starts,ends,counts,root)
    clusters = getClusterByHierarchy(root,hierarchy)
    
    for i,cluster in enumerate(clusters):
        cluster.id = i
        print cluster.start, ',', cluster.end, ',', cluster.count
    print "##############################"
        
    #################################################################
    color = ['ro','bo','yo','go','ko','mo','co','r*','b*']
    for i,id in enumerate(order):
        cluster_id = -1
        for cluster in clusters:
            if cluster.start <= i <= cluster.end:
                cluster_id = cluster.id
                break
        P.plot(testX[id,0],testX[id,1],color[cluster_id])
    P.show()
Beispiel #52
0
Datei: plot.py Projekt: pism/pism
def plot_profile(in_file, out_file):
    print("Reading %s to plot geometry profile for model %s, experiment %s, grid mode %s, step %s" % (
        in_file, model, experiment, mode, step))

    if out_file is None:
        out_file = os.path.splitext(in_file)[0] + "-profile.pdf"

    mask = read(in_file, 'mask')
    usurf = read(in_file, 'usurf')
    topg = read(in_file, 'topg')
    thk = read(in_file, 'thk')
    x = read(in_file, 'x')

    # theoretical grounding line position
    xg = MISMIP.x_g(experiment, step)
    # modeled grounding line position
    xg_PISM = find_grounding_line(x, topg, thk, mask)

    # mask out ice-free areas
    usurf = np.ma.array(usurf, mask=mask == 4)

    # compute the lower surface elevation
    lsrf = topg.copy()
    lsrf[mask == 3] = -MISMIP.rho_i() / MISMIP.rho_w() * thk[mask == 3]
    lsrf = np.ma.array(lsrf, mask=mask == 4)

    # convert x to kilometers
    x /= 1e3

    figure(1)
    ax = subplot(111)
    hold(True)
    plot(x, np.zeros_like(x), ls='dotted', color='red')
    plot(x, topg, color='black')
    plot(x, usurf, 'o', color='blue', markersize=4)
    plot(x, lsrf,  'o', color='blue', markersize=4)
    xlabel('distance from the divide, km')
    ylabel('elevation, m')
    title("MISMIP experiment %s, step %d" % (experiment, step))
    text(0.6, 0.9, "$x_g$ (model) = %4.0f km" % (xg_PISM / 1e3), color='r',
         transform=ax.transAxes)
    text(0.6, 0.85, "$x_g$ (theory) = %4.0f km" % (xg / 1e3), color='black',
         transform=ax.transAxes)

    _, _, ymin, ymax = axis(xmin=0, xmax=x.max())
    vlines(xg / 1e3, ymin, ymax, linestyles='dashed', color='black')
    vlines(xg_PISM / 1e3, ymin, ymax, linestyles='dashed', color='red')

    print("Saving '%s'...\n" % out_file)
    savefig(out_file)
Beispiel #53
0
def RasterPlot(st):
    neuronIdx = np.unique(st[:, 1])
    nNeurons = np.size(neuronIdx)
    nSpks, _ = st.shape
    vLenght = 0.1
    plt.ion()
    x = np.array([])
    y = np.array([])
    for idx, iNeuron in enumerate(neuronIdx):
        iSpkTimes = st[st[:, 1] == iNeuron, 0]
        x = np.r_[x, iSpkTimes]
        y = np.r_[y, iNeuron * np.ones((np.size(iSpkTimes),))]
    plt.vlines(x, y, y + vLenght)
    plt.draw()
Beispiel #54
0
 def _plot_vlines( self, x, y, label, params=dict() ):
     fparams = { 'color' : 'black',
                 'linestyle' : 'solid',
                 'linewidth' : 2.0,
                 'markersize' : 5 }
     fparams.update( params )
 
     pylab.vlines( x, [0], y, 
             color = fparams['color'],
             linestyle = fparams['linestyle'],
             linewidth = fparams['linewidth'],
             label = label )
     pylab.plot(x, y, 'o',
             color = fparams['color'],
             markersize = fparams['markersize'])
Beispiel #55
0
    def plot_lognormal_cdf(self,**kwargs):
        """
        Plot the fitted lognormal distribution
        """
        if not hasattr(self,'lognormal_dist'):
            return

        x=numpy.sort(self.data)
        n=len(x)
        xcdf = numpy.arange(n,0,-1,dtype='float')/float(n)
        lcdf = self.lognormal_dist.sf(x)

        D_location = argmax(xcdf-lcdf)
        pylab.vlines(x[D_location],xcdf[D_location],lcdf[D_location],color='m',linewidth=2)
        
        pylab.plot(x, lcdf,',',**kwargs)
Beispiel #56
0
def plot(mode):
    """ plot range """
    xmin, xmax, ymin, ymax = (-2, 2, -1, 3)
    fig = pl.figure()
    fig.subplots_adjust(left=0.15)
    ax = pl.subplot(1,1,1)

    interval = 0.5
    offset = 0.05

    """ move ticks"""
    pl.xticks(offset + np.arange(xmin, xmax+1, interval), np.arange(xmin, xmax+interval+1, interval))
    pl.yticks(offset + np.arange(ymin, ymax+1, interval), np.arange(ymin, ymax+interval+1, interval))

    pl.ylim([ymin,ymax])

    """ axis """
    pl.hlines([0], xmin, xmax, linestyles="dashed")
    pl.vlines([0], ymin, ymax, linestyles="dashed")

    """ label """
    pl.xlabel("x", style='italic', fontsize=25)
    pl.ylabel("l'(x)", style='italic', fontsize=25)

    """ title """
    pl.title(mode, fontdict={'size':28})

    X = np.linspace(xmin, xmax, 256, endpoint=True)

    """ plot funcitons """
    if mode == "(b)":
        pl.plot(X, exp(X), "--r", linewidth=5)
        pl.plot(X, hinge(X), "-b", linewidth=5)
    #pl.plot(X, logistic(X), linewidth=3, color="y")
    elif mode == "(a)":
        pl.plot(X, sigmoid(X), "-b", linewidth=5)
        pl.plot(X, ramp(X), "--r", linewidth=5)


    for i,item in enumerate(ax.get_xticklabels()):
        fontsize = 20
        item.set_fontsize(fontsize)

    for i,item in enumerate(ax.get_yticklabels()):
        fontsize = 20
        item.set_fontsize(fontsize)
    pl.show()
Beispiel #57
0
def plot_encoded(t, u, s, fig_title='', file_name=''):
    """
    Plot a time-encoded signal.

    Parameters
    ----------
    t : ndarray of floats
        Times (in s) at which the original signal was sampled.
    u : ndarray of floats
        Signal samples.
    s : ndarray of floats
        Intervals between encoded signal spikes.
    fig_title : string
        Plot title.
    file_name : string
        File in which to save the plot.

    Notes
    -----
    The spike times (i.e., the cumulative sum of the interspike
    intervals) must all occur within the interval `t-min(t)`.

    """

    dt = t[1]-t[0]
    cs = np.cumsum(s)
    if cs[-1] >= max(t)-min(t):
        raise ValueError('some spike times occur outside of signal''s support')

    p.clf()
    p.gcf().canvas.set_window_title(fig_title)
    p.axes([0.125, 0.3, 0.775, 0.6])
    p.vlines(cs+min(t), np.zeros(len(cs)), u[np.asarray(cs/dt, int)], 'b')
    p.hlines(0, 0, max(t), 'r')
    p.plot(t, u, hold=True)
    p.xlabel('t (s)')
    p.ylabel('u(t)')
    p.title(fig_title)
    p.gca().set_xlim(min(t), max(t))
    a = p.axes([0.125, 0.1, 0.775, 0.1])
    p.plot(cs+min(t), np.zeros(len(s)), 'ro')
    a.set_yticklabels([])
    p.xlabel('%d spikes' % len(s))
    p.gca().set_xlim(min(t), max(t))
    p.draw_if_interactive()
    if file_name:
        p.savefig(file_name)
Beispiel #58
0
def decoderDiagnostics(waveform=None):
    if waveform is None:
        waveform = badPacketWaveforms[-1]
    Fs_eff = Fs/upsample_factor
    ac = wifi.autocorrelate(waveform)
    ac_t = np.arange(ac.size)*16/Fs_eff
    synch = wifi.synchronize(waveform)/float(Fs_eff)
    pl.figure(2)
    pl.clf()
    pl.subplot(211)
    pl.specgram(waveform, NFFT=64, noverlap=64-1, Fc=Fc, Fs=Fs_eff, interpolation='nearest', window=lambda x:x)
    pl.xlim(0, waveform.size/Fs_eff)
    yl = pl.ylim(); pl.vlines(synch, *yl); pl.ylim(*yl)
    pl.subplot(212)
    pl.plot(ac_t, ac)
    yl = pl.ylim(); pl.vlines(synch, *yl); pl.ylim(*yl)
    pl.xlim(0, waveform.size/Fs_eff)
Beispiel #59
0
def plot_seg(nc, detection=None, annotation=None, show=False):
	
	length = len(nc)
	if detection==None:
		# Empty detection. Plot the first and last instance only.
		detection = [0, length-1]
	
	if annotation == None:
		# Plot single pane
		plt.figure(figsize=(7,2))
		plt.plot(np.linspace(0, length-1, length), nc)
		plt.vlines(detection, 0, 1, 'k')
		
	else:
		# Plot duo panes
		gs = gridspec.GridSpec(2, 1, height_ratios=[2, 1])
		plt.figure(figsize=(7,5))
	
		ax0 = plt.subplot(gs[0])
		ax1 = plt.subplot(gs[1], sharex=ax0)
	
		ax0.plot(np.linspace(0, length-1, length), nc)
		ax0.vlines(detection, 0, 1, 'k')
	   
		ax0.set_xlim([0, length])
		ax0.set_ylim([0, 1])
		ax0.get_xaxis().set_visible(False)
		ax0.set_title('Nolvety curve', fontsize=22)
		ax0.set_ylabel('Amplitude', fontsize=20)
	
		ax1.set_xlim([0, length])
		ax1.set_ylim([0, 1])
		ax1.vlines(annotation, 0, 1, 'r')
	
		ax1.get_xaxis().set_visible(False)
		ax1.set_title('Annotations', fontsize=22)

		plt.xlabel('Time frame', fontsize=20)
	
	if show:
		plt.show()
	else:
		plt.savefig(join(SAVETO+'FOOTE.pdf'), format='pdf')
	
	plt.close()
Beispiel #60
0
def plot_samples(S, axis_list=None):
    pl.scatter(S[:, 0], S[:, 1], s=2, marker="o", linewidths=0, zorder=10)
    if axis_list is not None:
        colors = [(0, 0.6, 0), (0.6, 0, 0)]
        for color, axis in zip(colors, axis_list):
            axis /= axis.std()
            x_axis, y_axis = axis
            # Trick to get legend to work
            pl.plot(0.1 * x_axis, 0.1 * y_axis, linewidth=2, color=color)
            # pl.quiver(x_axis, y_axis, x_axis, y_axis, zorder=11, width=0.01,
            pl.quiver(0, 0, x_axis, y_axis, zorder=11, width=0.01, scale=6, color=color)

    pl.hlines(0, -3, 3)
    pl.vlines(0, -3, 3)
    pl.xlim(-3, 3)
    pl.ylim(-3, 3)
    pl.xlabel("x")
    pl.ylabel("y")