def uncertainties_at_completeness(table='default', binwidth=0.1):
    '''
    write a table with the median uncertainties around the completeness value
    from the completeness table.
    '''
    comp90 = sfh_tests.read_completeness_table(table)
    if table == 'default':
        table = snap_src + '/tables/completeness_0.90.dat'
    table = table.replace('.dat', '_uncertainties.dat')
    opt_fits_src = snap_src + '/data/angst_no_trim'
    fmt = '%(target)s %(opt_filter1).3f %(opt_filter2).3f %(opt_color).3f %(ir_filter1).3f %(ir_filter2).3f %(ir_color).3f \n'
    title = '# ' + fmt.replace('%','').replace(')', '').replace('.3f','').replace('s','').replace('(','')
    with open(table, 'w') as out:
        out.write('# median uncertainty within +/-%.2f of completeness mag\n' % (binwidth/2))
        out.write(title)
        for i, target in enumerate(comp90['target']):
            ir_gal = galaxy_tests.load_galaxy(target, band='ir')
            opt_gal = galaxy_tests.load_galaxy(target, band='opt',
                                               fits_src=opt_fits_src)
            dline = {'target': target}
            for band, gal in zip(['opt', 'ir'], [opt_gal, ir_gal]):
                key = '%s_filter1' % band
                uncerts1, = np.nonzero((gal.mag1 < comp90[i][key] + binwidth/2) &
                                       (gal.mag1 > comp90[i][key] - binwidth/2))
                med_unct1 = np.median(gal.data.MAG1_ERR[uncerts1])
                dline[key] = med_unct1
                key = '%s_filter2' % band
                uncerts2, = np.nonzero((gal.mag2 < comp90[i][key] + binwidth/2) &
                                       (gal.mag2 > comp90[i][key] - binwidth/2))            
                
                med_unct2 = np.median(gal.data.MAG2_ERR[uncerts2])
                dline[key] = med_unct2
                med_color_unct = np.sqrt(med_unct1 ** 2 + med_unct2 ** 2)
                dline['%s_color' % band] = med_color_unct
                
            out.write(fmt % dline)
            
            
            
            
            
            
            
            
            
            
            
            
def plot_cmd_lf(target, band):
    '''simple figure with the data and LF'''
    import model_plots
    lims = model_plots.load_plot_limits()
    row = lims[lims['target'] == target.lower()]
    target = target.upper()

    print row
    if band == 'opt':
        fits_src = snap_src + '/data/angst_no_trim'
        cmd_errors_kw = {}
        ymin, ymax = row['opt_cmdmin'], row['opt_cmdmax']
    else:
        fits_src = 'default'
        cmd_errors_kw = {'errclr': -.5}
        ymin, ymax = row['ir_cmdmin'], row['ir_cmdmax']
    fig = plt.figure(figsize=(6, 6))
    gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])
    ax1 = plt.subplot(gs[0])
    ax2 = plt.subplot(gs[1])
    gal = galaxy_tests.load_galaxy(target, band=band, fits_src=fits_src)

    gal.plot_cmd(gal.color, gal.mag2, ax=ax1, scatter_off=True)
    hist, bins = rsp.math_utils.hist_it_up(gal.mag2)
    ax1.set_ylim(ymax, ymin)
    if band == 'opt':
        xmin = -2
    if band == 'ir':
        xmin = -1

    #ax1.set_ylim()
    #ax2.set_ylim()

    ax1.set_xlim(xmin, ax1.get_xlim()[1])
    gal.decorate_cmd(ax=ax1, trgb=True, cmd_errors_kw=cmd_errors_kw, text_kw={'distance_av': False})
    err = np.sqrt(hist)
    ax2.set_xscale('log')
    ax2.errorbar(hist, bins[:-1], xerr=err, color='black', drawstyle='steps-mid')
    ax2.plot(hist, bins[:-1], linestyle='mid-steps', color='black', lw=3)
    ax2.set_ylim(ax1.get_ylim())
    gal.put_a_line_on_it(ax2, gal.trgb)
    plt.subplots_adjust(wspace=0)
    ax2.tick_params(labelleft=False, labelright=True)
    ax2.set_xlim(min(hist), ax2.get_xlim()[1])
    ax2.set_xlabel('$\#$', fontsize=fontlarge)
    ax1.set_ylabel('$%s$' % gal.filter2, fontsize=fontlarge)
    ax1.set_xlabel('$%s-%s$' % (gal.filter1, gal.filter2), fontsize=fontlarge)
    add_color_cuts(gal.filter1, ax=ax1, vline_kw={'linestyle': '--', 'lw': 2})
    plt.tick_params(labelsize=fontmid)
    outfname = '%s_%s_cmd.png' % (target, band)
    outfile = os.path.join(snap_src, 'plots', outfname)
    fig.savefig(outfile, dpi=150)
def plot_opt_hess(targets=None, fits_src='default', filter1='F606W'):
    band = 'opt'
    ylim = (0.5, -7)
    if filter1 == 'F110W':
        band = 'ir'
        fits_src = 'default'
        ylim = (-2, -8)
    targets = galaxy_tests.load_targets(targets)
    galss = rsp.Galaxies.galaxies([galaxy_tests.load_galaxy(t, band=band,
                                                           fits_src=fits_src)
                                  for t in targets])

    gals = rsp.Galaxies.galaxies(galss.select_on_key('filter1', filter1))

    gals.squish('Color', 'Mag2', 'Trgb')

    mean_trgb = np.mean(gals.Trgbs)
    offset = gals.Trgbs - np.mean(gals.Trgbs)
    gals.Mag2o = np.concatenate([g.Mag2 - offset[i] for i, g in enumerate(gals.galaxies)])
    gals.Colorso = gals.Colors + gals.Mag2s - gals.Mag2o
    galshess =  rsp.astronomy_utils.hess(gals.Colorso, gals.Mag2o, 0.1, cbinsize=0.05)

    #N, xedges, yedges = binned_statistic_2d(gals.Colors, gals.Mag2s, gals.Mag2s, 'count', bins=2000)
    fig, ax = plt.subplots()
    #im = ax.imshow(np.log10(N.T), origin='lower',
    ##                           extent=[xedges[0], xedges[-1], yedges[0],
    #                                   yedges[-1]],
    #                           aspect='auto', interpolation='nearest',
    #                           cmap=plt.cm.RdBu)

    extent = [galshess[0][0], galshess[0][-1], galshess[1][-1], galshess[1][0]]
    imshow_kw={'norm': LogNorm(vmin=None, vmax=galshess[2].max()),
               'cmap': plt.cm.gray_r, 'interpolation': 'nearest',
               'aspect': 'equal', 'extent': extent}

    ax.plot(gals.Colorso, gals.Mag2o, ',', color='black')
    ax.autoscale(False)
    ax.set_xlim(-1, 3)
    ax.set_ylim(ylim)
    #ax.imshow(galshess[2], **imshow_kw)
    ax.set_aspect(1./2.)

    ax.set_xlabel('$%s-%s$' % (filter1, gals.galaxies[0].filter2), fontsize=fontlarge)
    ax.set_ylabel('$%s$' % gals.galaxies[0].filter2, fontsize=fontlarge)
    ax.hlines(mean_trgb, *ax.get_xlim(), lw=2, color='red', zorder=100)
    #ax.hlines(mean_trgb+1.5, *ax.get_xlim(), lw=2, color='red', zorder=100)
    #for k, v in poly_dict.items():
    #    ax.plot(v[:,0], v[:,1])
    #plt.colorbar(cs)
    #plt.savefig('opt_cmd_f606w.png', dpi=150)
    return fig, ax, gals
Beispiel #4
0
def completeness_below_trgb():
    targets = galaxy_tests.ancients()
    ast_kw = {'combined_filters': True, 'interpolate': True}

    for target in targets:
        fake_files = galaxy_tests.get_fake_files(target)
        for band, fake_file in zip(['opt', 'ir'], fake_files):
            if band == 'opt':
                fits_src = snap_src + '/data/angst_no_trim'
            else:
                continue
                fits_src = 'default'
            gal = galaxy_tests.load_galaxy(target, band=band,
                                           fits_src=fits_src)
            gal.make_hess(binsize=0.1, hess_kw={'cbinsize': 0.05})
            
            asts = rsp.Galaxies.artificial_star_tests(fake_file)
            asts.completeness(**ast_kw)
            
            imag, icol = np.argwhere(gal.hess[2] == gal.hess[2].max())[0]
            rc_mag2 = gal.hess[1][imag]
            comp = asts.fcomp2(rc_mag2 - 1.)
            print '%s %s %.3f %.3f' % (target, band, rc_mag2, comp)