コード例 #1
0
def day_plot(time_idx,
             x,
             title='',
             step=1,
             color='k',
             scale_sig=True,
             savefig=False):
    if time_idx is 'default':
        time_idx = list(range(len(x)))
    plt.figure()
    plt.rc('text', usetex=True)
    for ri, row in enumerate(x):
        current_step = ri * step
        y = x[ri, :]
        scaled = scale1(y)
        shifted = scaled + current_step
        if (x.shape[1] == len(time_idx)):
            plt.plot(time_idx, shifted, color)
        else:
            plt.plot(shifted, color)
    plt.ylim([-1, x.shape[0] * step])
    plt.ylabel('Channels')
    plt.xlabel('Time (s)')
    plt.title(title)
    plt.show()
    if savefig:
        plt.savefig('%s.pdf' % title)
    plt.close()
コード例 #2
0
ファイル: evaluate.py プロジェクト: 724686158/ryuMonitor
    def partial_autocorrelation(self):
        plt.rc('font', family='serif', serif='Times')
        plt.rc('text', usetex=True)
        plt.rc('xtick', labelsize=8)
        plt.rc('ytick', labelsize=8)
        plt.rc('axes', labelsize=8)

        # width as measured in inkscape
        width = 2.987
        height = width / 1.618

        fig, ax = plt.subplots()
        fig.subplots_adjust(left=.18, bottom=.19, right=.99, top=.97)

        # Plot PACF:
        lag_pacf = pacf(self.test, nlags=20, method='ols')
        # plt.subplot(122)
        plt.plot(lag_pacf)
        plt.axhline(y=0, linestyle='--', color='gray')
        plt.axhline(y=-1.96 / np.sqrt(len(self.test)),
                    linestyle='--',
                    color='gray')
        plt.axhline(y=1.96 / np.sqrt(len(self.test)),
                    linestyle='--',
                    color='gray')
        # plt.title('Partial Autocorrelation Function')

        # ax.grid(zorder=0)

        ax.set_ylabel('Partial Autocorrelation')
        ax.set_xlabel('Lag')

        fig.set_size_inches(width, height)
        fig.savefig('partial.pdf')
コード例 #3
0
def plot_barhist(df, y):
    plt.rc('font', family='serif')
    # matplotlib.rcParams['ps.useafm'] = True
    # matplotlib.rcParams['pdf.use14corefonts'] = True
    # matplotlib.rcParams['text.usetex'] = True
    matplotlib.rcParams['pdf.fonttype'] = 42

    col_order = _PROBLEMS
    order = [rename_scheme(s) for s in _SCHEMES]
    g = sns.catplot(x='scheme',
                    y=y,
                    col=None,
                    data=df,
                    kind='bar',
                    col_order=col_order,
                    order=order,
                    palette=sns.color_palette(['orangered'] * 4 +
                                              ['dodgerblue'] * 3))
    g.set_xticklabels(rotation=30, ha='right')
    plt.ylim(bottom=.75, top=1.)
    locs, _ = plt.yticks()
    labels = []
    for l in locs:
        labels.append('{:.0f}%'.format(l * 100.))
    plt.yticks(locs, labels)
    plt.tight_layout()
コード例 #4
0
def FeaturesRelationsLoop(Relationships, Features):
    
    """Function to plot the correlations between the classifiers features
    
    -Inputs:
            Relationships: Features correlations
            Features: Name of the feautures used, string."""
    
    #Plotting
    SMALL_SIZE = 17
    MEDIUM_SIZE = 10
    BIGGER_SIZE = 12

    plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
    plt.rc('axes', titlesize=SMALL_SIZE)     # fontsize of the axes title

    for n in range(4):
        for m in range(3):    
            plt.subplots()
            axes = plt.gca()
            tempvar='subject' + str((m+1)+(n*3))
            axes.set_xlim([0,Relationships[tempvar].shape[0]-1])
            axes.set_ylim([0,Relationships[tempvar].shape[0]-1])
            plt.grid()
            plt.ylabel('EEG ' + Features + ' features')
            plt.xlabel('EEG ' + Features + ' features')
            plt.title('Subject ' + str((m+1)+(n*3)) + ' features correlation')
            gra = plt.imshow(abs(Relationships[tempvar]), cmap='jet')
            cbar = plt.colorbar(gra, ticks=[0, 1], orientation='vertical')
            plt.show()
コード例 #5
0
ファイル: project.py プロジェクト: sakisakichen/CIS9650
def plot_corr_btw_walc_n_dalc(df):
    '''
    Walc & Dalc
    Also, we find the correlation coefficient between 'Walc' and 'Dalc' was high. 
    We used the bar chart to visualize their distribution, 
        and found although both Walc and Dalc had an increase pattern, 
    the distribution seemed to be a little different. 
    After level 2, the Dalc dropped dramatically than Walc.
    Therefore, we chose to keep both variables.
    '''
    fname = 'corr_btw_walc_n_dalc.png'
    print('(2) Save ' + fname + ': correlation between walc and dalc\n')\

    # Bar charts of Walc & Dalc
    plt.rc('figure', figsize=(10, 5))
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 2, 1)
    walc = df['Walc'].value_counts()
    walc = pd.DataFrame(walc)
    ax1.set_title('Weekly Alchocol Consumption Distribution')
    plt.ylabel('Count of Walc')
    plt.xlabel('Walc')
    ax1.bar(walc.index, walc['Walc'], color='Brown')

    ax2 = fig.add_subplot(1, 2, 2)
    dalc = df['Dalc'].value_counts()
    dalc = pd.DataFrame(dalc)
    ax2.set_title('Daily Alchocol Consumption Distribution')
    plt.ylabel('Count of Dalc')
    plt.xlabel('Dalc')
    ax2.bar(dalc.index, dalc['Dalc'], color='indianred')

    plt.savefig(fname)
コード例 #6
0
    def plot_Scat_function_candidates(self):

        allThetas = GetThetas.returnallThetas()

        angles = np.arange(0, 179, 0.5)

        val90 = self.Scat_function_value(500, 90)
        SvalsNorm = [self.Scat_function_value(500, i) / val90 for i in angles]

        plt.rc('text', usetex=True)
        plt.rc('font', family='serif')
        plt.plot(angles, SvalsNorm, color='g')
        plt.axvline(x=153.6, color='b')
        plt.axvline(x=143.1, color='b')
        plt.axvline(x=144.4, color='b')
        plt.axvline(x=155.7, color='b')
        plt.axvline(x=164, color='b', label='Candidates')

        plt.axvline(x=48,
                    linestyle='dashed',
                    color='r',
                    label=r'Brightnest Known SNR LE Example')

        #plt.axvspan(30,110,color='k',alpha=0.25,label='Observed LEs from Literature')
        plt.hist(allThetas)

        plt.xlabel(r'$\theta$', fontsize=20)
        plt.ylabel(r'Scattering Efficiency (Norm. to 90$^o$)', fontsize=20)

        plt.legend(loc='upper right', fontsize=16)
        plt.yscale('log')
コード例 #7
0
def display_TwoHopSchemes(two_hop_schemes, pathString):
    '''
    Produce a graph that compare ... 
    '''
    self = two_hop_schemes

    pylab.rc('axes', linewidth=2) # make the axes boundary lines bold 
    #fig, ax = plt.subplots()
    fig = plt.figure()
    ax = fig.add_axes([0.1, 0.1, 0.7, 0.7]) # left, bottom, width, height (range 0 to 1)
    rr.plot( self.region_CF_ICFsch3, 'red', lw=8, axes=ax, label='CF + ICF')
    rr.plot( self.region_DFIntegerCoeff_FCo, 'c', lw=4, axes=ax, label='DF + FCo')
    rr.plot( self.region_noInterference, 'blue', lw=2, axes=ax, label='Free Interf.')  
    
    
    fig.suptitle('$g ={},{},{},{}$'.format(self.g13, self.g14, self.g23, self.g24), fontsize=14, fontweight='bold')
    ax.set_title(r'$P_s=P_1=P_2={}, \, P_3={}, \, P_4={}, \, N=1$'.format(self.Ps, self.P3, self.P4),fontdict=self.font)
    
    ax.set_xlabel('$R_1$', fontdict=self.font)
    ax.set_ylabel('$R_2$', fontdict=self.font)
    #ax.set_xlim(xmin=0, xmax=3.5) 
    #ax.set_ylim(ymin=0, ymax=3.5) 
    ax.legend(loc=0)
    
    # savefig.save(path='{}compare_TwoHop_Schemes/PsP3P4_{}_{}_{}_g_{}_{}_{}_{}'.format(pathString, self.Ps, self.P3, self.P4, self.g13, self.g14, self.g23, self.g24), ext='pdf', close=False, verbose=True)    
    
    nameStr = 'PsP3P4_{}_{}_{}_g13g14g23g24_{}_{}_{}_{}'.format(self.Ps, self.P3, self.P4, self.g13, self.g14, self.g23, self.g24)
    savefig.save(path='{}compare_TwoHop_Schemes/{}'.format(pathString, nameStr), ext='pdf', close=False, verbose=True)
    
        
        
コード例 #8
0
def plotpowerspectrum(t, y, t1, t2, Fs, fileprefix):

    '''
    plot powerspectrum of time-series data between t1 and t2 and save plot to .png file
    '''
    
    filename = fileprefix + '_powerspectrum.png'
        
    # find indices for tlow, thigh
    n1 = np.where(t>=t1)[0]
    n2 = np.where(t>=t2)[0]
 
    # calculate welch estimate of power spectrum
    N = n2[0]-n1[0]+1;
    seglength = np.int(N/8.)
    f, P = scipy.signal.welch(y[n1[0]:n2[0]], fs=Fs, window='hanning', nperseg=seglength)
    
    # plot power spectrum
    plt.figure()
    plt.rc('text', usetex=True)
    plt.tick_params(labelsize=20)
    plt.loglog(f, P, linewidth=2)
    plt.xlabel('frequency (Hz)', size=22)
    plt.ylabel('power spectral density (1/Hz)', size=22)
    plt.grid(True)
    plt.savefig(filename, bbox_inches='tight', dpi=400)
    
    return
コード例 #9
0
    def plot_param_by_run(self, bins, h, lbl, logscale=False, ax=None):

        #runs = np.linspace(self.runs[0]-0.5, self.runs[-1]+0.5, self.nrun+1)
        runs = np.linspace(0.5, self.nrun + 0.5, self.nrun + 1)
        hmn = np.min(h[h > 0])
        hmn = 1e-4

        y, x = np.meshgrid(runs, bins, indexing='ij')

        plt.rc('text', usetex=True)
        plt.rc('font', family='serif', size=16)

        if ax is None:
            fig = plt.figure(figsize=(16, 4))
            ax = fig.gca()

        cmap = plt.get_cmap()
        cmap.set_bad(cmap(0))

        ax.pcolor(x, y, h, norm=LogNorm(), vmin=hmn, cmap=cmap)
        if logscale:
            ax.set_xscale('log')
        ax.set_ylim(self.nrun + 0.5, 0.5)

        ax.set_xlabel(lbl)
        ax.set_ylabel("run")

        #ax.get_xaxis().set_major_formatter(LogFormatterExponent())
        #ax.get_xaxis().set_minor_formatter(ScalarFormatter())

        ax.set_yticks(runs[:-1] + 0.5)
        ax.set_yticklabels(self.runs, fontsize=14)
コード例 #10
0
ファイル: graphics.py プロジェクト: rubmary/regret-matching
def make_plot(path_input, path_graph, proc, name, x_val):
    file = open(path_input)
    i = 0
    regret1 = []
    regret2 = []
    while i < MAX_VAL:
        line = file.readline()
        if not line:
            break
        regret1.append(float(line.split()[0]))
        regret2.append(float(line.split()[1]))
        i = i + 1

    file.close()

    if x_val == -1:
        x_val = i

    plt.rc('font', size=BIGGER_SIZE, family='serif')
    plt.figure()
    plt.title(proc + ': ' + name)
    plt.xlim(1, x_val)
    plt.xscale('log')
    plt.plot(regret1, label='Jugador 1')
    plt.plot(regret2, label='Jugador 2')
    if (proc == 'A'):
        plt.ylabel('Regret (max)')
    plt.xlabel('Iteraciones')
    plt.legend()
    plt.subplots_adjust(bottom=0.15, left=0.15, right=0.85)
    plt.savefig(path_graph)

    return x_val
コード例 #11
0
def display(oneSimulation,pathString, separate=False ,saveOnly=True):
    '''
    show/save figures
    '''
    self = oneSimulation

    pylab.rc('axes', linewidth=2) # make the axes boundary lines bold 
    #fig, ax = plt.subplots()
    fig = plt.figure()
    ax = fig.add_axes([0.1, 0.1, 0.7, 0.7]) # left, bottom, width, height (range 0 to 1)
    if separate:
        rr.plot( self.df_Region, 'red', lw=6, axes=ax, label='DF')
        rr.plot( self.cf_Region, 'blue', lw=4, axes=ax, label='CF')  
        rr.plot( self.fco_Region, 'red', lw=6, axes=ax, label='DF')
        rr.plot( self.icf_Region_bigR1, 'blue', lw=4, axes=ax, label='ICF')  
        rr.plot( self.icf_Region_bigR2, 'blue', lw=4, axes=ax)
    
    rr.plot(self.df_fco_region, 'red', lw=6, label='DF+FCo')
    rr.plot(self.cf_icf_region, 'blue', lw=4, label='CF+ICF')
    fig.suptitle('$g ={},{},{},{}$'.format(self.g13, self.g14, self.g23, self.g24), fontsize=14, fontweight='bold')
    ax.set_title(r'$P_s=P_1=P_2={}, \, P_3={}, \, P_4={}, \, N=1$'.format(self.Ps,
                 self.P3, self.P4),fontdict=self.font)
    
    ax.set_xlabel('$R_1$', fontdict=self.font)
    ax.set_ylabel('$R_2$', fontdict=self.font)
    #ax.set_xlim(xmin=0, xmax=3.5) 
    #ax.set_ylim(ymin=0, ymax=3.5) 
    ax.legend(loc=0)
    
    nameStr = 'PsP3P4_{}_{}_{}_g13g14g23g24_{}_{}_{}_{}'.format(self.Ps, self.P3, self.P4, 
                                                                self.g13, self.g14, self.g23, self.g24)
    savefig.save(path='{}/plots_CF_ICF__DF_FCo/{}'.format(pathString, nameStr), ext='pdf', close=saveOnly, verbose=True)        
        
コード例 #12
0
def Plotting_ROCcurve(events, fpr, tpr, roc_auc):

    """Function to plot the ROC curves and the area under the ROC curves
    
    -Inputs:
        events  -> Name of the events of interst to classify
        fpr   -> False positive rate
        tpr -> True positive rate
        roc_auc -> ROC area under the curves """

    #Plotting
    SMALL_SIZE = 10
    MEDIUM_SIZE = 15
    BIGGER_SIZE = 12

    plt.rc('font', size=MEDIUM_SIZE)          # controls default text sizes
    plt.rc('axes', titlesize=MEDIUM_SIZE)     # fontsize of the axes title
    plt.rc('xtick', labelsize=MEDIUM_SIZE)     # fontsize of the axes title
    plt.rc('ytick', labelsize=MEDIUM_SIZE)     # fontsize of the axes title
    plt.rc('legend', fontsize=SMALL_SIZE)          # controls default text sizes
    
    plt.figure()
    lw = 2
    for k in range(len(events)):
        plt.plot(fpr[k], tpr[k], lw=lw, label='ROC curve ' +  events[k] + ' (area = %0.2f)' % roc_auc[k])
    plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.0])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver operating characteristic curves')
    plt.legend(loc="lower right")

    plt.show()
コード例 #13
0
def makeAnimation(Simulation=None,
                  diagsXT=None,
                  fps=60,
                  repeat=True,
                  dx=50,
                  dt=60):
    if Simulation == None:
        return

    if diagsXT == None:
        from .diagXT import calcXTOnAllLinks
        diagsXT = calcXTOnAllLinks(Simulation, dx, dt)

    # get prj
    NEWdiagsXT = getPointsProjection(Simulation, diagsXT)

    fig = plt.figure(figsize=(9.6, 5.4), dpi=200, facecolor=[0.1, 0.1, 0.1])
    #...
    plt.rc('font', family='Cambria', size=6, style='normal', weight='light')
    #...
    # setup animation
    ani = FuncAnimation(fig,
                        _plotTraficolorNetwork,
                        fargs=(NEWdiagsXT, ),
                        frames=diagsXT[list(diagsXT)[0]]["T"].shape[1],
                        interval=int(1000 / fps),
                        repeat=repeat)
    return ani
def dynamic_range_main(folder_name_dict, plot_settings):

    if not plot_settings['only_plot']:
        plot_settings['savefolder_name'] = 'genotype_phenotype_plot_{}_{}' \
            .format(time.strftime("%Y%m%d-%H%M%S"), plot_settings['varying_parameter'])
        os.makedirs('save/{}'.format(plot_settings['savefolder_name']))
        sim_data_list_each_folder = prepare_data(folder_name_dict,
                                                 plot_settings)
        save_plot_data(sim_data_list_each_folder, plot_settings)
        # Save settings:
        settings_folder = 'save/{}/settings/'.format(
            plot_settings['savefolder_name'])
        save_settings(settings_folder, plot_settings)
    else:
        sim_data_list_each_folder = load_plot_data(
            plot_settings['only_plot_folder_name'])
        plot_settings['savefolder_name'] = plot_settings[
            'only_plot_folder_name']
    # if plot_settings['load_dynamic_range_parameter'] or not plot_settings['only_plot']:
    #     sim_data_list_each_folder = load_dynamic_range_parameter(sim_data_list_each_folder, plot_settings)
    #     save_plot_data(sim_data_list_each_folder, plot_settings)

    plot_axis(sim_data_list_each_folder, plot_settings)
    font = {'family': 'serif', 'size': 32, 'serif': ['computer modern roman']}
    plt.rc('font', **font)
コード例 #15
0
ファイル: yannick.py プロジェクト: END-team/final-project
def plot_transition_ratio(df1, df2):
    """
    plot stage transitions
    df1: normal sleep (df1 = analyse(base))
    df2: sleep depravation (df2 = analyse(depr))
    """    
    N = 5
    ind = np.arange(N)  # the x locations for the groups
    width = 0.2       # he width of the bars
    plt.close()
    plt.rc('font', family='Arial')

    fig, ax = plt.subplots(nrows=6, ncols=6, sharex='col', sharey='row')
    fig.suptitle("Comparison of the number of stage transitions (% of total transitions) (origin stage " + u'\u2192' + " dest. stage)", fontsize=20)        
    plt.subplots_adjust(wspace = 0.2,hspace = 0.4 )
    for i in range(0,6): # do not care about stage transitions > 5
        for j in range(0,6):     
            clef = '%t' + str(i) + '-' + str(j)
            normal = df1[clef].tolist()
            mean = sum(normal) / len(normal)
            normal.extend([mean])
            rects1 = ax[i,j].bar(ind, normal, width, color='b')
            depravation = df2[clef].tolist()
            mean = sum(depravation) / len(depravation)
            depravation.extend([mean])
            rects2 = ax[i,j].bar(ind+width, depravation, width, color='r')
            for label in (ax[i,j].get_xticklabels() + ax[i,j].get_yticklabels()):
                label.set_fontname('Arial')
                label.set_fontsize(8)            
            ax[i,j].set_title(str(i) + ' ' + u'\u2192' + ' ' + str(j))
            ax[i,j].set_xticks(ind+width)
            ax[i,j].set_xticklabels( ('1', '2', '3', '4', 'Avg') )
            ax[i,j].set_yticks(np.arange(0, 6, 2))
            ax[i,j].set_ylim([0,6])
    fig.legend( (rects1[0], rects2[0]), ('Baseline', 'Recovery'), loc = 'lower right', fontsize=10)
コード例 #16
0
def plotsignalsignalnoisetimeseries(t, s1, s2, d, t1, t2, fileprefix):
    '''
    plot two signal components and data between t1 and t2 and save plot to .png file
    '''

    filename = fileprefix + '.png'

    # find indices for tlow, thigh
    n1 = np.where(t >= t1)[0]
    n2 = np.where(t >= t2)[0]

    plt.figure()
    plt.rc('text', usetex=True)
    plt.tick_params(labelsize=20)
    plt.plot(t[n1[0]:n2[0]], d[n1[0]:n2[0]], color='k')
    plt.plot(t[n1[0]:n2[0]], s1[n1[0]:n2[0]], color='r')
    plt.plot(t[n1[0]:n2[0]], s2[n1[0]:n2[0]], color='g')

    # set symmetric ylimits if both positive and negative
    axes = plt.gca()
    y1, y2 = axes.get_ylim()
    if y1 < 0. and y2 > 0.:
        ymin = -max(np.abs(y1), np.abs(y2))
        ymax = max(np.abs(y1), np.abs(y2))
        axes.set_ylim([ymin, ymax])

    plt.xlabel('time (s)', size=22)
    plt.ylabel('data', size=22)
    plt.legend(['data', 'signal 1', 'signal 2'])
    plt.savefig(filename, bbox_inches='tight', dpi=400)

    return
コード例 #17
0
    def plot_scattering_function_for_obsangles(self, obsangle1, obsangle2,
                                               obsangle3, obsangle4, obsangle5,
                                               obsangle6, obsangle7, tmin,
                                               tmax, step):
        tvals = np.arange(tmin, tmax, step)

        plt.figure(figsize=(6, 6))
        plt.rc('axes', linewidth=2)
        plt.plot(tvals,
                 self.scattering_function(obsangle1, tmin, tmax, step)[0],
                 label=r'Obs Angle =%s$^o$' % obsangle1)
        plt.plot(tvals,
                 self.scattering_function(obsangle2, tmin, tmax, step)[0],
                 label=r'Obs Angle =%s$^o$' % obsangle2)
        plt.plot(tvals,
                 self.scattering_function(obsangle3, tmin, tmax, step)[0],
                 label=r'Obs Angle =%s$^o$' % obsangle3)
        plt.plot(tvals,
                 self.scattering_function(obsangle4, tmin, tmax, step)[0],
                 label=r'Obs Angle =%s$^o$' % obsangle4)
        plt.plot(tvals,
                 self.scattering_function(obsangle5, tmin, tmax, step)[0],
                 label=r'Obs Angle =%s$^o$' % obsangle5)
        plt.plot(tvals,
                 self.scattering_function(obsangle6, tmin, tmax, step)[0],
                 label=r'Obs Angle =%s$^o$' % obsangle6)
        plt.plot(tvals,
                 self.scattering_function(obsangle7, tmin, tmax, step)[0],
                 label=r'Obs Angle =%s$^o$' % obsangle7)

        plt.xlabel('Age', fontsize=18)
        plt.ylabel('Vega Magnitude / arcsec^2', fontsize=18)
        plt.tight_layout()
        plt.legend()
コード例 #18
0
ファイル: project.py プロジェクト: sakisakichen/CIS9650
def plot_corr_btw_fedu_n_medu(df):
    '''
    FEdu & Medu
    In this correlation chart, we find the correlation efficient between 'Fedu' and 'Medu' was high, 
    and we can take a closer look at the reltionship. 
    From the following bar chart, we can see Father's education had a different distribution compared to mother's education. 
    Most father's education were 2, while mothers tended to have higher education level.
    Therefore, we choose to keep both FEdu and MEdu.
    '''
    fname = 'corr_btw_fedu_n_medu.png'
    print('(1) Save ' + fname + ': correlation between FEdu and Medu\n')\

    # Bar charts of FEdu & Medu
    plt.rc('figure', figsize=(10, 5))

    fig = plt.figure()

    ax1 = fig.add_subplot(1, 2, 1)
    fedu = df['Fedu'].value_counts()
    fedu = pd.DataFrame(fedu)
    ax1.set_title('Father\'s Education Distribution')
    plt.ylabel('count of Fedu')
    plt.xlabel('Fedu')
    ax1.bar(fedu.index, fedu['Fedu'], color='cornflowerblue')

    ax2 = fig.add_subplot(1, 2, 2)
    medu = df['Medu'].value_counts()
    medu = pd.DataFrame(medu)
    ax2.set_title('Mother\'s Education Distribution')
    plt.ylabel('count of Medu')
    plt.xlabel('Medu')
    ax2.bar(medu.index, medu['Medu'], color='pink')

    plt.savefig(fname)
コード例 #19
0
def plothistogram(t, y, t1, t2, fileprefix):

    '''
    plot histogram of time-series data between t1 and t2 and save plot to .png file
    '''
    
    filename = fileprefix + '_hist.png'
        
    # find indices for tlow, thigh
    n1 = np.where(t>=t1)[0]
    n2 = np.where(t>=t2)[0]

    # histogram and best fit gaussian of h
    (mu, sigma) = norm.fit(y[n1[0]:n2[0]])
    
    plt.figure()
    plt.rc('text', usetex=True)
    plt.tick_params(labelsize=20)
    n, bins, patches = plt.hist(y[n1[0]:n2[0]], bins=50, normed='true')
    z = mlab.normpdf(bins, mu, sigma)
    l = plt.plot(bins, z, 'r--', linewidth=2)
    plt.xlabel('data', size=22)
    plt.savefig(filename, bbox_inches='tight', dpi=400)
    
    return
コード例 #20
0
ファイル: laplace.py プロジェクト: alexggmatthews/MLSALT4
def run_demo():
    plt.rc('font', size=25)  
    fig,axes = plt.subplots(2,3)


    alphas = [1.,5.,10.]
    linear_spaced = get_linear_spaced()

    axes[0,0].set_ylabel("Unnormalized")
    axes[1,0].set_ylabel("Normalized")
    lines = []

    for index in range(len(alphas)):
        alpha = alphas[index]
        current_normalizer = quadrature_normalizer(alpha)
        standard = target(alpha, linear_spaced)
        normalized = standard / current_normalizer
        laplace_normalized, laplace_raw = laplace_approx(alpha, linear_spaced)
        if index==0:
            lines = lines + axes[0,index].plot( linear_spaced, standard, 'b', label = 'Exact') 
            lines = lines + axes[0,index].plot( linear_spaced, laplace_raw, 'g', label = 'Laplace') 
        else:
            axes[0,index].plot( linear_spaced, standard, 'b') 
            axes[0,index].plot( linear_spaced, laplace_raw, 'g')
        axes[0,index].set_title('Alpha = '+str(alpha))
        axes[1,index].plot( linear_spaced, normalized, 'b')
        axes[1,index].plot( linear_spaced, laplace_normalized, 'g')
        axes[1,index].set_ylim( [0.,2.21])

    plt.subplots_adjust(right=0.7)
    plt.legend( handles = lines, loc= 7, bbox_to_anchor=(1.75, 1.1) )
    
    plt.show()
コード例 #21
0
ファイル: plot_utils.py プロジェクト: sadiess/a211w20
def triage(par, weights, parnames, figsize=[5,5], nbins = 30, figname=None, fontsize=8):
    
    npar = np.size(par[1,:])
    
    f, ax = plt.subplots(npar, npar, figsize=(figsize), sharex='col')
    # f, ax = plt.subplots(figsize=(10,10), sharex='col', sharey='row')
    plt.rc('font',size=fontsize)
    for h,v in it.product(range(npar), range(npar)) :
        if v < h :
            hvals, xedges, yedges = np.histogram2d(par[:,v], par[:,h], weights=weights[:,0], bins = nbins)
            hvals = np.rot90(hvals)
            hvals = np.flipud(hvals)
             
            Hmasked = np.ma.masked_where(hvals==0, hvals)
            hvals = hvals / np.sum(hvals)        
             
            X,Y = np.meshgrid(xedges,yedges) 
             
            sig1 = opt.brentq( conf_interval, 0., 1., args=(hvals,0.683) )
            sig2 = opt.brentq( conf_interval, 0., 1., args=(hvals,0.953) )
            sig3 = opt.brentq( conf_interval, 0., 1., args=(hvals,0.997) )
            lvls = [sig3, sig2, sig1]   
                     
            ax[h,v].pcolor(X, Y, (Hmasked), cmap=plt.cm.BuPu, norm = LogNorm())
            ax[h,v].contour(hvals, linewidths=(1.0, 0.5, 0.25), colors='lavender', levels = lvls, norm = LogNorm(), extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]])
            if v > 0:
                ax[h,v].get_yaxis().set_ticklabels([])
        elif v == h :
            ax[h,v].hist(par[:,h],bins = nbins,color='mediumslateblue',histtype='step',lw=1.5)
            ax[h,v].yaxis.tick_right()
            ax[h,v].get_yticklabels()
            
            conf_lims = np.percentile(par[:,h], [2.5, 16, 50, 84, 97.5])
            hmean = np.mean(par[:,h])
            hstd = np.std(par[:,h])
            
            print(parnames[h] + '\t%.3f +- %.3f'%(hmean, hstd)+ '; [2.5, 16, 50, 84, 97.5] %-tiles: ' + ' '.join(['%.3f'%(p) for p in conf_lims]))
            
            #textable.write( parnames[h] + ' & %.4f & %.4f'%(hmean, hstd)+ ' & ' + ' & '.join(['%.4f'%(p) for p in conf_lims]) + '\\\\\n')
            
            #for i in range(len(conf_lims)) :   ax[h,v].axvline(conf_lims[i], color='lavender', lw = (3. - np.abs(2-i))/2. )
            
        else :
            ax[h,v].axis('off')
             
        if v == 0:
            ax[h,v].set_ylabel(parnames[h])
            ax[h,v].get_yaxis().set_label_coords(-0.35,0.5)
        if h == npar-1:
            ax[h,v].set_xlabel(parnames[v])
            ax[h,v].get_xaxis().set_label_coords(0.5,-0.35)
            labels = ax[h,v].get_xticklabels()
            for label in labels: 
                label.set_rotation(90) 
         
         
    plt.tight_layout(pad=1.5, w_pad=-4, h_pad=-0.6)
    if figname:
        plt.savefig(figname, bbox_inches='tight')
def display70(oneSimulation,pathString, separate=False ,saveOnly=True):
    '''
    show/save figures
    '''
    self = oneSimulation
    
    tmp = np.asarray(oneSimulation.cf_icf01_region._geometry.boundary)
    tmp01= tmp[(0,1,3), :]
    
    tmp = np.asarray(oneSimulation.cf_icf_region._geometry.boundary)
    tmp03= tmp[(1,2,3,4), :]
    
    tmp = np.asarray(oneSimulation.df_fco_region._geometry.boundary)
    tmpDF = tmp[(0,1,2,3), :]


    

    pylab.rc('axes', linewidth=2) # make the axes boundary lines bold 
#     fig, ax = plt.subplots()
    fig = plt.figure()
    fig.set( size_inches=(8.8, 6) )
    
    ax = fig.add_axes([0.1, 0.1, 0.7, 0.7]) # left, bottom, width, height (range 0 to 1)
#     if separate:
#         rr.plot( self.df_region, 'red', lw=6, axes=ax, label='DF')
#         rr.plot( self.cf_region, 'blue', lw=4, axes=ax, label='CF')  
#         rr.plot( self.fco_region, 'red', lw=6, axes=ax, label='DF')
#         rr.plot( self.icf_region_bigR1, 'blue', lw=4, axes=ax, label='ICF')  
#         rr.plot( self.icf_region_bigR2, 'blue', lw=4, axes=ax)
    
    
    
#     rr.plot(self.df_fco_region, 'blue', lw=6, label='DF+FCo')
#     rr.plot(self.cf_icf_region, 'red', lw=4, label='CF+ICF Scheme 3')
#     rr.plot(self.cf_icf01_region, 'green', lw=2, label='CF+ICF Scheme 1' )
    
    
    ax.plot(tmpDF[:,0], tmpDF[:,1], 'blue', lw=6, label='DF+FCo')
    ax.plot(tmp03[:,0], tmp03[:,1], 'red', lw=4, label='CF+ICF Scheme 3')
    ax.plot(tmp01[:,0], tmp01[:,1], 'green', lw=2, label='CF+ICF Scheme 1' )
    
    
    
    
#     fig.suptitle('$g ={},{},{},{}$'.format(self.g13, self.g14, self.g23, self.g24), fontsize=14, fontweight='bold')
    ax.set_title(r'$P_s=P_1=P_2={}, \, P_3={}, \, P_4={}, \, N=1$'.format(self.Ps,
                 self.P3, self.P4),fontdict=self.font)
    
    ax.set_xlabel('$R_1$', fontdict=self.font)
    ax.set_ylabel('$R_2$', fontdict=self.font)
    #ax.set_xlim(xmin=0, xmax=3.5) 
    #ax.set_ylim(ymin=0, ymax=3.5) 
    ax.legend(loc=0)
    
    nameStr = 'PsP3P4_{}_{}_{}_g13g14g23g24_{}_{}_{}_{}'.format(self.Ps, self.P3, self.P4, 
                                                                self.g13, self.g14, self.g23, self.g24)
    savefig.save(path='{}/plots_CF_ICF03__CF_ICF01__DF_FCo/{}'.format(pathString, nameStr), ext='pdf', close=saveOnly, verbose=True)        
コード例 #23
0
def newCreateAndSaveMultilineFig(xDataList, yDataList, xLabel="", yLabel="",
                                 figFileRoot="", fileExt='.png', xMin=0,
                                 xMax=0, yMin=0, yMax=0, legendFlag=1,
                                 legendFont=12, traceNameList=[],
                                 legLoc=(0, 0)):
    """This subroutine saves a figure with multiple lines."""

    figFileName = figFileRoot + fileExt
    colorDict = createColorDictWithDashes()

    if xMax == 0:
        curMax = 0
        for n in range(0, len(xDataList)):
            if type(xDataList[n]) == list:
                if max(xDataList[n]) > curMax:
                    curMax = max(xDataList[n])
            else:
                if xDataList[n].any() > curMax:
                    curMax = max(xDataList[n])
        xMax = curMax

    if yMax == 0:
        curMax = 0
        for n in range(0, len(yDataList)):
            if type(yDataList[n]) == list:
                if max(yDataList[n]) > curMax:
                    curMax = max(yDataList[n])
            else:
                if yDataList[n].any() > curMax:
                    curMax = max(yDataList[n])
        yMax = curMax

    plt.axes([0.1, 0.1, 0.71, 0.8])
    if traceNameList == []:
        for n in range(0, len(xDataList)):
            traceNameList.append("Trace_" + str(n))

    for n in range(0, len(xDataList)):
        xData = convert_list_to_array(xDataList[n])
        yData = convert_list_to_array(yDataList[n])
        tempPlot = plt.plot(
            xData, yData, colorDict[str(n + 1)], hold="True",
            label=traceNameList[n])

    plt.xlabel(xLabel)
    plt.ylabel(yLabel)
    plt.xlim(xMin, xMax)
    plt.ylim(yMin, yMax)
    plt.rc("legend", fontsize=legendFont)

    if legendFlag == 1:
        if legLoc != (0, 0):
            print(legLoc)
            plt.legend(loc=legLoc)
        else:
            plt.legend()
    plt.savefig(figFileName, dpi=300)
    plt.clf()
コード例 #24
0
 def __init__(self, model_name):
     """ Inits SimulationPlotter with loading the simulation results. """
     # Load the data of the simulation results.
     self.__save_dir = 'models/' + model_name + '/simulation_result/'
     self.__file_header = self.__save_dir + model_name
     self.__state_data = np.genfromtxt(self.__file_header + '_state' +
                                       '.dat')
     self.__control_input_data = np.genfromtxt(self.__file_header +
                                               '_control_input' + '.dat')
     self.__error_data = np.genfromtxt(self.__file_header + '_error' +
                                       '.dat')
     self.__sim_conditions = simcon.SimulationConditions(self.__file_header)
     self.__time_sequence = np.linspace(
         0, self.__sim_conditions.simulation_time(),
         self.__state_data.shape[0])
     # Replace NaN with 0.
     self.__state_data[np.isnan(self.__state_data)] = 0
     self.__control_input_data[np.isnan(self.__control_input_data)] = 0
     self.__error_data[np.isnan(self.__error_data)] = 0
     # Set dimensions of the state and the control input.
     if self.__state_data.shape[0] == self.__state_data.size:
         self.__dim_state = 1
     else:
         self.__dim_state = self.__state_data.shape[1]
     if self.__control_input_data.shape[
             0] == self.__control_input_data.size:
         self.__dim_control_input = 1
     else:
         self.__dim_control_input = self.__control_input_data.shape[1]
     # Set the layout of the graphs.
     self.__num_plots = self.__dim_state + self.__dim_control_input + 1
     self.__num_plot_x = int(
         np.floor(self.__num_plots / np.sqrt(self.__num_plots)))
     self.__num_plot_y = int(np.ceil(self.__num_plots / self.__num_plot_x))
     # Set default figure scales.
     self.__figure_scale = 1
     self.__font_scale = 1
     self.__space_scale = 1
     # Set format of the graphs.
     sns.set_style("ticks")
     sns.set_palette("deep")
     sns.set_context("paper")
     plt.rc(
         'mathtext', **{
             'rm': 'serif',
             'it': 'serif:itelic',
             'bf': 'serif:bold',
             'fontset': 'cm'
         })
     plt.rcParams['xtick.direction'] = 'in'
     plt.rcParams['ytick.direction'] = 'in'
     plt.rcParams['pdf.fonttype'] = 42
     plt.rcParams['ps.fonttype'] = 42
     # Set the width of lines and axes.
     plt.rcParams['lines.linewidth'] = 1
     plt.rcParams['axes.linewidth'] = 0.5
コード例 #25
0
def show_cavity_step(title):
    plt.title(title, fontsize=40, y=1.02)
    plt.xlabel('Time [s]', fontsize=30)
    plt.ylabel(r'$| \vec V_{\rm acc}|$ [V]', fontsize=30)

    plt.ticklabel_format(style='sci', axis='y', scilimits=(1, 0))

    plt.rc('font', **{'size': 20})
    plt.legend(loc='upper right')
    plt.show()
コード例 #26
0
    def plot_many_thetas(self, theta1, theta2, theta3, tmin, tmax, step):

        plt.figure(figsize=(6, 6))
        plt.rc('axes', linewidth=2)
        self.plot_mags_vs_age(theta1, tmin, tmax, step)
        self.plot_mags_vs_age(theta2, tmin, tmax, step)
        self.plot_mags_vs_age(theta3, tmin, tmax, step)
        plt.xlabel('Age', fontsize=18)
        plt.ylabel('Vega Magnitude / arcsec^2', fontsize=18)
        plt.tight_layout()
        plt.legend()
コード例 #27
0
    def plot_z_vs_obsangle_for_given_age(self, t1, t2, t3, t4, t5, t6, t7,
                                         obsanglemin, obsanglemax, step):

        obsangles = np.arange(obsanglemin, obsanglemax, step)

        plt.figure(figsize=(6, 6))
        plt.rc('axes', linewidth=2)
        plt.plot(obsangles,
                 self.get_SB_vs_obsangle_for_given_age(t1, obsanglemin,
                                                       obsanglemax, step)[5],
                 color='r',
                 label='%s yrs' % t1)
        plt.plot(obsangles,
                 self.get_SB_vs_obsangle_for_given_age(t2, obsanglemin,
                                                       obsanglemax, step)[5],
                 color='orange',
                 label='%s yrs' % t2)
        plt.plot(obsangles,
                 self.get_SB_vs_obsangle_for_given_age(t3, obsanglemin,
                                                       obsanglemax, step)[5],
                 color='y',
                 label='%s yrs' % t3)
        plt.plot(obsangles,
                 self.get_SB_vs_obsangle_for_given_age(t4, obsanglemin,
                                                       obsanglemax, step)[5],
                 color='g',
                 label='%s yrs' % t4)
        plt.plot(obsangles,
                 self.get_SB_vs_obsangle_for_given_age(t5, obsanglemin,
                                                       obsanglemax, step)[5],
                 color='b',
                 label='%s yrs' % t5)
        plt.plot(obsangles,
                 self.get_SB_vs_obsangle_for_given_age(t6, obsanglemin,
                                                       obsanglemax, step)[5],
                 color='purple',
                 label='%s yrs' % t6)
        plt.plot(obsangles,
                 self.get_SB_vs_obsangle_for_given_age(t7, obsanglemin,
                                                       obsanglemax, step)[5],
                 color='m',
                 label='%s yrs' % t7)
        #plt.axhline(y=1630,linestyle='--',color='k',label='Edge of LMC')
        #plt.axhline(y=-1630,linestyle='--',color='k')
        plt.axhspan(-1630,
                    1630,
                    color='skyblue',
                    alpha=0.5,
                    label='Thickness of LMC')
        #plt.axhline(y=2000,linestyle='-.',color='k',label='Edge of 30 Dor')
        plt.xlabel('Observed Angular Separation', fontsize=18)
        plt.ylabel('z (lyrs)', fontsize=18)
        plt.tight_layout()
        plt.legend(loc='upper left', prop={'size': 15})
コード例 #28
0
ファイル: tools.py プロジェクト: queezz/SpectraExamples
def font_setup(size=13, weight='normal', family='serif', color='None'):
    ''' Set-up font for Matplotlib plots
    'family':'Times New Roman','weight':'heavy','size': 18
    '''
    import matplotlib.pylab as plt

    font = {'family': family, 'weight': weight, 'size': size}
    plt.rc('font', **font)
    plt.rcParams.update({
        'mathtext.default': 'regular',
        'figure.facecolor': color,
    })
コード例 #29
0
 def init_plot_parameter(self):
     #--- A4 landscape
     plt.rc('figure', figsize=self.figsize, autolayout=True)
     plt.rcParams.update({'font.size': self.fontsize})
     plt.subplots_adjust(left=0.1,
                         right=0.95,
                         bottom=0.05,
                         top=0.95,
                         hspace=0.35)
     plt.rcParams['savefig.facecolor'] = "0.9"
     if not self.fig_nr:
         self.fig_nr = 1
コード例 #30
0
def font_setup(size=13, weight="normal", family="serif", color="None"):
    """ Set-up font for Matplotlib plots
    'family':'Times New Roman','weight':'heavy','size': 18
    """
    import matplotlib.pylab as plt

    font = {"family": family, "weight": weight, "size": size}
    plt.rc("font", **font)
    plt.rcParams.update({
        "mathtext.default": "regular",
        "figure.facecolor": color,
    })
def plot_visibility(ts, target_alts, sun_alts, hrs_visible_per_night, min_alt):
    """Function to plot a chart of the target and solar altitude above the
    horizon at the LSST site as a function of time"""

    ts = np.array(ts)
    target_alts = np.array(target_alts)

    (fig, ax1) = plt.subplots(figsize=(10, 10))

    plt.rcParams.update({'font.size': 18})
    plt.rc('xtick', labelsize=18)
    plt.rc('ytick', labelsize=18)
    plt.xticks(rotation=45.0)

    idx = np.where(target_alts > -1e5)
    ax1.plot((ts - 2450000)[idx],
             target_alts[idx],
             'b-',
             label='Target altitude')
    ax1.set_xlabel('JD')
    ax1.set_ylabel('Maximum altitude [$^{\circ}$]', color='b')
    ax1.xaxis.label.set_fontsize(18)
    ax1.yaxis.label.set_fontsize(18)
    for label in ax1.get_xticklabels():
        label.set_fontsize(18)
    for label in ax1.get_yticklabels():
        label.set_fontsize(18)

    t = [(ts - 2450000).min(), (ts - 2450000).max()]
    ax1.plot(t, [min_alt] * len(t), 'g-.')

    ax1.grid(True)
    ax1.tick_params('y', colors='b')

    ax2 = ax1.twinx()
    ax2.plot(ts - 2450000,
             hrs_visible_per_night,
             'm--',
             label='Time target visible')
    ax2.set_ylabel('Hours per night', color='m')

    ax2.yaxis.label.set_fontsize(18)
    ax2.grid(False)
    ax2.tick_params('y', colors='m')

    fig.tight_layout()

    plt.legend()

    plt.savefig('target_visibility_from_lsst.png')

    plt.close()
コード例 #32
0
def violin_plot(ax, values_list, measure_name, group_names, fontsize, color='blue',  ttest=False):
    '''
    This is a little wrapper around the statsmodels violinplot code
    so that it looks nice :)    
    '''    
    
    # IMPORTS
    import matplotlib.pylab as plt
    import statsmodels.api as sm
    import numpy as np
    
    # Make your violin plot from the values_list
    # Don't show the box plot because it looks a mess to be honest
    # we're going to overlay a boxplot on top afterwards
    plt.sca(ax)
    
    # Adjust the font size
    font = { 'size'   : fontsize}
    plt.rc('font', **font)

    max_value = np.max(np.concatenate(values_list))
    min_value = np.min(np.concatenate(values_list))
    
    vp = sm.graphics.violinplot(values_list,
                            ax = ax,
                            labels = group_names,
                            show_boxplot=False,
                            plot_opts = { 'violin_fc':color ,
                                          'cutoff': True,
                                          'cutoff_val': max_value,
                                          'cutoff_type': 'abs'})
    
    # Now plot the boxplot on top
    bp = plt.boxplot(values_list, sym='x')
    
    for key in bp.keys():
        plt.setp(bp[key], color='black', lw=fontsize/10)
        
    # Adjust the power limits so that you use scientific notation on the y axis
    plt.ticklabel_format(style='sci', axis='y')
    ax.yaxis.major.formatter.set_powerlimits((-3,3))
    plt.tick_params(axis='both', which='major', labelsize=fontsize)

    # Add the y label
    plt.ylabel(measure_name, fontsize=fontsize)
    
    # And now turn off the major ticks on the y-axis
    for t in ax.yaxis.get_major_ticks(): 
        t.tick1On = False 
        t.tick2On = False

    return ax
コード例 #33
0
    def plot_run_correlation(self, C, ticks=None, lbl="", ax=None):

        ny, nx = C.shape
        i = np.linspace(0.5, ny + 0.5, ny + 1)
        j = np.linspace(0.5, nx + 0.5, nx + 1)
        if ticks is None:
            tx = range(1, nx + 1)
            ty = range(1, ny + 1)
        elif isinstance(ticks, tuple):
            tx, ty = ticks[0], ticks[1]
        else:
            tx, ty = ticks, ticks
        if isinstance(lbl, tuple):
            lx, ly = lbl[0], lbl[1]
        else:
            lx, ly = lbl, lbl

        #runs = np.linspace(self.runs[0]-0.5, self.runs[-1]+0.5, self.nrun+1)

        plt.rc('text', usetex=True)
        plt.rc('font', family='serif', size=16)

        if ax is None:
            fig = plt.figure(figsize=(8, 8))
            ax = fig.gca()

        x, y = np.meshgrid(j, i, indexing='ij')
        im = ax.pcolor(x, y, C, vmin=0, vmax=1)

        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.1)

        plt.colorbar(im, ax=ax, cax=cax)

        ax.set_ylim(i[-1], i[0])
        ax.set_xlim(j[0], j[-1])

        ax.set_yticks(i[:-1] + 0.5)
        ax.set_yticklabels(ty, fontsize=14)
        ax.set_xticks(j[:-1] + 0.5)
        ax.set_xticklabels(tx, fontsize=14)
        ax.tick_params("x",
                       labelrotation=90,
                       bottom=False,
                       top=True,
                       labelbottom=False,
                       labeltop=True)

        ax.set_xlabel(lx)
        ax.set_ylabel(ly)
        ax.set_aspect("equal")
コード例 #34
0
ファイル: main.py プロジェクト: patgra91/2048
def disp(m):
    fig, ax = plt.subplots()
    ax.matshow(m, cmap=plt.get_cmap('Set3'))
    for i in range(m.shape[0]):
        for j in range(m.shape[0]):
            c = m[j, i]
            if c > 0:
                ax.text(i, j, str(c), va='center', ha='center', color='black')

    plt.rc('font', size=30)
    plt.axis('off')
    #ax.set_axis_off()
    fig.set_size_inches(3, 3)
    plt.show()
コード例 #35
0
def p_plot(p_values, intervals, start=0, end=1):
    plt.close()
    with sns.axes_style("white", {"legend.frameon": True}):
        plt.rc("font", weight="bold")
        plt.rc("grid", lw=3)
        plt.rc("lines", lw=2)
        plt.rc("axes", lw=2)
        styles = ["--", "-."]
        for idx, interval in enumerate(intervals):
            p = p_values[:, :, idx, idx].flatten()
            p = p[~np.isnan(p)]
            p = np.sort(p)
            x = np.concatenate([[0], p, [1]])
            y = np.concatenate([[0],
                                (np.arange(p.shape[0]) + 1.0) / p.shape[0],
                                [1]])
            plt.plot(
                x,
                y,
                label="[{},{}]".format(50 - interval, 50 + interval),
                lw=2,
                ls=styles[idx // 6],
            )
        plt.plot([0, 1], [0, 1],
                 color="black",
                 ls="--",
                 lw=3,
                 label="U(0,1)",
                 alpha=0.7)
        plt.xlim([start, end])
        plt.ylim([start, end])
        plt.xlabel("p-value", fontsize=18, weight="bold")
        plt.ylabel("Empirical CDF", fontsize=18, weight="bold")
        plt.legend(loc="upper left", ncol=2)
コード例 #36
0
ファイル: subcube.py プロジェクト: vlas-sokolov/multicube
    def chi_squared_stats(self, plot_chisq=False):
        """
        Compute chi^2 statistics for an X^2 distribution.
        This is essentially a chi^2 test for normality being
        computed on residual from the fit. I'll rewrite it 
        into a chi^2 goodness of fit test when I'll get around
        to it.

        Returns
        -------
        prob_chisq : probability that X^2 obeys the chi^2 distribution

        dof : degrees of freedom for chi^2
        """
        # ------------------- TODO --------------------- #
        # rewrite it to a real chi-square goodness of fit!
        # this is essentially a chi^2 test for normality
        from scipy.stats import chisqprob

        # TODO: for Pearson's chisq test it would be
        # dof = self.xarr.size - self.specfit.fitter.npars - 1
        
        # NOTE: likelihood function should asymptotically approach
        #       chi^2 distribution too! Given that the whole point
        #       of calculating chi^2 is to use it for model 
        #       selection I should probably switch to it.

        # TODO: derive an expression for this "Astronomer's X^2" dof.
        dof = self.xarr.size
        prob_chisq = chisqprob(self.chi_squared, dof)

        # NOTE: for some reason get_modelcube returns zeros for some
        #       pixels even if corresponding Cube.parcube[:,y,x] is NaN
        prob_chisq[np.isnan(self.parcube.min(axis=0))] = np.nan

        if plot_chisq:
            if not plt.rcParams['text.usetex']:
                plt.rc('text', usetex=True)
            if self.mapplot.figure is None:
                self.mapplot()
            self.mapplot.plane = prob_chisq
            self.mapplot(estimator=None, cmap='viridis', vmin=0, vmax=1)
            labtxt = r'$\chi^2\mathrm{~probability~(%i~d.o.f.)}$' % dof
            self.mapplot.FITSFigure.colorbar.set_axis_label_text(labtxt)
            plt.show()

        self.prob_chisq = prob_chisq

        return prob_chisq, dof
コード例 #37
0
ファイル: DLLMDirect.py プロジェクト: matthieu-meaux/DLLM
 def plot(self):
     name = self.get_tag()
     Y_list = self.get_geom().get_XYZ()[1,:]
     plt.xlim(1.1*Y_list[0], 1.1*Y_list[-1])
     plt.xlabel('y')
     plt.ylabel('gamma')
     plt.plot(Y_list,self.__gamma)
     plt.rc("font", size=14)
     plt.savefig(name+"_gamma_distrib.png",format='png')
     plt.close()
     
     plt.xlim(1.1*Y_list[0], 1.1*Y_list[-1])
     plt.xlabel('y')
     plt.ylabel('iAoA')
     plt.plot(Y_list,self.__iAoA*self.RAD_TO_DEG)
     plt.rc("font", size=14)
     plt.savefig(name+"_iAoA_distrib.png",format='png')
     plt.close()
コード例 #38
0
ファイル: PlottingFun.py プロジェクト: bps10/birdsong
def AxisFormat(FONTSIZE = 22, TickSize = 10, TickDirection = 'out'):
    """

    Format axes to standard design.

    :param FONTSIZE: desired fontsize of all fonts.
    :type FONTSIZE: int
    :param TickSize: size of ticks in pxls.
    :type TickSize: int
    :param TickDirection: decide whether to plot ticks in or out
    :type TickDirection: str

    :returns: altered axes.

    .. note::
       * This function should work if called prior to plot input.

    **Usage**

    .. code-block:: python
       :emphasize-lines: 3

       fig = plt.figure(figsize=(8,6))
       ax = fig.add_subplot(111)
       pf.AxisFormat()

       ax.plot(np.arange(0,100), np.arange(0,100), 'b-', linewidth =2)

       plt.tight_layout()
       plt.show()

    **Exmaple**


    *simple plot without AxisFormat call*

    .. plot:: pyplots/AxisFormatDemo1.py
       :include-source:

    *simple plotnwith AxisFormat call*

    .. plot:: pyplots/AxisFormatDemo2.py
       :include-source:

    """
    font = {'weight': 'norm', 'size': FONTSIZE}
    legend = {'frameon': False}
    ticks = {'direction': TickDirection, 'major.size': TickSize,
             'minor.size': TickSize - 2}

    plt.rc('font', **font)
    plt.rc('legend', **legend)
    plt.rc('xtick', **ticks)
    plt.rc('ytick', **ticks)
コード例 #39
0
ファイル: Eye_Grow.py プロジェクト: bps10/NeitzModel
    def __init__(self):
        """
        """

        fig = plt.figure(facecolor = 'w', figsize = [12, 12])
        fig.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.05)
        
        ax1 = fig.add_subplot(1, 1, 1, aspect='equal')
        
        self.t = np.arange(0, len(Nodes['age']))
        self.x = xx[self.t]
        self.y = yy[self.t]
        self.age = Nodes['age'][self.t]

        plot_eye(Nodes,ax1)

        ax1.set_xlabel('mm',fontsize=20)
        ax1.set_ylabel('mm',fontsize=20)

        self.line1 = Line2D([], [], color='red', linewidth=4)
        self.line1e = Line2D([], [], color='red', marker='o', markeredgecolor='r', markersize=10)
        
        self.text = ax1.text(0.05, 0.05, 'Age: %s'%self.age[0] , fontsize=18, animated = True,
                            transform=ax1.transAxes)
                            
        ax1.add_line(self.line1)
        ax1.add_line(self.line1e)

        
        ax1.set_xlim(-14, 14)
        ax1.set_ylim(-14, 14)
        ax1.set_title('eye growth simulation',fontsize=20)


        ax1.set_xticks([-10, -5, 0, 5, 10])
        ax1.set_yticks([-10, -5, 0, 5, 10])
        
        
        plt.rc('xtick', labelsize=20)
        plt.rc('ytick', labelsize=20)
        plt.tight_layout()
        
        animation.TimedAnimation.__init__(self, fig, interval=10, blit=True)
コード例 #40
0
def display(oneSimulation,pathString ,saveOnly=True):
    '''
    Produce a graph that compare three ICF schemes
    '''
    self = oneSimulation
    
    # get the union rate region for plotting 
    icf_sch1 = rr.union( [self.icf_sch1_bigR1, self.icf_sch1_bigR2] )
    icf_sch2 = rr.union( [self.icf_sch2_bigR1, self.icf_sch2_bigR2] )
    icf_sch3 = rr.union( [self.icf_sch3_bigR1, self.icf_sch3_bigR2] )

    pylab.rc('axes', linewidth=2) # make the axes boundary lines bold 
    fig, ax = plt.subplots()
    rr.plot( icf_sch1, 'g', axes=ax, label='Scheme 1')
    rr.plot( icf_sch2, 'b', axes=ax, label='Scheme 2')
    rr.plot( icf_sch3, 'r', axes=ax, label='Scheme 3')  
    
    # plot the line: R2 = R1
    tmp = np.asarray(self.icf_sch1_bigR1._geometry.boundary)
    tmp2 = [[0, tmp[1, 0]], [0, tmp[1, 1] ] ]
    ax.plot( [0, tmp[1, 0]], [0, tmp[1, 1] ] , 'k--', lw=2)

    ax.set_title(r'$ P_3={}, \, P_4={}, \, N=1$'.format(self.P3, self.P4) , fontdict=self.font)
    ax.set_xlabel('$R_1$', fontdict=self.font)
    ax.set_ylabel('$R_2$', fontdict=self.font)
    ax.set_xlim(xmin=0, xmax=3.5) 
    ax.set_ylim(ymin=0, ymax=3.5) 
    ax.legend(loc='upper right')
    
    savefig.save(path='{}/compare_three_ICF_Schemes/P3P4_{}_{}'.format(pathString, self.P3, self.P4 ), ext='pdf', close=saveOnly, verbose=True)
    if (0):
        # add annotations for 3 regions
        plt.text(0.7, 2.3, 'capacity region by coherent coding with cardinality-bounding', color='red')
        plt.text(1, 1.8, 'non-coherent coding with cardinality-bounding', color='blue')
        plt.text(1.3, 1.4, 'capacity region by coherent coding with cardinality-bounding', color='green')
        
        bbox_props = dict(boxstyle="round,pad=0.1", fc="white", ec="g", lw=1)
        plt.text(1, 0.5, r'$1$', color='black', bbox=bbox_props)
        bbox_props = dict(boxstyle="round,pad=0.1", fc="white", ec="b", lw=1)
        plt.text(1.7, 0.4, r'$2$', color='black', bbox=bbox_props)
        bbox_props = dict(boxstyle="round,pad=0.1", fc="white", ec="r", lw=1)
        plt.text(2.2, 0.3, r'$3$', color='black', bbox=bbox_props)
コード例 #41
0
def OrientationPlot(OrientationHist_Data,BINS):
    """
    Plot an orienation histogram. For use with OrientationHist function

    Input
    -----
    OrientationHist_Data: computed from OrienationHist function
    BINS: bins used to compute OrientationHist

    Output
    ------
    Produces a polar plot with the orientation histogram data

    """
    RAD_BINS = BINS/(180./np.pi)
    ## Data Plot
    plt.rc('grid', color='gray', linewidth=1, linestyle='-')
    plt.rc('xtick', labelsize=25)
    plt.rc('ytick', labelsize=20)
    width, height = plt.rcParams['figure.figsize']
    size = min(width, height)
    fig = plt.figure(figsize=(size, size))
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True, axisbg='w')
    plt.polar(RAD_BINS,OrientationHist_Data/float(sum(OrientationHist_Data)), 'k',linewidth=4, marker='o')
    ax.set_rmax(0.2)
    plt.show()
コード例 #42
0
ファイル: smplots.py プロジェクト: petigura/specmatch-syn
def plot_matches(smresbest,lspec):
    """
    Plot best matches

    Plots the target spectrum along with the top matches
       
    """
    shift = 1
    fig,axL = plt.subplots(nrows=2,figsize=(20,12),sharex=True)
    
    plt.sca(axL[0])
    
    targpar = smresbest.rename(columns={'targobs':'obs'})
    targpar = dict(targpar['obs ord wlo whi'.split()].iloc[0])
    targpar['type'] = 'cps'
    targspec = smio.getspec_h5(**targpar)
    w = targspec['w']
    plt.plot(w,targspec['s'],'k')

    plt.rc('axes',color_cycle=['Tomato', 'RoyalBlue'])    
    for i in smresbest.index:
        # Plot target spectrum
        plt.sca(axL[0])
        y = shift*0.3
        plt.plot(w,lspec['lspec'][i]+y)

        par = dict(smresbest.ix[i])
        par['y'] = y+1
        annotate_matches(par)
        
        # Plot residuals
        plt.sca(axL[1])
        y = shift*0.2
        plt.plot(w,lspec['fres'][i]+y)

        par['y'] = y
        annotate_matches(par)
        shift+=1

    fig.subplots_adjust(left=.03,bottom=.03,top=0.97,right=.8)
コード例 #43
0
def create_bar_plots(bins, freq_list, height, group_names, colors, xlabel, ylabel, legend=True):
    import matplotlib.pylab as plt
    import numpy as np
    from matplotlib.ticker import MaxNLocator
    
    fig = plt.figure(figsize=(height*1.5, height))
    ax = fig.add_subplot(111)
    
    font = { 'size'   : 22 * height/8}

    plt.rc('font', **font)
    
    range = np.max(bins) - np.min(bins)
    w = range/((len(bins)-1) * len(group_names))

    for i, group in enumerate(group_names):
        
        bar = plt.bar(bins + w*i, freq_list[i],
                                width=w, label = group,
                                color=colors[i],
                                edgecolor='none')
        
        # Adjust the power limits so that you use scientific notation on the y axis
        plt.ticklabel_format(style='sci', axis='y')
        ax.yaxis.major.formatter.set_powerlimits((-3,3))

        for t in ax.yaxis.get_major_ticks(): 
            t.tick1On = False 
            t.tick2On = False 

    if legend:
        plt.legend(loc=0)
    
    plt.ylabel(ylabel)
    plt.xlabel(xlabel)
    # Make sure the layout looks good :)        
    fig.tight_layout()
    
    return fig
コード例 #44
0
def plot_graphs(df, trending_daily, day_from, day_to, limit, country_code, folder_out=None):
    days = pd.DatetimeIndex(start=day_from, end=day_to, freq='D')
    for day in days:
        fig = plt.figure()
        ax = fig.add_subplot(111)
        plt.rc('lines', linewidth=2)
        data = trending_daily.get_group(str(day.date()))
        places, clusters = top_trending(data, limit)
        for cluster in clusters:
            places.add(max_from_cluster(cluster, data))
        ax.set_prop_cycle(plt.cycler('color', ['r', 'b', 'yellow'] + [plt.cm.Accent(i) for i in np.linspace(0, 1, limit-3)]
                                     ) + plt.cycler('linestyle', ['-', '-', '-', '-', '-', '--', '--', '--', '--', '--']))
        frame = export(places, clusters, data)
        frame.sort_values('trending_rank', ascending=False, inplace=True)
        for i in range(len(frame)):
            item = frame.index[i]
            lat, lon, country = item
            result_items = ReverseGeoCode().get_address_attributes(lat, lon, 10, 'city', 'country_code')
            if 'city' not in result_items.keys():
                mark = "%s (%s)" % (manipulate_display_name(result_items['display_name']),
                                    result_items['country_code'].upper() if 'country_code' in result_items.keys() else country)
            else:
                if check_eng(result_items['city']):
                    mark = "%s (%s)" % (result_items['city'], result_items['country_code'].upper())
                else:
                    mark = "%.2f %.2f (%s)" % (lat, lon, result_items['country_code'].upper())
            gp = df.loc[item].plot(ax=ax, x='date', y='count', label=mark)
        ax.tick_params(axis='both', which='major', labelsize=10)
        ax.set_yscale("log", nonposy='clip')
        plt.xlabel('Date', fontsize='small', verticalalignment='baseline', horizontalalignment='right')
        plt.ylabel('Total number of views (log)', fontsize='small', verticalalignment='center', horizontalalignment='center', labelpad=6)
        gp.legend(loc='best', fontsize='xx-small', ncol=2)
        gp.set_title('Top 10 OSM trending places on ' + str(day.date()), {'fontsize': 'large', 'verticalalignment': 'bottom'})
        plt.tight_layout()
        db = TrendingDb()
        db.update_table_img(plt, str(day.date()), region=country_code)
        plt.close()
コード例 #45
0
ファイル: yannick.py プロジェクト: END-team/final-project
def plot_histogram(df1, df2):
    """
    plot histo for question 1 (Difference in REM sleep?)
        result => not concluant
    df1: normal sleep (df1 = analyse(base))
    df2: sleep depravation (df2 = analyse(depr))
    """    
    plt.rc('font', family='Arial')
    N = 5
    normal = df1['%5'].tolist()
    mean = sum(normal) / len(normal)
    normal.extend([mean])

    ind = np.arange(N)  # the x locations for the groups
    width = 0.35       # the width of the bars

    fig, ax = plt.subplots()
    rects1 = ax.bar(ind, normal, width, color='b')

    depravation = df2['%5'].tolist()
    mean = sum(depravation) / len(depravation)
    depravation.extend([mean])


    rects2 = ax.bar(ind+width, depravation, width, color='r')

    ax.set_ylabel('Sleep in REM stage (%)')
    ax.set_xlabel('Subjects')
    
    ax.set_title('REM sleep comparison', fontsize=20)
    ax.set_xticks(ind+width)
    ax.set_xticklabels( ('1', '2', '3', '4', 'Mean') )
    for label in (ax.get_xticklabels() + ax.get_yticklabels()):
           label.set_fontname('Arial')
           label.set_fontsize(8)            

    ax.legend( (rects1[0], rects2[0]), ('Baseline', 'After sleep depravation') ,  loc = 'lower right', fontsize=10 )
コード例 #46
0
ファイル: yannick.py プロジェクト: END-team/final-project
def plot_sleepTime(df1, df2):
    """
    First conclusion - obvious from experience -> sleep time longer after sleep depravation
    df1: normal sleep (df1 = analyse(base))
    df2: sleep depravation (df2 = analyse(depr))
    """    

    plt.rc('font', family='Arial')
    N = 5
    normal = df1['sleep duration'].tolist()
    mean = sum(normal) / len(normal)
    normal.extend([mean])

    ind = np.arange(N)  # the x locations for the groups
    width = 0.35       # the width of the bars

    fig, ax = plt.subplots()
    rects1 = ax.bar(ind, normal, width, color='b')

    depravation = df2['sleep duration'].tolist()
    mean = sum(depravation) / len(depravation)
    depravation.extend([mean])


    rects2 = ax.bar(ind+width, depravation, width, color='r')

    ax.set_ylabel('Sleep time (hours)')
    ax.set_xlabel('Subjects')
    
    ax.set_title('Overall sleep duration comparison', fontsize=20)
    ax.set_xticks(ind+width)
    ax.set_xticklabels( ('1', '2', '3', '4', 'Mean') )
    for label in (ax.get_xticklabels() + ax.get_yticklabels()):
           label.set_fontname('Arial')
           label.set_fontsize(8)            

    ax.legend( (rects1[0], rects2[0]), ('Baseline', 'Recovery'), loc = 'lower right', fontsize=10 )    
コード例 #47
0
def plot_spectrograms(bsl,rec,rate,title):
    plt.close()
    plt.rc('font', family='Arial')
    fig, ax = plt.subplots(nrows=9, ncols=2, sharex='col', sharey='row')
    fig.suptitle(title + " - REM stage", fontsize=20)
    plt.subplots_adjust(wspace = .05,hspace = 0.4 )
    ny_nfft=1024
    i=0
    plt.tick_params(axis='both', labelsize=8)
    while i<9:
        Pxx, freq, bins, im = ax[i,0].specgram(bsl[i],NFFT=ny_nfft,Fs=rate)
        ax[i,0].set_yticks(np.arange(0, 50, 10))
        ax[i,0].set_ylim([0, 40])
        if(i==8):
            ax[i,0].set_xlabel("Time, seconds", fontsize=10)
        ax[i,0].set_ylabel("Freq, Hz", fontsize=8)
        ax[i,0].set_title('Baseline, channel:'+str(i+1), fontsize=10)
        for label in (ax[i,0].get_xticklabels() + ax[i,0].get_yticklabels()):
            label.set_fontname('Arial')
            label.set_fontsize(8)
        i=i+1
    i=0
    while i<9:
        Pxx, freq, bins, im = ax[i,1].specgram(rec[i],NFFT=ny_nfft,Fs=rate)
        ax[i,0].set_yticks(np.arange(0, 50, 10))
        ax[i,1].set_ylim([0, 40])
        #ax[i,1].set_xlim([0, 10000]) #13000])
        if(i==8):
            ax[i,1].set_xlabel("Time, seconds", fontsize=10)
        #ax[i,1].set_ylabel("Freq, Hz")
        ax[i,1].set_title('Recovery, channel:'+str(i+1), fontsize=10)
        for label in (ax[i,0].get_xticklabels() + ax[i,0].get_yticklabels()):
            label.set_fontname('Arial')
            label.set_fontsize(8)
        i=i+1
    plt.show()
    return
コード例 #48
0
ファイル: SynGraphL2.py プロジェクト: lucasant10/Twitter
pl.axvline(x=51,color='r',ls='dashed')
pl.ylabel('Temp. Dev.')
pl.xlabel('Timestamp')
pl.rcParams.update({'font.size':14})

print '\nave_PN:', np.mean(e1_set[ind][:49]),  np.mean(e1_set[ind][51:]), np.mean(e1_set[ind])
print '\nave_PN:', np.mean(e2_set[ind][:49]),  np.mean(e2_set[ind][51:]), np.mean(e2_set[ind])
print '\nave_PN:', np.mean(e4_set[ind][:49]),  np.mean(e4_set[ind][51:]), np.mean(e4_set[ind])
if set_length == 1 and compare == True:
    pl.subplot(311)     
    pl.plot(x, e11, label = comp_with)
    pl.subplot(312)
    pl.plot(x, e21)
    pl.subplot(313)
    david2, = pl.semilogy(x, e41)
    pl.rc('legend',**{'fontsize':14})
    david3 = pl.legend([david1,david2],['TVGL','Baseline'], ncol=2, loc=7, bbox_to_anchor=(1,0.57), columnspacing=0.4) 
    david3.draw_frame(False)   
    print '\nave_Naive:', np.mean(e11)
    print '\nave_Naive:', np.mean(e21)
    print '\nave_Naive:', np.mean(e41)
Data_type = cov_mode + '%s'%(cov_mode_number) + '%s'%(samplesPerStep)
pl.savefig(Data_type)
pl.savefig(Data_type+'.eps', format = 'eps', bbox_inches = 'tight', dpi = 1000)
pl.show()
if set_length > 1:
    #print index1, index11, index12, index2, index21, index22
    print 'alpha = ', alpha_set[index11], ' beta = ', beta_set[index12], ' FroError = ', FroError[index1]
    print 'alpha = ', alpha_set[index21], ' beta = ', beta_set[index22], ' Score = ', Score[index2]
    print 'alpha = ', alpha_set[index31], ' beta = ', beta_set[index32], ' AIC = ', AIC[index3]
    print 'alpha = ', alpha_set[index41], ' beta = ', beta_set[index42], ' FroThetaDiff = ', FroThetaDiff[index4]
コード例 #49
0
ファイル: makemask.py プロジェクト: sameera2004/pyXPCS
def make_mask(data_file,mask_file='none'):
   global key, x, y,lc,data,im,xy,mymask,xx,yy,px,lx,lm,default_mask,maskfig
   # determine if a point is inside a given polygon or not
   # Polygon is a list of (x,y) pairs.
      
   
   #read input parameters
   print "masking the edf file"
   print "use mouse to select a region"
   print "m - to mask selected region"
   print "u - to unmask selected region"
   print "a - to cancel selected region"
   print "w - to save mask and exit"
   #print "e - to exit"
   
   data=loadedf(data_file)
   lx,ly=shape(data)
   if os.path.exists(mask_file) is True:
      mymask=loadedf(mask_file,0)
      automask=loadedf(mask_file,1)
      if shape(mymask)!=shape(data):
         mymask=zeros((lx,ly))
   else:
      mymask=zeros((lx,ly))
      automask=zeros((lx,ly))

   #points=[]
   #for i in range(lx):
   #    for j in range(ly):
   #     points.append([i,j]) 
   
   x, y = meshgrid(arange(lx), arange(ly))
   x, y = x.flatten(), y.flatten()
   points = vstack((x,y)).T

   key=[]
   x=0
   y=0
   xy=[]
   xx=[]
   yy=[]
   print "Make Mask"
  
   def on_click(event):
       print "On click"
       global key, x, y,lc,data,im,xy,mymask,xx,yy,px,lx,lm,default_mask,maskfig
       if not event.inaxes: 
           xy=[]
           return
       x,y=int(event.xdata), int(event.ydata)
       xx.append([x])
       yy.append([y])
       xy.append([y,x])
       lc.set_data(xx,yy)
       p.draw()
   def on_click_key(event):
       global key, x, y,lc,data,im,xy,mymask,xx,yy,px,lx,lm,default_mask,maskfig
       key=event.key
       if not event.inaxes: 
          xy=[]
          return
       if key=='a':
          xx=[]
          yy=[]
          xy=[]  
          x=0
          y=0
          lc.set_data(xx,yy)
          lm.set_data(xx,yy)
          p.draw()
       if key=='m':
           #print 'masking'
           xx.append(xx[0])#xx[-1]=xx[0]
           yy.append(yy[0])#yy[-1]=yy[0]
           xy.append(xy[0])#xy[-1]=xy[0]
           ind=points_inside_poly(points,xy).reshape(lx,ly).T
           mymask[ind]=1
           data=masked_array(data,mymask+automask)
           im.set_data(data)
           xx=[]
           yy=[]
           xy=[] 
           lc.set_data(xx,yy)
           lm.set_data(xx,yy)
           p.draw()
           x=0
           y=0 
           print "key m pressed"
       if key=='u': 
           xx.append(xx[0])#xx[-1]=xx[0]
           yy.append(yy[0])#yy[-1]=yy[0]
           xy.append(xy[0])#xy[-1]=xy[0]
           ind=points_inside_poly(points,xy).reshape(lx,ly).T
           mymask[ind]=0
           data=masked_array(data,mymask+automask)
           im.set_data(data)
           xx=[]
           yy=[]
           xy=[] 
           lc.set_data(xx,yy)
           lm.set_data(xx,yy)
           p.draw()
           x=0
           y=0
           print "key u pressed"
       if key=='r':
          mymask=0*mymask
          mymask=mymask.reshape(lx,ly)
          data=masked_array(data,mymask+automask)
          im.set_data(data)
          xx=[]
          yy=[]
          xy=[] 
          lc.set_data(xx,yy)
          lm.set_data(xx,yy)
          p.draw()
          x=0
          y=0 
          print "key r pressed"
       if key=='w':
          p.close()
          saveedf(mask_file,mymask,0)
          saveedf(mask_file,automask,1)
          print "key w pressed, CLOSING"
          return
   
   def on_move(event):
       #print"On move"
       global lm,x,y
       if not event.inaxes: return
       xm,ym=int(event.xdata), int(event.ydata)
       # update the line positions
       if x!=0: 
           lm.set_data((x,xm),(y,ym))
           p.draw()
   p.rc('image',origin = 'lower')
   p.rc('image',interpolation = 'nearest')
   p.figure()
   px=p.subplot(111)
   data=p.log(data+1)
   im=p.imshow(masked_array(data,mymask+automask))
   p.title("Select a ROI. Press m to mask or u to unmask it \n w to write mask and exit")
   lc,=px.plot((0,0),(0,0),'-+m',linewidth=1,markersize=8,markeredgewidth=1)
   lm,=px.plot((0,0),(0,0),'-+m',linewidth=1,markersize=8,markeredgewidth=1)
   px.set_xlim(0,ly)
   px.set_ylim(0,lx)
   #p.ion()
   cidb=p.connect('button_press_event',on_click)
   cidk=p.connect('key_press_event',on_click_key)
   cidm=p.connect('motion_notify_event',on_move)
   p.show()
コード例 #50
0
    for name in ['x', 'chord', 'rot_z', 'rthick']:
        spl_ae.add_spline(name, np.array([0, 0.25, 0.75, 1.]), spline_type='bezier')

    # configure
    spl_ae.configure()
    return p

    # --- 5

if __name__ == '__main__':

    p = configure_surface()
    p.setup()
    p.run()
    import matplotlib.pylab as plt
    plt.rc('lines', linewidth=3)

    plt.figure()
    plt.axis('equal')
    for i in range(p['blade_surface_st'].shape[1]):
        plt.plot(p['blade_surface_st'][:,i, 2], p['blade_surface_st'][:,i, 0], 'r-')
    plt.plot(p['blade_surface_st'][0, :, 2], p['blade_surface_st'][100, :, 0],'r-')
    plt.plot(p['blade_surface_st'][0, :, 2], p['blade_surface_st'][0, :, 0],'r-')
    plt.plot(p['z'], p['x'], 'r-', label='Original')

    # --- 6

    # add sweep to the blade
    p['x_C'][-1]=-.05
    p.run()
    for i in range(p['blade_surface_st'].shape[1]):
コード例 #51
0
Created on Sun Apr 06 18:42:59 2014

@author: lassnech
"""

from sklearn import svm
from sklearn import grid_search
import tmpfertilized as f
import matplotlib.pylab as plt
import matplotlib
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import numpy as np
from plottools import make_spiral, point_prob_plot, probaproxy
plt.rc('text', usetex=True)
plt.rc('font', family='serif')

np.random.seed(1)

n_classes = 2
n_trees = 200
ploty = [-6, 6, 100]
plotx = [-6, 6, 100]

X, Y = make_spiral(n_arms=n_classes, noise=.4)

##############################################################################
parameters = {'kernel': ['rbf'],
              'C': [1, 10, 100, 1000, 10000, 100000],
              'gamma': [10 ** x for x in range(-5, 3)],
コード例 #52
0
ファイル: tm_tools.py プロジェクト: nudtchengqing/time-maps
def make_heated_time_map(sep_array, Nside, width):

	print 'generating heated time map ...'
	
	# choose points within specified range. Example plot separations greater than 5 minutes:
#	indices = (sep_array[:,0]>5*60) & (sep_array[:,1]>5*60)
	indices=range(sep_array.shape[0]) # all time separations

	x_pts = np.log(sep_array[indices,0])
	y_pts = np.log(sep_array[indices,1])

	min_val = np.min([np.min(x_pts), np.min(y_pts)])
	
	x_pts = x_pts - min_val
	y_pts = y_pts - min_val
	
	max_val = np.max([np.max(x_pts), np.max(y_pts)])
	
	x_pts *= (Nside-1)/max_val
	y_pts *= (Nside-1)/max_val
	
	img=np.zeros((Nside,Nside))

	for i in range(len(x_pts)):

		img[x_pts[i],y_pts[i]] +=1

	img = ndi.gaussian_filter(img,width) # apply Gaussian filter
	
	img = np.sqrt(img) # taking the square root makes the lower values more visible

	img=np.transpose(img) # needed so the orientation is the same as scatterplot

	plt.imshow(img, origin='lower')
	
	## create custom tick marks. Calculate positions of tick marks on the transformed log scale of the image array
	
	plt.minorticks_off()
	
	## change font, which can also now accept latex: http://matplotlib.org/users/usetex.html
	plt.rc('text',usetex=True)
	plt.rc('font',family='serif')

	my_max = np.max([np.max(sep_array[indices,0]), np.max(sep_array[indices,1])])
	my_min = np.max([np.min(sep_array[indices,0]), np.min(sep_array[indices,1])])

	pure_ticks = np.array([1e-3,1,10,60*10,2*3600,1*24*3600, 7*24*3600])         # where the tick marks will be placed, in units of seconds. An additional value will be appended to the end for the max
	labels = ['1 msec','1 sec','10 sec','10 min','2 hr','1 day','1 week']  # tick labels

	index_lower=np.min(np.nonzero(pure_ticks >= my_min)) # index of minimum tick that is greater than or equal to the smallest time interval. This will be the first tick with a non-blank label
	
	index_upper=np.max(np.nonzero(pure_ticks <= my_max))
	
	ticks = pure_ticks[index_lower: index_upper + 1]
	ticks = np.log(np.hstack((my_min, ticks, my_max ))) # append values to beginning and end in order to specify the limits
	ticks = ticks - min_val
	ticks *= (Nside-1)/(max_val)
	
	labels= np.hstack(('',labels[index_lower:index_upper + 1],'')) # append blank labels to beginning and end
	
	plt.xticks(ticks, labels,fontsize=16)
	plt.yticks(ticks, labels,fontsize=16)

	plt.xlabel('Time Before Tweet',fontsize=18)
	plt.ylabel('Time After Tweet' ,fontsize=18)
	
	plt.show()

	return None
コード例 #53
0
def mpl_thumbnails(usetex=False):
    """
    Make png thumbnails
    """
    plt.rcdefaults()
    plt.rc('font', family='serif')
    plt.rc('xtick', labelsize='x-small')
    plt.rc('ytick', labelsize='x-small')
    plt.rc('text', usetex=usetex)
    plt.rc('savefig', format='pdf', bbox='tight')
    plt.rc('savefig', format='png', bbox='tight')
    plt.rc('figure', figsize=(4,3))
コード例 #54
0
def mpl_slides(usetex=False):
    """
    Set matplotlibrc to make pretty slides
    """
    plt.rcdefaults()
    plt.rc('font', family='serif', size=24)
    # The default PowerPoint page setup
    plt.rc('figure', figsize=(7,5.5))
    plt.rc('axes', titlesize=24, labelsize=20, linewidth=3)
    plt.rc('legend', fontsize=18, numpoints=1, scatterpoints=1)
    plt.rc('xtick', labelsize='small')
    plt.rc('ytick', labelsize='small')
    plt.rc('text', usetex=usetex)
    plt.rc('lines', linewidth=5)
    plt.rc('savefig', format='pdf', bbox='tight')
コード例 #55
0
def mpl_span_columns(usetex=False):
    """
    Set matplotlib to make pretty plots for publishing a full-page figure
    """
    plt.rcdefaults()
    plt.rc('font', family='serif', size=12.0, style='normal')
    plt.rc('figure', figsize=(7, 5.25))
    plt.rc('axes', titlesize=12, labelsize=10)
    plt.rc('legend', fontsize=8, numpoints=1, scatterpoints=1)
    plt.rc('xtick', labelsize='x-small')
    plt.rc('ytick', labelsize='x-small')
    plt.rc('text', usetex=usetex)
    plt.rc('savefig', format='pdf', bbox='tight')
コード例 #56
0
    # try a simple spline-based integration (good enough for small scales)
    
    xir[i] = intsp.integral(lnkf[0],(lnkf[-1]))/(2.0*math.pi**2)
    
#
#   for large r, do an expensive integration breaking integral into many pieces
#   each integrating between successive zeroes of sin(kr)
#
    xir2[i] = integrate.romberg(intfunc,lnk[0],lnk[-1],tol=1.e-14)/(2.0*math.pi**2)
            
    print "%.4f"%rd, "%.5e"%xir[i], "%.5e"%xir2[i]
    xiout.write('%.4f %.5e %.5e \n' % (rd, xir[i], xir2[i]))

fig1 = plt.figure()

plt.rc('text', usetex=True)
plt.rc('font',size=16,**{'family':'sans-serif','sans-serif':['Helvetica']})
plt.rc('xtick.major',pad=10); plt.rc('xtick.minor',pad=10)
plt.rc('ytick.major',pad=10); plt.rc('ytick.minor',pad=10)

#rfull,xifull = np.loadtxt('../s2_out.dat',usecols=(0,1),unpack=True)

plt.plot(lr,np.log10(np.abs(xir)),linewidth=1.5,c='b',label=r'$\sigma_2^2(r)$ Gaussian (spline)')
plt.plot(lr,np.log10(np.abs(xir2)),linewidth=1.5,c='m',label=r'$\sigma_2^2(r)$ TH (Romberg)')
plt.ylim(-10.0,8.0)
plt.xlim(-0.99,2.5)
#plt.xlim(8.0,16.0); 
plt.xlabel(r'\textbf{$\log_{10}(R/\rm Mpc)$}',labelpad = 5)
plt.ylabel(r'$\log_{10}(\sigma^2_2(R))$',labelpad = 10)
plt.title('power spectrum moment',fontsize=16)
plt.legend(loc='upper right')
コード例 #57
0
ファイル: tm_tools.py プロジェクト: nudtchengqing/time-maps
def make_time_map(times, times_tot_mins, sep_array, Ncolors):

	print 'rendering normal time map ...'
	
	## set up color list
	
	red=Color("red")
	blue=Color("blue")
	color_list = list(red.range_to(blue, Ncolors)) # range of colors evenly speced on the spectrum between red and blue. Each element is a colour object
	color_list = [c.hex for c in color_list] # give hex version
		
	fig=plt.figure()
	ax =fig.add_subplot(111)
	
	plt.rc('text',usetex=True)
	plt.rc('font',family='serif')
	
	colormap = plt.cm.get_cmap('rainbow')  # see color maps at http://matplotlib.org/users/colormaps.html
	
	order=np.argsort(times_tot_mins[1:-1]) # so that the red dots are on top
#	order=np.arange(1,len(times_tot_mins)-2) # dots are unsorted

	# taken from http://stackoverflow.com/questions/6063876/matplotlib-colorbar-for-scatter
	
	sc= ax.scatter(sep_array[:,0][order],sep_array[:,1][order],c=times_tot_mins[1:-1][order],vmin=0,vmax=24*60,s=25,cmap=colormap,marker='o',edgecolors='none')
	
	color_bar=fig.colorbar(sc,ticks=[0,24*15,24*30,24*45,24*60],orientation='horizontal',shrink=0.5)
	color_bar.ax.set_xticklabels(['Midnight','18:00','Noon','6:00','Midnight'])
	color_bar.ax.invert_xaxis()
	color_bar.ax.tick_params(labelsize=16)
	
	ax.set_yscale('log') # logarithmic axes
	ax.set_xscale('log')
	
	plt.minorticks_off()
	
	pure_ticks = np.array([1e-3,1,10,60*10,2*3600,1*24*3600, 7*24*3600]) # where the tick marks will be placed, in units of seconds.
	labels = ['1 msec','1 sec','10 sec','10 min','2 hr','1 day','1 week']  # tick labels
	
	max_val = np.max([np.max(sep_array[:,0]), np.max(sep_array[:,1])])
	
	ticks = np.hstack((pure_ticks, max_val))
	
	min_val = np.min([np.min(sep_array[:,0]), np.min(sep_array[:,1])])
	
	plt.xticks(ticks,labels,fontsize=16)
	plt.yticks(ticks,labels,fontsize=16)
	
	plt.xlabel('Time Before Tweet',fontsize=18)
	plt.ylabel('Time After Tweet',fontsize=18)
	
	plt.xlim((min_val, max_val))
	plt.ylim((min_val, max_val))
	
	ax.set_aspect('equal')
	
	plt.tight_layout()
	
	plt.show()

	return None
コード例 #58
0
ファイル: system_16.py プロジェクト: hippke/TTV-TDV-exomoons
# Run simulation. Make sure to add/remove the moons you want to simulate!
ttv_array, tdv_array = run_sim(
    R_star, 
    transit_duration, 
    [planet, firstmoon, secondmoon, thirdmoon])


# Output information
print 'TTV amplitude =', numpy.amax(ttv_array), \
    '[min] = ', numpy.amax(ttv_array) * 60, '[sec]'
print 'TDV amplitude =', numpy.amax(tdv_array), \
    '[min] = ', numpy.amax(tdv_array) * 60, '[sec]'

ax = plt.axes()
plt.plot(ttv_array, tdv_array, color = 'k')
plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
plt.rc('text', usetex=True)
plt.tick_params(axis='both', which='major', labelsize = 16)
plt.xlabel('transit timing variation [minutes]', fontsize = 16)
plt.ylabel('transit duration variation [minutes]', fontsize = 16)
ax.tick_params(direction='out')
plt.ylim([numpy.amin(tdv_array) * 1.2, numpy.amax(tdv_array) * 1.2])
plt.xlim([numpy.amin(ttv_array) * 1.2, numpy.amax(ttv_array) * 1.2])
plt.plot((0, 0), (numpy.amax(tdv_array) * 10., numpy.amin(tdv_array) * 10.), 'k', linewidth=0.5)
plt.plot((numpy.amin(ttv_array) * 10., numpy.amax(ttv_array) * 10.), (0, 0), 'k', linewidth=0.5)

# Fix axes for comparison with eccentric moon
plt.xlim(-0.15, +0.15)
plt.ylim(-0.65, +0.65)
plt.annotate(r"5:4:3", xy=(-0.145, +0.55), size=16)
コード例 #59
0
ファイル: CPUtime.py プロジェクト: alu0100846461/EQUIPO_1_B
#! /usr/bin/python
#!encoding: UTF-8

import matplotlib.pylab as pl
import numpy as np
import newton
import time

pl.rc('text', usetex=True)
pl.rc('font', family='Bookman')

g = (3.45,-5.8,-7.2,2.17)
tol = (10e-4,10e-5, 10e-7,10e-12)
nmax = (10,50,100,10)

X = []
Y = []

for i in range (0, 4):
    t0 = time.clock()
    for j in range (0, 10000):
        sol = newton.newton (g[i], tol[i], nmax[i], 0)
    tf = time.clock() - t0
    X = X + [i+1]
    Y = Y + [tf]

print Y

pl.plot(X,Y,'mp--')
pl.title(r'Costo computacional del m\'etodo de Newton') 
pl.xlabel(r'Cantidad de iteraciones (en decenas de miles)')