Exemple #1
0
 def custom_plot(self, name, period, fit_width, allesfit_dir, mode="posterior"):
     allesclass = allesfitter.allesclass(allesfit_dir)
     baseline_width = fit_width * 24
     baseline_to_period = fit_width / period
     fig, axes = plt.subplots(2, 3, figsize=(18, 6), gridspec_kw={'height_ratios': [3, 1]}, sharex='col')
     fig.subplots_adjust(left=0.5, right=1.5, hspace=0)
     style = 'full'
     allesclass.plot('lc', name, style, ax=axes[0][0], mode=mode)
     axes[0][0].set_title('lc, ' + style)
     allesclass.plot('lc', name, style + '_residuals', ax=axes[1][0], mode=mode)
     axes[1][0].set_title('')
     style = 'phase'
     allesclass.plot('lc', name, style, ax=axes[0][1], mode=mode, zoomwindow=baseline_to_period)
     axes[0][1].set_title('lc, ' + style)
     axes[0][1].set_xlim([- baseline_to_period / 2, baseline_to_period / 2])
     allesclass.plot('lc', name, style + '_residuals', ax=axes[1][1], mode=mode, zoomwindow=baseline_to_period)
     axes[1][1].set_title('')
     axes[1][1].set_xlim([- baseline_to_period / 2, baseline_to_period / 2])
     style = 'phasezoom'
     allesclass.plot('lc', name, style, ax=axes[0][2], mode=mode, zoomwindow=baseline_width)
     axes[0][2].set_title('lc, ' + style)
     axes[0][2].set_xlim([- baseline_width / 2, baseline_width / 2])
     allesclass.plot('lc', name, style + '_residuals', ax=axes[1][2], mode=mode, zoomwindow=baseline_width)
     axes[1][2].set_title('')
     axes[1][2].set_xlim([- baseline_width / 2, baseline_width / 2])
     fig.savefig(allesfit_dir + '/results/ns_' + mode + '_' + name + '_custom.pdf', bbox_inches='tight')
     style = ['phasezoom_occ']
     style = ['phase_variations']
Exemple #2
0
#::: plotting settings
import seaborn as sns
sns.set(context='paper',
        style='ticks',
        palette='deep',
        font='sans-serif',
        font_scale=1.5,
        color_codes=True)
sns.set_style({"xtick.direction": "in", "ytick.direction": "in"})
sns.set_context(rc={'lines.markeredgewidth': 1})

############################################################
#::: plot the fit
############################################################
alles = allesfitter.allesclass('allesfit')

fig = plt.figure(figsize=(12, 6), tight_layout=True)
gs = fig.add_gridspec(2, 3)
ax1 = fig.add_subplot(gs[0, :])
ax2 = fig.add_subplot(gs[1, 0])
ax3 = fig.add_subplot(gs[1, 1])
ax4 = fig.add_subplot(gs[1, 2])

alles.plot('Kepler',
           'B',
           'full',
           ax=ax1,
           kwargs_data={'rasterized': False},
           kwargs_ax={'title': ''})
alles.plot('Kepler',
def prepare_ttv_fit(datadir, ax=None):
    '''
    this must be run *after* reduce_phot_data()
    '''
    ax0 = ax
    
    alles = allesfitter.allesclass(datadir)
    window = alles.settings['fast_fit_width']
       
    if not os.path.exists( os.path.join(datadir,'ttv_preparation') ): os.makedirs(os.path.join(datadir,'ttv_preparation'))
    with open(os.path.join(datadir,'ttv_preparation','ttv_initial_guess_params.csv'),'w') as f:
        f.write('')
    
    def plot_all_transits_color_coded():
        for inst in alles.settings['inst_phot']:
            time = alles.data[inst]['time']
            for companion in alles.settings['companions_phot']:
                ind = []
                for i, t in enumerate(alles.data[companion+'_tmid_observed_transits']):
                    ind += list( np.where((time >= (t - window/2.)) & (time <= (t + window/2.)))[0] )
                ax.plot( alles.data[inst]['time'][ind], alles.data[inst]['flux'][ind], ls='none', marker='.', label=companion )
    
    
    for companion in alles.settings['companions_phot']:
        with open(os.path.join(datadir,'ttv_preparation','ttv_initial_guess_params.csv'),'a') as f:
            f.write('#TTV companion '+companion+',,,,,\n')
        
        #----------------------------------------------------------------------
        #::: get combined data from all instruments
        #----------------------------------------------------------------------
        all_times = []
        all_flux = []
        for inst in alles.settings['inst_phot']:
            all_times += list(alles.data[inst]['time'])
            all_flux += list(alles.data[inst]['flux'])
        ind_sort = np.argsort(all_times)
        all_times = np.array(all_times)[ind_sort]
        all_flux = np.array(all_flux)[ind_sort]
        
        #----------------------------------------------------------------------
        #::: get eclipse window
        #----------------------------------------------------------------------
        alles.initial_guess_params_median[companion+'_epoch']
        eclipse_width = eclipse_width_smart(alles.initial_guess_params_median[companion+'_period'], 
                                    alles.initial_guess_params_median[companion+'_rr'], 
                                    alles.initial_guess_params_median[companion+'_rsuma'], 
                                    alles.initial_guess_params_median[companion+'_cosi'], 
                                    alles.initial_guess_params_median[companion+'_f_s'], 
                                    alles.initial_guess_params_median[companion+'_f_c'], 
                                    )[0]
        
        #----------------------------------------------------------------------
        #::: compute tmid, ttv_guess and make per-transit-plots
        #----------------------------------------------------------------------
        tmids = []
        
        alles.data[companion+'_tmid_observed_transits'] = get_tmid_observed_transits(all_times,alles.initial_guess_params_median[companion+'_epoch'],alles.initial_guess_params_median[companion+'_period'],alles.settings['fast_fit_width'])
        N = len(alles.data[companion+'_tmid_observed_transits'])
        fig, axes = plt.subplots(N, 1, figsize=(6,4*N), sharey=True, tight_layout=True)
        
        for i, t in enumerate(alles.data[companion+'_tmid_observed_transits']):
            ind_tr1 = np.where((all_times >= (t - window/2.)) & (all_times <= (t + window/2.)))[0]
            tr_times = all_times[ind_tr1]
            tr_flux = all_flux[ind_tr1]
            t_exp = np.median(np.diff(tr_times))
            N_points_in_eclipse = int(eclipse_width/t_exp)
            try:
                trend = flatten(tr_times, tr_flux, window_length=eclipse_width/2., method='biweight', return_trend=True)[1]
                tmid = np.median( tr_times[ np.argsort(trend)[0:int(N_points_in_eclipse/2.)] ] )
            except:
                warnings.warn('Install wotan for improved performance of prepare_ttv_fit().')
                trend = None
                tmid = np.median( tr_times[ np.argsort(tr_times)[0:int(N_points_in_eclipse/2.)] ] )
            ttv_guess = tmid - t
            tmids.append(tmid)
            
            ax = axes[i]
            ax.plot(tr_times, tr_flux, 'b.', rasterized=True)
            if trend is not None: ax.plot(tr_times, trend, 'r-')
            ax.axvline(t,c='grey',ls='--',label='linear prediction')
            ax.axvline(tmid,c='r',ls='--',label='flux minimum')
            ax.set(xlabel='Time', ylabel='Flux', xlim=[t-window/2., t+window/2.])
            ax.text(0.95,0.95,'Transit '+str(i+1), va='top', ha='right', transform=ax.transAxes)
            with open(os.path.join(datadir,'ttv_preparation','ttv_initial_guess_params.csv'),'a') as f:
               f.write(companion+'_ttv_transit_'+str(i+1)+','+np.format_float_positional(ttv_guess,4)+',1,uniform '+np.format_float_positional(ttv_guess-0.01,4)+' '+np.format_float_positional(ttv_guess+0.01,4)+',TTV$_\mathrm{'+companion+';'+str(i+1)+'}$,d\n')
        axes[0].legend()
        fig.savefig(os.path.join(datadir,'ttv_preparation','ttv_preparation_'+companion+'_per_transit.pdf'), bbox_inches='tight')
        plt.close(fig)
         
        tmids = np.array(tmids)
        
        
        #----------------------------------------------------------------------
        #::: ttv guess 0-C plot
        #----------------------------------------------------------------------
        nr = np.array([ int(np.round( (t-tmids[0]) / alles.initial_guess_params_median[companion+'_period'] )) for t in tmids ]) #get corresponding transit number
        nr -= int(nr[-1]/2.) #shift into the middle of the data set
        period_mean, epoch_mean = np.polyfit(nr, tmids, 1)             
        
        fig, axes = plt.subplots(2,1,figsize=(6,8),tight_layout=True,sharex=True)
        axes[0].plot(nr, tmids, 'bo', label='Companion '+companion)
        axes[0].plot(nr, epoch_mean + nr * period_mean, 'b-')
        axes[0].set(xlabel='Nr.', ylabel='Transit mid-time')
        axes[0].legend()
        axes[1].plot(nr, tmids-(epoch_mean + nr * period_mean), 'bo')
        axes[1].axhline(0,c='grey',ls='--')
        fig.savefig(os.path.join(datadir,'ttv_preparation','ttv_preparation_'+companion+'_oc.pdf'), bbox_inches='tight')
        
        period_dev = np.abs( (period_mean-alles.initial_guess_params_median[companion+'_period'])/alles.initial_guess_params_median[companion+'_period'] )
        epoch_dev = np.abs( (epoch_mean-alles.initial_guess_params_median[companion+'_epoch'])/alles.initial_guess_params_median[companion+'_epoch'] )
        
        print('\nCompanion', companion)
        print('Initial guess for mean period and epoch:')
        print(np.format_float_positional(alles.initial_guess_params_median[companion+'_period']), 
              np.format_float_positional(alles.initial_guess_params_median[companion+'_epoch']))
        print('New estimate for mean period and epoch:')
        print(np.format_float_positional(period_mean,4), 
              np.format_float_positional(epoch_mean,4))
        # print('Deviation from another:')
        # print(np.format_float_positional(period_dev,4), 
        #       np.format_float_positional(epoch_dev,4))
        if (period_dev > 0.01) or (epoch_dev > 0.01):
            print('\n! Consider updating your initial guess to these new estimated mean values.')
            print('\n! If you do, then you must rerun this code.')
        else:
            print('\n! Looks great! You are ready to fit.')

        
        #----------------------------------------------------------------------
        #::: full lightcurve plot
        #----------------------------------------------------------------------
        flux_min = np.nanmin(all_flux)
        flux_max = np.nanmax(all_flux)
        if ax0 is None:
            days = np.max(all_times) - np.min(all_times)
            figsizex = np.max( [5, 5*(days/10.)] )
            fig, ax = plt.subplots(figsize=(figsizex, 4)) #figsize * 5 for every 20 days
        for inst in alles.settings['inst_phot']:
            ax.plot(alles.fulldata[inst]['time'], alles.fulldata[inst]['flux'],ls='none',marker='.',color='silver')
            # ax.plot(alles.data[inst]['time'], alles.data[inst]['flux'],ls='none',marker='.',label=inst) #color code by instrument
        plot_all_transits_color_coded() #color code by companion
                
        ax.plot( alles.data[companion+'_tmid_observed_transits'], np.ones_like(alles.data[companion+'_tmid_observed_transits'])*0.997*flux_min, 'k^', zorder=12 )
        for i, tmid in enumerate(alles.data[companion+'_tmid_observed_transits']):
            ax.text( tmid, 0.992*flux_min, str(i+1), ha='center', zorder=12 )  
            ax.axvline( tmid, color='grey', zorder=11 )
        ax.set(ylim=[0.99*flux_min, 1.002*flux_max], xlabel='Time (BJD)', ylabel='Realtive Flux', title='Companion '+companion) 
        ax.legend(loc='best')
    
        fname = os.path.join(datadir,'ttv_preparation','ttv_preparation_'+companion+'.jpg')
        fig = plt.gcf()
        fig.savefig(fname, bbox_inches='tight' )  
        plt.close(fig)
                
Exemple #4
0
def plot_viol(pathdataoutp, pvalthrs=1e-3, boolonlytess=False):

    strgtimestmp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
    print('allesfitter postprocessing violin plot started at %s...' %
          strgtimestmp)

    liststrgruns = ['woutTESS', 'alldata']
    if boolonlytess:
        liststrgruns.append(['TESS'])

    numbruns = len(liststrgruns)
    indxruns = np.arange(numbruns)

    liststrgpara = [[] for i in indxruns]
    listlablpara = [[] for i in indxruns]
    listobjtalle = [[] for i in indxruns]
    for i, strgruns in enumerate(liststrgruns):
        pathdata = pathdataoutp + 'allesfits/allesfit_%s' % strgruns
        print('Reading from %s...' % pathdata)
        config.init(pathdata)
        liststrgpara[i] = np.array(config.BASEMENT.fitkeys)
        listlablpara[i] = np.array(config.BASEMENT.fitlabels)
        # read the chain
        listobjtalle[i] = allesfitter.allesclass(pathdata)

    liststrgparaconc = np.concatenate(liststrgpara)
    liststrgparaconc = np.unique(liststrgparaconc)
    listlablparaconc = np.copy(liststrgparaconc)
    for k, strgparaconc in enumerate(liststrgparaconc):
        for i, strgruns in enumerate(liststrgruns):
            if strgparaconc in liststrgpara[i]:
                listlablparaconc[k] = listlablpara[i][np.where(
                    liststrgpara[i] == strgparaconc)[0][0]]

    ticklabl = ['w/o TESS', 'w/ TESS']
    if boolonlytess:
        ticklabl.append(['only TESS'])

    xpos = 0.6 * (np.arange(numbruns) + 1.)
    for k, strgpara in enumerate(liststrgparaconc):
        booltemp = True
        for i in indxruns:
            if not strgpara in liststrgpara[i]:
                booltemp = False
        if not booltemp:
            continue

        figr, axis = plt.subplots(figsize=(5, 4))
        chanlist = []
        for i in indxruns:
            chanlist.append(
                (listobjtalle[i].posterior_params[strgpara] -
                 np.mean(listobjtalle[i].posterior_params[strgpara])) * 24. *
                60.)
        axis.violinplot(chanlist, xpos, showmedians=True, showextrema=False)
        axis.set_xticks(xpos)
        axis.set_xticklabels(ticklabl)
        if strgpara == 'b_period':
            axis.set_ylabel('P [min]')
        else:
            axis.set_ylabel(listlablparaconc[k])
        plt.tight_layout()

        path = pathdataoutp + 'viol_%04d.svg' % (k)
        print('Writing to %s...' % path)
        figr.savefig(path)
        plt.close()

    listyear = [2021, 2023, 2025]
    numbyear = len(listyear)
    indxyear = np.arange(numbyear)
    timejwst = [[[] for i in indxruns] for k in indxyear]
    for k, year in enumerate(listyear):
        epocjwst = astropy.time.Time('%d-01-01 00:00:00' % year,
                                     format='iso').jd
        for i in indxruns:
            epoc = listobjtalle[i].posterior_params['b_epoch']
            peri = listobjtalle[i].posterior_params['b_period']
            indxtran = (epocjwst - epoc) / peri
            indxtran = np.mean(np.rint(indxtran))
            if indxtran.size != np.unique(indxtran).size:
                raise Exception('')

            timejwst[k][i] = epoc + peri * indxtran

            timejwst[k][i] -= np.mean(timejwst[k][i])
            timejwst[k][i] *= 24. * 60.

    listfigr = []
    listaxis = []

    ## temporal evolution
    figr, axis = plt.subplots(figsize=(5, 4))
    listfigr.append(figr)
    listaxis.append(axis)
    axis.violinplot([timejwst[k][1] for k in indxyear], listyear)
    axis.set_xlabel('Year')
    axis.set_ylabel('Transit time residual [min]')
    plt.tight_layout()
    path = pathdataoutp + 'jwsttime.svg'
    print('Writing to %s...' % path)
    plt.savefig(path)
    plt.close()

    ## without/with/only TESS prediction comparison
    figr, axis = plt.subplots(figsize=(5, 4))
    listfigr.append(figr)
    listaxis.append(axis)
    axis.violinplot(timejwst[1], xpos, points=2000)
    axis.set_xticks(xpos)
    axis.set_xticklabels(ticklabl)
    axis.set_ylabel('Transit time residual in 2023 [min]')
    #axis.set_ylim([-300, 300])
    plt.tight_layout()
    path = pathdataoutp + 'jwstcomp.svg'
    print('Writing to %s...' % path)
    plt.savefig(path)
    plt.close()

    return listfigr, listaxis

    # all parameter summary
    figr, axis = plt.subplots(figsize=(4, 3))
    chanlist = []
    axis.violinplot(chanlist, xpos, showmedians=True, showextrema=False)
    axis.set_xticks(valutick)
    axis.set_xticklabels(labltick)
    axis.set_ylabel(lablparatemp)
    plt.tight_layout()
    path = pathdataoutp + 'para_%s.pdf'
    print('Writing to %s...' % path)
    figr.savefig(path)
    plt.close()

    # plot p values
    ## threshold p value to conclude significant difference between posteriors with and without TESS
    if pvalthrs is None:
        pvalthrs = 1e-6

    lablparacomp = [[] for u in indxruns]
    for u in indxruns:

        lablparacomp[u] = list(
            set(lablpara[indxrunsfrst[u]]).intersection(
                lablpara[indxrunsseco[u]]))

        # post-processing
        ## calculate the KS test statistic between the posteriors
        numbparacomp = len(lablparacomp[u])
        pval = np.empty(numbparacomp)
        for j in range(numbparacomp):
            kosm, pval[j] = scipy.stats.ks_2samp([indxrunsfrst[u]][:, j],
                                                 chan[indxrunsseco[u]][:, j])
            kosm, pval[j] = scipy.stats.ks_2samp(chan[indxrunsfrst[u]][:, j],
                                                 chan[indxrunsseco[u]][:, j])

        ## find the list of parameters whose posterior with and without TESS are unlikely to be drawn from the same distribution
        indxparagood = np.where(pval < pvalthrs)[0]
        if indxparagood.size > 0:

            figr, axis = plt.subplots(figsize=(12, 5))
            indxparacomp = np.arange(numbparacomp)
            axis.plot(indxparacomp, pval, ls='', marker='o')
            axis.plot(indxparacomp[indxparagood],
                      pval[indxparagood],
                      ls='',
                      marker='o',
                      color='r')
            axis.set_yscale('log')
            axis.set_xticks(indxparacomp)
            axis.set_xticklabels(lablparacomp[u])
            if u == 0:
                axis.set_title('Posteriors with TESS vs. without TESS')
            if u == 1:
                axis.set_title('Posteriors without TESS vs. only TESS')
            if u == 2:
                axis.set_title('Posteriors with TESS vs. only TESS')

            axis.axhline(pvalthrs, ls='--', color='black', alpha=0.3)
            plt.tight_layout()
            path = pathdataoutp + 'kosm_com%d.pdf' % u
            print('Writing to %s...' % path)
            figr.savefig(path)
            plt.close()
def prepare_ttv_fit(datadir, ax=None):
    '''
    this must be run *after* reduce_phot_data()
    '''
    ax0 = ax

    alles = allesfitter.allesclass(datadir)

    def plot_all_transits_color_coded():
        width = alles.settings['fast_fit_width']
        for inst in alles.settings['inst_phot']:
            time = alles.data[inst]['time']
            for companion in alles.settings['companions_phot']:
                ind = []
                for i, t in enumerate(alles.data[companion +
                                                 '_tmid_observed_transits']):
                    ind += list(
                        np.where((time >= (t - width / 2.))
                                 & (time <= (t + width / 2.)))[0])
                ax.plot(alles.data[inst]['time'][ind],
                        alles.data[inst]['flux'][ind],
                        ls='none',
                        marker='.',
                        label=companion)

    for companion in alles.settings['companions_phot']:
        print('#TTV companion ' + companion)
        all_times = []
        all_flux = []
        for inst in alles.settings['inst_phot']:
            all_times += list(alles.data[inst]['time'])
            all_flux += list(alles.data[inst]['flux'])

        alles.data[companion +
                   '_tmid_observed_transits'] = get_tmid_observed_transits(
                       all_times,
                       alles.initial_guess_params_median[companion + '_epoch'],
                       alles.initial_guess_params_median[companion +
                                                         '_period'],
                       alles.settings['fast_fit_width'])
        for i, t in enumerate(alles.data[companion +
                                         '_tmid_observed_transits']):
            print(companion + '_ttv_transit_' + str(i + 1) +
                  ',0,1,uniform -0.05 0.05,TTV$_\mathrm{' + companion + ';' +
                  str(i + 1) + '}$,d')

        #::: plot
        flux_min = np.nanmin(all_flux)
        flux_max = np.nanmax(all_flux)
        if ax0 is None:
            days = np.max(all_times) - np.min(all_times)
            figsizex = np.max([5, 5 * (days / 10.)])
            fig, ax = plt.subplots(figsize=(figsizex,
                                            4))  #figsize * 5 for every 20 days
        for inst in alles.settings['inst_phot']:
            ax.plot(alles.fulldata[inst]['time'],
                    alles.fulldata[inst]['flux'],
                    ls='none',
                    marker='.',
                    color='silver')
            # ax.plot(alles.data[inst]['time'], alles.data[inst]['flux'],ls='none',marker='.',label=inst) #color code by instrument
        plot_all_transits_color_coded()  #color code by companion

        ax.plot(
            alles.data[companion + '_tmid_observed_transits'],
            np.ones_like(alles.data[companion + '_tmid_observed_transits']) *
            0.997 * flux_min,
            'k^',
            zorder=12)
        for i, tmid in enumerate(alles.data[companion +
                                            '_tmid_observed_transits']):
            ax.text(tmid, 0.992 * flux_min, str(i + 1), ha='center', zorder=12)
            ax.axvline(tmid, color='grey', zorder=11)
        ax.set(ylim=[0.99 * flux_min, 1.002 * flux_max],
               xlabel='Time (BJD)',
               ylabel='Realtive Flux',
               title='Companion ' + companion)
        ax.legend(loc='best')

        if not os.path.exists(os.path.join(datadir, 'results')):
            os.makedirs(os.path.join(datadir, 'results'))
        fname = os.path.join(datadir, 'results',
                             'preparation_for_TTV_fit_' + companion + '.jpg')
        fig = plt.gcf()
        fig.savefig(fname, bbox_inches='tight')
        plt.close(fig)
Exemple #6
0
 ns_derived_file = object_dir + "/results/ns_derived_table.csv"
 ns_file = object_dir + "/results/ns_table.csv"
 if not os.path.exists(ns_derived_file) or not os.path.exists(ns_file):
     raise ValueError("Bayesian fit posteriors files {" + ns_file + ", " +
                      ns_derived_file + "} not found")
 star_df = pd.read_csv(object_dir + "/params_star.csv")
 object_id = star_df.iloc[0]["obj_id"]
 ra = star_df.iloc[0]["ra"]
 dec = star_df.iloc[0]["dec"]
 coords = str(ra) + " " + str(dec)
 fit_derived_results = pd.read_csv(object_dir +
                                   "/results/ns_derived_table.csv")
 fit_results = pd.read_csv(object_dir + "/results/ns_table.csv")
 candidates_count = len(
     fit_results[fit_results["#name"].str.contains("_period")])
 alles = allesfitter.allesclass(object_dir)
 since = Time.now() if args.since is None else Time(args.since, scale='utc')
 percentile = 99.7 if args.error_sigma == 3 else 95 if args.error_sigma == 2 else 68
 for i in np.arange(0, candidates_count):
     period_row = fit_results[fit_results["#name"].str.contains(
         "_period")].iloc[i]
     period = period_row["median"]
     period_distribution = alles.posterior_params[period_row["#name"]]
     period_low_err = period - np.percentile(period_distribution,
                                             50 - percentile / 2)
     period_up_err = np.percentile(period_distribution,
                                   50 + percentile / 2) - period
     name = object_id + "_" + period_row["#name"].replace("_period", "")
     epoch_row = fit_results[fit_results["#name"].str.contains(
         "_epoch")].iloc[i]
     epoch = epoch_row["median"].item()
Exemple #7
0
 def custom_plot(name, period, fit_width, allesfit_dir, mode="posterior"):
     """
     Creates a custom fit plot from the allesfitter data
     @param name: the candidate name
     @param period: the final period
     @param fit_width: the fit_width window
     @param allesfit_dir: the directory where allesfitter data is stred
     @param mode: the allesfitter plot model
     """
     allesclass = allesfitter.allesclass(allesfit_dir)
     baseline_width = fit_width * 24
     baseline_to_period = fit_width / period
     fig, axes = plt.subplots(2,
                              3,
                              figsize=(18, 6),
                              gridspec_kw={'height_ratios': [3, 1]},
                              sharex='col')
     fig.subplots_adjust(left=0.5, right=1.5, hspace=0)
     style = 'full'
     allesclass.plot('lc', name, style, ax=axes[0][0], mode=mode)
     axes[0][0].set_title('lc, ' + style)
     allesclass.plot('lc',
                     name,
                     style + '_residuals',
                     ax=axes[1][0],
                     mode=mode)
     axes[1][0].set_title('')
     style = 'phase'
     allesclass.plot('lc',
                     name,
                     style,
                     ax=axes[0][1],
                     mode=mode,
                     zoomwindow=baseline_to_period)
     axes[0][1].set_title('lc, ' + style)
     axes[0][1].set_xlim([-baseline_to_period / 2, baseline_to_period / 2])
     allesclass.plot('lc',
                     name,
                     style + '_residuals',
                     ax=axes[1][1],
                     mode=mode,
                     zoomwindow=baseline_to_period)
     axes[1][1].set_title('')
     axes[1][1].set_xlim([-baseline_to_period / 2, baseline_to_period / 2])
     style = 'phasezoom'
     allesclass.plot('lc',
                     name,
                     style,
                     ax=axes[0][2],
                     mode=mode,
                     zoomwindow=baseline_width)
     axes[0][2].set_title('lc, ' + style)
     axes[0][2].set_xlim([-baseline_width / 2, baseline_width / 2])
     allesclass.plot('lc',
                     name,
                     style + '_residuals',
                     ax=axes[1][2],
                     mode=mode,
                     zoomwindow=baseline_width)
     axes[1][2].set_title('')
     axes[1][2].set_xlim([-baseline_width / 2, baseline_width / 2])
     fig.savefig(allesfit_dir + '/results/ns_' + mode + '_' + name +
                 '_custom.pdf',
                 bbox_inches='tight')
     style = ['phasezoom_occ']
     style = ['phase_variations']
Exemple #8
0
def plot_spots_new(datadir):

    alles = allesfitter.allesclass(datadir)

    for inst in alles.BASEMENT.settings['inst_phot']:
        fig = plt.figure()
        plt.subplot(111, projection="aitoff")
        plt.grid(True)
        for i in [1, 2]:
            lons = alles.posterior_params['host_spot_' + str(i) + '_long_' +
                                          inst][0:20]
            lats = alles.posterior_params['host_spot_' + str(i) + '_lat_' +
                                          inst][0:20]
            sizes = alles.posterior_params['host_spot_' + str(i) + '_size_' +
                                           inst][0:20]
            brightnesses = alles.posterior_params['host_spot_' + str(i) +
                                                  '_brightness_' + inst][0:20]
            lon_list, lat_list, brightness_list = convert_many_points_to_an_area(
                lons, lats, sizes, brightnesses)
            c = SkyCoord(ra=lon_list * u.deg, dec=lat_list * u.deg)
            lon_list_aitoff = c.ra.wrap_at(180 * u.deg).radian
            lat_list_aitoff = c.dec.radian
            plt.scatter(lon_list_aitoff,
                        lat_list_aitoff,
                        c=brightness_list,
                        vmin=0,
                        vmax=1)
        plt.colorbar(label='Relative spot brightness')
        plt.xlabel('Longitude (deg)')
        plt.ylabel('Latitude (deg)')
        plt.tight_layout()
        plt.xticks(ticks=np.deg2rad(
            [-150, -120, -90, -60, -30, 0, 30, 60, 90, 120, 150, 180]),
                   labels=[
                       '', '', r'$270^\circ$', '', '', r'$0^\circ$', '', '',
                       r'$90^\circ$', '', '', r'$180^\circ$'
                   ])
        plt.yticks(ticks=np.deg2rad([-90, -60, -30, 0, 30, 60, 90]),
                   labels=[
                       '', r'$-60^\circ$', r'$-30^\circ$', '0', r'$30^\circ$',
                       r'$60^\circ$', ''
                   ])
        fig.savefig(os.path.join(alles.BASEMENT.outdir,
                                 'spots_aitoff_' + inst + '.pdf'),
                    bbox_inches='tight')

        fig = plt.figure()
        plt.xlim([0, 360])
        plt.ylim([-90, 90])
        for i in [1, 2]:
            lons = alles.posterior_params['host_spot_' + str(i) + '_long_' +
                                          inst][0:20]
            lats = alles.posterior_params['host_spot_' + str(i) + '_lat_' +
                                          inst][0:20]
            sizes = alles.posterior_params['host_spot_' + str(i) + '_size_' +
                                           inst][0:20]
            brightnesses = alles.posterior_params['host_spot_' + str(i) +
                                                  '_brightness_' + inst][0:20]
            lon_list, lat_list, brightness_list = convert_many_points_to_an_area(
                lons, lats, sizes, brightnesses)
            plt.scatter(lon_list, lat_list, c=brightness_list, vmin=0, vmax=1)
        plt.colorbar(label='Relative spot brightness')
        plt.xlabel('Longitude (deg)')
        plt.ylabel('Latitude (deg)')
        plt.tight_layout()
        fig.savefig(os.path.join(alles.BASEMENT.outdir,
                                 'spots_cartesian_' + inst + '.pdf'),
                    bbox_inches='tight')
Exemple #9
0
#::: plotting settings
import seaborn as sns
sns.set(context='paper',
        style='ticks',
        palette='deep',
        font='sans-serif',
        font_scale=1.5,
        color_codes=True)
sns.set_style({"xtick.direction": "in", "ytick.direction": "in"})
sns.set_context(rc={'lines.markeredgewidth': 1})

###############################################################################
#::: plot the fit
###############################################################################
alles = allesfitter.allesclass('allesfit_year_1')
fig, axes = plt.subplots(2,
                         3,
                         figsize=(15, 5),
                         gridspec_kw={'height_ratios': [3, 1]},
                         sharex='col')

alles.plot('TESS',
           'c',
           'phasezoom',
           ax=axes[0, 0],
           kwargs_data={'rasterized': False},
           kwargs_ax={'title': ''})
alles.plot('TESS',
           'c',
           'phasezoom_residuals',
Exemple #10
0
import astropy.units as u
from astropy.time import Time

from lcbuilder.eleanor import TargetData
from sherlockpipe import constants as const
from sherlockpipe import tpfplotter
from sherlockpipe.nbodies.megno import MegnoStabilityCalculator
from sherlockpipe.nbodies.stability_calculator import StabilityCalculator
from sherlockpipe.sherlock import Sherlock

# sherlock = Sherlock(None)
# sherlock = sherlock.filter_multiplanet_ois()
# sherlock.ois.to_csv("multiplanet_ois.csv")

#Allesfitter stuff
alles = allesfitter.allesclass("/mnt/0242522242521AAD/dev/workspaces/git_repositories/sherlockpipe/TIC305048087_[2]_bck/fit_2/")
alles.posterior_samples("lc", "SOI_2_period")
allesfitter.ns_output("/mnt/0242522242521AAD/dev/workspaces/git_repositories/sherlockpipe/run_tests/analysis/TIC142748283_all/fit_0/ttvs_0")
results = pickle.load(open('/mnt/0242522242521AAD/dev/workspaces/git_repositories/sherlockpipe/run_tests/analysis/dietrich/TIC467179528_all/fit_2/results/ns_derived_samples.pickle', 'rb'))
logging.info(results)

#Stability plots
# stability_dir = "/mnt/0242522242521AAD/dev/workspaces/git_repositories/sherlockpipe/run_tests/analysis/dietrich/TIC467179528_all/fit_2/stability_0/"
# df = pandas.read_csv(stability_dir + "stability_megno.csv")
# df = df[(df["megno"] < 3)]
# stability_calc = MegnoStabilityCalculator(5e2)
# for key, row in df.iterrows():
#     stability_calc.plot_simulation(row, stability_dir, str(key))

# filename = "/home/martin/Downloads/resimplepulsations/P2.5_R1.28_1354.197892531283.csv"
# df = pandas.read_csv(filename, float_precision='round_trip', sep=',',
Exemple #11
0
def plot_viol(pathbase, liststrgstar, liststrgruns, lablstrgruns, pathimag, pvalthrs=1e-3):

    strgtimestmp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
    print('allesfitter postprocessing violin plot started at %s...' % strgtimestmp)
    
    # construct global object
    gdat = gdatstrt()
    
    # copy unnamed inputs to the global object
    #for attr, valu in locals().iter():
    for attr, valu in locals().items():
        if '__' not in attr and attr != 'gdat':
            setattr(gdat, attr, valu)

    # runs to be compared for each star
    gdat.numbruns = len(liststrgruns)
    gdat.indxruns = np.arange(gdat.numbruns)
    
    gdat.pathimag = pathimag
    gdat.liststrgstar = liststrgstar

    # stars
    numbstar = len(liststrgstar)
    gdat.indxstar = np.arange(numbstar)

    # plotting
    gdat.strgplotextn = 'png'

    # read parameter keys, labels and posterior from allesfitter output
    liststrgpara = [[] for i in gdat.indxruns]
    listlablpara = [[] for i in gdat.indxruns]
    gdat.listobjtalle = [[[] for m in gdat.indxstar] for i in gdat.indxruns]
    for i in gdat.indxruns:
        for m in gdat.indxstar:
            pathalle = pathbase + '%s/allesfits/allesfit_%s/' % (gdat.liststrgstar[m], gdat.liststrgruns[i])
            print('Reading from %s...' % pathalle)
            config.init(pathalle)
            liststrgpara[i] = np.array(config.BASEMENT.fitkeys)
            listlablpara[i] = np.array(config.BASEMENT.fitlabels)
            # read the chain
            print('pathalle')
            print(pathalle)
            gdat.listobjtalle[i][m] = allesfitter.allesclass(pathalle)
    
    # concatenate the keys, labels from different runs
    gdat.liststrgparaconc = np.concatenate(liststrgpara)
    gdat.liststrgparaconc = np.unique(gdat.liststrgparaconc)
    gdat.listlablparaconc = np.copy(gdat.liststrgparaconc)
    for k, strgparaconc in enumerate(gdat.liststrgparaconc):
        for i, strgruns in enumerate(liststrgruns):
            if strgparaconc in liststrgpara[i]:
                gdat.listlablparaconc[k] = listlablpara[i][np.where(liststrgpara[i] == strgparaconc)[0][0]]
    
    gdat.numbparaconc = len(gdat.liststrgparaconc)
    gdat.indxparaconc = np.arange(gdat.numbparaconc)
    for k, strgpara in enumerate(gdat.liststrgparaconc):
        booltemp = True
        for i in gdat.indxruns:
            if not strgpara in liststrgpara[i]:
                booltemp = False
        if not booltemp:
            continue
        
        ## violin plot
        ## mid-transit time prediction
        plot(gdat, gdat.indxstar, indxpara=np.array([k]), strgtype='paracomp')
        ## per-star 
        #for m in gdat.indxstar:
        #    plot(gdat, indxstar=np.array([m]), indxpara=k, strgtype='paracomp')
        
    # calculate the future evolution of epoch
    gdat.listyear = [2021, 2023, 2025]
    numbyear = len(gdat.listyear)
    gdat.indxyear = np.arange(numbyear)
    gdat.timejwst = [[[[] for m in gdat.indxstar] for i in gdat.indxruns] for k in gdat.indxyear]
    for k, year in enumerate(gdat.listyear):
        epocjwst = astropy.time.Time('%d-01-01 00:00:00' % year, format='iso').jd
        for i in gdat.indxruns:
            for m in gdat.indxstar:
                epoc = gdat.listobjtalle[i][m].posterior_params['b_epoch']
                peri = gdat.listobjtalle[i][m].posterior_params['b_period']
                indxtran = (epocjwst - epoc) / peri
                indxtran = np.mean(np.rint(indxtran))
                if indxtran.size != np.unique(indxtran).size:
                    raise Exception('')
                gdat.timejwst[k][i][m] = epoc + peri * indxtran
                gdat.timejwst[k][i][m] -= np.mean(gdat.timejwst[k][i][m])
                gdat.timejwst[k][i][m] *= 24. * 60.
    
    listfigr = []
    listaxis = []

    # temporal evolution of mid-transit time prediction
    plot(gdat, gdat.indxstar, strgtype='epocevol')
    ## per-star 
    #for m in gdat.indxstar:
    #    plot(gdat, indxstar=np.array([m]), strgtype='epocevol')
    
    ## mid-transit time prediction
    plot(gdat, gdat.indxstar, strgtype='jwstcomp')
    ## per-star 
    #for m in gdat.indxstar:
    #    plot(gdat, indxstar=np.array([m]), strgtype='jwstcomp')
    
    return listfigr, listaxis