def desample(x, y, num):
    import fitting as my_fits
    ddy = np.abs(np.gradient(np.gradient(y)))
    f_arr = cdf(x, ddy)
    f_arr = f_arr * (x[-1] - x[0]) + x[0]
    f = my_fits.piecewise(f_arr, x)
    new_x = f(np.linspace(x[0], x[-1], num))
    new_y = my_fits.piecewise(x, y)(new_x)
    return new_x, new_y
def gaussian_cdf_space(mu, sig, num, sig_lim=5):
    import fitting as my_fits
    x = np.linspace(mu - sig_lim * sig, mu + sig_lim * sig, 300)
    cdf = gaussian_cdf(x, mu, sig)
    fit = my_fits.piecewise(cdf, x)
    temp = np.linspace(0, 1, num + 1)  #splitting into equal area sections
    y = (temp[1:] + temp[:-1]) / 2  #making point the center of each section
    arr = fit(y)
    #plt.plot(x,gaussian(x,mu,sig))
    #plt.scatter(arr,gaussian(arr,mu,sig))
    #plt.show()
    return arr
def shadeStats(age, y, stat, upperLim):
    if upperLim:
        plt.fill_between(age,y, where= (age >= stat[2]) & (age <= stat[3]),\
                color='.3', label=r'1$\sigma$ lower lim: %.3g Myr' % stat[2])
        plt.fill_between(age,y, where= (age >= stat[1]) & (age <= stat[2]),\
                color='.6',alpha=1, label=r'2$\sigma$ lower lim: %.3g Myr' % stat[1])
        plt.fill_between(age,y, where= (age >= stat[0]) & (age <= stat[1]),\
                color='.9',alpha=1,label=r'3$\sigma$ lower lim: %.3g Myr' % stat[0])
        return

    age2 = np.linspace(stat[0], stat[-1], 500)
    interp = my_fits.piecewise(age, y)
    y2 = interp(age2)

    plt.vlines(x=stat[2],ymin= 0,ymax= interp(stat[2]), \
            label='BAFFLES median age: %.3g Myr' % stat[2] ,color = 'orange')
    plt.fill_between(age2,y2, where= (age2 >= stat[1]) & (age2 <= stat[3]),color='.3', \
            label='68%% CI: %.2g - %.2g' % (stat[1],stat[-2]))
    plt.fill_between(age2,y2, where= (age2 >= stat[0]) & (age2 <= stat[-1]),color='.6',\
            alpha=0.5, label='95%% CI: %.2g - %.2g' % (stat[0],stat[-1]))
def robs_fomalhaut():
    import astropy
    from scipy.signal import savgol_filter
    t = astropy.io.fits.open(join('data','Fom-age-pdf.fits'))
    data = t[0].data
    x = np.linspace(np.min(data)-10,np.max(data)+10,1000)
    cdf = np.array([(data < n).sum() for n in x],dtype='float')/len(x)
    cdf /= cdf[-1]

    smoothed = savgol_filter(cdf, 51, 3)

    pdf = np.gradient(smoothed)
    pdf = savgol_filter(pdf,101,3)
    prob.normalize(x,pdf)
    
    #plt.plot(x,pdf,label='PDF')
    #plt.hist(data,bins=100,density=True)
    #plt.show()

    pdf[0:2],pdf[-2:] = [0,0],[0,0]
    
    return my_fits.piecewise(x,pdf)
def combined_validation_subplots():
    const = utils.init_constants(METAL)
    #Omitting each cluster
    name = join('plots', METAL + '_combined_validation_subplots.pdf')
    pp = PdfPages(name)
    baf_default = baffles.age_estimator(METAL)

    fig, ax = plt.subplots(3, 2, figsize=(14, 15))
    cmap = plt.cm.get_cmap('RdYlBu_r')
    norm = mpl.colors.Normalize(vmin=const.BV_RANGE[0], vmax=const.BV_RANGE[1])
    sc = plt.scatter([], [], c=[], norm=norm, cmap=cmap)

    fig.tight_layout(pad=.4, w_pad=1, h_pad=2)
    fig.subplots_adjust(left=0.06)
    fig.subplots_adjust(bottom=0.06)
    fig.subplots_adjust(top=.95)
    fig.subplots_adjust(right=0.9)
    #cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
    cbar_ax = fig.add_axes([0.92, 0.25, 0.02, 0.5])
    fig.colorbar(sc, cax=cbar_ax)

    for index, i in enumerate([1, 3, 5, 6, 7,
                               8]):  #[0,4,5,6,7,8] for submission 2!
        print(const.CLUSTER_NAMES[i])
        baf = baffles.age_estimator(METAL, default_grids=False)
        baf.make_grids(bv_m, fits, omit_cluster=i)
        p_val = baf.posterior_product(bv_m[i][0], bv_m[i][1])

        pl = ax[int(index / 2), index % 2]
        pl.plot(const.AGE,
                p_val.array,
                linewidth=2,
                linestyle='--',
                label='Posterior with removal')
        pl.set_title(const.CLUSTER_NAMES[i], size=my_plot.TITLE_SIZE)

        bv_arr = bv_m[i][0]
        p = baf_default.posterior_product(bv_m[i][0],
                                          bv_m[i][1],
                                          upperLim_arr=None,
                                          showStars=True)
        #print(p.stars_posteriors)
        age, y = const.AGE, p.array
        givenAge = const.CLUSTER_AGES[i]

        for star, post in enumerate(p.stars_posteriors):
            color = cmap(norm(bv_arr[star]))
            prob.scale_to_height(post, np.max(y))
            pl.plot(const.AGE,
                    post,
                    alpha=1,
                    linewidth=1,
                    color=color,
                    zorder=0)

        if (givenAge):
            print('Isochronal age exists within %f %% CI' %
                  prob.get_percentile(age, y, givenAge))
            pl.axvline(x=givenAge,
                       color='r',
                       label='Isochronal age: %d Myr' % givenAge)
            #if (givenErr):
            #    if (type(givenErr) == float or type(givenErr) == int):
            #        givenErr = [-1*givenErr,givenErr]
            #    pl.axvspan(givenAge+givenErr[0], givenAge+givenErr[1], alpha=0.2, color='r',zorder=0)
        #if (mamajekAge):
        #    plt.axvline(x=mamajekAge,color='C2',label='MH08 age: %d' % mamajekAge)

        pl.plot(age, y, color='C0', linewidth=2)
        stat = p.stats
        age2 = np.linspace(stat[0], stat[-1], 500)
        interp = my_fits.piecewise(age, y)
        y2 = interp(age2)
        pl.vlines(x=stat[2],ymin= 0,ymax= interp(stat[2]), \
                label='BAFFLES median age: %.3g Myr' % stat[2] ,color = 'orange')
        pl.fill_between(age2,y2, where= (age2 >= stat[1]) & (age2 <= stat[3]),color='.3', \
                label='68%% CI: %.2g - %.2g' % (stat[1],stat[-2]))
        pl.fill_between(age2,y2, where= (age2 >= stat[0]) & (age2 <= stat[-1]),color='.6',\
                alpha=0.5, label='95%% CI: %.2g - %.2g' % (stat[0],stat[-1]))
        pl.set_ylim([0, np.max(y) * 1.5])
        r = my_plot.getAgeRange(p.stats, p.stars_posteriors, givenAge)
        pl.set_xlim(r)
        pl.legend()
        pl.minorticks_on()
        pl.tick_params(axis='both', which='both', right=True, top=True)

    # Set common labels
    fig.text(0.5,
             0.02,
             'Age (Myr)',
             size=my_plot.AXIS_LABEL_SIZE,
             ha='center',
             va='center')
    fig.text(0.01,
             0.5,
             'Probability Density (Myr^-1)',
             size=my_plot.AXIS_LABEL_SIZE,
             ha='center',
             va='center',
             rotation='vertical')
    fig.text(0.99,
             0.5,
             'B-V',
             size=my_plot.AXIS_LABEL_SIZE,
             ha='center',
             va='center',
             rotation='vertical')
    pp.savefig()
    plt.close()
    printName(name)
    pp.close()
def get_percentile(age, y, givenAge):
    import fitting as my_fits
    c = cdf(age, y)
    fit = my_fits.piecewise(age, c)
    return np.abs(fit(givenAge) - .5) * 2 * 100
def stats(age, y, upperLim=False):
    import fitting as my_fits
    c = cdf(age, y)
    probs = UL_PROBS if upperLim else GAUSS_PROBS
    fit = my_fits.piecewise(c, age)
    return fit(probs)
Exemple #8
0
def undo_picklable(fits):
    const = utils.init_constants('lithium')
    for c,i in [(c,i) for c in range(len(fits)) for i in range(2)]:
        if type(fits[c][i]) != type(np.poly1d([1])):
            fits[c][i] = my_fits.piecewise(const.BV,fits[c][i])
    return fits