示例#1
0
文件: GSRT.py 项目: blueray45/GSRT
def run_analysis(filename,mode,method):
    click.echo('Reading file : %s'%filename)
    data = IOfile.parsing_input_file(filename)
    click.echo('Creating class...')
    theclass = TFC(data)
    click.echo('Calculating transfer function using %s method'%method)
    if method=='tf_kramer286_sh':
        theclass.tf_kramer286_sh()
    elif method=='tf_knopoff_sh':
        theclass.tf_knopoff_sh()
    elif method=='tf_knopoff_sh_adv':
        theclass.tf_knopoff_sh_adv()
        
    plt.plot(theclass.freq,np.abs(theclass.tf[0]),label=method)
    plt.xlabel('frequency (Hz)')
    plt.ylabel('Amplification')
    plt.yscale('log')
    plt.xscale('log')
    plt.grid(True,which='both')
    plt.legend(loc='best',fancybox=True,framealpha=0.5)
    #plt.axis('tight')
    plt.autoscale(True,axis='x',tight=True)
    plt.tight_layout()
    plt.savefig('test.png', format='png')
    click.echo(click.style('Calculation has been finished!',fg='green'))
示例#2
0
    def plot(self, y, *args, **kwargs):
        '''
        Plot something vs this frequency

        This plots whateve is given vs. `self.f_scaled` and then
        calls `labelXAxis`.

        '''
        
        try:
            if len(shape(y))>2:
                # perhapsthe dimensions are empty, try to squeeze it down
                y= y.squeeze()
                if len(shape(y))>2:
                    # the dimensions are full, so lets loop and plot each
                    for m in range(shape(y)[1]):
                        for n in range(shape(y)[2]):
                            self.plot(y[:,m,n], *args, **kwargs)
                    return
            if len(y)==len(self):
                pass
            else:
                
                raise IndexError(['thing to plot doesn\'t have same'
                                 ' number of points as f'])
        except(TypeError):
            y = y*npy.ones(len(self))

        plot(self.f_scaled, y,*args, **kwargs)
        autoscale(axis='x', tight=True)
        self.labelXAxis()
示例#3
0
文件: GFP.py 项目: macyli01/livespin
    def getValueGFP(self, radius=10, name='', plot=False):
        mean = []
        movie = np.zeros((self.images[0].shape[0],
                          self.images[0].shape[1] * self.lengthSeq))
        if plot:
            pylab.figure(figsize=(6, 22))
        for index, im in enumerate(self.images):

            center = [(self.params[index][1] + self.params[index][1 + 6]) / 2.,
                      (self.params[index][2] + self.params[index][2 + 6]) / 2.]
            GFP = segmentationClass.Segmentation(im.image)
            GFP.defineFG()
            GFP.smooth_corr()
            mask = GFP.rond_mask(center, radius)
            val = np.sum(mask * GFP.smooth) / 1. / np.sum(mask)
            #val = np.average(GFP.smooth)
            movie[:,
                  index * im.shape[1]:(index + 1) * im.shape[1]] = GFP.smooth
            mean.append(val)
            if plot:
                pylab.subplot(len(self.images), 2, 2 * index + 1)
                pylab.imshow(GFP.smooth, 'gray')
                #pylab.title("t = {0}".format())
                pylab.axis('off')
                pylab.subplot(len(self.images), 2, 2 * index + 2)
                pylab.imshow(mask, 'gray')
                pylab.autoscale(False)
                pylab.axis('off')
                pylab.plot(self.params[index][2::6], self.params[index][1::6],
                           'ro')
                pylab.title('{0:.0f}'.format(val))
        if plot:
            pylab.savefig(name)
            pylab.close()
        return np.sum(nlargest(3, mean)) / 3., movie
示例#4
0
    def __init__(self, strictness=1):
        self.on = False
        self.pts = []
        self.marks = []

        self.fig = pl.gcf()
        self.ax = pl.gca()
        pl.autoscale(enable=False)
        self.cid_move = self.fig.canvas.mpl_connect('motion_notify_event',
                                                    self.onmove)
        self.cid_click = self.fig.canvas.mpl_connect('button_release_event',
                                                     self.onclick)
        self.cid_exit = self.fig.canvas.mpl_connect('axes_leave_event',
                                                    self.onexit)
        self.cid_keyup = self.fig.canvas.mpl_connect('key_release_event',
                                                     self.on_keyup)

        img = self.ax.get_images()[0].get_array().view(np.ndarray)
        img = (img - img.min()) / (img.max() - img.min())
        img *= 255
        img = img.astype(np.uint8)
        edge_img = cv2.Canny(img, img.mean(),
                             img.mean() + strictness * img.std())
        self.edge_pts = np.argwhere(edge_img)
        self.fig.canvas.start_event_loop(timeout=-1)
def plot_cpu_usr_sys(dstat_dict):

    figs = [x for x in dstat_dict.keys() if "cpu" in x]
    if not figs:
        print "No CPU data available to plot"
    datetimes = [DT.datetime.strptime(t, "%d-%m %H:%M:%S")
                 for t in dstat_dict['time']]
    hfmt = dates.DateFormatter('%H:%M:%S')
    if len(figs) == 1:
        plots = [plots]
    for i in range(len(figs)):
        f, plots = pl.subplots(1)
        plots.plot(datetimes, dstat_dict[figs[i]]['usr'], 'r-', label="usr",
                   linewidth=.5)
        plots.plot(datetimes, dstat_dict[figs[i]]['sys'], 'b-', label="sys",
                   linewidth=.5)
        plots.set_title(figs[i]+" usr/sys")
        plots.legend(loc='best')
        plots.xaxis.set_major_locator(dates.MinuteLocator())
        plots.xaxis.set_major_formatter(hfmt)
        pl.xticks(rotation='vertical')
        pl.subplots_adjust(bottom=.15)
        pl.autoscale()
        fil = figs[i]+"-usr-sys.svg"
        print fil
        pl.savefig(fil, format="svg")
示例#6
0
def render_image(img):
    print("rerendering..")
    plt.clf()
    plt.imshow(img)
    plt.draw()
    pl.autoscale(False)
    print("OK")
示例#7
0
    def go(self):
        self.rayss.append(self.bundles.generate_rays())
        l = []
        for k in self.rayss:
            for i in k:
                for j in self.lenses:
                    j.propagate_ray(i)
                l.append(i.vertices())

        for j in l:
            x = []
            y = []
            z = []
            for k in j:
                x.append(k[0])
                y.append(k[1])
                z.append(k[2])
                pl.figure(4)
                pl.title("Ray displayed in x/z plane")
                pl.xlabel("z displacement (mm)")
                pl.ylabel("x displacement (mm)")
                pl.plot(z, x, 'r')
                pl.autoscale(enable=True, axis='y')
                pl.autoscale(enable=True, axis='x')
                pl.grid()
        pl.show()
示例#8
0
    def plot(self, y, *args, **kwargs):
        '''
        Plot something vs this frequency

        This plots whateve is given vs. `self.f_scaled` and then
        calls `labelXAxis`.

        '''

        try:
            if len(shape(y)) > 2:
                # perhapsthe dimensions are empty, try to squeeze it down
                y = y.squeeze()
                if len(shape(y)) > 2:
                    # the dimensions are full, so lets loop and plot each
                    for m in range(shape(y)[1]):
                        for n in range(shape(y)[2]):
                            self.plot(y[:, m, n], *args, **kwargs)
                    return
            if len(y) == len(self):
                pass
            else:

                raise IndexError([
                    'thing to plot doesn\'t have same'
                    ' number of points as f'
                ])
        except (TypeError):
            y = y * npy.ones(len(self))

        plot(self.f_scaled, y, *args, **kwargs)
        autoscale(axis='x', tight=True)
        self.labelXAxis()
def main():
    title = 'MoS$_2$-1ML (VASP-PAW-PBE.Mo_pv)'
    xlabel = [
        '$\mathrm{\Gamma}$', '$\mathrm{K}$', '$\mathrm{M}$',
        '$\mathrm{\Gamma}$'
    ]
    xlabelpos = [1, 21, 31, 48]
    ylimit = [-6.5, 5.5]
    yminor = 4
    [nkpt, nband, nion, kpt, ev, proj] = read_procar()
    efermi = get_efermi()
    [econ, eval] = find_edges(ev, efermi + 1)
    eshift = eval

    fig = pl.gcf()
    fig.set_size_inches(5, 6)
    fig.subplots_adjust(bottom=0.05, left=0.12, top=0.94, right=0.96)
    fig.set_dpi(300)
    fig.suptitle(title, fontsize=13)
    ax = pl.gca()
    mpl.rcParams['font.sans-serif'] = 'Arial'  #'Helvetica'
    pl.ylabel('Energy (eV)', fontsize=12)
    pl.xticks(xlabelpos, xlabel, size=12)
    pl.yticks(size=10)
    ax.yaxis.set_minor_locator(mpl.ticker.AutoMinorLocator(yminor))
    pl.autoscale(enable=True, axis='y')
    pl.tick_params(axis='y',
                   which='major',
                   direction='out',
                   length=3,
                   width=0.8,
                   left='on',
                   right='off',
                   pad=5)
    pl.tick_params(axis='y',
                   which='minor',
                   direction='out',
                   length=2,
                   width=0.5,
                   left='on',
                   right='off')
    pl.tick_params(axis='x', which='both', top='off', bottom='off')
    for xline in xlabelpos:
        pl.axvline(x=xline, color='k', linewidth=0.6)
    x = np.arange(ev.shape[1]) + 1
    for i in range(ev.shape[0]):
        pl.plot(x, ev[i, :] - eshift, 'k-')

    plot_projection(proj, ev, [1], [5, 6, 7, 8, 9], eshift, 'b')
    plot_projection(proj, ev, [2, 3], [2, 3, 4], eshift, 'r')
    pl.scatter(-99, -99, marker='o', c='b', alpha=0.5, label='Mo d')
    pl.scatter(-99, -99, marker='o', c='r', alpha=0.5, label='S p')

    pl.xlim(x.min(), x.max())
    pl.ylim(ylimit)
    pl.axhline(y=eval - eshift, color='g', linestyle='--')
    pl.axhline(y=econ - eshift, color='g', linestyle='--')
    mpl.rcParams['pdf.fonttype'] = 42
    pl.legend(loc=1, prop={'size': 8})
    pl.savefig('band_proj.pdf')
示例#10
0
 def getValueGFP(self, radius = 10, name = '', plot = False):
     mean = []
     movie = np.zeros((self.images[0].shape[0], self.images[0].shape[1]*self.lengthSeq))
     if plot:
         pylab.figure(figsize = (6,22))
     for index, im in enumerate(self.images):
         
         center = [(self.params[index][1] + self.params[index][1+6])/2., (self.params[index][2] + self.params[index][2+6])/2.]
         GFP = segmentationClass.Segmentation(im.image)
         GFP.defineFG()
         GFP.smooth_corr()
         mask = GFP.rond_mask(center, radius)
         val = np.sum(mask*GFP.smooth)/1. /np.sum(mask)
         #val = np.average(GFP.smooth)
         movie[:,index*im.shape[1]:(index+1)*im.shape[1]] = GFP.smooth
         mean.append(val)
         if plot:
             pylab.subplot(len(self.images),2,2*index+1)
             pylab.imshow(GFP.smooth, 'gray')
             #pylab.title("t = {0}".format())
             pylab.axis('off')
             pylab.subplot(len(self.images),2,2*index+2)
             pylab.imshow(mask, 'gray')
             pylab.autoscale(False)
             pylab.axis('off')
             pylab.plot(self.params[index][2::6], self.params[index][1::6], 'ro')
             pylab.title('{0:.0f}'.format(val))
     if plot:   
         pylab.savefig(name)
         pylab.close()
     return np.sum(nlargest(3, mean))/3., movie
示例#11
0
文件: wplot.py 项目: antiface/dsp-2
def ax_pianoroll(title='notes'):
    '''Twelve named semitones on the x-axis, one octave.'''
    pl.cla()
    pl.title(title)
    pl.xticks(pl.frange(0, 1, npts=12, closed=0), 'C. C# D. D# E. F. F# G. G# A. A# B.'.split())
    pl.yticks(pl.arange(24))
    pl.grid(True, axis='x')
    pl.xlim(-.5/12,11.5/12)
    pl.autoscale(True,axis='y')
示例#12
0
def plot_locpot_z(lattice_constant, a, elements, numofatoms, atom_pos, locpot):
    import matplotlib as mpl
    mpl.use("PDF")
    import pylab as pl
    potz = np.empty([locpot.shape[2]])
    for z in range(locpot.shape[2]):
        potz[z] = locpot[:, :, z].sum() / locpot.shape[0] / locpot.shape[1]


#        print '{0:4d} {1:12.6f}'.format(z,potz[z])
    sz = np.linalg.norm(a[2]) * lattice_constant
    #    print potz.max()

    # Plot Setting
    pl.title('LOCPOT', size=12)
    pl.xlabel('Z', size=10)
    pl.ylabel('Local potential (eV)', size=10)
    xminor = 4
    yminor = 4

    fig = pl.gcf()
    fig.set_size_inches(5, 3)
    fig.subplots_adjust(bottom=0.14, left=0.12, top=0.88, right=0.95)
    fig.set_dpi(300)
    mpl.rcParams['font.sans-serif'] = 'Arial'
    ax = pl.gca()
    ax.xaxis.set_minor_locator(mpl.ticker.AutoMinorLocator(xminor))
    ax.yaxis.set_minor_locator(mpl.ticker.AutoMinorLocator(yminor))
    pl.xticks(size=8)
    pl.yticks(size=8)
    pl.tick_params(axis='x',
                   which='major',
                   direction='in',
                   length=3,
                   width=1,
                   top='on',
                   bottom='on',
                   pad=6)
    pl.tick_params(axis='y',
                   which='major',
                   direction='in',
                   length=3,
                   width=1,
                   left='on',
                   right='on',
                   pad=6)
    pl.autoscale(enable=True, axis='x')
    pl.autoscale(enable=True, axis='y')

    # Plot
    z = np.arange(potz.shape[0]) / float(potz.shape[0])
    pl.plot(z, potz, '-', label='locpot_z')
    #    pl.legend(loc=1,prop={'size':8})
    pl.savefig('locpot_z.pdf')

    return
    def csv_reader(self, mode):
        if(mode == 1):
            if(test):
                inputFile = self.testFileName
            else:
                inputFile = self.filename
        else:
            inputFile = self.filename
        with open(inputFile, 'r') as csv_file:
            reader = csv.reader(csv_file, delimiter = ',')
            Hour = [];
            Minute = [];
            Time = [];
            RawIR = [];
            Blinks = [];
            ActualBlinks = [];


            # Skips the first line which does not contain data
            next(reader)

            for row in reader:
                if mode == 2:
                    Hour.append(float(row[0]))
                    Minute.append(float(row[1]))
                elif mode==1:
                    Blinks.append(float(row[4]))
                    ActualBlinks.append(float(row[5]))
                #####CHANGE THIS NICOLE
                if(float(row[2])<49):
                    Time.append(float(row[2])+60)
                else:
                    Time.append(float(row[2]))
                RawIR.append(float(row[3]))
                
            if mode ==1:
                totalOpTime = max(Time) - min(Time)
                print "Average Sampling Frequency: "
                print len(Time)/totalOpTime
                if(self.MatchedBlinks != 0 and self.ActualBlinks != 0 and self.DetectedBlinks !=0):
                    print "Accuracy of Blink Detection: " + str(self.MatchedBlinks/self.ActualBlinks)
                    print "# of Actual Blinks: " + str(self.ActualBlinks)
                    print "# of Detected Blinks: " + str(self.DetectedBlinks)
            
                pl.rcParams.update({'font.size': 18})
                pl.figure(1)
                pl.xlabel("Time(s)")
                pl.ylabel("IR Values")
                pl.title("IR Blink Sensor Results")
                pl.plot(Time, RawIR, linewidth = 2, color = 'gray')
                pl.autoscale()
                pl.plot(Time, Blinks, linewidth = 2, color = 'red')
                pl.plot(Time, ActualBlinks, linewidth = 2, color = 'blue')
                pl.show()
            else:
                return [Time, RawIR, Hour, Minute]
示例#14
0
def save_maxima(image, new_x, new_y, dist, outpath, nameCondition):
    pylab.close('all')
    pylab.imshow(image)
    pylab.axis('off')
    pylab.autoscale(False)
    for i in xrange(len(new_x)):
        points = pylab.plot(new_x[i], new_y[i], 'wo')
        squares = pylab.gca().add_patch(pylab.Rectangle((new_x[i] - dist/2, new_y[i] - dist/2), dist, dist, edgecolor = 'w', alpha = 0.3, lw = 3))
    pylab.savefig("{0}/found_maxima_n{1}_{2}.png".format(outpath, len(new_x), nameCondition))
    pylab.close()
def draw_the_track_cross_section(image, crossection_points):
    track_polygon = get_polygon(crossection_points)
    cross_section = get_image_cross_section(image, track_polygon)

    pylab.plot(map(lambda pixel: 255 - pixel[2], cross_section))
    pylab.ylim(0, 255)
    pylab.xlim(0, len(cross_section))
    pylab.xticks([])
    pylab.autoscale(False)
    pylab.show()
def bargraph_cfd(xitems, yitems, figname, xLabel, yLabel):
    #fig = plt.figure(dpi=100)
    
    plt.bar(arange(len(xitems)), yitems, align='center')
    plt.autoscale(True, axis='both')
    plt.tight_layout(pad=7.0)
    plt.xticks(arange(len(xitems)), xitems, rotation=90)
    plt.xlabel(xLabel)
    plt.ylabel(yLabel)
    plt.title(figname)
    plt.savefig(IOtools.results_rootpath+os.sep+figname+".png") 
示例#17
0
def analyse_connectivity(sheet_name,proj_name,lhi):
    or_bins = numpy.linspace(0,numpy.pi/2,30)
    projection = topo.sim[sheet_name].projections()[proj_name]
    or_pref = topo.sim[projection.src.name].sheet_views['OrientationPreference'].view()[0]*numpy.pi
    or_pref_target = topo.sim[projection.dest.name].sheet_views['OrientationPreference'].view()[0]*numpy.pi
    
    domain_orientation_connection_strength = numpy.zeros((30,1))
    pinwheel_orientation_connection_strength = numpy.zeros((30,1))
    
    pinwheels = numpy.where(lhi.flatten()<0.1)[0]
    domains = numpy.where(lhi.flatten()>0.9)[0]
    
    for i in pinwheels:
        cf = projection.cfs.flatten()[i]
        this_or = or_pref_target.flatten()[i]
        ors = cf.input_sheet_slice.submatrix(or_pref).flatten()
        weights = numpy.multiply(cf.weights,cf.mask).flatten()
        
        for j,k in enumerate(numpy.digitize(circular_dist(ors,this_or,numpy.pi),or_bins)):
            print k    
            pinwheel_orientation_connection_strength[k-1] += weights[j]

    for i in domains:
        cf = projection.cfs.flatten()[i]
        this_or = or_pref_target.flatten()[i]
        ors = cf.input_sheet_slice.submatrix(or_pref).flatten()
        weights = numpy.multiply(cf.weights,cf.mask).flatten()
        
        for j,k in enumerate(numpy.digitize(circular_dist(ors,this_or,numpy.pi),or_bins)):
            domain_orientation_connection_strength[k-1] += weights[j]

        
    import pylab
    pylab.figure()
    pylab.subplot(2,1,1)
    pylab.hold('on')
    pylab.plot(numpy.linspace(0,numpy.pi/2,30,endpoint=False)+numpy.pi/2/60,pinwheel_orientation_connection_strength,'k',linewidth=2.0)
    pylab.plot(numpy.linspace(0,numpy.pi/2,30,endpoint=False)+numpy.pi/2/60,pinwheel_orientation_connection_strength,'ko')
    pylab.title(proj_name,fontsize=20)
    pylab.autoscale(tight=True)
    pylab.title('pinwheels')
    
    pylab.subplot(2,1,2)
    pylab.hold('on')
    pylab.plot(numpy.linspace(0,numpy.pi/2,30,endpoint=False)+numpy.pi/2/60,domain_orientation_connection_strength,'k',linewidth=2.0)
    pylab.plot(numpy.linspace(0,numpy.pi/2,30,endpoint=False)+numpy.pi/2/60,domain_orientation_connection_strength,'ko')
    pylab.title(proj_name,fontsize=20)
    pylab.autoscale(tight=True)
    pylab.title('domains')
    
    from param import normalize_path
    pylab.savefig(normalize_path('PPconnectivity: ' + proj_name + str(topo.sim.time()) + '.png'));
示例#18
0
def plot_locpotc(lpc, ef, sc):
    import matplotlib as mpl
    mpl.use("PDF")
    import pylab as pl

    # Plot Setting
    #    pl.title('LOCPOT',size=12)
    pl.xlabel('c axis ($\mathrm{\AA}$)', size=12)
    pl.ylabel('Local potential (eV)', size=12)
    xminor = 5
    yminor = 5

    fig = pl.gcf()
    fig.set_size_inches(6, 4)
    fig.subplots_adjust(bottom=0.13, left=0.10, top=0.96, right=0.97)
    fig.set_dpi(300)
    mpl.rcParams['font.sans-serif'] = 'Arial'
    ax = pl.gca()
    ax.xaxis.set_minor_locator(mpl.ticker.AutoMinorLocator(xminor))
    ax.yaxis.set_minor_locator(mpl.ticker.AutoMinorLocator(yminor))
    pl.xticks(size=10)
    pl.yticks(size=10)
    pl.tick_params(axis='x',
                   which='major',
                   direction='in',
                   length=3,
                   width=1,
                   top='on',
                   bottom='on',
                   pad=6)
    pl.tick_params(axis='y',
                   which='major',
                   direction='in',
                   length=3,
                   width=1,
                   left='on',
                   right='on',
                   pad=6)
    ax.margins(0.1)
    pl.autoscale(enable=True, axis='x')
    pl.autoscale(enable=True, axis='y')
    pl.xlim([0, sc])

    # Plot
    pl.plot(lpc[:, 1] * sc, lpc[:, 2] - ef, '-', label='locpot_c')
    pl.axhline(y=0.0, color='g', linestyle='--')
    #    pl.legend(loc=1,prop={'size':8})
    pl.savefig('locpotc.pdf')

    return
示例#19
0
def save_spectrogram(wav_file, spectrogram_path):
    sound_info, frame_rate = get_wav_info(wav_file)
    pylab.figure(num = None, figsize = (19, 12), frameon = False)
    pylab.subplot(111)
    pylab.specgram(sound_info, Fs = frame_rate)
    pylab.gca().get_yaxis().set_visible(False)
    pylab.gca().get_xaxis().set_visible(False)
    pylab.gca().set_yticklabels([])
    pylab.gca().set_xticklabels([])
    pylab.gca().set_axis_off()
    pylab.axis('off')
    pylab.autoscale(False)
    pylab.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
    # extent = pylab.gca().get_window_extent().transformed(pylab.gcf().dpi_scale_trans.inverted())
    pylab.savefig(spectrogram_path, bbox_inches = 'tight', pad_inches = -0.05)
示例#20
0
def main():
    '''Exemple d'utilisation de la fonction d'affichage d'un astre phase vue depuis la Terre'''
    w,h = pylab.figaspect(1.)
    fig = pylab.figure(figsize = (int(2. * w), int(2. * h)))
    ax = fig.add_subplot(111, axisbg = '0.1') # 0.1 c'est gris fonce
    pylab.xlabel('alt')
    pylab.ylabel('az')
    astre = ephem.Moon()
    obs = ephem.city('Paris')
    obs.date = '2013/3/16 21:000:00'
    astre.compute(obs)
    pylab.title('Moon Phase ('+str(astre.phase)+') - '+str(obs.date))
    # ra_dec = False : Apparent topocentric position represented by the properties : ra and dec, and alt and az.
    object_phase (ax, obs, False, astre, astre.alt * 180. / math.pi, astre.az * 180. / math.pi, astre.size / 1000., '0.2', '0.85')
    pylab.autoscale()
    pylab.show()
示例#21
0
def save_maxima(image, new_x, new_y, dist, outpath, nameCondition):
    pylab.close('all')
    pylab.imshow(image)
    pylab.axis('off')
    pylab.autoscale(False)
    for i in xrange(len(new_x)):
        points = pylab.plot(new_x[i], new_y[i], 'wo')
        squares = pylab.gca().add_patch(
            pylab.Rectangle((new_x[i] - dist / 2, new_y[i] - dist / 2),
                            dist,
                            dist,
                            edgecolor='w',
                            alpha=0.3,
                            lw=3))
    pylab.savefig("{0}/found_maxima_n{1}_{2}.png".format(
        outpath, len(new_x), nameCondition))
    pylab.close()
示例#22
0
def plot_muscle_activity(filepath, exc=None, act=None):
    """Plots provided muscle activity and saves to a pdf file.

    Parameters
    ----------
    filepath: string
        Path name of pdf file to print to.
    exc: pandas DataFrame
        DataFrame containing muscle excitation and muscle name information.
    act: pandas DataFrame
        DataFrame containing muscle activation and muscle name information.
    """

    if (exc is None) and (act is None):
        raise Exception("Please provide either excitation or "
                        "activation information")
    elif act is None:
        N = len(exc.columns)
    else:
        N = len(act.columns)

    # Create plots
    num_rows = 5
    num_cols = np.ceil(float(N) / num_rows)
    fig = pl.figure(figsize=(11, 8.5))
    for i in range(N):
        pl.subplot(num_rows, num_cols, i + 1)
        if not (exc is None):
            pl.plot(exc.index, exc[exc.columns[i]], label='e')
        if not (act is None):
            pl.plot(act.index, act[act.columns[i]], label='a')
        pl.ylim(0, 1)
        if i == 1:
            pl.legend(frameon=False, fontsize=8)
        if not (exc is None):
            pl.title(exc.columns[i], fontsize=8)
        else:
            pl.title(act.columns[i], fontsize=8)
        pl.autoscale(enable=True, axis='x', tight=True)
        pl.xticks([])
        pl.yticks([])
    pl.tight_layout()
    pl.savefig(filepath)
    pl.close(fig)
示例#23
0
    def show_fft(self, samples=1000, channel=0, clock_rate = 2000.0):
        import pylab as pl
    
        task = self.AnalogInputTask()
        task.create_voltage_channel('Dev1/ai1', terminal = 'rse', min_val=-10, max_val=10)    # current amplifier

        task.configure_timing_sample_clock(rate = clock_rate)
        task.start()        
        data = task.read(samples, fill_mode='group_by_channel',timeout=1000)
        del task

        myfft = np.fft.fftshift(np.fft.fft(data[channel]))
        freq = np.fft.fftshift(np.fft.fftfreq(len(data[0]),1.0/clock_rate))
        
        pl.xlim((0,clock_rate/2))  
        pl.autoscale(axis='y')
        pl.ylim(ymin=0)
        pl.plot(freq,myfft)
        pl.show()
示例#24
0
def plot_bootstraps(origin,
                    bootstraps,
                    labels,
                    ellipse_level=0.95,
                    scatter_alpha=0.5,
                    colors=None):
    fig = pl.figure(figsize=(14, 10))
    ax = pl.axes(aspect=1)
    #ax = pl.axes([-1, -1, 1, 1])
    default_colors = "bgrcmyk"  # TODO
    for i, l in enumerate(labels):
        # random color -- do better than random but so they stay distinct and
        # not limited by predefined set of colors
        # c = np.random.rand(3,1)
        c = (colors or default_colors)[i % len(default_colors)]
        # scatter plot all the bootstrap samples
        bs = bootstraps[:, i]
        if scatter_alpha:
            ax.scatter(bs[:, 0], bs[:, 1], c=c[0], alpha=scatter_alpha)
        # plot original 'center'
        x, y = origin[i][:2]
        ax.plot(x, y, 'o', label=l, markeredgewidth=2, markerfacecolor=c[0])
        ax.text(x,
                y,
                l,
                fontsize=12,
                bbox=dict(facecolor='white', alpha=0.8),
                color=c[0],
                horizontalalignment='center',
                verticalalignment='center')
        # plot ellipse
        if ellipse_level:
            # estimate mean/cov for bootstraps
            _make_ellipse(bs.mean(0)[:2],
                          np.cov(bs, rowvar=0)[:2, :2],
                          ax,
                          level=ellipse_level,
                          color=c)
    # and now plot all the sample points we got
    #break
    # pl.legend()
    pl.autoscale(tight=False)
示例#25
0
def generate_dataset_for_GAN():
    # Create data directories if not already there
    if not os.path.exists("./gaussian_images"):
        os.makedirs("./gaussian_images")
    if not os.path.exists("./sinusoidal_images"):
        os.makedirs("./sinusoidal_images")

    # Instantiate generator
    generator = imgen.Image_Generator()

    plt.rcParams['savefig.pad_inches'] = 0
    plt.autoscale(tight=True)

    # Create 1000 Gaussian images with random onehot pixels
    for x in range(0, 1000):
        image = generator.create_image(np.random.randint(6), 0.25, 0.0625,
                                       (64, 64), "gaussian")

        # Save images to the ./gaussian_images directory
        plt.imshow(image, cmap="gray", interpolation="nearest", vmin=0, vmax=1)
        plt.xticks([])
        plt.yticks([])
        plt.savefig("gaussian_images/gaussian" + str(x) + ".png",
                    bbox_inches="tight",
                    pad_inches=0,
                    transparent=True,
                    dpi=136.9)

    # Create 1000 sinusoidal images with random onehot pixels
    for x in range(0, 1000):
        image = generator.create_image(np.random.randint(6), 0.25, 0.0625,
                                       (512, 512), "sinusoidal")

        # Save images to the ./sinusoidal_images directory
        plt.imshow(image, cmap="gray", interpolation="nearest", vmin=0, vmax=1)
        plt.xticks([])
        plt.yticks([])
        plt.savefig("sinusoidal_images/sinusoidal" + str(x) + ".png",
                    bbox_inches="tight",
                    pad_inches=0,
                    transparent=True,
                    dpi=136.9)
示例#26
0
文件: roi.py 项目: bensondaled/pyfluo
    def __init__(self, strictness=1):
        self.on = False
        self.pts = []
        self.marks = []

        self.fig = pl.gcf()
        self.ax = pl.gca()
        pl.autoscale(enable=False)
        self.cid_move = self.fig.canvas.mpl_connect('motion_notify_event', self.onmove)
        self.cid_click = self.fig.canvas.mpl_connect('button_release_event', self.onclick)
        self.cid_exit = self.fig.canvas.mpl_connect('axes_leave_event', self.onexit)
        self.cid_keyup = self.fig.canvas.mpl_connect('key_release_event', self.on_keyup)

        img = self.ax.get_images()[0].get_array().view(np.ndarray)
        img = (img-img.min())/(img.max()-img.min())
        img *= 255
        img = img.astype(np.uint8)
        edge_img = cv2.Canny(img, img.mean(), img.mean()+strictness*img.std())
        self.edge_pts = np.argwhere(edge_img)
        self.fig.canvas.start_event_loop(timeout=-1)
示例#27
0
 def plot(self, y, *args, **kwargs):
     '''
     Plot something vs this frequency
     
     This plots whateve is given vs. `self.f_scaled` and then 
     calls `labelXAxis`.
     
     '''
     try:
         if len(y)==len(self):
             pass
         else:
             raise IndexError(['thing to plot doesnt have same'
                              ' number of points as f'])
     except(TypeError):
         y = y*npy.ones(len(self))
         
     plot(self.f_scaled, y,*args, **kwargs)
     autoscale(axis='x', tight=True)
     self.labelXAxis()
示例#28
0
def _analyse_push_pull_connectivity(sheet_name,proj_name):
    or_bins = numpy.linspace(0,numpy.pi,31)
    phase_bins = numpy.linspace(0,numpy.pi*2,31)
    
    projection = topo.sim[sheet_name].projections()[proj_name]
    or_pref = topo.sim[projection.src.name].sheet_views['OrientationPreference'].view()[0]*numpy.pi
    phase_pref = topo.sim[projection.src.name].sheet_views['PhasePreference'].view()[0]*numpy.pi*2
    or_pref_target = topo.sim[projection.dest.name].sheet_views['OrientationPreference'].view()[0]*numpy.pi
    phase_pref_target = topo.sim[projection.dest.name].sheet_views['PhasePreference'].view()[0]*2*numpy.pi
    
    phase_connection_strength = numpy.zeros((30,1))
    orientation_connection_strength = numpy.zeros((30,1))
    
    for (i,cf) in enumerate(projection.cfs.flatten()):
        this_or = or_pref_target.flatten()[i]
        this_phase = phase_pref_target.flatten()[i]
        ors = cf.input_sheet_slice.submatrix(or_pref).flatten()
        phases = cf.input_sheet_slice.submatrix(phase_pref).flatten()
        weights = numpy.multiply(cf.weights,cf.mask).flatten()
        
        for j,k in enumerate(numpy.digitize(circular_dist(ors,this_or,numpy.pi),or_bins)):
            orientation_connection_strength[k-1] += weights[j]
        for j,k in enumerate(numpy.digitize(circular_dist(phases,this_phase,2*numpy.pi),phase_bins)):
            phase_connection_strength[k-1] += weights[j]
        
    import pylab
    pylab.figure()
    pylab.subplot(2,1,1)
    pylab.hold('on')
    pylab.plot(numpy.linspace(0,numpy.pi,30,endpoint=False)+numpy.pi/60,orientation_connection_strength,'k',linewidth=2.0)
    pylab.plot(numpy.linspace(0,numpy.pi,30,endpoint=False)+numpy.pi/60,orientation_connection_strength,'ko')
    pylab.title(proj_name,fontsize=20)
    pylab.autoscale(tight=True)
    pylab.subplot(2,1,2)
    pylab.hold('on')
    pylab.plot(numpy.linspace(0,numpy.pi*2,30,endpoint=False)+2*numpy.pi/60,phase_connection_strength,'k',linewidth=2.0)
    pylab.plot(numpy.linspace(0,numpy.pi*2,30,endpoint=False)+2*numpy.pi/60,phase_connection_strength,'ko')
    pylab.autoscale(tight=True)
    
    from param import normalize_path
    pylab.savefig(normalize_path('PPconnectivity: ' + proj_name + str(topo.sim.time()) + '.png'));
示例#29
0
def show_sig(rtransform, start, end, rate, subsample):
	interval = end - start
	subsample = subsample[:interval]
	intpersec = rate/interval
	sig = filter(lambda x:x>1, rtransform)
	if not len(sig):
		return
	print start/float(rate)
	print sig
	subplot(3,1,1)
	axis([start, end, -0.5, 0.5])
	plot(xrange(start, end), subsample)
	subplot(3,1,2)
	xlim(0,rate)
	autoscale(axis='y')
	plot(xrange(0, rate), rtransform)
	subplot(3,1,3)
	xlim(0,rate)
	autoscale(axis='y')
	plot(xrange(0, rate), smooth(rtransform, 10))
	show()
示例#30
0
def plotStock(dates, symbol, name, trades, turnovers, amounts, masterAmounts):
    masterAmounts = numpy.array(masterAmounts)
    amounts = numpy.array(amounts)
    numpy.seterr(all='ignore')
    masters = (masterAmounts / amounts) * 100
    masters[numpy.isnan(masters)] = 0
    masterAmounts = masterAmounts / 10000000
    turnovers = pylab.array(turnovers)
    turnovers = turnovers * 100
    pylab.figure(figsize=(16,10), dpi=200)
    pylab.subplot(3,1,1)
    pylab.title(symbol +  ' ' + name + ' (' + dates[-1] + ')')  
    pylab.plot(trades, color = 'black', label = u'收盘价格')
    pylab.ylabel(u'价格')
    pylab.legend(loc = 'upper left')
    pylab.autoscale(True, 'both', None)
    pylab.grid(True)
    pylab.subplot(3,1,2)
    pylab.plot(masterAmounts, color = 'red', label = u'主力流入')
    pylab.ylabel(u'千万')
    pylab.legend(loc = 'upper left')
    pylab.autoscale(True, 'both', None)
    pylab.grid(True)
    pylab.subplot(3,1,3)
    pylab.plot(masters, color = 'blue', label = u'主力占比')
#    pylab.plot(turnovers, color = 'green', label = u'换手率')
    pylab.xlabel(u'日期')
    pylab.ylabel(u'百分比-100%')
    pylab.legend(loc = 'upper left')
    pylab.autoscale(True, 'both', None)
    pylab.grid(True)
    pylab.savefig(symbol, dpi=200)
示例#31
0
    def plot(self, y, *args, **kwargs):
        '''
        Plot something vs this frequency

        This plots whateve is given vs. `self.f_scaled` and then
        calls `labelXAxis`.

        '''
        try:
            if len(y) == len(self):
                pass
            else:
                raise IndexError([
                    'thing to plot doesn\'t have same'
                    ' number of points as f'
                ])
        except (TypeError):
            y = y * npy.ones(len(self))

        plot(self.f_scaled, y, *args, **kwargs)
        autoscale(axis='x', tight=True)
        self.labelXAxis()
示例#32
0
 def draw2D(self, title, image=[]):
     pylab.figure()
     if image == []:
         pylab.imshow(self.image, 'gray')
     else:
         pylab.imshow(image, 'gray')
     pylab.axis('off')
     pylab.autoscale(False)
     for i in xrange(self.nComponents):
         xeq = lambda t: self.params[6 * i + 3] * np.cos(t) * np.cos(self.params[6 * i + 5]) + self.params[
                                                                                                   6 * i + 4] * np.sin(
             t) * np.sin(self.params[6 * i + 5]) + self.params[6 * i + 1]
         yeq = lambda t: - self.params[6 * i + 3] * np.cos(t) * np.sin(self.params[6 * i + 5]) + self.params[
                                                                                                     6 * i + 4] * np.sin(
             t) * np.cos(self.params[6 * i + 5]) + self.params[6 * i + 2]
         t = np.linspace(0, 2 * np.pi, 100)
         x = xeq(t)
         y = yeq(t)
         pylab.scatter(self.params[6 * i + 2], self.params[6 * i + 1], color='k')
         pylab.plot(y.astype(int), x.astype(int), self.colors[i] + '-')
     pylab.savefig(title)
     pylab.close()
示例#33
0
def pos_analysis(data):
    """
    Analyze position.
    """
    tmerc_map = create_map(data.GPS_Lon.values, data.GPS_Lat.values)
    gps_y, gps_x = tmerc_map(data.GPS_Lon.values, data.GPS_Lat.values)
    gpos_y, gpos_x = tmerc_map(data.GPOS_Lon.values, data.GPOS_Lat.values)
    gpsp_y, gpsp_x = tmerc_map(
        data.GPSP_Lon[pl.isfinite(data.GPSP_Lon.values)].values,
        data.GPSP_Lat[pl.isfinite(data.GPSP_Lat.values)].values)

    pl.plot(gpos_y, gpos_x, '.', label='est')

    pl.plot(gps_y, gps_x, 'x', label='GPS')

    pl.plot(gpsp_y, gpsp_x, 'ro', label='cmd')

    pl.xlabel('E, m')
    pl.ylabel('N, m')
    pl.grid()
    pl.autoscale(True, 'both', True)
    pl.legend(loc='best')
    return locals()
示例#34
0
def plot_reserve_activity(filepath, reserves):
    """Plots provided reservec acutator activations and saves to a pdf file.

    Parameters
    ----------
    filepath: string
        Path name of pdf file to print to.
    reserves: pandas DataFrame
        DataFrame containing reserve activity and name information.
    """

    fig = pl.figure()
    NR = len(reserves.columns)
    for i in range(NR):
        pl.subplot(NR, 1, i + 1)
        pl.plot(reserves.index, reserves[reserves.columns[i]])
        pl.ylim(-1, 1)
        pl.title(reserves.columns[i], fontsize=8)
        pl.axhline(0)
        pl.autoscale(enable=True, axis='x', tight=True)
    pl.tight_layout()
    pl.savefig(filepath)
    pl.close(fig)
示例#35
0
def main():
    pl.title('MoS$_2$-1ML (VASP-PAW-PBE.Mo_pv)',fontsize=12)
    xlabel=['$\mathrm{\Gamma}$','$\mathrm{K}$','$\mathrm{M}$','$\mathrm{\Gamma}$']
    xlabelpos=[1,21,31,48]
    ef = get_efermi()
    ylimit=[-7,6]
    yminor=4 

    fig=pl.gcf()
    fig.set_size_inches(5,6)
    fig.subplots_adjust(bottom=0.05,left=0.12, top=0.95, right=0.96)
    fig.set_dpi(300)
    ax = pl.gca()
    mpl.rcParams['font.sans-serif']='Arial' #'Helvetica'
    pl.ylabel('Energy (eV)',fontsize=10)
    pl.xticks(xlabelpos,xlabel,size=10)
    pl.yticks(size=9)
    ax.yaxis.set_minor_locator(mpl.ticker.AutoMinorLocator(yminor))
    pl.autoscale(enable=True,axis='y')
    pl.tick_params(axis='y',which='major',direction='out',length=4, width=1,left='on',right='off',pad=5)
    pl.tick_params(axis='y',which='minor',direction='out',length=3, width=0.5,left='on',right='off')
    pl.tick_params(axis='x',which='both',top='off',bottom='off')
    for xline in xlabelpos:
        pl.axvline(x=xline,color='k',linewidth=0.6)
    ev=read_eigenvalues_vasp()
    x=ev[0,:]
    econ,eval=find_edges(ev,ef)
    print 'E_fermi: {0}   Band edges: {1} {2}'.format(ef,econ,eval)
    for i in range(ev.shape[0]-1):
        pl.plot(x,ev[i+1,:]-eval,'k-')
    pl.xlim(x.min(),x.max())
    pl.ylim(ylimit)
    pl.axhline(y=econ-eval,color='g',linestyle='--')
    pl.axhline(y=0.0,color='g',linestyle='--')
    mpl.rcParams['pdf.fonttype']=42
    pl.savefig('band.pdf')
示例#36
0
#figure()
#figure(facecolor="white")
fig.set_facecolor("white")
#print 'U =',u[0:4],x[0:4],y[0:4]
subplot(311)
bounds = [0, 1, 100]
img = imshow(transpose(u),
             origin='lower',
             cmap='jet',
             extent=[-2.0, 18.0, -4.0, 4.0])
#imshow(u,cmap='jet')
#colorbar(img, cmap=cmap, norm=norm, boundaries=bounds, ticks=[0, 5, 10])
#colorbar(boundaries=bounds)
#clim(0,1)
autoscale()
colorbar()

subplot(312)
xlabel('x/D')
ylabel('1 - U/Uinf')
ylim([0, 1])
plt, = plot(x, cline)

#fig.tight_layout()


def update(val):
    ct = sct.val
    ti = sti.val
示例#37
0
				mean_sfr[ix][iy] = np.mean(np.log10(sfrall[sel]))
				mean_z[ix][iy] = np.mean(zall[sel])
				mean_zcold[ix][iy] = np.mean(np.log10(zcoldall[sel]))
	
#		pl.matshow(mean_sfr)
		ssel = np.where((zall > _z-zbin/2.) &
						(zall < _z+zbin/2.))

		pl.close()
		a1 =  pl.figure(1)
		pl.imshow(mean_sfr,extent=[pmin,pmax,tmin,tmax],interpolation='nearest')
		pl.xticks(np.arange(pmin,pmax,10))
		pl.yticks(np.arange(tmin,tmax,10))
		pl.xlabel('deg')
		pl.ylabel('deg')		
		pl.autoscale(False)
		pl.plot(theta[ssel],phi[ssel],'.',color='gray',alpha=0.5)
		cbar = pl.colorbar()
		cbar.set_label(r'$\log({\rm SFR} [M_{\odot}/yr)]$',rotation=270)
		pl.text(10,10,r'$'+trunc(_z-zbin/2.,1)+'<z<'+trunc(_z+zbin/2.,1)+'$',bbox=dict(facecolor='0.85', alpha=0.85),fontsize=18)
		pl.savefig('sfr_iz'+trunc(iz,0)+'.png',bbox_inches='tight',dpi=350)
		pl.close(a1)
#		pl.matshow(mean_zcold)

		a2 = pl.figure(2)
		pl.imshow(mean_zcold,extent=[pmin,pmax,tmin,tmax],interpolation='nearest')
		pl.xticks(np.arange(pmin,pmax,10))
		pl.yticks(np.arange(tmin,tmax,10))
		pl.xlabel('deg')
		pl.ylabel('deg')		
		pl.autoscale(False)
示例#38
0
    def plot(self, trace_filters=None, spike_filters=None, xlim=None, ylim=None, legend=False, xlabel=None, xscale=None, fig_trace_kwargs=None, fig_event_kwargs=None):
        import pylab
        import mreorg
        import numpy as np

        trace_filters = trace_filters or []
        spike_filters = spike_filters or []

        fig_trace_kwargs = fig_trace_kwargs or {}
        fig_event_kwargs = fig_event_kwargs or {}

        tr_figs = []
        for filt in trace_filters:
            fig = pylab.figure(**fig_trace_kwargs)
            tr_figs.append(fig)

            trs = self.filter_traces(filt)


            print 'Plotting:', filt, len(trs)
            for res in trs:
                if xlim:
                    time_mask = np.logical_and(
                                    res.raw_data.time_pts>xlim[0],
                                    res.raw_data.time_pts<xlim[1],
                            )
                    time, data = res.raw_data.time_pts[time_mask], res.raw_data.data_pts[time_mask]
                else:
                    time, data = res.raw_data.time_pts, res.raw_data.data_pts

                if xscale is not None:
                    time = time * xscale
                pylab.plot(time, data,'-', label=','.join(res.tags), ms=2 )

            if len(trs)==0:
                pylab.close(fig)

            else:
                pylab.ylabel(filt)
                if legend:
                    pylab.legend()

                if ylim:
                    pylab.ylim(*ylim)
                else:
                    pylab.autoscale(axis='y')
                if xlabel is not None:
                    pylab.xlabel(xlabel)

                mreorg.PM.save_figure(figname=filt)
                mreorg.PM.save_active_figures()


        spike_figs = []
        for filt in spike_filters:
            f2 = pylab.figure(**fig_event_kwargs)
            spike_figs.append(f2)
            #trs = self.filter_events(filt)
            trs = list(it.chain( *[f.filter_events(filt) for f in self.results_files] ) )
            trs = self.filter_events(filt)
            print ' -- plotting:', filt, len(trs)
            for i,res in enumerate(trs):
                evt_times = res.times

                pylab.plot( evt_times, i+ 0*evt_times, 'x', label=','.join(res.tags))
            if xlim:
                pylab.xlim(*xlim)
            pylab.ylabel(filt)
            if legend:
                pylab.legend()
            if ylim:
                pylab.ylim(*ylim)
            else:
                pylab.ylim(0, len(trs))
            mreorg.PM.save_active_figures()

        return tr_figs, spike_figs
示例#39
0
# loadtext actually comes from numpy, which pylab has.
wave,fnu,sig = pylab.loadtxt(infile, skiprows=3, usecols=(0,1,2), unpack=True)

# for plotting purposes, multiply by scale factor to bring to order unity
factor = 1E29
fnu *= factor
sig *= factor

# If continuum file exists, grab it, for later plotting, fitting of EW.
if(os.path.exists(contfile)):
    pixcont, wavcont, concont = numpy.loadtxt(contfile,comments="#", usecols=(0,1,2), unpack=True)
    concont *=factor

 # JRR simplify, just make 1 plot
start =  2600
end = 3700
pylab.plot(wave[start:end], fnu[start:end], lincolor, linestyle='steps')   # plot spectrum
pylab.plot(wave[start:end], sig[start:end], errcolor, linestyle='steps')   # plot 1 sigma uncert spectrum
pylab.autoscale(axis='x', tight=True)

# If continuum file exists, plot the continuum
if(os.path.exists(contfile)):
    this = numpy.where((wavcont > wave[start]) & (wavcont < wave[end]))
    pylab.plot(wavcont[this[0]], concont[this[0]], 'y', linestyle='steps') # plot this portion of the continuum

# Here is where simple linear interpolation of continuum should go, to have continuum values at every wavelength.
# Next, look up the EW formula.  
# Next, define boundaries, where EW goes positive again on either side.
# Next, sum up the EW for every pixel within the boundaries
# Finally, print it up.
示例#40
0
def chooseAnchors(spec, method):
    stime = time.time()
    if method == 1:
        # original
        spec *= spec
        cutoff = args.anchorThresh * np.std(spec)

        t3 = np.where(spec < cutoff)
        t4 = np.where(spec >= cutoff)
        spec[t3] = 0
        print "cutoff val:", cutoff
        print "below cutoff:", len(t3[0])
        print "over cutoff:", len(t4[0])

        tmp = np.delete(spec.flatten(), np.where(spec.flatten() < cutoff))

        if args.showPlots:
            h = np.histogram(tmp, bins=100)
            pylab.bar(h[1][1:], h[0])
            pylab.autoscale()
            pylab.show()

        # return anchor points
        log.info("ChooseAnchor(1) time: %fs" % (time.time() - stime))
        tmp[np.where(tmp > 0)] = 1
        return tmp
    elif method == 2:
        # non squared (Better)
        cutoff = args.anchorThresh * np.std(spec)

        # swing everything positive
        spec = abs(spec)

        belowCut = np.where(spec < cutoff)
        aboveCut = np.where(spec >= cutoff)
        spec[belowCut] = 0
        print "cutoff val:", cutoff
        #print "below cutoff:",len(belowCut[0])
        #print "over cutoff(Anchors):",len(aboveCut[0])

        if args.showPlots:
            spec2 = spec.copy()
            spec2[np.where(spec2 > 0)] = np.log(spec2[np.where(spec2 > 0)])
            img = pylab.imshow(np.transpose(spec2))
            pylab.colorbar(img)
            pylab.show()

        print spec.shape
        #tmp=np.delete(spec,np.where(spec<cutoff))
        spec[np.where(spec < cutoff)] = 0
        spec[np.where(spec >= cutoff)] = 1
        #print tmp.flatten().shape
        #print np.min(tmp), np.max(tmp)

        if args.showPlots:
            print "Final distribution of Anchors:"
            h = np.histogram(tmp, bins=100)
            pylab.bar(h[1][1:], h[0])
            pylab.autoscale()
            pylab.show()

        # return anchor points
        #tmp[np.where(tmp>0)]=1
        log.info("ChooseAnchor(2) time: %fs" % (time.time() - stime))
        return spec
    elif method == 3:
        # method as described in github worldveil/dejavu/fingerprint.py
        # generate binary mask
        binMask = generate_binary_structure(2, 1)
        grownBinMask = iterate_structure(binMask, args.footprintSize)

        filter = maximum_filter(spec, footprint=grownBinMask)
        local_max = filter == spec
        background = (spec == 0)
        eroded_background = binary_erosion(background,
                                           structure=grownBinMask,
                                           border_value=1)

        # Boolean mask of arr2D with True at peaks
        detected_peaks = local_max - eroded_background
        return detected_peaks.astype(int)
    else:
        print "you fail"
        exit()
示例#41
0
    end = race_start+datetime.timedelta(days=1, hours=12)

    import time
    now = time.time()
    print "loading data"
    samples = load_messages(0x402, "Bus Voltage", start, end)
    print "loaded data",
    print "took %s seconds to load %d data points" % (time.time() - now, len(samples))

    now = time.time()
    print "simplifying via vertical line test"
    samples = list(simplify_by_extrema(samples))
    print "simplified to %d data points in %s seconds" % (len(samples), time.time() - now)
    

    now = time.time()
    print "simplifying via ramer-douglas-peucker"
    trans = transform_to_screen(samples, [to_utc(start), to_utc(end)], [40.0, 140.0], 600, 600)
    trans_simple = simplify_ramer_douglas_peucker(list(trans), 2.0)
    samples = list(transform_to_sample(trans_simple, [to_utc(start), to_utc(end)], [40.0, 140.0], 600, 600))

    print "simplified to %d data points in %s seconds" % (len(samples), time.time() - now)
    times =[x[0] for x in samples]
    voltages = [x[1] for x in samples]

    pylab.autoscale(False)
    pylab.plot(times, voltages)
    pylab.axis([start, end, 40.0, 140.0])
    pylab.show()

示例#42
0
ax = pylab.subplot(111)

p1 = ax.bar(x,y, align='center')
pylab.setp(p1, color='#3333B3')

for xx,yy in zip(x,y):
    pylab.annotate('%.2f' % yy, xy=(xx, yy), xytext=(0,2), textcoords='offset points', ha='center', va='bottom', fontproperties=font)

pylab.xticks(x, x, fontproperties=font2)
pylab.yticks(fontproperties=font2)

pylab.title('The percentage of shortest path changes\n for each O-D pair on Chicago Sketch', fontproperties=font2)
pylab.xlabel('Number of times the shortest path for an O-D pair \nchanged 0, 1, 2, 3, $\ldots$, times, out of 26 iterations', fontproperties=font2)
pylab.ylabel('Percentage of total number of O-D pairs', fontproperties=font2)

pylab.autoscale(enable=True, axis='x')
pdf.savefig(fig, bbox_inches='tight')

#------------------------------ 
counts =[]
with open('sp_change_berlin', 'r') as f:
    for line in f:
        o, d, count = map(int, line.split())
        counts.append(count)

x, y = map(list,zip(*Counter(counts).items()))
x = map(lambda t:t-1, x)
y = map(lambda t:100*t/49688.0, y)

x = x[:16]
y = y[:16]
示例#43
0
def plotedi(fn, saveplot=False, component=None):
    edi = MTedi.Edi()
    try:
        edi.readfile(fn)
    except:
        print '\n\tERROR - not a valid EDI file: {0}\n'.format(fn)
        sys.exit()

    # if saveplot is True:
    #     import matplotlib
    # matplotlib.use('Agg')

    import pylab

    lo_comps = []
    if component is not None:
        'n' in component.lower()
        try:
            if 'n' in component.lower():
                lo_comps.append('n')
        except:
            pass
        try:
            if 'e' in component.lower():
                lo_comps.append('e')
        except:
            pass
    if len(lo_comps) == 0:
        lo_comps = ['n', 'e']

    res_te = []
    res_tm = []
    phi_te = []
    phi_tm = []
    reserr_te = []
    reserr_tm = []
    phierr_te = []
    phierr_tm = []

    for r in edi.Z.resistivity:
        res_te.append(r[0, 1])
        res_tm.append(r[1, 0])

    for p in edi.Z.phase:
        phi_te.append(p[0, 1] % 90)
        phi_tm.append(p[1, 0] % 90)

    if pylab.np.mean(phi_te) > 90 and pylab.np.mean(phi_tm) > 90:
        phi_te = [i % 90 for i in phi_te]
        phi_tm = [i % 90 for i in phi_tm]

    for r in edi.Z.resistivity_err:
        reserr_te.append(r[0, 1])
        reserr_tm.append(r[1, 0])
    for p in edi.Z.phase_err:
        phierr_te.append(p[0, 1])
        phierr_tm.append(p[1, 0])

    periods = 1. / edi.freq

    resplotelement_xy = None
    resplotelement_yx = None

    axes = pylab.figure('EDI ' + fn)
    ax1 = pylab.subplot(211)

    if 'n' in lo_comps:
        resplotelement_xy = pylab.errorbar(periods,
                                           res_te,
                                           reserr_te,
                                           marker='x',
                                           c='b',
                                           fmt='x')
    if 'e' in lo_comps:
        resplotelement_yx = pylab.errorbar(periods,
                                           res_tm,
                                           reserr_tm,
                                           marker='x',
                                           c='r',
                                           fmt='x')
    pylab.xscale('log', nonposx='clip')
    pylab.yscale('log', nonposy='clip')
    minval = pylab.min(pylab.min(res_te, res_tm))
    maxval = pylab.max(pylab.max(res_te, res_tm))
    pylab.xlim(0.5 * pylab.min(periods), 2 * pylab.max(periods))

    # ylim([0.1,100])
    pylab.ylim([minval / 10, maxval * 10])

    pylab.autoscale(False)

    pylab.ylabel(r' $\rho$ (in $\Omega m$)')
    pylab.setp(ax1.get_xticklabels(), visible=False)
    # share x only
    ax2 = pylab.subplot(212, sharex=ax1)
    pylab.autoscale(False)

    # ylim(-45,135)
    if 'n' in lo_comps:
        pylab.errorbar(periods, phi_te, phierr_te, marker='x', c='b', fmt='x')
    if 'e' in lo_comps:
        pylab.errorbar(periods, phi_tm, phierr_tm, marker='x', c='r', fmt='x')
    pylab.ylabel('Phase angle ($\degree$)')
    pylab.xlabel('Period (in s)')
    pylab.plot([pylab.xlim()[0], pylab.xlim()[1]], [45, 45], '-.', c='0.7')
    pylab.ylim([-0, 90])

    ax1.legend([resplotelement_xy, resplotelement_yx],
               ['$E_{X}/B_Y$', '$E_Y/B_X$'],
               loc=2,
               ncol=1,
               numpoints=1,
               markerscale=0.8,
               frameon=True,
               labelspacing=0.3,
               prop={'size': 8},
               fancybox=True,
               shadow=False)

    pylab.tight_layout()
    if saveplot is True:

        pylab.ioff()
        outfn = op.splitext(fn)[0] + '.png'
        pylab.savefig(outfn, bbox_inches='tight')
        pylab.close('all')
        pylab.ion()
        return outfn

    else:
        pylab.ion()
        pylab.show(block=True)

        return None
示例#44
0
    cdf = NP.cumsum(hist * delta)

    print(cdf[-1])

    # assert False

    # print(E_series.min())
    # print(E_series.max())

    import pylab as PL

    PL.plot(bin_centers,
            cdf)

    PL.autoscale(axis='x', tight=True)

    PL.show()

    # print(len(E_series))
    # print(E_series.min())
    # print(E_series.max())

    # import pylab as PL
    # PL.hist(E_series.)


    # N = 1024
    # days_to_seconds = 60 * 60 * 24

    # periods = NP.linspace(0.9 * days_to_seconds, 1.1 * days_to_seconds, N)
        score_ts = clf.score(X_ts, Y_ts)

        # Display scores and errors of each set
        if classifier is 'rfc':
            print 'Error from level '+str(l)+' from RandomForestClassifier'
        elif classifier is 'dtc':
            print 'Error from level '+str(l)+' from DecisionTreeClassifier'
        print "LS error: "+str((1-score_ls)*100)+"%"
        print "TS error: "+str((1-score_ts)*100)+"%"
        if classifier is 'dtc':
            print 'Node count: '+str(clf.tree_.node_count)
            print 'Depth of the tree: '+str(depth(clf.tree_))
        print "------------------"
        errors.append((1-score_ts)*100)
     
    pl.xlabel('Levels')
    pl.ylabel('Error (%)') 
    if classifier is 'rfc':
        pl.title(r'Error on TS from RandomForestClassifier (n=1000)')
    elif classifier is 'dtc':
        pl.title(r'Error on TS from DecisionTreeClassifier')  
    pl.bar(np.arange(len(errors)),errors, color='blue', align='center')
    pl.autoscale(tight=True)
    pl.xticks(range(0,15),range(1,16), size='small')
    pl.yticks(range(0,30,5), range(0,30,5), size='small')
    if classifier is 'rfc':
        pl.savefig('mean_error_TS_rfc_game.png')
    elif classifier is 'dtc':
        pl.savefig('mean_error_TS_dtc_game.png')
 
示例#46
0
x = np.random.uniform(0, 4 * np.pi, size=200)
y = np.cos(x) + np.random.random(size=len(x))

#%%
# Compute a lowess smoothing of the data
smoothed = sm.nonparametric.lowess(exog=x, endog=y, frac=0.2)
type(smoothed)  # numpy.ndarray
smoothed.shape  # (200, 2)
smoothed

# Plot the fit line
fig, ax = pylab.subplots()

ax.scatter(x, y)
ax.plot(smoothed[:, 0], smoothed[:, 1], c="k")
pylab.autoscale(enable=True, axis="x", tight=True)

#%%
# Compute a lowess smoothing of the data
smoothed = sm.nonparametric.lowess(exog=x,
                                   endog=y,
                                   xvals=np.linspace(0, 4 * np.pi, 20),
                                   frac=0.2)
type(smoothed)  # numpy.ndarray
smoothed.shape  # (20, )
np.array([np.linspace(0, 4 * np.pi, 20), smoothed])

# Plot the fit line
fig, ax = pylab.subplots()

ax.scatter(x, y)
                    C['spike_syn']), np.std(C['spike_syn'])
                vol_syn[j], st_vol_syn = np.mean(C['vol_syn']), np.std(
                    C['vol_syn'])
                mean[j], st_mean[j] = moments[0], st_moments[0]
                var[j], st_var[j] = moments[1], st_moments[1]
                stdv[j], st_stdv[j] = moments[2], st_moments[2]
                skw[j], st_skw[j] = moments[3], st_moments[3]
                kurt[j], st_kurt[j] = moments[4], st_moments[4]
            else:
                print 'something was wrong'
                exit(0)

colors = ['k', 'maroon', "crimson", "y", 'royalblue', 'magenta']

fig, ax = pl.subplots(nrows=2, ncols=3, figsize=(12, 8))
pl.autoscale(enable=True, axis='y', tight=True)
x = std_noise
ax[0, 0].errorbar(x,
                  vol_syn,
                  yerr=st_vol_syn,
                  fmt='-o',
                  c=colors[0],
                  elinewidth=1,
                  ecolor='g')
ax[1, 0].errorbar(x,
                  spike_syn,
                  yerr=st_spike_syn,
                  fmt='-o',
                  c=colors[1],
                  elinewidth=1,
                  ecolor='g')
def main(experiment):
    swapped = False
    use_geodesic = True

    experiments = dict(
        cat = dict(
            file1 = 'meshes/tosca/cat0.mat',
            file2 = 'meshes/tosca/cat2.mat',
            mu = [0.7],
            Ks = np.arange(10, 50, 5),
        ),
        david = dict(
            file1 = 'meshes/tosca_holes/david0_halfed.obj',
            file2 = 'meshes/tosca_holes/david10_nolegs_nohead.obj',
            mu = [0.7],
            Ks = np.arange(10, 50, 5),
        ),
        hand = dict(
            file1 = 'meshes/hand_868.obj',
            file2 = 'meshes/hand_868_holes2.obj',
            mu = [5.0],
            Ks = np.arange(10, 50, 2),
        ),
    )
    if experiment not in experiments:
        print "Usage: python %s <experiment>" % sys.argv[0]
        print "where experiment is one of: %s" % (', '.join(experiments.keys()))
        sys.exit(1)

    exp = experiments[experiment]
    file1, file2 = exp['file1'], exp['file2']
    mu, Ks = exp['mu'], exp['Ks']

    print "this will take a while..."

    # load meshes
    verts1, tris1, verts2, tris2, ij = load_shape_pair(file1, file2, check=False, normalize=False)
    if swapped: # swapped?
        verts2, tris2, verts1, tris1 = verts1, tris1, verts2, tris2
        ij = ij[:,::-1]

    if use_geodesic:
        D = compute_geodesic_distance_matrix(verts1, tris1)

    eigenvector_algorithms = [
        ('MHB', partial(cmm.manifold_harmonics, scaled=False)),
    ]

    for cmu in mu:
        name = 'CMHB' if len(mu) == 1 else 'CMHB %f' % (cmu)
        eigenvector_algorithms.append(
            (name, partial(
                cmm.compressed_manifold_modes, 
                mu=cmu, maxiter=10000, verbose=0, scaled=False)))

    mapping_algorithms = [
        ('rotation', partial(align.optimal_rotation, allow_reflection=True)),
        #('permutation', partial(align.optimal_permutation, allow_reflection=True)),
    ]

    print "computing basis functions (first mesh)"
    runs = [(K, name, algo) for K in Ks for name, algo in eigenvector_algorithms]
    Phis1 = Parallel(-1)(
        delayed(algo)(verts1, tris1, K)
        for K, name, algo in runs)
    print "computing basis functions (second mesh)"
    Phis2 = Parallel(-1)(
        delayed(algo)(verts2, tris2, K)
        for K, name, algo in runs)

    # run for different number of eigenfunctions K
    errors_per_mapping_algorithm = defaultdict(lambda: defaultdict(list))
    C_by_mapping_algorithm = defaultdict(lambda: defaultdict(list))
    for (K, eigenvector_algorithm_name, algo), Phi1, Phi2 in zip(runs, Phis1, Phis2):
        for mapping_algorithm_name, mapping_algorithm in mapping_algorithms:
            # compute the mapping between the eigenfunctions
            C = mapping_algorithm(Phi1[ij[:,0]].T, Phi2[ij[:,1]].T)
            Phi1_rot = np.dot(C, Phi1.T).T

            # for all points in shape 2 where there is a correspondence to shape 1 (all j),
            # find corresponding point i in shape 1
            tree = cKDTree(Phi1_rot)
            distance_eigenspace, nearest = tree.query(Phi2[ij[:, 1]])
            ij_corr = np.column_stack((ij[:,0], nearest))

            # compute error
            if use_geodesic:
                errors = D[ij_corr[:,0], ij_corr[:,1]]
            else:
                errors = veclen(verts1[ij_corr[:, 0]] - verts1[ij_corr[:,1]])
            mean_error = np.mean(errors)
            errors_per_mapping_algorithm[mapping_algorithm_name][eigenvector_algorithm_name].append(mean_error)
            C_by_mapping_algorithm[mapping_algorithm_name][eigenvector_algorithm_name].append(C)
            print "%s/%s (K=%d) %.2f" % (mapping_algorithm_name, eigenvector_algorithm_name, K, mean_error)

    for mapping_algorithm_name, C_by_trial in C_by_mapping_algorithm.iteritems():
        for trial_name, Cs in C_by_trial.iteritems():
            # just use the last rotation matrix computed
            C = Cs[-2]
            pl.figure(mapping_algorithm_name + '_' + trial_name, figsize=(4,3.5))
            plot_functional_map(reorder_functional_map(C), newfig=False)
            pl.subplots_adjust(left=0.01, right=1, top=0.95, bottom=0.05)

    show_correspondence(
        verts1, tris1, verts2, tris2, ij, 
        points=5, color_only_correspondences=True,
        colormap='Paired', #offset_factor=(-1.8, +0.0, 0.),
        show_spheres=False, blend_factor=1.0, block=False)

    for mapping_algorithm_name, errors_per_trial in errors_per_mapping_algorithm.iteritems():
        #pl.rcParams.update({'font.size': 6})
        pl.figure(mapping_algorithm_name + '_' + file1 + '_' + file2, figsize=(2.5,2.5))
        pl.rc('text', usetex=False)
        style_by_name = dict(
            CMHB=dict(c=(6/255., 50/255., 100/255.), lw=2),
            MHB=dict(c=(121/255., 6/255., 34/255.), lw=1)
        )
        for trial_name, errors in sorted(errors_per_trial.items(), key=lambda (k,v): k):
            print trial_name, errors
            style = style_by_name.get(trial_name, {})
            pl.plot(Ks, errors, label=trial_name, **style)
        pl.locator_params(nbins=4)
        pl.legend().draggable()
        pl.autoscale(tight=True)
        pl.ylim(bottom=0)
        pl.grid()
        pl.xlabel(r'$K$')
        pl.ylabel(r'geodesic error')
        pl.tight_layout()
    pl.show()
示例#49
0
    def draw2D_new(self, title, image=[]):
        tt=np.array(self.image.shape)/50.
        pylab.figure(figsize=tt, dpi=50.)
        if image == []:
            pylab.imshow(self.image, 'gray')
        else:
            pylab.imshow(image, 'gray')
        pylab.axis('off')
        pylab.autoscale(False)
        for i in xrange(self.nComponents):

            k1 = np.array([[self.params[6 * i + 3] ** 2, self.params[6 * i + 3] * self.params[6 * i + 4] * self.params[6 * i + 5]],
                           [self.params[6 * i + 3] * self.params[6 * i + 4] * self.params[6 * i + 5], self.params[6 * i + 4] ** 2]])
            w1, v1 = np.linalg.eig(k1)
            idx = w1.argsort()
            w1 = w1[idx]
            v1 = v1[:, idx]
            angle=-(np.arctan(v1[1][1]/v1[0][1]))+np.pi#x+2*(pi/4-x)+pi/2#since in the image X and Y are inverted, so need to minus 90 degree and flip around pi/4
            #print angle
            w2 = np.zeros((1 , 2))
            w2[0,1] = np.sqrt(2)*np.max([self.params[6 * i + 3], self.params[6 * i + 4]])
            w2[0,0] = w2[0,1]*w1[0]/w1[1]

            xeq = lambda t: w2[0,1] * np.cos(t) * np.cos(angle) + w2[0,0] * np.sin(
                t) * np.sin(angle) + self.params[6 * i + 1]
            yeq = lambda t: - w2[0,1] * np.cos(t) * np.sin(angle) + w2[0,0] * np.sin(
                t) * np.cos(angle) + self.params[6 * i + 2]
            t = np.linspace(0, 2 * np.pi, 100)
            x = xeq(t)
            y = yeq(t)
            pylab.scatter(self.params[6 * i + 2], self.params[6 * i +1], color=self.colors[i], s=2)
            pylab.plot(y.astype(int), x.astype(int), self.colors[i] + '-')

            pylab.plot([self.params[6 * i + 2], yeq(0)],[self.params[6 * i + 1],xeq(0)],self.colors[i]+'-')
            #draw for inipara before optimization
            k1 = np.array([[self.inipara[6 * i + 3] ** 2, self.inipara[6 * i + 3] * self.inipara[6 * i + 4] * self.inipara[6 * i + 5]],
                           [self.inipara[6 * i + 3] * self.inipara[6 * i + 4] * self.inipara[6 * i + 5], self.inipara[6 * i + 4] ** 2]])
            w1, v1 = np.linalg.eig(k1)
            idx = w1.argsort()
            w1 = w1[idx]
            v1 = v1[:, idx]
            angle=-(np.arctan(v1[1][1]/v1[0][1]))+np.pi#x+2*(pi/4-x)+pi/2#since in the image X and Y are inverted, so need to minus 90 degree and flip around pi/4

            w2 = np.zeros((1 , 2))
            w2[0,1] = np.sqrt(2)*np.max([self.inipara[6 * i + 3], self.inipara[6 * i + 4]])
            w2[0,0] = w2[0,1]*w1[0]/w1[1]

            xeq = lambda t: w2[0,1] * np.cos(t) * np.cos(angle) + w2[0,0] * np.sin(
                t) * np.sin(angle) + self.inipara[6 * i + 1]
            yeq = lambda t: - w2[0,1] * np.cos(t) * np.sin(angle) + w2[0,0] * np.sin(
                t) * np.cos(angle) + self.inipara[6 * i + 2]
            t = np.linspace(0, 2 * np.pi, 100)
            x = xeq(t)
            y = yeq(t)
            x=x[0::5]
            y=y[0::5]
            pylab.scatter(self.inipara[6 * i + 2], self.inipara[6 * i +1], color=self.colors[i], s=1)
            pylab.plot(y.astype(int), x.astype(int), self.colors[i] + '--')

            pylab.plot([self.inipara[6 * i + 2], yeq(0)],[self.inipara[6 * i + 1],xeq(0)],self.colors[i]+'-')

        if self.nComponents==3:
            minind=np.argmin([np.linalg.norm(self.params[1:3]-self.params[7:9]),np.linalg.norm(self.params[1:3]-self.params[13:15]),np.linalg.norm(self.params[7:9]-self.params[13:15])])
            if minind==0:
                cenind=[1,7]
            elif minind==1:
                cenind=[1,13]
            else:
                cenind=[7,13]
            pylab.plot([self.params[cenind[0]+1],self.params[cenind[1]+1]], [self.params[cenind[0]],self.params[cenind[1]]], '-m')
        pylab.savefig(title,bbox_inches='tight', pad_inches=0)
        pylab.close()
示例#51
0
for i in range(expert.cluster_num):
    expert.plot_model(partition=i, show_plot=False, save_fig_folder=folder_name) #(i==expert.cluster_num-1))

pl.figure(expert.cluster_num+1)
pl.plot(prediction_error_history)
pl.title("Prediction Error History")
pl.xlabel("time")
pl.ylabel("Prediction Error")
save_figure.save(folder_name+"/Prediction Error History")

pl.figure(expert.cluster_num+2)
pl.hist(state1_history)
pl.title("Resultant State Histogram")
pl.xlabel("State")
pl.ylabel("# of Occurrence")
pl.autoscale(True)
save_figure.save(folder_name+"/Resultant State Histogram")

pl.figure(expert.cluster_num+3)
pl.hist2d(state0_history, action0_history)
pl.title("Initial State vs Initial Action Histogram")
pl.xlabel("State")
pl.ylabel("Action")
pl.colorbar()
save_figure.save(folder_name+"/Initial State vs Initial Action Histogram")

#print("Most common Action")
def most_common(lst):
    return max(set(lst), key=lst.count)
bin_num = 100
bin_size = int(len(action0_history)/bin_num)
示例#52
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-

import pylab as pl
import numpy as np

weka = [0, 0, 1.5, 0.5, 9, 0, 0, 3, 0, 0.5, 5, 14, 15.5, 2, 12]

# Main
if __name__ == "__main__":
    pl.xlabel('Levels')
    pl.ylabel('Error (%)')
    pl.title(
        r'Error on 10-fold cross-validation with functional tree from Weka')
    pl.bar(np.arange(len(weka)), weka, color='blue', align='center')
    pl.autoscale(tight=True, axis='x')
    pl.xticks(np.arange(0, 15), range(1, 16), size='small')
    pl.yticks(range(0, 55, 5), range(0, 55, 5), size='small')
    pl.savefig('weka_ft_game.png')
    pl.savefig('weka_ft_game.eps')
示例#53
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-

import pylab as pl
import numpy as np

databases = ['IRIS','BREASTCANCER','PIMA','VEHICLE','LANDSAT']
weka = [5,2.86,23.29,22.45,14.18]

# Main
if __name__ == "__main__":
    pl.xlabel('Databases')
    pl.ylabel('Error (%)')
    pl.title(r'Error on 10-fold cross-validation with functional tree from Weka')
    pl.bar(np.arange(len(weka)),weka, color='blue', align='center')
    pl.autoscale(tight=True, axis='x')
    pl.xticks(range(len(databases)),databases, size='small')
    pl.yticks(range(0,70,5), range(0,70,5), size='small')
    pl.savefig('weka_ft_learning.png')
    pl.savefig('weka_ft_learning.eps')
示例#54
0
文件: GFP.py 项目: macyli01/livespin
    def getGFPband(self, name='', time=-1, width=70, plot=True, save=True):
        results = []
        for index, im in enumerate(self.images):
            dx, dy = np.indices(im.shape)
            c1 = (int(self.params[index][1]), int(self.params[index][2]))
            c2 = (int(self.params[index][1 + 6]),
                  int(self.params[index][2 + 6]))
            center = [(self.params[index][1] + self.params[index][1 + 6]) / 2.,
                      (self.params[index][2] + self.params[index][2 + 6]) / 2.]
            product = (dx - c1[0]) * (c2[1] - c1[1]) + (dy - c1[1]) * (c1[0] -
                                                                       c2[0])
            orthProduct = (dx - c1[0]) * (c1[0] - c2[0]) + (dy - c1[1]) * (
                c1[1] - c2[1])
            distance = np.sqrt((dx - c1[0])**2 +
                               (dy - c1[1])**2) * np.sign(orthProduct)
            product = np.abs(product)
            mask = np.zeros(im.shape)
            mask[product < np.percentile(product, 5)] = 1
            X = distance[mask == 1].flatten()
            Y = im.image[mask == 1].flatten()
            Z = zip(X, Y)
            Z.sort()
            Xsort, Ysort = zip(*Z)
            Xsort = np.array(Xsort)
            c1proj = np.argmax(Xsort == 0)
            c2proj = np.argmax(Xsort == distance[c2[0], c2[1]])

            try:
                s = Sequence(Ysort, [c1proj, c2proj], r=width)
                s.hScale()
                out = s.vScale()

            except IndexError:
                out = np.zeros(2 * width)
                #print "--- debug ---"
            if plot:
                pylab.figure(figsize=(17, 6))
                pylab.subplot(1, 3, 2)
                pylab.imshow(distance * mask)
                pylab.title("Distance")
                pylab.autoscale(False)
                pylab.axis('off')
                pylab.plot(self.params[index][2::6],
                           self.params[index][1::6],
                           'ro',
                           label="centres des cellules")
                pylab.legend(numpoints=1)
                pylab.subplot(1, 3, 1)
                pylab.title("GFP")
                pylab.imshow(im.image, 'gray')
                pylab.autoscale(False)
                pylab.axis('off')
                pylab.plot(self.params[index][2::6],
                           self.params[index][1::6],
                           'ro',
                           label="centres des cellules")
                pylab.legend(numpoints=1)

                pylab.subplot(1, 3, 3)
                pylab.plot(Ysort, 'r')
                pylab.axvline(x=c1proj)
                pylab.axvline(x=c2proj)
                pylab.xlabel("Distance")
                pylab.ylabel("Fluorescence (GFP)")

                if save:
                    pylab.savefig("{0}_t{1:02d}.png".format(
                        name, time + index))
                else:
                    pylab.show()
                pylab.close('all')
            results.append(out)

        return results, c1, c2
示例#55
0
    def divideangle(self, tSelect): # compute division angle after detecting cell division

        if tSelect > 0 and tSelect < len(self.listObj):
            params2 = self.listObj[tSelect][0].params
            params3 = self.listObj[tSelect][1].params
            angleFind = angle.AngleFinder(3, params3)
            a, distDaughtercells, rightOrder = angleFind.getAngle_gaussian()

            th_dist=25
            if rightOrder and (distDaughtercells <= th_dist):

                #fileout.write(",TAU{0},ORDER{1},DIST{2},T{3},A{4}\n".format(traj.tau, str(rightOrder)[0], distDaughtercells, tSelect, a))
                plotflag=1
                if plotflag:
                    pylab.figure()
                    for indexIm in range(-2, 1):
                        pylab.subplot(2, 3, indexIm+3)
                        if tSelect+indexIm > 0:

                            imfilePrevious = glob("edga_*_t{0:04d}.tif".format(tSelect+indexIm))
                            try:
                                imagePrevious = cv2.imread(imfilePrevious[0], cv.CV_LOAD_IMAGE_UNCHANGED)
                                if len(imagePrevious.shape) == 3:
                                    print imagePrevious.shape, len(imagePrevious.shape)
                                    imagePrevious = imagePrevious[:,:,0]
                                pylab.imshow(imagePrevious, 'gray')
                                pylab.axis('off')
                            except IndexError:
                                print "no image at ", "edga_*s{0}_t{1:04d}.tif".format( 'dir', tSelect+indexIm)
                                pass
                            pylab.title("t = {0}".format(tSelect+indexIm))
                    imfile = glob("edga_*_t{0:04d}.tif".format(tSelect+indexIm))
                    if len(imfile) > 1:
                        print "too many images"
                        raise IndexError
                    try:
                        image = cv2.imread(imfile[0], cv.CV_LOAD_IMAGE_UNCHANGED)
                        if len(image.shape) == 3:
                            image = image[:,:,0]
                        pylab.subplot(2,3,4)
                        pylab.imshow(image, 'gray')
                        pylab.axis('off')
                        pylab.autoscale(False)
                        angleFind.draw()
                        pylab.title("angle={0:.0f} degree".format(a*180./np.pi))
                        pylab.subplot(2,3,5)
                        pylab.imshow(image, 'gray')
                        pylab.axis('off')
                        pylab.autoscale(False)
                        angleFind.draw2D_new()
                        pylab.subplot(2,3,6)
                        pylab.imshow(image, 'gray')
                        pylab.axis('off')
                        pylab.autoscale(False)
                        GaussClasses.GaussianObject(2, params=params2).draw2D_new()
                    except IndexError:
                        print "no image at : ", "edga_*s{0}_t{1:04d}.tif".format('dir', tSelect+indexIm)
                    pylab.title("t = {0}".format(tSelect))
                    #pylab.legend()
                    #pylab.savefig("../angle_s{0}_x{1:03d}_y{2:03d}_t{3:03d}.png".format('dir', int(x), int(y), int(tSelect)))
                    pylab.savefig("../angle_t{0:03d}.png".format(int(tSelect)))
                    pylab.close()
            return a*180./np.pi
示例#56
0
    def getGFPband(self, name = '', time = -1, width = 70, plot = True, save = True):
        results = []
        for index, im in enumerate(self.images):
            dx, dy = np.indices(im.shape)
            c1 = (int(self.params[index][1]), int(self.params[index][2]))
            c2 = (int(self.params[index][1+6]), int(self.params[index][2+6]))
            center = [(self.params[index][1] + self.params[index][1+6])/2., (self.params[index][2] + self.params[index][2+6])/2.]
            product = (dx -c1[0])*(c2[1] - c1[1]) + (dy - c1[1])*(c1[0] - c2[0])
            orthProduct = (dx -c1[0])*(c1[0] - c2[0]) + (dy - c1[1])*(c1[1] - c2[1])
            distance = np.sqrt((dx - c1[0])**2 + (dy - c1[1])**2) * np.sign(orthProduct)
            product = np.abs(product)
            mask = np.zeros(im.shape)
            mask[product < np.percentile(product, 5)] = 1
            X = distance[mask == 1].flatten()
            Y = im.image[mask == 1].flatten()
            Z = zip(X, Y)
            Z.sort()
            Xsort, Ysort = zip(*Z)
            Xsort = np.array(Xsort)
            c1proj = np.argmax(Xsort == 0)
            c2proj = np.argmax(Xsort == distance[c2[0], c2[1]])
            
            try:
                s = Sequence(Ysort, [c1proj, c2proj], r = width)
                s.hScale()
                out = s.vScale()

            except IndexError:
                out = np.zeros(2*width)
                #print "--- debug ---"
            if plot:
                pylab.figure(figsize = (17,6))
                pylab.subplot(1,3,2)
                pylab.imshow(distance*mask)
                pylab.title("Distance")
                pylab.autoscale(False)
                pylab.axis('off')
                pylab.plot(self.params[index][2::6], self.params[index][1::6], 'ro', label = "centres des cellules")
                pylab.legend(numpoints = 1)
                pylab.subplot(1,3,1)
                pylab.title("GFP")
                pylab.imshow(im.image, 'gray')
                pylab.autoscale(False)
                pylab.axis('off')
                pylab.plot(self.params[index][2::6], self.params[index][1::6], 'ro', label = "centres des cellules")
                pylab.legend(numpoints = 1)

                pylab.subplot(1,3,3)
                pylab.plot(Ysort, 'r')
                pylab.axvline(x = c1proj)
                pylab.axvline(x = c2proj)
                pylab.xlabel("Distance")
                pylab.ylabel("Fluorescence (GFP)")

                if save:
                    pylab.savefig("{0}_t{1:02d}.png".format(name, time+index))
                else:
                    pylab.show()
                pylab.close('all')
            results.append(out)
            
        return results, c1, c2