def vel_kms_to_masyr(vel=1000.0, z=1.0):

    vel = vel * u.kilometer / u.second

    vel_mas_per_year = (vel.to(u.kpc / u.yr) *
                        cosmo.arcsec_per_kpc_proper(z).to(u.mas / u.kpc))
    if z < 0.1:
        d = cosmo.angular_diameter_distance(z).to(u.kpc)
        loc_vel_mas_per_year = ((vel.to(u.kpc / u.yr) / d) * (u.rad)).to(
            u.mas / u.yr)

    #table 6 says 0.7 mas is max resolution, for 93GHz band

    print("D_A (z=%g) = " % z, cosmo.angular_diameter_distance(z))
    print("D_L (z=%g) = " % z, cosmo.luminosity_distance(z))
    print("arcsec/kpc (z=%g) =" % z, cosmo.arcsec_per_kpc_proper(z))
    print("mas/kpc (z=%g) =" % z,
          cosmo.arcsec_per_kpc_proper(z).to(u.mas / u.kpc))
    print("physical res for 10 mas (z=%g) = " % z,
          10 * u.mas / (cosmo.arcsec_per_kpc_proper(z).to(u.mas / u.pc)))
    print("vel [km/s] = %g" % vel.to_value())
    print("vel [km/s] =", vel)
    print("vel [pc/Myr] =", vel.to(u.pc / u.Myr))
    print(vel)
    print("vel [kpc/yr] =", vel.to(u.kpc / u.yr))
    print("vel [mas/yr] = ", vel_mas_per_year)
    if z < 0.1: print("loc vel [mas/yr] = ", loc_vel_mas_per_year)
    print("motion in 10 yr lifetime = ", vel_mas_per_year * 10 * u.yr)

    return vel_mas_per_year
Пример #2
0
def make_phys_gif_plots():
    natural_base = '_nref11_RD0020_'
    refined_base = '_nref11n_nref10f_refine200kpc_z4to2_RD0020_'
    box_size = ds.arr(rb_width,'code_length').in_units('kpc')
    box_size = np.ceil(box_size/2.)
    res_list = [0.2,0.5,1,5,10]
    fontrc ={'fontname':'Helvetica','fontsize':20}
    mpl.rc('text', usetex=True)
    make_imshow = True
    properties = ['hden','temp']
    lims = {'hden':(-6,-1),'temp':(4.5,6.5)}

    for line in lines:
        field = 'Emission_'+line
        for index in 'xyz':
            for res in res_list:
                for prop in properties:
                    if res == res_list[0]:
                        fileinNAT = 'frbs/frb'+index+natural_base+prop+'_'+field+'_forcedres.cpkl'
                        fileinREF = 'frbs/frb'+index+refined_base+prop+'_'+field+'_forcedres.cpkl'
                        pixsize = round(cosmo.arcsec_per_kpc_proper(redshift).value*0.182959,2)
                    else:
                        fileinNAT = 'frbs/frb'+index+natural_base+prop+'_'+field+'_'+str(res)+'kpc.cpkl'
                        fileinREF = 'frbs/frb'+index+refined_base+prop+'_'+field+'_'+str(res)+'kpc.cpkl'
                        pixsize = round(cosmo.arcsec_per_kpc_proper(redshift).value*res,2)

                    frbNAT = cPickle.load(open(fileinNAT,'rb'))
                    frbREF = cPickle.load(open(fileinREF,'rb'))
                    frbNAT = np.log10(frbNAT/(1.+redshift)**4)
                    frbREF = np.log10(frbREF/(1.+redshift)**4)

                    bsL,bsR = -1*box_size.value,box_size.value

                    fig,ax = plt.subplots(1,2)
                    fig.set_size_inches(10,6)

                    im = ax[0].imshow(frbNAT,extent=(bsL,bsR,bsR,bsL),
                                    vmin=lims[prop][0],vmax=lims[prop][1],interpolation=None,
                                    cmap='viridis',origin='lower')
                    im1= ax[1].imshow(frbREF,extent=(bsL,bsR,bsR,bsL),
                                    vmin=lims[prop][0],vmax=lims[prop][0],interpolation=None,
                                    cmap='viridis',origin='lower')

                    axins = inset_axes(ax[1],
                            width="5%",  # width = 10% of parent_bbox width
                            height="100%",  # height : 50%
                            loc=3,bbox_to_anchor=(1.07, 0.0, 1, 1),bbox_transform=ax[1].transAxes,borderpad=0)

                    ax[0].set_title('Natural',**fontrc)
                    ax[1].set_title('Forced Refine',**fontrc)
                    cb = fig.colorbar(im1, cax=axins,label=r'log( photons s$^{-1}$ cm$^{-2}$ sr$^{-1}$)')
                    if line == 'CIII_977':
                        lineout = 'CIII 977'
                    else:
                        lineout = line
                        fig.suptitle('z=2, '+lineout+', '+str(res)+'kpc'+', '+str(pixsize)+'"',**fontrc)
                        plt.savefig('z2_'+index+'_'+prop+'_'+field+'_'+str(res)+'kpc.pdf')
                        plt.close()
    return
Пример #3
0
def arcsec2kpc(redshift):
    """Compute and return the scale factor to convert a physical axis in arcseconds
    to kpc.

    """
    from astropy.cosmology import WMAP9 as cosmo
    return 1 / cosmo.arcsec_per_kpc_proper(redshift).value  # [kpc/arcsec]
Пример #4
0
def cutout_radius_100kpc(redshift, pixscale=0.262, radius_kpc=100):
    """Get a cutout radius of 100 kpc [in pixels] at the redshift of the cluster.

    """
    from astropy.cosmology import WMAP9 as cosmo
    arcsec_per_kpc = cosmo.arcsec_per_kpc_proper(redshift).value
    radius = np.rint(radius_kpc * arcsec_per_kpc / pixscale).astype(int) # [pixels]
    return radius
Пример #5
0
def ellipse_sbprofile(ellipsefit, band=('g', 'r', 'z'), refband='r',
                      minerr=0.02, redshift=None, pixscale=0.262):
    """Convert ellipse-fitting results to a magnitude, color, and surface brightness
    profiles.

    """
    if redshift:
        from astropy.cosmology import WMAP9 as cosmo
        smascale = pixscale / cosmo.arcsec_per_kpc_proper(redshift).value # [kpc/pixel]
        smaunit = 'kpc'
    else:
        smascale = 1.0
        smaunit = 'pixels'

    indx = np.ones(len(ellipsefit[refband]), dtype=bool)

    sbprofile = dict()
    sbprofile['smaunit'] = smaunit
    sbprofile['sma'] = ellipsefit['r'].sma[indx] * smascale

    with np.errstate(invalid='ignore'):
        for filt in band:
            #area = ellipsefit[filt].sarea[indx] * pixscale**2

            sbprofile['mu_{}'.format(filt)] = 22.5 - 2.5 * np.log10(ellipsefit[filt].intens[indx])

            #sbprofile[filt] = 22.5 - 2.5 * np.log10(ellipsefit[filt].intens[indx])
            sbprofile['mu_{}_err'.format(filt)] = ellipsefit[filt].int_err[indx] / \
              ellipsefit[filt].intens[indx] / np.log(10)

            #sbprofile['mu_{}'.format(filt)] = sbprofile[filt] + 2.5 * np.log10(area)

            # Just for the plot use a minimum uncertainty
            #sbprofile['{}_err'.format(filt)][sbprofile['{}_err'.format(filt)] < minerr] = minerr

    sbprofile['gr'] = sbprofile['mu_g'] - sbprofile['mu_r']
    sbprofile['rz'] = sbprofile['mu_r'] - sbprofile['mu_z']
    sbprofile['gr_err'] = np.sqrt(sbprofile['mu_g_err']**2 + sbprofile['mu_r_err']**2)
    sbprofile['rz_err'] = np.sqrt(sbprofile['mu_r_err']**2 + sbprofile['mu_z_err']**2)

    # Just for the plot use a minimum uncertainty
    sbprofile['gr_err'][sbprofile['gr_err'] < minerr] = minerr
    sbprofile['rz_err'][sbprofile['rz_err'] < minerr] = minerr

    # Add the effective wavelength of each bandpass, although this needs to take
    # into account the DECaLS vs BASS/MzLS filter curves.
    from speclite import filters
    filt = filters.load_filters('decam2014-g', 'decam2014-r', 'decam2014-z', 'wise2010-W1', 'wise2010-W2')
    for ii, band in enumerate(('g', 'r', 'z', 'W1', 'W2')):
        sbprofile.update({'{}_wave_eff'.format(band): filt.effective_wavelengths[ii].value})

    return sbprofile
Пример #6
0
def cutout_radius_cluster(redshift, cluster_radius, pixscale=0.262, factor=1.0,
                          rmin=50, rmax=500, bound=False):
    """Get a cutout radius which depends on the richness radius (in h^-1 Mpc)
    R_LAMBDA of each cluster (times an optional fudge factor).

    Optionally bound the radius to (rmin, rmax).

    """
    from astropy.cosmology import WMAP9 as cosmo

    radius_kpc = cluster_radius * 1e3 * cosmo.h # cluster radius in kpc
    radius = np.rint(factor * radius_kpc * cosmo.arcsec_per_kpc_proper(redshift).value / pixscale)

    if bound:
        radius[radius < rmin] = rmin
        radius[radius > rmax] = rmax

    return radius
Пример #7
0
def make_emission_gif_plots():
    natural_base = '_nref11_RD0016_'
    refined_base = '_nref11n_nref10f_refine200kpc_z4to2_RD0016_'
    nref11f_base = '_nref11f_refine200kpc_z4to2_RD0016_'
    box_size = ds.arr(rb_width,'code_length').in_units('kpc')
    box_size = np.ceil(box_size/2.)
    res_list = [0.2,0.5,1.0,5.0,10.0]
    fontrc ={'fontname':'Helvetica','fontsize':20}
    mpl.rc('text', usetex=True)
    make_obs = True

    if make_obs:
        cmap = mymap
        norm = None
    else:
        cmap = 'viridis'
        norm = None

    for line in lines:
        field = 'Emission_'+line
        for index in 'xyz':
            for res in res_list:
                if res == res_list[0]:
                    fileinNAT = 'frbs/frb'+index+natural_base+field+'_forcedres.cpkl'
                    fileinREF = 'frbs/frb'+index+refined_base+field+'_forcedres.cpkl'
                    fileinN11 = 'frbs/frb'+index+nref11f_base+field+'_forcedres.cpkl'
                    pixsize = round(cosmo.arcsec_per_kpc_proper(redshift).value*0.182959,2)
                else:
                    fileinNAT = 'frbs/frb'+index+natural_base+field+'_'+str(res)+'kpc.cpkl'
                    fileinREF = 'frbs/frb'+index+refined_base+field+'_'+str(res)+'kpc.cpkl'
                    fileinN11 = 'frbs/frb'+index+nref11f_base+field+'_'+str(res)+'kpc.cpkl'
                    pixsize = round(cosmo.arcsec_per_kpc_proper(redshift).value*res,2)

                frbNAT = cPickle.load(open(fileinNAT,'rb'))
                frbREF = cPickle.load(open(fileinREF,'rb'))
                frbN11 = cPickle.load(open(fileinN11,'rb'))

                if make_obs == True:
                    frbNAT = np.log10(frbNAT/(1.+redshift)**4)
                    frbREF = np.log10(frbREF/(1.+redshift)**4)
                    frbN11 = np.log10(frbN11/(1.+redshift)**4)
                else:
                    frbNAT = np.log10(frbNAT)
                    frbREF = np.log10(frbREF)
                    frbN11 = np.log10(frbN11)

                bsL,bsR = -1*box_size.value,box_size.value

                fig,ax = plt.subplots(1,3)
                fig.set_size_inches(14,6)


                ax[0].imshow(frbNAT,cmap=cmap,vmin=-5,vmax=3,
                             extent=(bsL,bsR,bsR,bsL),origin='lower',
                             interpolation=None)

                ax[1].imshow(frbREF,cmap=cmap,vmin=-5,vmax=3,
                             extent=(bsL,bsR,bsR,bsL),origin='lower',
                             interpolation=None)

                im2 = ax[2].imshow(frbN11,cmap=cmap,vmin=-5,vmax=3,
                             extent=(bsL,bsR,bsR,bsL),origin='lower',
                             interpolation=None)

                axins = inset_axes(ax[2],width="5%", height="100%",loc=3,
                                   bbox_to_anchor=(1.07, 0.0, 1, 1),
                                   bbox_transform=ax[2].transAxes,borderpad=0)

                ax[0].set_title('Natural',**fontrc)
                ax[1].set_title('Forced Refine 10',**fontrc)
                ax[2].set_title('Forced Refine 11',**fontrc)
                cb = fig.colorbar(im2, cax=axins,label=r'log( photons s$^{-1}$ cm$^{-2}$ sr$^{-1}$)')
                if line == 'CIII_977':
                    lineout = 'CIII 977'
                else:
                    lineout = line
                fig.suptitle('z=3, '+lineout+', '+str(res)+'kpc'+', '+str(pixsize)+'"',**fontrc)
                plt.savefig('z3_'+index+'_'+field+'_'+str(res)+'kpc_SBdim_obscol.pdf')
                plt.close()

    return
        camdirz = -camposz/dist_to_cam
        camupx = 1
        camupy = 0
        camupz = 0
        fov_kpc = 50
        camobj_1 = camera(camposx,camposy,camposz,camdirx,camdiry,camdirz,camupx,camupy,camupz,fov_kpc)
        global pixscale_kpc, pixscale_arcsec_z
        global z, surf_bright_lim, age_limit, sig_kernel, cube_vel_per_bin, rebin_cut, camera_n

        rebin_cut = 1.0
        cube_vel_per_bin= 1.


        redshift = ds.current_redshift
        pixscale_kpc        = camobj_1.fov*(abs(max_x-min_x))/(2*im_size) #kpc/pixel
        pixscale_arcsec_z   = pixscale_kpc*cosmo.arcsec_per_kpc_proper(redshift).value  #this is the arcsec/pixel scale at redshift 2


    if True:
        print 'running for gas...'
        vel_los_gas, vel_map_gas, disp_map_gas = make_maps(gas_mass, gas_x_cen.value[()],  gas_y_cen.value[()], gas_z_cen.value[()], 
                                                           gas_vx_cen, gas_vy_cen, gas_vz_cen, 
                                                           im_size, max_x, min_x, camobj_1, gas_temp)
        print 'running for young...'

        vel_los_yng, vel_map_yng, disp_map_yng = make_maps(star_mass, star_x_cen.value[()],  star_y_cen.value[()], star_z_cen.value[()], 
                                                           star_vx_cen, star_vy_cen, star_vz_cen, im_size, max_x, min_x, camobj_1, 
                                                           star_age = star_age_all,  star_age_min = 0., star_age_max = 1.e8)
        print 'running for old...'

        vel_los_old, vel_map_old, disp_map_old = make_maps(star_mass, star_x_cen.value[()],  star_y_cen.value[()], star_z_cen.value[()], 
        plt.ylim(y2[0], y2[1])
        plt.title(galaxies[i])
        plt.tight_layout()

    pdf.savefig()
    plt.close()
os.system('open %s &' % name_cc)

#color vs size for sersic fits
size_color = np.zeros(12)
size_four = np.zeros(12)
size_eight = np.zeros(12)

kpcrad = np.zeros([12, 2])
for w in range(0, 12):
    arcsecperkpc = cosmo.arcsec_per_kpc_proper(redshifts[w])
    for i in range(0, 2):
        kpcrad[w][i] = (0.025 * sizepix[w][i]) / arcsecperkpc.value

for w in range(0, 12):
    size_four[w] = kpcrad[w][0]
    size_color[w] = mags[1][w][0] - mags[1][w][1]
    size_eight[w] = kpcrad[w][1]

x3 = minmax([size_four, size_eight])
y3 = minmax([size_color])
if modeltype[0] == 'sersic' or modeltype[1] == 'sersic':
    name_cs = 'color_v_size_' + one + '_' + two + '.pdf'

    with PdfPages(name_cs) as pdf:
        plt.figure()
Пример #10
0
def build_sample_dynamics(sample=dynamic_sample,print_match=True):
    """finds Rachel's galaxies in the 3dhst catalogs
    matches on distance < 3 arcseconds and logM < 0.4 dex
    this will FAIL if we have two identical IDs in UDS/COSMOS... unlikely but if used
    in the future as a template for multi-field runs, beware!!!
    """

    # load catalog, define matching
    bez = load_rachel_sample()
    matching_radius = 3 # in arcseconds
    matching_mass = 0.4 # in dex

    # note: converting to physical sizes, not comoving. I assume matches Rachel's catalog
    arcsec_size = bez['Re']*WMAP9.arcsec_per_kpc_proper(bez['z']).value

    # output formatting
    fields = ['COSMOS','UDS']
    id_str_out = '/Users/joel/code/python/prospector_alpha/data/3dhst/'+sample['runname']+'.ids'
    ids = []

    # let's go
    for field in fields:
        outbase = '/Users/joel/code/python/prospector_alpha/data/3dhst/'+field+'_'+sample['runname']

        # load data
        phot = td_io.load_phot_v41(field)
        fast = td_io.load_fast_v41(field)
        zbest = td_io.load_zbest(field)
        mips = td_io.load_mips_data(field)
        gris = td_io.load_grism_dat(field,process=True)
        morph = td_io.load_morphology(field,'F160W')
        rf = td_io.load_rf_v41(field)

        # match
        match, bezmatch_flag, dist = [], [], []
        threed_cat = coords.SkyCoord(ra=phot['ra']*u.degree, 
                                     dec=phot['dec']*u.degree)
        for i in range(len(bez)):
            bzcat = coords.SkyCoord(ra=bez['RAdeg'][i]*u.deg,dec=bez['DEdeg'][i]*u.deg)  
            close_mass = np.where((np.abs(fast['lmass']-bez[i]['logM']) < matching_mass) & \
                                  (phot['use_phot'] == 1))[0]
                         
            idx, d2d, d3d = bzcat.match_to_catalog_sky(threed_cat[close_mass])
            if d2d.value*3600 < matching_radius:
                match.append(int(close_mass[idx]))
                bezmatch_flag.append(True)
                dist.append(d2d.value[0]*3600)
            else:
                bezmatch_flag.append(False)

        print '{0} galaxies matched in {1}'.format(len(match),field)
        if len(match) == 0:
            continue

        # full match
        bezmatch_flag = np.array(bezmatch_flag,dtype=bool)
        phot = phot[match]
        fast = fast[match]
        zbest = zbest[match]
        mips = mips[match]
        morph = morph[match]
        gris = gris[match]
        rf = rf[match]

        # print out relevant parameters for visual inspection
        for kk in range(bezmatch_flag.sum()):   
            print 'dM:{0},\t dz:{1},\t dr:{2},\t dist:{3}'.format(\
                   fast[kk]['lmass']-bez[bezmatch_flag][kk]['logM'], fast[kk]['z']-bez[bezmatch_flag][kk]['z'], morph[kk]['re']-arcsec_size[kk],dist[kk])

        # assemble ancillary data
        phot['f_MIPS_24um'] = mips['f24tot']
        phot['e_MIPS_24um'] = mips['ef24tot']

        # save UV+IR SFRs + emission line info in .dat file
        for name in mips.dtype.names:
            if name != 'z' and name != 'id':
                zbest[name] = mips[name]
            elif name == 'z':
                zbest['z_sfr'] = mips[name]
        for name in gris.dtype.names: zbest[name] = gris[name]

        # save UVJ cut in .dat file
        zbest['uvj'] = calc_uvj_flag(rf)

        # rename bands in photometric catalogs
        for column in phot.colnames:
            if column[:2] == 'f_' or column[:2] == 'e_':
                phot.rename_column(column, column.lower()+'_'+field.lower())    

        # are we removing the zeropoint offsets? (don't do space photometry!)
        if sample['rm_zp_offsets']:
            phot = remove_zp_offsets(field,phot)

        # include bezanson catalog info
        not_to_save = ['z', 'ID', 'Filter']
        for i,name in enumerate(bez.colnames):
            if name not in not_to_save:
                zbest[name] = bez[bezmatch_flag][name]
            elif name == 'z':
                zbest['z_bez'] = bez[bezmatch_flag][name]

        # write out
        ascii.write(phot, output=outbase+'.cat', 
                    delimiter=' ', format='commented_header',overwrite=True)
        ascii.write(fast, output=outbase+'.fout', 
                    delimiter=' ', format='commented_header',
                    include_names=fast.keys()[:11],overwrite=True)
        ascii.write(zbest, output=outbase+'.dat', 
                    delimiter=' ', format='commented_header',overwrite=True)
        ### save IDs
        ids = ids + [field+'_'+str(id) for id in phot['id']]

    print 'number of matched galaxies: {0} (out of {1})'.format(len(ids),len(bez))
    ascii.write([ids], output=id_str_out, Writer=ascii.NoHeader,overwrite=True)
Пример #11
0
from astropy.cosmology import WMAP9 as cosmo
from astropy import units as u
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

small_radius = 7 * u.kpc
large_radius = 50 * u.kpc

z_range = np.linspace(0.02, 1.50, 75)

small_angles = []
large_angles = []

for z in z_range:
    scale = cosmo.arcsec_per_kpc_proper(z)
    small_angles.append((small_radius * scale).value)
    large_angles.append((large_radius * scale).value)

plt.figure()

plt.plot(z_range, small_angles, label="Typical Small Galaxy (Radius 7 Kpc)")
plt.plot(z_range, large_angles, label="Typical Large Galaxy (Radius 50 Kpc)")
plt.axhline(y=10, color='r', linestyle='-', label="ASASSN cut")
plt.legend()

path = "plots/galaxy_radius.pdf"

print "Saving to", path

plt.savefig(path)
Пример #12
0
def plot_composites(pdata,outfolder,contours,contour_colors=True,
                    calibration_plot=True,brown_data=False,paperplot=False):

    ### image qualities
    fs = 10 # fontsize
    maxlim = 0.01 # limit of maximum

    ### contour color limits (customized for W1-W2)
    color_limits = [-1.0,2.6]
    kernel = None

    ### output blobs
    gradient, gradient_error, arcsec,objname_out, obj_size_kpc, background_out = [], [], [], [], [], []

    ### begin loop
    fig = None
    for idx in xrange(len(pdata['objname'])):

        if paperplot:
            if ('NGC 4168' not in pdata['objname'][idx]) & ('NGC 1275' not in pdata['objname'][idx]):
                continue

        ### load object information
        objname = pdata['objname'][idx]
        fagn = pdata['pars']['fagn']['q50'][idx]
        ra, dec = load_coordinates(objname)
        phot_size = load_structure(objname,long_axis=True) # in arcseconds

        ### load image and WCS
        try:
            if brown_data:
                ### convert from DN to flux in Janskies, from this table: 
                # http://wise2.ipac.caltech.edu/docs/release/allsky/expsup/sec2_3f.html
                img1, noise1 = load_image(objname,contours[0]), None
                img1, noise1 = img1*1.9350E-06, noise1*(1.9350e-06)**-2
                img2, noise2 = load_image(objname,contours[1]), None
                img2, noise2 = img2*2.7048E-06, noise2*(2.7048E-06)**-2

                ### translate object location into pixels using WCS coordinates
                wcs = WCS(img1.header)
                pix_center = wcs.all_world2pix([[ra[0],dec[0]]],1)
            else:
                img1, noise1 = load_wise_data(objname,contours[0].split(' ')[1])
                img2, noise2 = load_wise_data(objname,contours[1].split(' ')[1])

                ### translate object location into pixels using WCS coordinates
                wcs = WCS(img1.header)
                pix_center = wcs.all_world2pix([[ra[0],dec[0]]],1)

                if (pix_center.squeeze()[0]-4 > img1.shape[1]) or \
                    (pix_center.squeeze()[1]-4 > img1.shape[0]) or \
                    (np.any(pix_center < 4)):
                    print 'object not in image, checking for additional image'
                    print pix_center, img1.shape
                    img1, noise1 = load_wise_data(objname,contours[0].split(' ')[1],load_other = True)
                    img2, noise2 = load_wise_data(objname,contours[1].split(' ')[1],load_other = True)

                    wcs = WCS(img1.header)
                    pix_center = wcs.all_world2pix([[ra[0],dec[0]]],1)
                    print pix_center, img1.shape
        except:
            gradient.append(None)
            gradient_error.append(None)
            arcsec.append(None)
            kpc.append(None)
            objname_out.append(None)
            continue

        size = calc_dist(wcs, pix_center, phot_size, img1.data.shape)

        ### convert inverse variance to noise
        noise1.data = (1./noise1.data)**0.5
        noise2.data = (1./noise2.data)**0.5

        ### build image extents
        extent = image_extent(size,pix_center,wcs)

        ### convolve W1 to W2 resolution
        w1_convolved, kernel = match_resolution(img1.data,contours[0],contours[1],
                                                    kernel=kernel,data1_res=px_scale)
        w1_convolved_noise, kernel = match_resolution(noise1.data,contours[0],contours[1],
                                                      kernel=kernel,data1_res=px_scale)

        #### put onto same scale, and grab slices
        data2, footprint = reproject_exact(img2, img1.header)
        noise2, footprint = reproject_exact(noise2, img1.header)

        img1_slice = w1_convolved[size[2]:size[3],size[0]:size[1]]
        img2_slice = data2[size[2]:size[3],size[0]:size[1]]
        noise1_slice = w1_convolved_noise[size[2]:size[3],size[0]:size[1]]
        noise2_slice = noise2[size[2]:size[3],size[0]:size[1]]

        ### subtract background from both images
        # identify background pixels.
        # background is any pixel consistent within X sigma of background!
        sigma = 3.0
        if paperplot:
            sigma = 5.0
        mean1, median1, std1 = sigma_clipped_stats(w1_convolved, sigma=sigma,iters=10)
        background1 = img1_slice < (median1+std1) 
        img1_slice -= median1
        mean2, median2, std2 = sigma_clipped_stats(data2, sigma=sigma, iters=10)
        background2 = img2_slice < (median2+std2)
        img2_slice -= median2

        #### calculate the color
        flux_color  = convert_to_color(img1_slice, img2_slice,None,None,contours[0],contours[1],
                                       minflux=-np.inf, vega_conversions=brown_data)

        ### don't show any "background" pixels!
        background = background1 | background2
        flux_color[background] = np.nan

        ### plot colormap
        count = 0
        if paperplot:
            if fig is None:
                fig, axall = plt.subplots(1,2, figsize=(12,6))
                fig.subplots_adjust(right=0.8,wspace=0.4,hspace=0.3,left=0.12)
                cb_ax = fig.add_axes([0.83, 0.15, 0.05, 0.7])
                ax = np.ravel(axall[0])
            else:
                ax = np.ravel(axall[1])
                count = 1
            vmin, vmax = -0.4,1.05
        else:
            fig, ax = plt.subplots(1,2, figsize=(12,6))
            vmin, vmax = color_limits[0], color_limits[1]
        ax = np.ravel(ax)
        img = ax[0].imshow(flux_color, origin='lower',extent=extent,vmin=vmin,vmax=vmax,cmap='plasma')

        if not paperplot:
            cbar = fig.colorbar(img, ax=ax[0])
        elif count == 0:
            cbar = fig.colorbar(img, cax=cb_ax)
            cbar.set_label('(W1-W2) [Vega]', fontdict={'fontsize':18})

        ax[0].set_xlabel(r'$\Delta$(arcsec)')
        ax[0].set_ylabel(r'$\Delta$(arcsec)')

        ### plot W1 contours
        if not paperplot:
            plot_contour(ax[0],np.log10(img2_slice),ncontours=20)

        ### find image center in W2 image, and mark it
        # do this by finding the source closest to center
        tbl = []
        nthresh, box_size = 20, 4
        fake_noise2_error = copy.copy(noise2_slice)
        bad = np.logical_or(np.isinf(noise2_slice),np.isnan(noise2_slice))
        fake_noise2_error[bad] = fake_noise2_error[~bad].max()
        while len(tbl) < 1:
            threshold = nthresh * std1 # peak threshold, @ 20 sigma
            tbl = find_peaks(img2_slice, threshold, box_size=box_size, subpixel=True, border_width=3, error = fake_noise2_error)
            nthresh -=2
        
            if nthresh < 2:
                nthresh = 20
                box_size += 1

        '''
        center = np.array(img2_slice.shape)/2.
        idxmax = ((center[0]-tbl['x_peak'])**2 + (center[1]-tbl['y_peak'])**2).argmin()
        fig, ax = plt.subplots(1,1, figsize=(6,6))
        ax.plot(tbl['x_peak'][idxmax],tbl['y_peak'][idxmax],'x',color='red',ms=10)
        ax.imshow(img2_slice,origin='lower')
        plot_contour(ax, np.log10(img2_slice),ncontours=20)
        plt.show()
        '''


        ### find size of biggest one
        imgcenter = np.array(img2_slice.shape)/2.
        idxmax = ((imgcenter[0]-tbl['x_centroid'])**2 + (imgcenter[1]-tbl['y_centroid'])**2).argmin()
        center = [tbl['x_centroid'][idxmax], tbl['y_centroid'][idxmax]]

        ### find center in arcseconds (NEW)
        center_coordinates = SkyCoord.from_pixel(imgcenter[0],imgcenter[1],wcs)
        x_pos_obj = SkyCoord.from_pixel(center[0],imgcenter[1],wcs)
        y_pos_obj = SkyCoord.from_pixel(imgcenter[0],center[1],wcs)
        xarcsec = x_pos_obj.separation(center_coordinates).arcsec
        if center[0] < imgcenter[0]:
            xarcsec = -xarcsec
        yarcsec = y_pos_obj.separation(center_coordinates).arcsec
        if center[1] < imgcenter[1]:
            yarcsec = -yarcsec

        #xarcsec = (extent[1]-extent[0])*center[0]/float(img2_slice.shape[0]) + extent[0]
        #yarcsec = (extent[3]-extent[2])*center[1]/float(img2_slice.shape[1]) + extent[2]
        ax[0].scatter(xarcsec,yarcsec,color='black',marker='x',s=50,linewidth=2)

        ### add in WISE PSF
        wise_psf = 6 # in arcseconds
        start = 0.85*extent[0]

        if not paperplot:
            ax[0].plot([start,start+wise_psf],[start,start],lw=2,color='k')
            ax[0].text(start+wise_psf/2.,start+1, '6"', ha='center')
            ax[0].set_xlim(extent[0],extent[1]) # reset plot limits b/c of text stuff
            ax[0].set_ylim(extent[2],extent[3])
        else:
            ax[0].set_xlim(-65,65)
            ax[0].set_ylim(-65,65)

        ### gradient
        phys_scale = float(1./WMAP9.arcsec_per_kpc_proper(pdata['z'][idx]).value)
        if objname == 'CGCG 436-030':
            center[1] = center[1]+1.5
            yarcsec += px_scale*1.5

        grad, graderr, x_arcsec, back = measure_gradient(img1_slice,img2_slice, 
                                  noise1_slice, noise2_slice, background,
                                  ax, center,
                                  tbl['peak_value'][idxmax], (xarcsec,yarcsec),
                                  phys_scale,paperplot=paperplot)

        obj_size_phys = phot_size*phys_scale
        if not paperplot:
            ax[1].text(0.05,0.06,r'f$_{\mathrm{AGN,MIR}}$='+"{:.2f}".format(pdata['pars']['fagn']['q50'][idx])+\
                                    ' ('+"{:.2f}".format(pdata['pars']['fagn']['q84'][idx]) +
                                    ') ('+"{:.2f}".format(pdata['pars']['fagn']['q16'][idx])+')',
                                    transform=ax[1].transAxes,color='black',fontsize=9)

            ax[1].axvline(phot_size, linestyle='--', color='0.2',lw=2,zorder=-1)

        else:
            ax[0].text(0.98,0.94,objname,transform=ax[0].transAxes,fontsize=14,weight='bold',ha='right')
            ax[0].text(0.98,0.88,r'$\nabla$(2 kpc)='+"{:.2f}".format(grad[1]),fontsize=14,transform=ax[0].transAxes,ha='right')

        gradient.append(grad)
        gradient_error.append(graderr)
        arcsec.append(x_arcsec)
        obj_size_kpc.append(obj_size_phys)
        objname_out.append(objname)
        background_out.append(back)
        print objname, back

        # I/O
        outname = outfolder+'/'+objname+'.png'
        if paperplot:
            outname = outfolder+'/sample_wise_gradient.png'

        if (not paperplot) | (count == 1):
            if not paperplot:
                plt.tight_layout()
            plt.savefig(outname,dpi=150)
            plt.close()

    out = {
            'gradient': np.array(gradient),
            'gradient_error': np.array(gradient_error),
            'arcsec': np.array(arcsec),
            'obj_size_brown_kpc': np.array(obj_size_kpc),
            'objname': objname_out,
            'background_fraction': np.array(background_out)
          }
    if not paperplot:
        pickle.dump(out,open(outfile, "wb"))