In [1]:
import numpy as np
import os
import pandas as pd
import seaborn as sns
from astrometry.util.fits import fits_table, merge_tables

# to make this notebook's output stable across runs
np.random.seed(7)

# To plot pretty figures
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12

%load_ext autoreload
%autoreload 2

In [2]:
import obiwan.qa.plots_common as plots


/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/matplotlib/__init__.py:1405: UserWarning: 
This call to matplotlib.use() has no effect because the backend has already
been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.

  warnings.warn(_use_error_msg)

heatmaps


In [4]:
summary= fits_table('summary.fits')


Converted brickname from |S8 to <U8

In [5]:
bricks= fits_table(os.path.join(os.environ['HOME'],'Downloads',
                                'survey-bricks.fits.gz'))
keep=pd.Series(np.char.strip(bricks.brickname)).isin(np.char.strip(summary.brickname))
bricks.cut(keep)
bricks= bricks[ np.argsort(bricks.brickname)]
summary= summary[ np.argsort(summary.brickname)]
for key in ['ra','dec']:
    summary.set(key,bricks.get(key))


Converted brickname from |S8 to <U8

In [ ]:


In [33]:
fig,ax=plt.subplots(figsize=(10,5))

num_density= summary.n_injected / 0.25**2 # n/deg2
keep=summary.dec > 10

kw=dict(edgecolors='none',marker='o',s=15,rasterized=True)
cax= ax.scatter(summary.ra[keep],summary.dec[keep], 
                c=num_density[keep], **kw)
           
cbar = fig.colorbar(cax) #, ticks=[-1, 0, 1])
cbar.set_label('Number / deg2')
#cbar.ax.set_yticklabels(['< -1', '0', '> 1'])



In [34]:
plt.scatter?


/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/matplotlib/__init__.py:1405: UserWarning: 
This call to matplotlib.use() has no effect because the backend has already
been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.

  warnings.warn(_use_error_msg)

In [ ]:
x,y,z = np.meshgrid(summary.ra,summary.dec,num_density)
#plt.imshow(x,y,c=z)

obiwan outputs


In [3]:
#dat= fits_table('randoms_rank98.fits')
dat= fits_table('randoms_rank90.fits') # apflux_resid info
len(dat)


Converted unique_id from |S20 to <U20
Converted tractor_brickname from |S4 to <U4
Converted tractor_type from |S4 to <U4
Out[3]:
8113

In [62]:
dat.get_columns()


Out[62]:
['id',
 'ra',
 'dec',
 'x',
 'y',
 'gflux',
 'mw_transmission_g',
 'rflux',
 'mw_transmission_r',
 'zflux',
 'mw_transmission_z',
 'n',
 'rhalf',
 'e1',
 'e2',
 'unique_id',
 'psql_id',
 'psql_ra',
 'psql_dec',
 'psql_g',
 'psql_r',
 'psql_z',
 'psql_rhalf',
 'psql_n',
 'psql_ba',
 'psql_pa',
 'psql_redshift',
 'tractor_release',
 'tractor_brickid',
 'tractor_brickname',
 'tractor_objid',
 'tractor_brick_primary',
 'tractor_type',
 'tractor_ra',
 'tractor_dec',
 'tractor_ra_ivar',
 'tractor_dec_ivar',
 'tractor_bx',
 'tractor_by',
 'tractor_dchisq',
 'tractor_ebv',
 'tractor_mjd_min',
 'tractor_mjd_max',
 'tractor_flux_u',
 'tractor_flux_g',
 'tractor_flux_r',
 'tractor_flux_i',
 'tractor_flux_z',
 'tractor_flux_y',
 'tractor_flux_ivar_u',
 'tractor_flux_ivar_g',
 'tractor_flux_ivar_r',
 'tractor_flux_ivar_i',
 'tractor_flux_ivar_z',
 'tractor_flux_ivar_y',
 'tractor_apflux_g',
 'tractor_apflux_r',
 'tractor_apflux_z',
 'tractor_apflux_resid_g',
 'tractor_apflux_resid_r',
 'tractor_apflux_resid_z',
 'tractor_mw_transmission_u',
 'tractor_mw_transmission_g',
 'tractor_mw_transmission_r',
 'tractor_mw_transmission_i',
 'tractor_mw_transmission_z',
 'tractor_mw_transmission_y',
 'tractor_nobs_u',
 'tractor_nobs_g',
 'tractor_nobs_r',
 'tractor_nobs_i',
 'tractor_nobs_z',
 'tractor_nobs_y',
 'tractor_rchisq_u',
 'tractor_rchisq_g',
 'tractor_rchisq_r',
 'tractor_rchisq_i',
 'tractor_rchisq_z',
 'tractor_rchisq_y',
 'tractor_fracflux_u',
 'tractor_fracflux_g',
 'tractor_fracflux_r',
 'tractor_fracflux_i',
 'tractor_fracflux_z',
 'tractor_fracflux_y',
 'tractor_fracmasked_u',
 'tractor_fracmasked_g',
 'tractor_fracmasked_r',
 'tractor_fracmasked_i',
 'tractor_fracmasked_z',
 'tractor_fracmasked_y',
 'tractor_fracin_u',
 'tractor_fracin_g',
 'tractor_fracin_r',
 'tractor_fracin_i',
 'tractor_fracin_z',
 'tractor_fracin_y',
 'tractor_anymask_u',
 'tractor_anymask_g',
 'tractor_anymask_r',
 'tractor_anymask_i',
 'tractor_anymask_z',
 'tractor_anymask_y',
 'tractor_allmask_u',
 'tractor_allmask_g',
 'tractor_allmask_r',
 'tractor_allmask_i',
 'tractor_allmask_z',
 'tractor_allmask_y',
 'tractor_psfsize_u',
 'tractor_psfsize_g',
 'tractor_psfsize_r',
 'tractor_psfsize_i',
 'tractor_psfsize_z',
 'tractor_psfsize_y',
 'tractor_psfdepth_u',
 'tractor_psfdepth_g',
 'tractor_psfdepth_r',
 'tractor_psfdepth_i',
 'tractor_psfdepth_z',
 'tractor_psfdepth_y',
 'tractor_galdepth_u',
 'tractor_galdepth_g',
 'tractor_galdepth_r',
 'tractor_galdepth_i',
 'tractor_galdepth_z',
 'tractor_galdepth_y',
 'tractor_fracdev',
 'tractor_fracdev_ivar',
 'tractor_shapeexp_r',
 'tractor_shapeexp_r_ivar',
 'tractor_shapeexp_e1',
 'tractor_shapeexp_e1_ivar',
 'tractor_shapeexp_e2',
 'tractor_shapeexp_e2_ivar',
 'tractor_shapedev_r',
 'tractor_shapedev_r_ivar',
 'tractor_shapedev_e1',
 'tractor_shapedev_e1_ivar',
 'tractor_shapedev_e2',
 'tractor_shapedev_e2_ivar',
 'obiwan_mask',
 'targets_mask']

Input properties (eBOSS)

  • ra,dec region
  • brightness, shape, size, redshift

NGC only


In [6]:
region='ngc'
corners=dict(ngc=dict(ra=(126,168),dec=(14,34)))

fig,ax=plt.subplots()
kw=dict(m='o',s=5.,alpha=0.75)
# plots.myscatter(ax,dat.ra,dat.dec, 
#                 color='b',label='uniform_randoms',**kw)
ax.plot(dat.ra,dat.dec,'b,')
isRec= dat.obiwan_mask == 1
# plots.myscatter(ax,dat.ra[isRec],dat.dec[isRec], 
#                 color='y',label='uniform_randoms',**kw)
ax.plot(dat.ra[isRec],dat.dec[isRec],'g,')
# plt.xlim(corners[region]['ra'])
plt.xlim(153,153.75)
plt.ylim(corners[region]['dec'])


Out[6]:
(14, 34)

In [5]:
def myhist(ax,data,bins=20,color='b',normed=False,lw=2,ls='solid',label=None,
           range=None,return_h=False):
    kw= dict(bins=bins,color=color,normed=normed,
             histtype='step',range=range,lw=lw,ls=ls)
    if label:
        kw.update(label=label)
    h,bins,_=ax.hist(data,**kw)
    if return_h:
        return h

def my_step(ax,bins,height,
            lw=2,color='b',ls='solid',label=None):
    """if plt.hist returns tuple (height,bins) then this reproces that plot.
    
    e.g. bin centers and horizontal lines at the right place...
    """
    kw= dict(color=color,lw=lw,ls=ls)
    if label:
        kw.update(label=label)
    ax.step(bins[:-1],height,where='mid',**kw)

fig,axes=plt.subplots(3,1,figsize=(5,12))
plt.subplots_adjust(hspace=0.2,wspace=0.2)
xlim= dict(g=(21.5,23.25),
           r=(20.5,23),
           z=(19.5,22.5))

kw_hist= dict(bins=30,normed=False)
for ax,band in zip(axes,'grz'):
    flux=dict(input_noise_ext= dat.get(band+'flux'),
              intput_noise= dat.get(band+'flux')/\
                          dat.get('mw_transmission_'+band),
              input= plots.mag2flux(dat.get('psql_'+band))
             )
    for key,color in zip(sorted(list(flux.keys()),key=lambda x:len(x)),
                         'kbg'):
        mag= plots.flux2mag(flux[key])
        myhist(ax,mag,range=xlim[band],
               color=color,label=key,**kw_hist)
    ax.set_xlabel('%s (AB mag)' % band)
    
axes[0].legend(loc='upper left')


Out[5]:
<matplotlib.legend.Legend at 0x115935240>

fracflux, fracin, ranges?


In [18]:
fig,axes=plt.subplots(3,1,figsize=(5,12))
plt.subplots_adjust(hspace=0.2,wspace=0.2)

xlim= (0,1)

isRec= dat.obiwan_mask == 1
kw_hist= dict(bins=30,normed=False)
for ax,band in zip(axes,'grz'):
    myhist(ax,dat.get('tractor_fracflux_%s' % band)[isRec],
           range=xlim,**kw_hist)
    ax.set_yscale('log')



In [24]:
fig,axes=plt.subplots(3,1,figsize=(5,12))
plt.subplots_adjust(hspace=0.2,wspace=0.2)

xlim= (-0.2,1.2)

isRec= dat.obiwan_mask == 1
kw_hist= dict(bins=30,normed=False)
for ax,band in zip(axes,'grz'):
    myhist(ax,dat.get('tractor_fracin_%s' % band)[isRec],
           range=xlim,**kw_hist)
    ax.set_yscale('log')
    
fracin= np.mean(np.array([dat.tractor_fracin_g,
                          dat.tractor_fracin_r,
                          dat.tractor_fracin_z]),axis=0) > 0.7
print('Fracin cut removes %d/%d' % (len(dat[~fracin]),len(dat)))


/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:15: RuntimeWarning: invalid value encountered in greater
  from ipykernel import kernelapp as app
Fracin cut removes 2103/8113

Are the any systematics in psql vs. +noise fluxes?

No, but looks like bug in option to add noise, looks like noise wasn't added... Or is it that the noise added averages to zero for the ~ 20x20 pixels or whatever


In [726]:
fig,ax=plt.subplots()

kw_hist= dict(bins=10,normed=False)
ylim=2e-15
for band,color in zip('grz','gbm'):
    flux= plots.mag2flux(dat.get('psql_'+band))
    flux_noise= dat.get(band+'flux')/\
                    dat.get('mw_transmission_'+band)
    myhist(ax,flux_noise-flux,range=(-ylim,ylim),color=color,
           label=band,**kw_hist)
    ax.set_ylabel('Number')
    ax.set_xlabel('dflux (input - db)')
ax.legend()


Out[726]:
<matplotlib.legend.Legend at 0x15cba4e10>

In [720]:
xlim= dict(g=(21.5,23.25),
           r=(20.5,23),
           z=(19.5,22.5))

kw_hist= dict(color='b',bins=30,normed=False)
ylim=2e-15
for ax,band in zip(axes,'grz'):
    flux= plots.mag2flux(dat.get('psql_'+band))
    flux_noise= dat.get(band+'flux')/\
                    dat.get('mw_transmission_'+band)
    g = sns.jointplot(plots.flux2mag(flux_noise),flux_noise-flux,
                      stat_func=None)
                      #plots.flux2mag(-1*(flux_noise - flux))) # color="g")
    g.ax_joint.set_ylim(-ylim,ylim)
    g.ax_joint.set_xlabel(band+' mag')
    g.ax_joint.set_ylabel('dflux (input - db)')

# ax.legend() #loc='upper left')


Fraction recovered


In [618]:
eboss_or_desi='eboss'

fig,axes=plt.subplots(3,1,figsize=(5,12))
plt.subplots_adjust(hspace=0.2,wspace=0.2)
xlim= dict(g=(21.5,23.25),
           r=(20.5,23),
           z=(19.5,22.5))


class getDepth(object):
    def __init__(self):
        self.desi= dict(g=24.0,
                        r=23.4,
                        z=22.5)
        self.eboss_ngc= dict(g=22.9,
                             r=self.desi['r'],
                             z=self.desi['z'])
        self.eboss_sgc= dict(g=22.825,
                             r=self.desi['r'],
                             z=self.desi['z'])
# D= plots.getDepth()
D= getDepth()

kw= dict(normed=False,return_vals=True)
for ax,band in zip(axes,'grz'):
    mag= plots.flux2mag(dat.get(band+'flux'))
    mag_rec= mag[isRec]
    n,bins= np.histogram(mag,bins=30,range=xlim[band],normed=False)
    n_rec,_= np.histogram(mag[isRec],bins=bins,range=xlim[band],normed=False)
    my_step(ax,bins,n_rec.astype(float)/n)
    ax.axhline(0.5,c='k',ls='--')
    #ax.axvline(plots.getDepth().eboss_ngc(band),c='k',ls='--')
    ax.axvline(D.eboss_ngc[band],c='k',ls='--')
#     ax.step(bins[:-1],n_rec/n,where='mid')
    ax.set_xlabel('%s (AB mag)' % band)
for ax in axes:
    ax.set_ylabel('Fraction Recovered')
    ax.set_ylim(0,1)
axes[0].legend(loc='upper left')


/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:30: RuntimeWarning: invalid value encountered in true_divide
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/matplotlib/cbook.py:2649: UserWarning: Saw kwargs ['ls', 'linestyle'] which are all aliases for 'linestyle'.  Kept value from 'linestyle'
  seen=seen, canon=canonical, used=seen[-1]))
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/matplotlib/axes/_axes.py:545: UserWarning: No labelled objects found. Use label='...' kwarg on individual plots.
  warnings.warn("No labelled objects found. "

In [508]:
fig,ax=plt.subplots(1,2,figsize=(8,5))
plt.subplots_adjust(wspace=0.3)

kw=dict(color='b',m='o',s=10.,alpha=0.25)
plots.myscatter_open(ax[0],dat.e1,dat.e2,**kw)
plots.myscatter_open(ax[1],dat.psql_ba,dat.psql_pa,**kw)

ax[0].set_aspect('equal')
ax[1].set_aspect(abs((ax[1].get_xlim()[1]-ax[1].get_xlim()[0])/\
                     (ax[1].get_ylim()[1]-ax[1].get_xlim()[0])))

for i,xlab,ylab in [(0,'e1','e2'),(1,'ba','pa')]:
    ax[i].set_xlabel(xlab)
    ax[i].set_ylabel(ylab)



In [509]:
fig,ax=plt.subplots(1,2,figsize=(8,5))
plt.subplots_adjust(wspace=0.3)

isRec= dat.obiwan_mask == 1
kw=dict(color='b',m='o',s=10.,alpha=0.25)
plots.myscatter_open(ax[0],dat.e1[isRec],dat.e2[isRec],**kw)
plots.myscatter_open(ax[1],dat.psql_ba[isRec],dat.psql_pa[isRec],**kw)

ax[0].set_aspect('equal')
ax[1].set_aspect(abs((ax[1].get_xlim()[1]-ax[1].get_xlim()[0])/\
                     (ax[1].get_ylim()[1]-ax[1].get_xlim()[0])))

for i,xlab,ylab in [(0,'e1','e2'),(1,'ba','pa')]:
    ax[i].set_xlabel(xlab)
    ax[i].set_ylabel(ylab)
plt.suptitle('Recovered')


Out[509]:
<matplotlib.text.Text at 0x145d19828>

horizontal bar plot by type: number input, recovered, measures of PSF, EXP...


In [35]:
types= np.char.strip(dat.get('tractor_type'))
types[pd.Series(types).isin(['SIMP','REX']).values]= 'EXP'
use_types= ['PSF','EXP','DEV','COMP']

isRec=dat.obiwan_mask == 1
#number input, recovered,...
injected= [0,len(dat[dat.n == 1]),len(dat[dat.n == 4]),0]
recovered= [0,len(dat[(isRec) & (dat.n == 1)]),
                  len(dat[(isRec) & (dat.n == 4)]),0]
tractor= [len(dat[(isRec) & (types == typ)])
               for typ in use_types]

df= pd.DataFrame(dict(type=use_types,
                      injected=injected,
                      recovered=recovered,
                      tractor=tractor))
df.set_index('type',inplace=True)
df.head()


Out[35]:
injected recovered tractor
type
PSF 0 0 176
EXP 7453 6428 6507
DEV 839 714 451
COMP 0 0 8

In [36]:
fig,ax= plt.subplots(figsize=(8, 5))
df.plot.barh(ax=ax)
xlab=ax.set_xlabel('Number')
plt.savefig('hey')


Confusion matrix


In [44]:
def create_confusion_matrix(answer_type,predict_type, 
                            poss_types=['PSF','SIMP','EXP','DEV','COMP','REX']):
    '''compares classifications of matched objects, returns 2D array which is conf matrix and xylabels
    return 5x5 confusion matrix and colum/row names
    answer_type,predict_type -- arrays of same length with reference and prediction types'''
    for typ in set(answer_type): assert(typ in poss_types)
    for typ in set(predict_type): assert(typ in poss_types)
    ans_types= set(poss_types)
    cm=np.zeros((len(poss_types),len(poss_types)))-1
    for i_ans,ans_type in enumerate(poss_types):
        ind= np.where(answer_type == ans_type)[0]
        for i_pred,pred_type in enumerate(poss_types):
            n_pred= np.where(predict_type[ind] == pred_type)[0].size
            if ind.size > 0: cm[i_ans,i_pred]= float(n_pred)/ind.size # ind.size is constant for loop over pred_types
            else: cm[i_ans,i_pred]= 0 #np.nan
    return cm

def plot_confusion_matrix(cm,answer_names,all_names, qafile='test.png'):
    plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues, vmin=0,vmax=1)
    cbar=plt.colorbar()
    plt.xticks(range(len(all_names)), all_names)
    plt.yticks(range(len(answer_names)), answer_names)
    ylab=plt.ylabel('Truth')
    xlab=plt.xlabel('Tractor')
    for row in range(len(answer_names)):
        for col in range(len(all_names)):
            if np.isnan(cm[row,col]):
                plt.text(col,row,'n/a',va='center',ha='center')
            elif cm[row,col] > 0.5:
                plt.text(col,row,'%.2f' % cm[row,col],va='center',ha='center',color='yellow')
            else:
                plt.text(col,row,'%.2f' % cm[row,col],va='center',ha='center',color='black')
    plt.savefig(qafile, bbox_extra_artists=[xlab,ylab], bbox_inches='tight',dpi=150)
    plt.close()

# Confusion matrix for distribution of object types
# Basic cm, use slim=False
#types= ['PSF','REX', 'SIMP', 'EXP', 'DEV', 'COMP']
input_type= np.array(['EXP']*len(dat))
input_type[(isRec) & (dat.n == 4)]= 'DEV'
cm= create_confusion_matrix(input_type[isRec],types[isRec], poss_types=use_types)
qafile = 'cm.png'
plot_confusion_matrix(cm,use_types,use_types, qafile)

In [529]:
fig,ax=plt.subplots()
    
xlim=(0,2.5)
kw=dict(normed=False,range=xlim)

n,bins= np.histogram(dat.rhalf,bins=30,**kw)
n_rec,_= np.histogram(dat.rhalf[isRec],bins=bins,**kw)
my_step(ax,bins,n_rec/n)
ax.axhline(0.5,c='k',ls='--')

ax.set_xlabel('rhalf (arcsec)')
ax.set_ylabel('Fraction Recovered')
ax.set_ylim(0.0,1.)


/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:8: RuntimeWarning: invalid value encountered in true_divide
  
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/matplotlib/cbook.py:2649: UserWarning: Saw kwargs ['ls', 'linestyle'] which are all aliases for 'linestyle'.  Kept value from 'linestyle'
  seen=seen, canon=canonical, used=seen[-1]))
Out[529]:
(0.0, 1.0)

In [541]:
def eboss_ts(gmag,rz,gr,region='ngc'):
    colorCut= dict(sgc= ((gmag > 21.825) &
                         (gmag < 22.825) &
                         (-0.068 * rz + 0.457 < gr) &
                         (gr < 0.112 * rz + 0.773) &
                         (0.218 * gr + 0.571 < rz) &
                         (rz < -0.555 * gr + 1.901)),
                   ngc= ((gmag > 21.825) &
                         (gmag < 22.9) &
                         (-0.068 * rz + 0.457 < gr) &
                         (gr < 0.112 * rz + 0.773) &
                         (0.637 * gr + 0.399 < rz) &
                         (rz < -0.555 * gr + 1.901)))
    return colorCut[region]

fig,ax=plt.subplots(4,2,figsize=(10,12))
plt.subplots_adjust(hspace=0.2,wspace=0.2)

rz= dat.psql_r - dat.psql_z
gr= dat.psql_g - dat.psql_r
is_elg_input= eboss_ts(dat.psql_g,rz,gr,region='ngc')
is_elg_trac= np.zeros(len(dat),bool)
mags={}
for band in 'grz':
    mags[band]= plots.flux2mag(dat.get('tractor_flux_'+band)[isRec]/\
                                 dat.get('tractor_mw_transmission_'+band)[isRec])
is_elg_trac[isRec][eboss_ts(mags['g'],mags['r']-mags['z'],mags['g']-mags['r'],region='ngc')]= True

kw=dict(marker='.',s=20,alpha=1)
kw_hist=dict(bins=30,range=(21.5,23.25),normed=False)

lab,keep= 'recovered & ELG (input) & ELG (tractor)', ((is_elg_input) & (isRec) & (is_elg_trac))
ax[0,0].scatter(rz[keep],gr[keep],
                c='b',label=lab,**kw)
myhist(ax[0,1],dat.psql_g[keep],color='b',label=lab,**kw_hist)
lab,keep= 'recovered & ELG (input) & not ELG (tractor)', ((is_elg_input) & (isRec) & (~is_elg_trac))
if len(rz[keep]) > 0:
    ax[0,0].scatter(rz[keep],gr[keep],
                    c='r',label=lab,**kw)
    myhist(ax[0,1],dat.psql_g[keep],color='r',label=lab,**kw_hist)

lab,keep= 'not recovered & ELG', (is_elg_input) & (~isRec)
ax[1,0].scatter(rz[keep],gr[keep],
                c='b',label=lab,**kw)
myhist(ax[1,1],dat.psql_g[keep],color='b',label=lab,**kw_hist)

lab,keep= 'recovered & not ELG (input) & not ELG (tractor)', ((~is_elg_input) & (isRec) & (~is_elg_trac))
ax[2,0].scatter(rz[keep],gr[keep],
                c='b',label=lab,**kw)
myhist(ax[2,1],dat.psql_g[keep],color='b',label=lab,**kw_hist)
lab,keep= 'recovered & not ELG (input) & ELG (tractor)', ((~is_elg_input) & (isRec) & (is_elg_trac))
if len(rz[keep]) > 0:
    ax[2,0].scatter(rz[keep],gr[keep],
                    c='r',label=lab,**kw)
    myhist(ax[2,1],dat.psql_g[keep],color='r',label=lab,**kw_hist)
             
lab,keep= 'not recovered & not ELG', (~is_elg_input) & (~isRec)
ax[3,0].scatter(rz[keep],gr[keep],
                c='b',label=lab,**kw)
myhist(ax[3,1],dat.psql_g[keep],color='b',label=lab,**kw_hist)

num_plotted= len(rz[(is_elg_input) & (isRec)]) + \
             len(rz[(is_elg_input) & (~isRec)]) + \
             len(rz[(~is_elg_input) & (isRec)]) + \
             len(rz[(~is_elg_input) & (~isRec)])
assert(num_plotted == len(rz))


ax[-1,0].set_xlabel('r-z')
ax[-1,1].set_xlabel('g')
for row in range(4):
    ax[row,0].set_ylabel('g-r')
    ax[row,1].set_ylabel('Number')

for row in range(4):
    for col in range(2):
        ax[row,col].legend(loc='upper left')
    ax[row,0].set_xlim(0.5,2)
    ax[row,0].set_ylim(0.2,1.3)


/Users/kaylan1/PhdStudent/Research/desi/obiwan/py/obiwan/qa/plots.py:39: RuntimeWarning: divide by zero encountered in log10
  np.linspace(ylim[0],ylim[1],nbins[1])))
/Users/kaylan1/PhdStudent/Research/desi/obiwan/py/obiwan/qa/plots.py:39: RuntimeWarning: invalid value encountered in log10
  np.linspace(ylim[0],ylim[1],nbins[1])))
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:27: RuntimeWarning: invalid value encountered in subtract
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:6: RuntimeWarning: invalid value encountered in greater
  
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:6: RuntimeWarning: invalid value encountered in less
  
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:7: RuntimeWarning: invalid value encountered in less
  import sys
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:12: RuntimeWarning: invalid value encountered in greater
  if sys.path[0] == '':
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:12: RuntimeWarning: invalid value encountered in less
  if sys.path[0] == '':
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:13: RuntimeWarning: invalid value encountered in less
  del sys.path[0]
(8292,) (8292,)

In [460]:
dat.get_columns()


Out[460]:
['id',
 'ra',
 'dec',
 'x',
 'y',
 'gflux',
 'mw_transmission_g',
 'rflux',
 'mw_transmission_r',
 'zflux',
 'mw_transmission_z',
 'n',
 'rhalf',
 'e1',
 'e2',
 'unique_id',
 'psql_id',
 'psql_ra',
 'psql_dec',
 'psql_g',
 'psql_r',
 'psql_z',
 'psql_rhalf',
 'psql_n',
 'psql_ba',
 'psql_pa',
 'psql_redshift',
 'tractor_release',
 'tractor_brickid',
 'tractor_brickname',
 'tractor_objid',
 'tractor_brick_primary',
 'tractor_type',
 'tractor_ra',
 'tractor_dec',
 'tractor_ra_ivar',
 'tractor_dec_ivar',
 'tractor_bx',
 'tractor_by',
 'tractor_dchisq',
 'tractor_ebv',
 'tractor_mjd_min',
 'tractor_mjd_max',
 'tractor_flux_u',
 'tractor_flux_g',
 'tractor_flux_r',
 'tractor_flux_i',
 'tractor_flux_z',
 'tractor_flux_y',
 'tractor_flux_ivar_u',
 'tractor_flux_ivar_g',
 'tractor_flux_ivar_r',
 'tractor_flux_ivar_i',
 'tractor_flux_ivar_z',
 'tractor_flux_ivar_y',
 'tractor_apflux_resid_g',
 'tractor_apflux_resid_r',
 'tractor_apflux_resid_z',
 'tractor_mw_transmission_u',
 'tractor_mw_transmission_g',
 'tractor_mw_transmission_r',
 'tractor_mw_transmission_i',
 'tractor_mw_transmission_z',
 'tractor_mw_transmission_y',
 'tractor_nobs_u',
 'tractor_nobs_g',
 'tractor_nobs_r',
 'tractor_nobs_i',
 'tractor_nobs_z',
 'tractor_nobs_y',
 'tractor_rchisq_u',
 'tractor_rchisq_g',
 'tractor_rchisq_r',
 'tractor_rchisq_i',
 'tractor_rchisq_z',
 'tractor_rchisq_y',
 'tractor_fracflux_u',
 'tractor_fracflux_g',
 'tractor_fracflux_r',
 'tractor_fracflux_i',
 'tractor_fracflux_z',
 'tractor_fracflux_y',
 'tractor_fracmasked_u',
 'tractor_fracmasked_g',
 'tractor_fracmasked_r',
 'tractor_fracmasked_i',
 'tractor_fracmasked_z',
 'tractor_fracmasked_y',
 'tractor_fracin_u',
 'tractor_fracin_g',
 'tractor_fracin_r',
 'tractor_fracin_i',
 'tractor_fracin_z',
 'tractor_fracin_y',
 'tractor_anymask_u',
 'tractor_anymask_g',
 'tractor_anymask_r',
 'tractor_anymask_i',
 'tractor_anymask_z',
 'tractor_anymask_y',
 'tractor_allmask_u',
 'tractor_allmask_g',
 'tractor_allmask_r',
 'tractor_allmask_i',
 'tractor_allmask_z',
 'tractor_allmask_y',
 'tractor_psfsize_u',
 'tractor_psfsize_g',
 'tractor_psfsize_r',
 'tractor_psfsize_i',
 'tractor_psfsize_z',
 'tractor_psfsize_y',
 'tractor_psfdepth_u',
 'tractor_psfdepth_g',
 'tractor_psfdepth_r',
 'tractor_psfdepth_i',
 'tractor_psfdepth_z',
 'tractor_psfdepth_y',
 'tractor_galdepth_u',
 'tractor_galdepth_g',
 'tractor_galdepth_r',
 'tractor_galdepth_i',
 'tractor_galdepth_z',
 'tractor_galdepth_y',
 'tractor_fracdev',
 'tractor_fracdev_ivar',
 'tractor_shapeexp_r',
 'tractor_shapeexp_r_ivar',
 'tractor_shapeexp_e1',
 'tractor_shapeexp_e1_ivar',
 'tractor_shapeexp_e2',
 'tractor_shapeexp_e2_ivar',
 'tractor_shapedev_r',
 'tractor_shapedev_r_ivar',
 'tractor_shapedev_e1',
 'tractor_shapedev_e1_ivar',
 'tractor_shapedev_e2',
 'tractor_shapedev_e2_ivar',
 'obiwan_mask',
 'targets_mask']

In [470]:
fig,ax=plt.subplots()
    
# xlim=(0,2.5)
xlim=None
kw=dict(range=None,normed=False,bins=30)

myhist(ax,dat.psql_redshift,color='b',label='input',**kw)

lab,keep= 'input & ELG', (is_elg_input)
myhist(ax,dat.psql_redshift[keep],color='g',label=lab,**kw)

lab,keep= 'recovered & ELG', (isRec) & (is_elg_input)
myhist(ax,dat.psql_redshift[keep],color='k',label=lab,**kw)

lab,keep= 'not recovered & ELG', (~isRec) & (is_elg_input)
myhist(ax,dat.psql_redshift[keep],color='m',label=lab)

ax.set_xlabel('redshift')
ax.set_ylabel('Number')
ax.legend(loc='upper left')


Out[470]:
<matplotlib.legend.Legend at 0x138d644e0>

2 panel plot

  • left panel

    • fraction of input that are ELGs based on truth input
    • fraction of ELGs that are recovered
  • right panel

    • fraction of recovered ELGs that are tractor would call ELGs (correct targets)
    • fraction of recovered ELGs that tractor would not call ELGs (lost targets)
    • fraction of recovered that are not ELGs but would would call ELGs (contaminated targets)

In [549]:
rz= dat.psql_r - dat.psql_z
gr= dat.psql_g - dat.psql_r
is_elg_input= eboss_ts(dat.psql_g,rz,gr,region='ngc')
is_elg_trac= np.zeros(len(dat),bool)
mags={}
for band in 'grz':
    mags[band]= plots.flux2mag(dat.get('tractor_flux_'+band)[isRec]/\
                                 dat.get('tractor_mw_transmission_'+band)[isRec])
is_elg_trac[isRec][eboss_ts(mags['g'],mags['r']-mags['z'],mags['g']-mags['r'],region='ngc')]= True


/Users/kaylan1/PhdStudent/Research/desi/obiwan/py/obiwan/qa/plots.py:39: RuntimeWarning: divide by zero encountered in log10
  np.linspace(ylim[0],ylim[1],nbins[1])))
/Users/kaylan1/PhdStudent/Research/desi/obiwan/py/obiwan/qa/plots.py:39: RuntimeWarning: invalid value encountered in log10
  np.linspace(ylim[0],ylim[1],nbins[1])))
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:8: RuntimeWarning: invalid value encountered in subtract
  
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:6: RuntimeWarning: invalid value encountered in greater
  
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:6: RuntimeWarning: invalid value encountered in less
  
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:7: RuntimeWarning: invalid value encountered in less
  import sys
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:12: RuntimeWarning: invalid value encountered in greater
  if sys.path[0] == '':
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:12: RuntimeWarning: invalid value encountered in less
  if sys.path[0] == '':
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:13: RuntimeWarning: invalid value encountered in less
  del sys.path[0]

In [556]:
plt.scatter(mags['g'],mags['g']-dat.psql_g[isRec],alpha=0.2)
plt.ylim(-1,1)


Out[556]:
(-1, 1)

What do input ELGs look like in color space for input and measured colors?

There are two ways to loose ELGs

  • don't recover them
  • recover them but measured properties fail target selection

There are two ways to measure an ELG

  • Truly passes TS, then recover it with measure that still pass TS
  • does not pass TS, but recover it and measure error is such that is passes TS

In [600]:
fig,axes=plt.subplots(3,2,figsize=(12,9))
plt.subplots_adjust(wspace=0.2,hspace=0.4)

kw_scatter=dict(marker='.',s=20,alpha=1)
kw_hist=dict(range=(21.5,23.5),normed=False)

# Row 0
row=0
lab,keep= 'true ELG',isRec & is_elg_input
axes[row,0].scatter(dat.psql_r[keep]-dat.psql_z[keep],
              dat.psql_g[keep]-dat.psql_r[keep],
              c='k',label=lab,**kw_scatter)
myhist(axes[row,1],dat.psql_g[keep],bins=30,color='k',label=lab,**kw_hist)

# Rows 1 & 2
mags={}
for band in 'grz':
    mags[band]= plots.flux2mag(dat.get('tractor_flux_'+band)/\
                                 dat.get('tractor_mw_transmission_'+band))
is_elg_trac= eboss_ts(mags['g'],mags['r']-mags['z'],mags['g']-mags['r'],region='ngc')

lab,keep= 'lost (recovered but fail TS)', (isRec) & (is_elg_input) & (~is_elg_trac)
row=1
axes[row,0].scatter(dat.psql_r[keep]-dat.psql_z[keep],
                    dat.psql_g[keep]-dat.psql_r[keep],
                    c='g',label=lab,**kw_scatter)
myhist(axes[row,1],dat.psql_g[keep],bins=30,color='g',label=lab,**kw_hist)
row=2
axes[row,0].scatter(mags['r'][keep]-mags['z'][keep],
                    mags['g'][keep]-mags['r'][keep],
                    c='g',label=lab,**kw_scatter)
myhist(axes[row,1],mags['g'][keep],bins=30,color='g',label=lab,**kw_hist)

lab,keep= 'Tractor ELG (correct)', (isRec) & (is_elg_input) & (is_elg_trac)
row=1
axes[row,0].scatter(dat.psql_r[keep]-dat.psql_z[keep],
                    dat.psql_g[keep]-dat.psql_r[keep],
                    c='b',label=lab,**kw_scatter)
myhist(axes[row,1],dat.psql_g[keep],bins=30,color='b',label=lab,**kw_hist)
row=2
axes[row,0].scatter(mags['r'][keep]-mags['z'][keep],
                    mags['g'][keep]-mags['r'][keep],
                    c='b',label=lab,**kw_scatter)
myhist(axes[row,1],mags['g'][keep],bins=30,color='b',label=lab,**kw_hist)

lab,keep= 'Tractor ELG (contamiation)', (isRec) & (~is_elg_input) & (is_elg_trac)
row=1
axes[row,0].scatter(dat.psql_r[keep]-dat.psql_z[keep],
                    dat.psql_g[keep]-dat.psql_r[keep],
                    c='b',label=lab,**kw_scatter)
myhist(axes[row,1],dat.psql_g[keep],bins=30,color='c',label=lab,**kw_hist)
row=2
axes[row,0].scatter(mags['r'][keep]-mags['z'][keep],
                    mags['g'][keep]-mags['r'][keep],
                    c='b',label=lab,**kw_scatter)
myhist(axes[row,1],mags['g'][keep],bins=30,color='c',label=lab,**kw_hist)


lab,keep= 'lost (not recovered)', (~isRec) & (is_elg_input)
row=1
axes[row,0].scatter(dat.psql_r[keep]-dat.psql_z[keep],
                    dat.psql_g[keep]-dat.psql_r[keep],
                    c='m',label=lab,**kw_scatter)
myhist(axes[row,1],dat.psql_g[keep],bins=30,color='m',label=lab,**kw_hist)
row=2
axes[row,0].scatter(mags['r'][keep]-mags['z'][keep],
                    mags['g'][keep]-mags['r'][keep],
                    c='m',label=lab,**kw_scatter)
myhist(axes[row,1],mags['g'][keep],bins=30,color='m',label=lab,**kw_hist)


col=0
for row in range(3):
    axes[row,col].set_xlim(0.5,2)
    axes[row,col].set_ylim(0.2,1.3)
axes[0,col].set_xlabel('True r-z')
axes[0,col].set_ylabel('True g-r')
axes[1,col].set_xlabel('True r-z')
axes[1,col].set_ylabel('True g-r')
axes[2,col].set_xlabel('Tractor r-z')
axes[2,col].set_ylabel('Tractor g-r')

col=1
axes[0,col].set_xlabel('True g')
axes[1,col].set_xlabel('True g')
axes[2,col].set_xlabel('Tractor g')
kw_leg= dict(loc='upper left',fontsize=8)
axes[0,col].legend(**kw_leg)
axes[1,col].legend(**kw_leg)
axes[2,col].legend(**kw_leg)
    



# myhist(axes[2],mags['g'][keep],bins=bins,color='g',label='meas ELG',**kw)
# keep= (isRec) & (is_elg_input) & (~is_elg_trac)
# myhist(axes[2],mags['g'][keep],bins=bins,color='k',label='meas not ELG',**kw)

# #for ax in axes:
# #     ax.set_xlim(0.5,2)
# #     ax.set_ylim(0.2,1.3)
# for ax in axes[2:]:


/Users/kaylan1/PhdStudent/Research/desi/obiwan/py/obiwan/qa/plots.py:39: RuntimeWarning: divide by zero encountered in log10
  np.linspace(ylim[0],ylim[1],nbins[1])))
/Users/kaylan1/PhdStudent/Research/desi/obiwan/py/obiwan/qa/plots.py:39: RuntimeWarning: invalid value encountered in log10
  np.linspace(ylim[0],ylim[1],nbins[1])))
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:19: RuntimeWarning: invalid value encountered in subtract
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:6: RuntimeWarning: invalid value encountered in greater
  
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:6: RuntimeWarning: invalid value encountered in less
  
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:7: RuntimeWarning: invalid value encountered in less
  import sys
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:12: RuntimeWarning: invalid value encountered in greater
  if sys.path[0] == '':
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:12: RuntimeWarning: invalid value encountered in less
  if sys.path[0] == '':
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:13: RuntimeWarning: invalid value encountered in less
  del sys.path[0]
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:28: RuntimeWarning: invalid value encountered in subtract
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:29: RuntimeWarning: invalid value encountered in subtract
/Users/kaylan1/.local/lib/python3.6/site-packages/numpy/lib/function_base.py:748: RuntimeWarning: invalid value encountered in greater_equal
  keep = (tmp_a >= mn)
/Users/kaylan1/.local/lib/python3.6/site-packages/numpy/lib/function_base.py:749: RuntimeWarning: invalid value encountered in less_equal
  keep &= (tmp_a <= mx)
Out[600]:
<matplotlib.legend.Legend at 0x14943ec18>

Hist for the three above colors, three hists per band


In [686]:
x_ivar=0
x_var= ['true_mag','galdepth','redshift'][x_ivar]
kw_hist=dict(bins=30,normed=False)

figs,axes= plt.subplots(3,1,figsize=(5,10))
plt.subplots_adjust(hspace=0.4)

ratio_area= 1. 
for ax,band in zip(axes,'grz'):
    if x_var == 'true_mag':
        _x_var= plots.flux2mag(dat.get(band+'flux')/\
                               dat.get('mw_transmission_'+band))
        xlab= 'true mag %s' % band
        xlim= dict(g=(21.6,23),
                   r=(20.75,22.5),
                   z=(19.5,22))
    elif x_var == 'galdepth':
        flux_for_depth= 5 / np.sqrt(dat.get('tractor_galdepth_'+band))
        _x_var= plots.flux2mag(flux_for_depth/\
                                 dat.get('mw_transmission_'+band))
        xlab= 'galdepth %s' % band
        xlim= dict(g=(22.5,24.5),
                   r=(22.5,24.5),
                   z=(21.5,23.5))
    elif x_var == 'redshift':
        _x_var= dat.psql_redshift
        xlab= 'redshift'
        xlim= dict(g=(0,1.5),
                   r=(0,1.5),
                   z=(0,1.5))
    #isPostiveFlux= ((np.isfinite(dmag)) &
    #                (np.isfinite(true_mag)))
    #isPostiveFlux= np.ones(len(dmag),bool)
    #print('true_mag=',true_mag[isPostiveFlux],'trac_mag=',dmag[isPostiveFlux])
    
    # Plot
    for lab,color,keep in [('lost (recovered but fail TS)','g', (isRec) & (is_elg_input) & (~is_elg_trac)),
                           ('Tractor ELG','b', (isRec) & (is_elg_input) & (is_elg_trac)),
                           ('Tractor ELG (contamiation)', 'c',(isRec) & (~is_elg_input) & (is_elg_trac))]:
        myhist(ax,_x_var[keep],color=color,label=lab,range=xlim[band],**kw_hist)
    ylab='Number'
    if kw_hist['normed']:
        ylab='PDF'
    ax.set_ylabel(ylab)
    ax.set_xlabel(xlab)

axes[0].legend(loc=(0,1.01),ncol=2,fontsize=12,markerscale=3)


Out[686]:
<matplotlib.legend.Legend at 0x15f2840b8>

dmag for the three above colors


In [693]:
percentile_lines=False
x_ivar=0
y_ivar=0
x_var= ['true_mag','galdepth','redshift'][x_ivar]
y_var= ['dmag','chisq'][y_ivar]

figs,axes= plt.subplots(3,1,figsize=(6,10))
plt.subplots_adjust(hspace=0.4)

ratio_area= 1. 
for ax,band in zip(axes,'grz'):
    fix= ratio_area * np.average([dat.get('tractor_apflux_resid_'+band)[:,6],
                                  dat.get('tractor_apflux_resid_'+band)[:,7]],
                                axis=0)
    assert(len(fix)) == len(dat)
    if y_var == 'dmag':
        _y_var= plots.flux2mag(dat.get('tractor_flux_'+band)) -\
                   plots.flux2mag(dat.get(band+'flux')+  fix)
        ylab= 'dmag (Tractor - True)'
        ylim=(-2,2)
    elif y_var == 'chisq':
        _y_var= dat.get('tractor_flux_'+band) -\
                   (dat.get(band+'flux')+  fix)
        _y_var *= np.sqrt(dat.get('tractor_flux_ivar_'+band))
        ylab= 'chiflux (Tractor - True) * sqrt(ivar)'
        ylim=(-10,10)
    
    if x_var == 'true_mag':
        _x_var= plots.flux2mag(dat.get(band+'flux')/\
                               dat.get('mw_transmission_'+band))
        xlab= 'true mag %s' % band
        xlim= dict(g=(21.6,23),
                   r=(20.75,22.5),
                   z=(19.5,22))
    elif x_var == 'galdepth':
        flux_for_depth= 5 / np.sqrt(dat.get('tractor_galdepth_'+band))
        _x_var= plots.flux2mag(flux_for_depth/\
                                 dat.get('mw_transmission_'+band))
        xlab= 'galdepth %s' % band
        xlim= dict(g=(21,24.5),
                   r=(21,24.5),
                   z=(21,24.5))
    elif x_var == 'redshift':
        _x_var= dat.psql_redshift
        xlab= 'redshift'
        xlim= dict(g=(0,1.5),
                   r=(0,1.5),
                   z=(0,1.5))
    
    #isPostiveFlux= ((np.isfinite(dmag)) &
    #                (np.isfinite(true_mag)))
    #isPostiveFlux= np.ones(len(dmag),bool)
    #print('true_mag=',true_mag[isPostiveFlux],'trac_mag=',dmag[isPostiveFlux])
    
    # Plot
    for lab,color,keep in [('lost (recovered but fail TS)','g', (isRec) & (is_elg_input) & (~is_elg_trac)),
                           ('Tractor ELG','b', (isRec) & (is_elg_input) & (is_elg_trac)),
                           ('Tractor ELG (contamiation)', 'c',(isRec) & (~is_elg_input) & (is_elg_trac))]:
        if percentile_lines:
            binned= plots.bin_up(_x_var[keep],_y_var[keep], 
                                 bin_minmax=xlim[band],nbins=30)
            for perc in ['q25','q75']:
                kw= dict(c=color,lw=2)
                if perc == 'q25':
                    kw.update(label=lab)
                ax.plot(binned['binc'],binned[perc],**kw)
        else:
            ax.scatter(_x_var[keep],_y_var[keep],
                       alpha=1,s=5,c=color,label=lab)
            #ax.scatter(true_mag[(isPostiveFlux) & (keep)],dmag[(isPostiveFlux) & (keep)],
            #           alpha=1,s=5,c=color,label=lab)
    
for ax,band in zip(axes,'grz'):
    ax.axhline(0,c='k',ls='--')
    ax.set_ylim(ylim)
axes[1].set_ylabel(ylab)
axes[0].legend(loc=(0,1.01),ncol=2,fontsize=12,markerscale=3)

for ax in axes:
    ax.set_xlabel(xlab)


/Users/kaylan1/PhdStudent/Research/desi/obiwan/py/obiwan/qa/plots.py:39: RuntimeWarning: divide by zero encountered in log10
  np.linspace(ylim[0],ylim[1],nbins[1])))
/Users/kaylan1/PhdStudent/Research/desi/obiwan/py/obiwan/qa/plots.py:39: RuntimeWarning: invalid value encountered in log10
  np.linspace(ylim[0],ylim[1],nbins[1])))

dflux/std dev vs. Unit Gaussian


In [96]:
figs,axes= plt.subplots(3,1,figsize=(6,8))
plt.subplots_adjust(hspace=0.4)

isRec= dat.obiwan_mask == 1

xlims=(-4,4)
for ax,band in zip(axes,'grz'):
    apflux_apflux_diff= dat.get('tractor_apflux_'+band)[:,-1] -\
                    dat.get('tractor_apflux_'+band)[:,-2]
    apflux_apfluxresid_diff= dat.get('tractor_apflux_'+band)[:,5] - \
                    dat.get('tractor_apflux_resid_'+band)[:,5]
    
    bins= np.linspace(xlims[0],xlims[1],num=30)
    myhist(ax,apflux_apflux_diff[isRec],bins=bins,color='k',
           normed=True,label='fix: apflux_apflux_diff')
    myhist(ax,apflux_apfluxresid_diff[isRec],bins=bins,color='b',
           normed=True,label='fix: apfluxresid_apflux_diff')
    #ax.axvline(np.median(fix[isRec]),c='y',ls='-',label='median(fix)')
    ax.axvline(0,c='r',ls='-')
    plots.mytext(ax,0.9,0.9,band,fontsize=14)
    
    #isPostiveFlux= ((np.isfinite(dmag)) &
    #                (np.isfinite(true_mag)))
    #isPostiveFlux= np.ones(len(dmag),bool)
    #print('true_mag=',true_mag[isPostiveFlux],'trac_mag=',dmag[isPostiveFlux])

xlab=axes[-1].set_xlabel(r'apflux difference')
#for ax,band in zip(axes,'grz'):
#    ax.set_xlim(ylim)
for ax in axes:
    ax.set_ylabel('PDF')
axes[0].legend(loc=(0,1.01),ncol=2,fontsize=12,markerscale=3)


Out[96]:
<matplotlib.legend.Legend at 0x11f3f5898>

In [93]:
figs,axes= plt.subplots(3,1,figsize=(6,8))
plt.subplots_adjust(hspace=0.4)

apply_fix= True
sub_median= False

isRec= dat.obiwan_mask == 1
data_lab='data'
if apply_fix:
    data_lab+='+fix'
if sub_median:
    data_lab+='-median'

xlims=(-4,4)
for ax,band in zip(axes,'grz'):
    #fix= dat.get('tractor_apflux_'+band)[:,-1] -\
    #        dat.get('tractor_apflux_'+band)[:,-2]
    fix= dat.get('tractor_apflux_'+band)[:,4] - \
            dat.get('tractor_apflux_resid_'+band)[:,4]
    dflux= dat.get('tractor_flux_'+band) - dat.get(band+'flux')
    dflux_wfix= dflux + fix
    
    bins= np.linspace(xlims[0],xlims[1],num=30)
    myhist(ax,dflux[isRec],bins=bins,color='k',
           label='data',normed=True)
    myhist(ax,dflux_wfix[isRec],bins=bins,color='b',
           label='data_wfix',normed=True)
    #ax.axvline(np.median(dflux[isRec]),c='y',ls='-',label='median(data)')
    ax.axvline(0,c='b',ls='-')
    plots.mytext(ax,0.9,0.9,band,fontsize=14)
    
    #isPostiveFlux= ((np.isfinite(dmag)) &
    #                (np.isfinite(true_mag)))
    #isPostiveFlux= np.ones(len(dmag),bool)
    #print('true_mag=',true_mag[isPostiveFlux],'trac_mag=',dmag[isPostiveFlux])

xlab=axes[-1].set_xlabel(r'$\Delta$flux (Tractor - True)')
#for ax,band in zip(axes,'grz'):
#    ax.set_xlim(ylim)
for ax in axes:
    ax.set_ylabel('PDF')
axes[0].legend(loc=(0,1.01),ncol=2,fontsize=12,markerscale=3)


Out[93]:
<matplotlib.legend.Legend at 0x11ebbc7f0>

In [128]:
figs,axes= plt.subplots(3,1,figsize=(6,10))
plt.subplots_adjust(hspace=0.4)

apply_fix= False
sub_mean= True
use_psql_flux=False
num_std_lims=(-6,6)

from scipy.stats import norm
rv = norm()
isRec= dat.obiwan_mask == 1

def gauss_model(p,x):
    return 1/np.sqrt(2*np.pi*p[0]**2) * np.exp(-x**2/(2*p[0]**2))

for ax,band in zip(axes,'grz'):
    data_lab= 'data'
    if apply_fix:
        fix= np.average([dat.get('tractor_apflux_resid_'+band)[:,6],
                         dat.get('tractor_apflux_resid_'+band)[:,7]],
                        axis=0)
        data_lab+='+fix'
        #fix= apflux_apfluxresid_diff= dat.get('tractor_apflux_'+band)[:,5] - \
        #            dat.get('tractor_apflux_resid_'+band)[:,5]
        
    else:
        fix=0
    if use_psql_flux:
        num_std_dev= dat.get('tractor_flux_'+band) -\
                       (plots.mag2flux(dat.get('psql_'+band))+  fix)
    else: 
        num_std_dev= dat.get('tractor_flux_'+band) -\
                        (dat.get(band+'flux')+  fix)

    num_std_dev *= np.sqrt(dat.get('tractor_flux_ivar_'+band))
    if sub_mean:
        #keep= ((num_std_dev >= num_std_lims[0]) &
        #       (num_std_dev <= num_std_lims[0]) 
        dflux_mean= np.mean(num_std_dev[isRec])
        num_std_dev -= dflux_mean
        print('%s: dflux_mean=%f' % (band,dflux_mean))
        data_lab+=' minus mean (%.2f)' % dflux_mean
    
    bins= np.linspace(num_std_lims[0],num_std_lims[1],num=30)
    h=myhist(ax,num_std_dev[isRec],bins=bins,color='b',
           label=data_lab,normed=True,
           return_h=True)
    
    from scipy.optimize import leastsq
    #fitfunc = lambda p, x: p[0]*np.cos(2*np.pi/p[1]*x+p[2]) + p[3] 
    errfunc = lambda p, x, y: gauss_model(p, x) - y
    p0 = [1.] # Initial guess
    binc= (bins[:-1]+bins[1:])/2
    p1, success = leastsq(errfunc, p0[:], args=(binc, h))
    assert(success != 0)
    norm_fit= norm(scale=p1[0])
    ax.plot(bins,norm_fit.pdf(bins),'k-',label=r'Fit $\sigma=$%.2f' % p1[0])

    
    #ax.axvline(np.mean(num_std_dev[isRec]),c='g',ls='--',label='mean(data)')
    ax.plot(bins,rv.pdf(bins),'k--',label='Standard Norm')
    ax.axvline(0,c='k',ls='dotted')
    plots.mytext(ax,0.9,0.9,band,fontsize=14)
    #isPostiveFlux= ((np.isfinite(dmag)) &
    #                (np.isfinite(true_mag)))
    #isPostiveFlux= np.ones(len(dmag),bool)
    #print('true_mag=',true_mag[isPostiveFlux],'trac_mag=',dmag[isPostiveFlux])

xlab=axes[-1].set_xlabel(r'$\Delta$flux (Tractor - True) * sqrt(ivar)')
#for ax,band in zip(axes,'grz'):
#    ax.set_xlim(ylim)
for ax in axes:
    ax.set_ylabel('PDF')
    ax.legend(loc='upper left',fontsize=10,markerscale=3)


g: dflux_mean=-1.481467
r: dflux_mean=-1.928699
z: dflux_mean=-1.641154

In [134]:
types=np.char.strip(dat.tractor_type)
types[types == 'EXP']


Out[134]:
{'', 'COMP', 'DEV', 'EXP', 'PSF', 'SIMP'}

In [147]:
typ= 'exp'
plt.scatter(dat.rhalf[types == typ.upper()],dat.get('tractor_shape'+typ+'_r')[types == typ.upper()])
plt.ylim(0,3)
plt.xlim(0,3)


Out[147]:
(0, 3)

In [152]:
typ='dev'
isType= types == typ.upper()
x=1/np.sqrt(dat.get('tractor_shape%s_e1_ivar' % typ))
keep= np.isfinite(x) & isType
_=plt.hist(x[keep])


/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:3: RuntimeWarning: divide by zero encountered in true_divide
  This is separate from the ipykernel package so we can avoid doing imports until

In [142]:
plt.scatter(dat.e1[isRec],dat.tractor_shapeexp_e1[isRec])


Out[142]:
<matplotlib.collections.PathCollection at 0x116d2f160>

In [153]:
plt.scatter(dat.e2[isRec],-dat.tractor_shapeexp_e2[isRec])


Out[153]:
<matplotlib.collections.PathCollection at 0x124206f98>

In [131]:
band='g'
xlim=(22,25.5)
ylim=(-10,10)
nbins=(60,30)

num_std_dev= dat.get('tractor_flux_'+band) -\
                        dat.get(band+'flux')
num_std_dev *= np.sqrt(dat.get('tractor_flux_ivar_'+band))
true_mag= plots.flux2mag(dat.get(band+'flux')/\
                           dat.get('mw_transmission_'+band))

fig,ax=plt.subplots()
#plots.myhist2D(ax,true_mag[isRec],num_std_dev[isRec],
#               xlim=xlim,ylim=(-10,10),nbins=(60,30))
#bins= np.linspace(xlim[0],xlim[1],num=30)

H, xbins, ybins = np.histogram2d(true_mag[isRec],num_std_dev[isRec],
                                 bins=(np.linspace(xlim[0],xlim[1],nbins[0]),
                                       np.linspace(ylim[0],ylim[1],nbins[1])))
cmap = plt.cm.binary
cmap.set_bad('w', 1.)
H[H == 0] = 1  # prevent warnings in log10
ax.imshow(np.log10(H).T, origin='lower',
          #extent=[xbins[0], xbins[-1], ybins[0], ybins[-1]],
          extent=[xlim[0], xlim[1], ylim[0], ylim[1]],
          cmap=cmap, interpolation='nearest',
          aspect='auto')


Out[131]:
<matplotlib.image.AxesImage at 0x1218f2208>

In [728]:
fig,ax=plt.subplots()

kw=dict(range=(21,24),normed=True)
myhist(ax,dat.psql_g[isRec],bins=30,color='b',label='truth',**kw)
myhist(ax,mags['g'],bins=bins,color='g',label='meas',**kw)
myhist(ax,dat.psql_g[ is_elg_input],bins=30,color='r',label='truth + ELG',**kw)

#for ax in axes:
#     ax.set_xlim(0.5,2)
#     ax.set_ylim(0.2,1.3)
ax.set_xlabel('g')
#     ax.set_ylabel('g-r')
ax.legend(loc='upper left')


Out[728]:
<matplotlib.legend.Legend at 0x15bb1b7f0>

In [548]:
fig,axes=plt.subplots(1,2,figsize=(10,5))
plt.subplots_adjust(wspace=0.2)
# xlim=(0,2.5)
xlim=None
kw=dict(range=(0,2),normed=False)

# Left panel
ax= axes[0]
n_tot,bins= np.histogram(dat.psql_redshift,bins=30,**kw)

lab,keep= 'ELG fraction', (is_elg_input)
n_elg,bins= np.histogram(dat.psql_redshift[keep],bins=bins,**kw)
my_step(ax,bins,n_elg/n_tot,color='b',label=lab)

lab,keep= 'ELG fraction & Recovered', (isRec) & (is_elg_input)
n_elg_rec,_= np.histogram(dat.psql_redshift[keep],bins=bins,**kw)
my_step(ax,bins,n_elg_rec/n_tot,color='g',label=lab)

# Right panel
ax= axes[1]
lab,keep= 'correct Targets', (isRec) & (is_elg_input) & (is_elg_trac)
n_corr,_= np.histogram(dat.psql_redshift[keep],bins=bins,**kw)
my_step(ax,bins,n_corr/n_elg_rec,color='b',label=lab)
print('n_corr=',n_corr)

lab,keep= 'lost Targets', (isRec) & (is_elg_input) & (~is_elg_trac)
n_lost,_= np.histogram(dat.psql_redshift[keep],bins=bins,**kw)
my_step(ax,bins,n_lost/n_elg_rec,color='g',label=lab)
print('n_lost=',n_lost)

lab,keep= 'contaminated Targets', (isRec) & (~is_elg_input) & (is_elg_trac)
n_contam,_= np.histogram(dat.psql_redshift[keep],bins=bins,**kw)
my_step(ax,bins,n_contam/n_elg_rec,color='m',label=lab)
print('n_contam=',n_contam)

for ax in axes:
    ax.axhline(0.5,c='k',ls='--')
    ax.set_ylim(-0.1,1.1)
    ax.set_ylabel('Fraction')
    ax.set_xlabel('redshift')
axes[0].legend(loc='upper left')
axes[1].legend(loc=(1.01,0))


n_corr= [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
n_lost= [   2    6    5   18    8    5   11    1    3   26   84  559 1091  724  395
  256   73   81   31   13   13    4    0    0    0    0    0    0    0    0]
n_contam= [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:13: RuntimeWarning: invalid value encountered in true_divide
  del sys.path[0]
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/matplotlib/cbook.py:2649: UserWarning: Saw kwargs ['ls', 'linestyle'] which are all aliases for 'linestyle'.  Kept value from 'linestyle'
  seen=seen, canon=canonical, used=seen[-1]))
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:17: RuntimeWarning: invalid value encountered in true_divide
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:23: RuntimeWarning: invalid value encountered in true_divide
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:28: RuntimeWarning: invalid value encountered in true_divide
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:33: RuntimeWarning: invalid value encountered in true_divide
Out[548]:
<matplotlib.legend.Legend at 0x1430a9d30>

In [417]:
def myhist2D(ax,x,y,xlim=(),ylim=(),nbins=()):
    #http://www.astroml.org/book_figures/chapter1/fig_S82_hess.html
    H, xbins, ybins = np.histogram2d(x,y,
                                     bins=(np.linspace(xlim[0],xlim[1],nbins[0]),
                                           np.linspace(ylim[0],ylim[1],nbins[1])))
    cmap = plt.cm.binary
    ax.imshow(H.T, origin='lower',
              extent=[xbins[0], xbins[-1], ybins[0], ybins[-1]],
              cmap=cmap, interpolation='nearest',
              aspect='auto')
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)


isRec= dat.obiwan_mask == 1
fig,axes=plt.subplots(1,2,figsize=(8,5))
plt.subplots_adjust(wspace=0.3)

kw=dict(xlim=(0.2,1.0),ylim=(0,180),nbins=(30,30))
for ax,keep in zip(axes,
                   [np.ones(len(dat),bool),isRec]):
    myhist2D(ax,dat.psql_ba[keep],dat.psql_pa[keep],**kw)

# ax[0].set_aspect('equal')
# ax[1].set_aspect(abs((ax[1].get_xlim()[1]-ax[1].get_xlim()[0])/\
#                      (ax[1].get_ylim()[1]-ax[1].get_xlim()[0])))

for i in range(2):
    axes[i].set_xlabel('ba')
axes[0].set_ylabel('pa')


Out[417]:
<matplotlib.text.Text at 0x14084df60>

How to Fix dflux using apflux_resid!!!!

  • the fix makes faint end of the residual have larger scatter than bright end which is what expect

In [334]:
band='z'
figs,ax= plt.subplots(5,1,figsize=(5,12))

isRec= dat.obiwan_mask == 1
dflux= dat.get('tractor_flux_'+band)[isRec] - dat.get(band+'flux')[isRec]
rad_aper= [0.5,0.75,1.0,1.5,2.0,3.5,5.0,7.0]
for cnt,i_aper in enumerate([4,5,6,7,-1]):
    ratio_area= 1. 
    #ratio_area= (1.5*dat.rhalf[isRec] / rad_aper[i_aper])**2
    if i_aper == -1:
        fix= ratio_area * np.average([dat.get('tractor_apflux_resid_'+band)[isRec,6],
                                      dat.get('tractor_apflux_resid_'+band)[isRec,7]],
                                    axis=0)
        assert(len(fix)) == len(dat[isRec])
    else:
        fix= dat.get('tractor_apflux_resid_'+band)[isRec,i_aper]* ratio_area
    print('fix=',fix,'dflux=',dflux)
    y= dflux - fix
    ax[cnt].scatter(dat.get(band+'flux')[isRec],y,
                    alpha=0.2,c='b')
    ax[cnt].axhline(np.median(y),c='r',ls='--')
    print('median=',np.median(y))

for i in range(5):
    ax[i].axhline(0,c='k',ls='--')
#     ax[i].set_yscale('log')
#     ax[i].set_ylim(1e-2,2e1)
    ax[i].set_ylim(-5,5)


fix= [ 0.46955267 -0.21419707  0.2856611  ...,  0.21198358  0.13909206
 -0.32362264] dflux= [-0.60327875  0.13913705 -0.08202423 ..., -0.05187323 -0.03534078
 -0.02667671]
median= -0.531838792528
fix= [ 0.83753693 -0.44062534  0.81644279 ...,  0.25070146  0.35351264
 -1.73575914] dflux= [-0.60327875  0.13913705 -0.08202423 ..., -0.05187323 -0.03534078
 -0.02667671]
median= -0.44539169405
fix= [ 1.32278228 -0.80876064  1.78851771 ..., -1.24446416 -0.04480623
 -2.68531513] dflux= [-0.60327875  0.13913705 -0.08202423 ..., -0.05187323 -0.03534078
 -0.02667671]
median= -0.179187853022
fix= [ 2.67648363 -1.0258615   0.90383226 ..., -2.88036346  1.83955121
 -4.72889614] dflux= [-0.60327875  0.13913705 -0.08202423 ..., -0.05187323 -0.03534078
 -0.02667671]
median= 0.235969813752
fix= [ 1.99963295 -0.91731107  1.34617499 ..., -2.06241381  0.89737249
 -3.70710564] dflux= [-0.60327875  0.13913705 -0.08202423 ..., -0.05187323 -0.03534078
 -0.02667671]
median= 0.0162609069016

dmag

  • True mag: brightness of source + its noise + extinction
  • dmag: tractor measured mag - true_mag - sky_mag from sky at that source position

In [340]:
band='z'
figs,ax= plt.subplots(5,1,figsize=(5,12))

isRec= dat.obiwan_mask == 1
rad_aper= [0.5,0.75,1.0,1.5,2.0,3.5,5.0,7.0]
for cnt,i_aper in enumerate([4,5,6,7,-1]):
    ratio_area= 1. 
    #ratio_area= (1.5*dat.rhalf[isRec] / rad_aper[i_aper])**2
    if i_aper == -1:
        fix= ratio_area * np.average([dat.get('tractor_apflux_resid_'+band)[isRec,6],
                                      dat.get('tractor_apflux_resid_'+band)[isRec,7]],
                                    axis=0)
        assert(len(fix)) == len(dat[isRec])
    else:
        fix= dat.get('tractor_apflux_resid_'+band)[isRec,i_aper]* ratio_area
    dmag= plots.flux2mag(dat.get('tractor_flux_'+band)[isRec]) -\
            plots.flux2mag(dat.get(band+'flux')[isRec]+  fix)
    true_mag= plots.flux2mag(dat.get(band+'flux')[isRec]/\
                             dat.get('mw_transmission_'+band)[isRec])
    isPostiveFlux= ((np.isfinite(dmag)) &
                    (np.isfinite(true_mag)))
    print('true_mag=',true_mag[isPostiveFlux],'trac_mag=',dmag[isPostiveFlux])
    ax[cnt].scatter(true_mag[isPostiveFlux],dmag[isPostiveFlux],
                    alpha=0.2,c='b')
    ax[cnt].axhline(np.median(dmag[isPostiveFlux]),c='r',ls='--')
    print('median=',np.median(dmag[isPostiveFlux]))
    
    binned= plots.bin_up(true_mag[isPostiveFlux],dmag[isPostiveFlux], 
                         bin_minmax=(16,25),nbins=30)
    for perc in ['q25','q75']:
        ax[cnt].plot(binned['binc'],binned[perc],c='r',lw=2)

for i in range(5):
    ax[i].axhline(0,c='k',ls='--')
    ax[i].set_ylim(-2,2)


/Users/kaylan1/PhdStudent/Research/desi/obiwan/py/obiwan/qa/plots.py:39: RuntimeWarning: divide by zero encountered in log10
  np.linspace(ylim[0],ylim[1],nbins[1])))
/Users/kaylan1/PhdStudent/Research/desi/obiwan/py/obiwan/qa/plots.py:39: RuntimeWarning: invalid value encountered in log10
  np.linspace(ylim[0],ylim[1],nbins[1])))
true_mag= [ 20.93833542  21.20184135  20.8072052  ...,  21.31015587  21.77809906
  21.01568413] trac_mag= [ 0.29185285 -0.1210452   0.08480629 ...,  0.09607506  0.09786368
 -0.08881957]
median= 0.133546854082
true_mag= [ 20.93833542  21.20184135  20.8072052  ...,  21.31015587  21.77809906
  21.01568413] trac_mag= [ 0.3762652  -0.20637092  0.19661195 ...,  0.10948405  0.20720452
 -0.65323161]
median= 0.10447186237
true_mag= [ 20.93833542  21.20184135  20.8072052  ...,  21.31015587  21.77809906
  21.01568413] trac_mag= [ 0.47840095 -0.3612303   0.37558672 ..., -0.58803373 -0.00557145
 -1.31910432]
median= 0.0395384160801
true_mag= [ 20.93833542  21.20184135  20.8072052  ...,  20.82847595  21.31015587
  21.77809906] trac_mag= [ 0.72108025 -0.4641138   0.21396448 ..., -1.81171733 -5.21707271
  0.76005683]
median= -0.0505317558301
true_mag= [ 20.93833542  21.20184135  20.8072052  ...,  21.31015587  21.77809906
  21.01568413] trac_mag= [ 0.60650687 -0.41145386  0.2977802  ..., -1.32543575  0.4433763
 -3.94433459]
median= -0.0074523196963

num std deviations


In [338]:
band='z'
figs,ax= plt.subplots(5,1,figsize=(5,12))

isRec= dat.obiwan_mask == 1
rad_aper= [0.5,0.75,1.0,1.5,2.0,3.5,5.0,7.0]
for cnt,i_aper in enumerate([4,5,6,7,-1]):
    ratio_area= 1. 
    #ratio_area= (1.5*dat.rhalf[isRec] / rad_aper[i_aper])**2
    if i_aper == -1:
        fix= ratio_area * np.average([dat.get('tractor_apflux_resid_'+band)[isRec,6],
                                      dat.get('tractor_apflux_resid_'+band)[isRec,7]],
                                    axis=0)
        assert(len(fix)) == len(dat[isRec])
    else:
        fix= dat.get('tractor_apflux_resid_'+band)[isRec,i_aper]* ratio_area
    num_std_dev= (dat.get('tractor_flux_'+band)[isRec] -\
                  (dat.get(band+'flux')[isRec]+  fix))*\
            np.sqrt(dat.get('tractor_flux_ivar_'+band)[isRec])
    true_mag= plots.flux2mag(dat.get(band+'flux')[isRec]/\
                             dat.get('mw_transmission_'+band)[isRec])
    print('true_mag=',true_mag,'num_std_dev=',num_std_dev)
    ax[cnt].scatter(true_mag,num_std_dev,
                    alpha=0.2,c='b')
    ax[cnt].axhline(np.median(num_std_dev),c='r',ls='--')
    print('median=',np.median(num_std_dev))
    
    binned= plots.bin_up(true_mag,num_std_dev, bin_minmax=(16,25),nbins=30)
    for perc in ['q25','q75']:
        ax[cnt].plot(binned['binc'],binned[perc],c='r',lw=2)

for i in range(5):
    ax[i].axhline(0,c='k',ls='--')
    ax[i].set_ylim(-5,5)


true_mag= [ 20.93833542  21.20184135  20.8072052  ...,  21.31015587  21.77809906
  21.01568413] num_std_dev= [-4.34730214  1.21810205 -1.3827519  ..., -0.75389706 -0.73209095
  1.21890048]
median= -1.60525274255
true_mag= [ 20.93833542  21.20184135  20.8072052  ...,  21.31015587  21.77809906
  21.01568413] num_std_dev= [-5.8384393   1.99870241 -3.3788592  ..., -0.86452258 -1.63200962
  7.01542316]
median= -1.15402747036
true_mag= [ 20.93833542  21.20184135  20.8072052  ...,  21.31015587  21.77809906
  21.01568413] num_std_dev= [ -7.80473904   3.26783082  -7.03453518 ...,   3.40749519   0.0397263
  10.91315038]
median= -0.151277299666
true_mag= [ 20.93833542  21.20184135  20.8072052  ...,  21.31015587  21.77809906
  21.01568413] num_std_dev= [-13.29017572   4.01627538  -3.70750422 ...,   8.08162013  -7.86888209
  19.30161971]
median= 0.781358373371
true_mag= [ 20.93833542  21.20184135  20.8072052  ...,  21.31015587  21.77809906
  21.01568413] num_std_dev= [-10.54745738   3.6420531   -5.3710197  ...,   5.74455766  -3.91457789
  15.10738504]
median= 0.0549080444017

delta RA, Dec


In [281]:
i= dat.obiwan_mask == 1
plt.scatter(dat.mw_transmission_g[i],
            dat.mw_transmission_g[i] - dat.tractor_mw_transmission_g[i])
plt.ylim(-1e-4,1e-4)


Out[281]:
(-0.0001, 0.0001)

In [282]:
i= dat.obiwan_mask == 1
plt.scatter(dat.ra[i],
            (dat.ra[i] - dat.tractor_ra[i])*3600)
plt.ylim(-1.2,1.2)


Out[282]:
(-1.2, 1.2)

In [283]:
i= dat.obiwan_mask == 1
plt.scatter((dat.ra[i] - dat.tractor_ra[i])*3600,
            (dat.dec[i] - dat.tractor_dec[i])*3600)
plt.axhline(0,c='k',ls='--')
plt.axvline(0,c='k',ls='--')
plt.ylim(-1.2,1.2)
plt.xlim(-1.2,1.2)
plt.xlabel(r'$\Delta \, RA$')
plt.ylabel(r'$\Delta \, Dec$')


Out[283]:
<matplotlib.text.Text at 0x13ba78a90>

In [285]:
i= dat.obiwan_mask == 1
sns.distplot((dat.tractor_nora[i] - dat.tractor_ra[i])*3600,
             (dat.dec[i] - dat.tractor_dec[i])*3600)
plt.axhline(0,c='k',ls='--')
plt.axvline(0,c='k',ls='--')
plt.ylim(-1.2,1.2)
plt.xlim(-1.2,1.2)
plt.xlabel(r'$\Delta \, RA$')
plt.ylabel(r'$\Delta \, Dec$')


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-285-3335e05cd327> in <module>()
      1 i= dat.obiwan_mask == 1
----> 2 sns.distplot((dat.tractor_nora[i] - dat.tractor_ra[i])*3600,
      3              (dat.dec[i] - dat.tractor_dec[i])*3600)
      4 plt.axhline(0,c='k',ls='--')
      5 plt.axvline(0,c='k',ls='--')

AttributeError: 'tabledata' object has no attribute 'tractor_nora'

In [298]:
band='g'
figs,ax= plt.subplots(3,1,figsize=(5,10))

isRec= dat.obiwan_mask == 1
dflux= dat.get('tractor_flux_'+band)[isRec] - dat.get(band+'flux')[isRec]
rad_aper= [0.5,0.75,1.0,1.5,2.0,3.5,5.0,7.0]
for cnt,i_aper in enumerate([4,5,6]):
    ratio_area= (1.5*dat.rhalf[isRec] / rad_aper[i_aper])**2
    fix= dat.get('tractor_apflux_resid_'+band)[isRec,i_aper]* ratio_area
    print('fix=',fix,'dflux=',dflux)
    sns.distplot(fix,ax=ax[cnt])
    ax[cnt].set_xlim(-0.2,0.2)


fix= [ 0.01410908  0.00205612  0.0094271  ...,  0.05565902  0.00697286
  0.00865769] dflux= [-0.17664099  0.04343205 -0.02215747 ..., -0.12600998 -0.06912357
  0.01782683]
fix= [ 0.00511783 -0.00519097  0.01246918 ...,  0.01146335  0.00121295
  0.00036051] dflux= [-0.17664099  0.04343205 -0.02215747 ..., -0.12600998 -0.06912357
  0.01782683]
fix= [ 0.00151087 -0.00555547  0.00538299 ..., -0.02107371  0.00137389
 -0.00986581] dflux= [-0.17664099  0.04343205 -0.02215747 ..., -0.12600998 -0.06912357
  0.01782683]

psfsize --> rhalf


In [ ]:
dat.tractor_allmask_g

In [243]:
# recovered
isRec= ((dat.obiwan_mask == 1) &
        (dat.tractor_brick_primary) &
        (dat.tractor_allmask_g == 0) & 
        (dat.tractor_allmask_r == 0) & 
        (dat.tractor_allmask_z == 0) & 
        ((dat.tractor_flux_g > 0) |
         (dat.tractor_flux_r > 0) |
         (dat.tractor_flux_z > 0))
       )
        
# Types
tractor_type= np.char.strip(dat.tractor_type)
TYPES= list(set(tractor_type))
isType={}
for typ in TYPES:
    isType[typ]= tractor_type == typ
print(isType.keys())
# rhalf ~ fwhm/2
fwhm_or_rhalf= np.zeros(len(dat))+np.nan
for typ in TYPES:
    if typ in ['','COMP']:
        continue
    i= (isType[typ]) & (isRec)
    if typ == 'PSF':
        fwhm_or_rhalf[i]= np.mean([dat.get('tractor_psfsize_'+band)[i]
                                   for band in 'grz'],axis=0) / 2
    elif typ == 'SIMP':
        fwhm_or_rhalf[i]= 0.5
    elif typ == 'EXP':
        fwhm_or_rhalf[i]= dat.tractor_shapeexp_r[i]
    elif typ == 'DEV':
        fwhm_or_rhalf[i]= dat.tractor_shapedev_r[i]


dict_keys(['', 'DEV', 'PSF', 'COMP', 'EXP', 'SIMP'])
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:8: RuntimeWarning: invalid value encountered in greater
  
/Users/kaylan1/miniconda3/envs/mlbook/lib/python3.6/site-packages/ipykernel_launcher.py:9: RuntimeWarning: invalid value encountered in greater
  if __name__ == '__main__':

In [244]:
e1= np.zeros(len(dat))+np.nan
e2=e1.copy()
for typ in ['SIMP','EXP','DEV']:
    i= (isType[typ]) & (isRec)
    if typ in ['SIMP','EXP','REX']:
        e1[i]= dat.tractor_shapeexp_e1[i]
        e2[i]= dat.tractor_shapeexp_e2[i]
    elif typ in ['DEV']:
        e1[i]= dat.tractor_shapedev_e1[i]
        e2[i]= dat.tractor_shapedev_e2[i]

Delta plots


In [255]:
diff={}

for key in ['ra','dec']:
    diff['delta_'+key]= dat.get('tractor_'+key)[isRec] - dat.get(key)[isRec] 
for key in 'xy':
    diff['delta_'+key]= dat.get('tractor_b'+key)[isRec] - dat.get(key)[isRec]
# More complicated quantities
diff['avg_num_std']= np.mean([(dat.get('tractor_flux_'+band)[isRec] - dat.get(band+'flux')[isRec])*\
                                np.sqrt(dat.get('tractor_flux_ivar_'+band)[isRec])
                              for band in 'grz'],axis=0)
diff['fracflux_sum']= np.sum([dat.get('tractor_fracflux_'+band)[isRec]
                              for band in 'grz'],axis=0)
diff['anymask_sum']= np.sum([dat.get('tractor_anymask_'+band)[isRec]
                             for band in 'grz'],axis=0)
diff['allmask_sum']= np.sum([dat.get('tractor_allmask_'+band)[isRec]
                             for band in 'grz'],axis=0)
assert(len(diff['avg_num_std']) == len(dat[isRec]))
for band in 'grz':
    diff[band+'_mag']= plots.flux2mag(dat.get(band+'flux')[isRec]/\
                                      dat.get('mw_transmission_'+band)[isRec])
    

diff['delta_rhalf']= fwhm_or_rhalf[isRec] - dat.rhalf[isRec]
diff['delta_e1']= e1[isRec] - dat.e1[isRec]
diff['delta_e2']= e2[isRec] - dat.e1[isRec]
# Scale
for key in ['ra','dec']:
    diff['delta_'+key]*= 3600 # arcsec
# Add Hue
diff['typ']= tractor_type[isRec]

diff_df= pd.DataFrame(diff)

In [260]:
diff_df.columns


Out[260]:
Index(['allmask_sum', 'anymask_sum', 'avg_num_std', 'delta_dec', 'delta_e1',
       'delta_e2', 'delta_ra', 'delta_rhalf', 'delta_x', 'delta_y',
       'fracflux_sum', 'g_mag', 'r_mag', 'typ', 'z_mag'],
      dtype='object')

In [189]:
cols=['avg_num_std','delta_rhalf','typ','delta_e1','delta_e2']
sns.pairplot(diff_df[cols], hue="typ")


Out[189]:
<seaborn.axisgrid.PairGrid at 0x13172a9b0>

Color by exp or dev: dflux/sigma vs. mag, delta_rhalf, e1, e2


In [252]:
set(dat.tractor_fracflux_g[dat.obiwan_mask == 1])


Out[252]:
{0.0,
 0.0047294269315898418,
 0.0023323663044720888,
 0.0081588653847575188,
 0.0011112581705674529,
 0.00022863196500111371,
 0.0028280213009566069,
 0.030261635780334473,
 0.0059115500189363956,
 0.0083711715415120125,
 0.025556182488799095,
 0.0027173240669071674,
 0.0037926218938082457,
 0.00010892535647144541,
 0.0012100641615688801,
 0.012101290747523308,
 14.269735336303711,
 2.6745290756225586,
 2.8670837879180908,
 3.1662344932556152,
 3.4293971061706543,
 4.0342559814453125,
 4.6869664192199707,
 4.2039799690246582,
 4.6072125434875488,
 5.1494345664978027,
 0.00043466495117172599,
 0.003186654532328248,
 0.00039661111077293754,
 0.016525644809007645,
 0.0072397477924823761,
 0.046174246817827225,
 0.035119015723466873,
 0.00099933159071952105,
 0.04029545933008194,
 0.0039268843829631805,
 0.05319729819893837,
 0.035980585962533951,
 0.015883620828390121,
 7.1345424652099609,
 7.6121649742126465,
 7.8426203727722168,
 7.5551371574401855,
 7.2274575233459473,
 53.890106201171875,
 2.1058113574981689,
 0.0021151273977011442,
 0.48074543476104736,
 0.30374348163604736,
 0.01520820427685976,
 78.014678955078125,
 0.0043114498257637024,
 0.021147154271602631,
 0.0080924537032842636,
 0.0042782332748174667,
 0.014719894155859947,
 -0.016780922189354897,
 0.05286865308880806,
 0.02588401734828949,
 0.032105665653944016,
 0.016524665057659149,
 0.15338337421417236,
 0.031374458223581314,
 0.031712781637907028,
 0.040225639939308167,
 0.24791301786899567,
 0.02515222504734993,
 35.384681701660156,
 0.88722628355026245,
 0.029777966439723969,
 242.52635192871094,
 0.0019409952219575644,
 262.66131591796875,
 0.024800173938274384,
 0.016671650111675262,
 0.11056958884000778,
 0.014150612056255341,
 0.0019752904772758484,
 0.011684291064739227,
 0.023002736270427704,
 0.078789584338665009,
 0.00076079560676589608,
 0.00071176706114783883,
 0.00053090794244781137,
 0.0050068278796970844,
 0.0022040982730686665,
 305.32778930664062,
 0.00079166959039866924,
 0.086347818374633789,
 0.0019182795658707619,
 0.013557636179029942,
 0.0026297206059098244,
 0.006730162538588047,
 0.0058425301685929298,
 0.014439904130995274,
 0.0047968262806534767,
 0.005891451146453619,
 0.27767303586006165,
 0.27765396237373352,
 0.006315404549241066,
 0.017492348328232765,
 0.016349012032151222,
 0.021700674667954445,
 0.017674857750535011,
 0.019980007782578468,
 -0.001210983726195991,
 0.00094040122348815203,
 0.00070836779195815325,
 0.0013671108754351735,
 0.0013050996931269765,
 0.0030812646728008986,
 0.0022382165770977736,
 0.008688594214618206,
 0.0024312986060976982,
 0.008744741789996624,
 0.009035731665790081,
 0.0096628917381167412,
 0.0051619065925478935,
 0.0065440190955996513,
 0.0087470067664980888,
 0.0014299220638349652,
 0.00031275968649424613,
 -0.00023636672995053232,
 0.0034496295265853405,
 0.018878903239965439,
 0.0038034056778997183,
 0.004217144101858139,
 0.057325955480337143,
 0.01572548970580101,
 0.0092544518411159515,
 0.049897190183401108,
 0.016388889402151108,
 0.0014315806329250336,
 0.033767934888601303,
 0.010960932821035385,
 0.060251589864492416,
 0.00030056218383833766,
 1.7589198250789195e-05,
 -7.692537474213168e-05,
 -0.0001087374912458472,
 0.0015342835104092956,
 0.0077529367990791798,
 0.0020579514093697071,
 0.30950009822845459,
 1.197462797164917,
 0.0033193500712513924,
 0.0062030227854847908,
 0.0073475511744618416,
 0.00029207879560999572,
 0.0036139613948762417,
 0.0042140609584748745,
 0.016031883656978607,
 0.3094877302646637,
 0.16868343949317932,
 0.001471834140829742,
 0.015761552378535271,
 0.01629704050719738,
 0.030194340273737907,
 0.0033712964504957199,
 0.011107264086604118,
 0.0031989198178052902,
 0.021881280466914177,
 0.029040036723017693,
 0.00010615983046591282,
 0.0033833535853773355,
 0.0037341269198805094,
 0.0018255526665598154,
 0.0034144560340791941,
 0.00095064961351454258,
 0.0010783302132040262,
 0.0026173295918852091,
 0.0020925367716699839,
 0.00085371383465826511,
 0.0018671773141250014,
 0.0076300934888422489,
 0.0046875313855707645,
 -0.004469127394258976,
 0.0042519858106970787,
 0.014928012154996395,
 0.0015788181917741895,
 0.0032517828512936831,
 0.0011628784704953432,
 0.00068210740573704243,
 0.0077416445128619671,
 0.0073294187895953655,
 0.013896435499191284,
 0.29160904884338379,
 0.45901989936828613,
 0.036918878555297852,
 0.0089933872222900391,
 0.039824843406677246,
 0.12461221218109131,
 0.66359269618988037,
 0.046008467674255371,
 1.3118312358856201,
 0.28300464153289795,
 0.00073404080467298627,
 0.0003850518842227757,
 -0.00016969972057268023,
 -5.7023356930585578e-05,
 0.00065057026222348213,
 0.0050882552750408649,
 0.27581644058227539,
 0.13229990005493164,
 0.0090340087190270424,
 0.0017859647050499916,
 0.0087938020005822182,
 0.0038163824938237667,
 0.003563897218555212,
 0.0054650469683110714,
 0.053335927426815033,
 0.0036839039530605078,
 0.043916255235671997,
 0.016479911282658577,
 0.020323814824223518,
 0.024330439046025276,
 0.0079422611743211746,
 0.004613460972905159,
 0.017116250470280647,
 0.00060978194233030081,
 0.00077674200292676687,
 0.0013749900972470641,
 0.0016377608990296721,
 0.0012549612438306212,
 0.0015874285018071532,
 0.0015750344609841704,
 0.0010878596222028136,
 0.0011326823150739074,
 0.0015051609370857477,
 0.00099216634407639503,
 0.0017347210086882114,
 0.0035908096469938755,
 0.0064539783634245396,
 0.0023453931789845228,
 0.080257952213287354,
 0.0011035714996978641,
 0.015087041072547436,
 0.012988838367164135,
 0.0064075319096446037,
 0.0089156953617930412,
 0.0052636447362601757,
 0.0058414521627128124,
 0.002910226583480835,
 0.017020825296640396,
 0.0005986727774143219,
 0.044127229601144791,
 0.035281065851449966,
 0.017896536737680435,
 0.04097164049744606,
 0.03484821692109108,
 0.0044860877096652985,
 0.032718662172555923,
 0.02830231562256813,
 0.00036116171395406127,
 -0.00060164328897371888,
 0.00012451563088688999,
 0.00022760198044124991,
 -0.0001875789457699284,
 0.00018074888794217259,
 0.00022678148525301367,
 0.0017120135016739368,
 0.0053748381324112415,
 0.091292023658752441,
 1.9477224349975586,
 0.007445906288921833,
 0.0010996805503964424,
 0.015501474030315876,
 0.00036963584716431797,
 0.00056045991368591785,
 0.022613659501075745,
 0.006904741283506155,
 0.005098243709653616,
 0.0026794872246682644,
 0.0052360496483743191,
 0.0015857419930398464,
 0.080714128911495209,
 0.2869049608707428,
 0.027644818648695946,
 0.0018188413232564926,
 0.016170090064406395,
 0.029798692092299461,
 0.015973752364516258,
 0.0020297225564718246,
 0.0021868404000997543,
 0.0060475808568298817,
 0.0019083363004028797,
 0.0058848005719482899,
 0.0045462888665497303,
 0.0040046018548309803,
 0.0060977977700531483,
 0.0034865480847656727,
 0.0039303344674408436,
 0.0068969805724918842,
 0.0059498031623661518,
 0.0019778294954448938,
 0.3974425196647644,
 0.0059730177745223045,
 0.0010543232783675194,
 0.011248267255723476,
 0.016093974933028221,
 0.11903676390647888,
 0.0010947167174890637,
 -4.63393225800246e-05,
 0.11015911400318146,
 0.0038274149410426617,
 0.093342743813991547,
 0.050667725503444672,
 0.00080005801282823086,
 0.099043019115924835,
 0.097706921398639679,
 0.10922742635011673,
 0.061075456440448761,
 0.056689627468585968,
 0.042253859341144562,
 0.074288733303546906,
 0.10062826424837112,
 0.11307228356599808,
 0.018109805881977081,
 0.00046209112042561173,
 -0.00019222631817683578,
 0.00025590375298634171,
 5.6827342632459477e-05,
 0.00085352972382679582,
 0.005917601753026247,
 0.053260203450918198,
 0.038466807454824448,
 0.0025258220266550779,
 0.25306200981140137,
 0.015242338180541992,
 0.0062207961454987526,
 0.014363029040396214,
 0.0099111581221222878,
 0.013448932208120823,
 0.010090448893606663,
 -0.0033141262829303741,
 0.052761923521757126,
 0.19202448427677155,
 0.0058570145629346371,
 1390.4716796875,
 0.0046850680373609066,
 0.01990797370672226,
 0.0012087689246982336,
 0.024300405755639076,
 -0.028416922315955162,
 0.021201202645897865,
 -0.0034608151763677597,
 0.00063397421035915613,
 0.0011263234773650765,
 0.0010269327322021127,
 0.0015313035110011697,
 0.00035687221679836512,
 0.0017186036566272378,
 0.0019791445229202509,
 0.0011617509881034493,
 0.0012025578180328012,
 0.00060522614512592554,
 0.0003415294922888279,
 0.011762420646846294,
 0.0051923650316894054,
 0.0074044126085937023,
 0.0054102796129882336,
 0.011822782456874847,
 0.0023913865443319082,
 0.0038999801035970449,
 0.0017523055430501699,
 0.0042414981871843338,
 0.029894363135099411,
 0.015101205557584763,
 0.017084848135709763,
 0.0043400637805461884,
 0.016909610480070114,
 0.016911160200834274,
 0.046718250960111618,
 0.044167649000883102,
 0.033085953444242477,
 0.05440903827548027,
 0.00067855295492336154,
 0.00062759470893070102,
 0.00085214030696079135,
 0.00066171091748401523,
 0.0007811921532265842,
 0.0001110314842662774,
 0.003018710995092988,
 0.0091750510036945343,
 0.0024213162250816822,
 0.005536374170333147,
 0.0014804794918745756,
 0.0025874569546431303,
 1.1736938953399658,
 0.0082884849980473518,
 0.019760504364967346,
 0.0095151197165250778,
 0.021912289783358574,
 0.018592191860079765,
 0.053238548338413239,
 0.0028793185483664274,
 0.0010713345836848021,
 0.00036361883394420147,
 0.0023425004910677671,
 0.0029079101514071226,
 0.0014166317414492369,
 0.0037662468384951353,
 0.0010903596412390471,
 0.002096664858981967,
 0.0034299909602850676,
 0.0068633542396128178,
 0.0012675139587372541,
 0.0015859219711273909,
 0.052868783473968506,
 0.22200864553451538,
 0.74896711111068726,
 0.013644023798406124,
 0.011906309984624386,
 0.0060466965660452843,
 0.013443036936223507,
 0.0089222630485892296,
 0.00047172213089652359,
 0.091200307011604309,
 0.00073857605457305908,
 0.0057681496255099773,
 0.0076400930993258953,
 0.007065861951559782,
 0.0018466038163751364,
 0.0010328812059015036,
 0.32025143504142761,
 0.072704285383224487,
 0.015745893120765686,
 0.003908887505531311,
 0.070791140198707581,
 0.24327565729618073,
 0.0049486309289932251,
 0.020164504647254944,
 0.057404652237892151,
 0.055869355797767639,
 0.07571817934513092,
 0.14257587492465973,
 0.00077110790880396962,
 0.00059494265588000417,
 0.00081370287807658315,
 -0.0029539091046899557,
 0.031025756150484085,
 0.0025441055186092854,
 0.0023123626597225666,
 0.0039365892298519611,
 0.053199406713247299,
 0.039587382227182388,
 0.01509998831897974,
 0.013834104873239994,
 0.011567340232431889,
 0.011207566596567631,
 0.0086693624034523964,
 0.052469022572040558,
 0.00025778435519896448,
 0.048450961709022522,
 0.0052376105450093746,
 0.0025761439464986324,
 0.0018156708683818579,
 0.017277078703045845,
 0.00058775965590029955,
 0.00060923106502741575,
 0.00078179023694247007,
 0.00076847232412546873,
 -0.00019735388923436403,
 0.0001445085508748889,
 0.00052717409562319517,
 0.0013461419148370624,
 0.00028741813730448484,
 0.0014504686696454883,
 0.00090775347780436277,
 0.099856898188591003,
 0.080813929438591003,
 -0.00052096077706664801,
 0.001601899741217494,
 0.29473596811294556,
 0.39328485727310181,
 0.24674707651138306,
 0.40735346078872681,
 0.015359806828200817,
 0.0037440536543726921,
 0.012263226322829723,
 0.0024165390059351921,
 0.0052093742415308952,
 0.00035794443101622164,
 0.00092948530800640583,
 0.0033822804689407349,
 0.031893327832221985,
 0.0022004577331244946,
 0.0043959352187812328,
 0.0026090701576322317,
 0.00071817240677773952,
 0.37379464507102966,
 0.0019053592113777995,
 0.0053674168884754181,
 0.045046944171190262,
 0.032755155116319656,
 0.031827230006456375,
 0.0050758309662342072,
 0.034843344241380692,
 0.0025995785836130381,
 0.00030044469167478383,
 0.00044642112334258854,
 0.00030270140268839896,
 0.00012977435835637152,
 -0.00037535917363129556,
 0.00034537751344032586,
 0.00047194052604027092,
 0.00044360049651004374,
 -0.00022781229927204549,
 0.00018947248463518918,
 0.15075837075710297,
 0.00039788370486348867,
 0.0046047610230743885,
 0.0053296727128326893,
 0.0016044831136241555,
 0.0025676756631582975,
 0.001302030635997653,
 0.001748093287460506,
 0.017541181296110153,
 0.096169129014015198,
 0.0027568689547479153,
 0.0048528066836297512,
 0.027920564636588097,
 0.017704924568533897,
 0.022664865478873253,
 0.0037981951609253883,
 0.0124600725248456,
 0.013591338880360126,
 0.012363632209599018,
 0.0084264772012829781,
 0.010953743942081928,
 0.0025558667257428169,
 0.0034427950158715248,
 0.0019744271412491798,
 0.011244864203035831,
 0.14291876554489136,
 0.043807931244373322,
 0.085140176117420197,
 0.00038648772169835865,
 0.0022678517270833254,
 0.0061729811131954193,
 0.0034927723463624716,
 0.11030139774084091,
 0.0096649155020713806,
 0.027981184422969818,
 0.089087866246700287,
 0.031308434903621674,
 0.019012473523616791,
 0.012302182614803314,
 0.10105755180120468,
 0.052641414105892181,
 0.0064826235175132751,
 0.009226776659488678,
 0.00094772787997499108,
 0.00080281781265512109,
 -0.012530094943940639,
 0.0011757547035813332,
 0.0024871760979294777,
 0.0051734833978116512,
 0.0027848498430103064,
 0.37327030301094055,
 0.019159520044922829,
 0.020402396097779274,
 0.02310713566839695,
 0.0098933819681406021,
 0.02794262208044529,
 0.00015064515173435211,
 0.024648511782288551,
 0.0021494273096323013,
 0.0018092404352501035,
 0.00035045400727540255,
 -0.00051612674724310637,
 0.00082027644384652376,
 0.0010901737259700894,
 0.00072271109092980623,
 0.0010830584215000272,
 0.0010416927980259061,
 0.0011897060321643949,
 0.0007676354143768549,
 0.0037270246539264917,
 0.0019375183619558811,
 0.0014737572055310011,
 0.0090421987697482109,
 0.0026920391246676445,
 0.0017348707187920809,
 0.0029300260357558727,
 0.0024101543240249157,
 0.0045161056332290173,
 0.063209861516952515,
 0.0016453712014481425,
 0.057715322822332382,
 0.026324298232793808,
 0.0047627948224544525,
 0.019932057708501816,
 0.032249834388494492,
 0.046102907508611679,
 0.041956331580877304,
 0.0083899758756160736,
 0.043861057609319687,
 0.05926981195807457,
 0.00052051170496270061,
 0.00046081020263954997,
 0.00092486216453835368,
 0.16210733354091644,
 0.0059051034040749073,
 0.0046383854933083057,
 -0.0016431466210633516,
 0.0054979296401143074,
 0.0005807848647236824,
 0.0028855402488261461,
 0.007301372941583395,
 0.0012003236915916204,
 0.029028326272964478,
 0.030134588479995728,
 0.0017576086102053523,
 0.0015977304428815842,
 0.021286575123667717,
 0.016234962269663811,
 0.0051231067627668381,
 0.028233615681529045,
 0.012549726292490959,
 0.012518731877207756,
 0.02436467818915844,
 0.0011567596811801195,
 0.0038765196222811937,
 0.0012296561617404222,
 0.001322941156104207,
 0.0034950573462992907,
 0.0036511619109660387,
 0.0014841307420283556,
 0.0012179214973002672,
 0.0011964079458266497,
 -0.0029092791955918074,
 0.0010335580445826054,
 0.0020029679872095585,
 0.01625698059797287,
 0.61544555425643921,
 0.028455197811126709,
 0.01191860344260931,
 0.0083059659227728844,
 0.00093012955039739609,
 0.011532016098499298,
 -0.00024232242139987648,
 0.001630447106435895,
 0.0024394013453274965,
 -0.00050725089386105537,
 0.0065225209109485149,
 0.0047176922671496868,
 0.016423311084508896,
 0.017685975879430771,
 0.0013666821178048849,
 0.26643481850624084,
 0.15599361062049866,
 0.22988715767860413,
 0.28501239418983459,
 0.032191544771194458,
 0.099493294954299927,
 0.046296387910842896,
 0.22548893094062805,
 0.15685299038887024,
 0.15211036801338196,
 0.00063211406813934445,
 0.00091038580285385251,
 0.00036177347647026181,
 -4.1509239963488653e-05,
 0.00028150092111900449,
 0.00070887740002945065,
 0.00048838864313438535,
 -1.8205220840172842e-05,
 0.0051369224674999714,
 0.0050996099598705769,
 0.35522794723510742,
 0.15250349044799805,
 1.9106520414352417,
 1.0761984586715698,
 0.013176680542528629,
 -0.0097925653681159019,
 0.067968614399433136,
 0.0002252406848128885,
 0.0003750122559722513,
 0.0003001264703925699,
 0.029868097975850105,
 0.0013663489371538162,
 0.013994308188557625,
 0.028792830184102058,
 0.001042985706590116,
 0.0016049420228227973,
 0.00044068822171539068,
 0.00093061232473701239,
 0.00020609551575034857,
 0.0014496309449896216,
 -0.00054074323270469904,
 -0.0010003173956647515,
 -0.0007101396331563592,
 0.0017901858082041144,
 0.0011427944991737604,
 0.61169582605361938,
 0.27197414636611938,
 0.084909021854400635,
 0.055787622928619385,
 0.0020646480843424797,
 0.014262857846915722,
 0.0079689649865031242,
 0.066269226372241974,
 0.0004497472255025059,
 0.0027221695054322481,
 0.0011247650254517794,
 0.0028885486535727978,
 0.0071203592233359814,
 0.0054974439553916454,
 0.015909038484096527,
 0.011857237666845322,
 0.11925944685935974,
 0.001609358936548233,
 0.0079528428614139557,
 0.0010258294641971588,
 0.053145322948694229,
 0.052313957363367081,
 0.021258387714624405,
 0.010473284870386124,
 0.035617861896753311,
 0.014233861118555069,
 0.034742031246423721,
 0.00081915355985984206,
 0.00078714959090575576,
 0.00070761091774329543,
 7.3208750109188259e-05,
 -0.00011820341751445085,
 0.0001907237310661003,
 0.0002206470089731738,
 -9.7589872893877327e-05,
 0.000109977598185651,
 0.00067505933111533523,
 0.051858413964509964,
 0.0019867015071213245,
 -0.00011972663924098015,
 0.00057522649876773357,
 0.28498423099517822,
 0.081962227821350098,
 0.14870798587799072,
 0.18240320682525635,
 0.16882288455963135,
 0.013181333430111408,
 0.012166504748165607,
 0.0074415253475308418,
 0.014761094935238361,
 0.0044525908306241035,
 0.032736189663410187,
 -0.0048138597048819065,
 0.00310350744985044,
 0.0030974277760833502,
 0.0016407724469900131,
 0.018796658143401146,
 0.010886048898100853,
 0.0029108873568475246,
 0.0027159205637872219,
 0.0016892640851438046,
 0.0029927878640592098,
 0.0074916272424161434,
 0.0049378960393369198,
 0.0011170892976224422,
 0.0028855926357209682,
 0.0014603263698518276,
 0.0069419867359101772,
 0.0055310935713350773,
 0.010214738547801971,
 0.0018409515032544732,
 0.0014934150967746973,
 0.31871956586837769,
 0.99842613935470581,
 0.0014980685664340854,
 0.0067020123824477196,
 0.0025292104110121727,
 0.01196629460901022,
 0.012815422378480434,
 0.012310094200074673,
 0.02658504992723465,
 0.0079396432265639305,
 0.0003289275337010622,
 0.20118637382984161,
 0.0048866192810237408,
 0.002443424891680479,
 0.0037708203308284283,
 0.0063891331665217876,
 0.1239909753203392,
 0.35305473208427429,
 0.25400230288505554,
 0.20532295107841492,
 0.11995765566825867,
 0.011458314955234528,
 0.04194728285074234,
 0.028075255453586578,
 0.015924490988254547,
 0.015355147421360016,
 0.039179958403110504,
 0.048784412443637848,
 0.031465806066989899,
 0.017843522131443024,
 0.074148572981357574,
 0.051753498613834381,
 0.0004754583933390677,
 0.00050884817028418183,
 0.0008058692910708487,
 0.00088672671699896455,
 0.00069694290868937969,
 0.0034854866098612547,
 0.17501425743103027,
 0.065131902694702148,
 0.1432645320892334,
 0.037188652902841568,
 0.0066090906038880348,
 0.0037728631868958473,
 0.014795192517340183,
 0.00099087599664926529,
 0.0038455808535218239,
 0.023657329380512238,
 0.0037186229601502419,
 0.00028171259327791631,
 0.00024959561415016651,
 0.00039557236596010625,
 0.074181810021400452,
 0.18770338594913483,
 0.10540773719549179,
 0.001326953643001616,
 0.030121544376015663,
 0.01941094733774662,
 0.018657663837075233,
 0.031210998073220253,
 0.0047542843967676163,
 0.015812018886208534,
 -0.016797801479697227,
 0.013601759448647499,
 0.0064567122608423233,
 0.018159607425332069,
 0.0018595695728436112,
 0.0019334793323650956,
 0.0015618555480614305,
 0.00038147869054228067,
 0.0035002848599106073,
 0.0013070531422272325,
 0.0013102419907227159,
 0.0019118316704407334,
 0.00078898819629102945,
 0.00098423066083341837,
 0.0073899277485907078,
 0.055090956389904022,
 0.047507338225841522,
 0.076922468841075897,
 0.010505507700145245,
 0.0021646721288561821,
 0.010454605333507061,
 0.078064508736133575,
 0.11617333441972733,
 0.00011865110718645155,
 0.037719085812568665,
 0.0086663514375686646,
 0.0016222780104726553,
 0.0022456233855336905,
 0.017168562859296799,
 0.027675312012434006,
 0.049289505928754807,
 0.040313523262739182,
 0.034223597496747971,
 0.015525858849287033,
 0.050586860626935959,
 0.052837532013654709,
 0.0068254880607128143,
 0.053075354546308517,
 0.00043041975004598498,
 0.00073085696203634143,
 0.0025506059173494577,
 6.1192367866169661e-05,
 8.2954931713175029e-05,
 -7.6862001151312143e-05,
 0.0032849351409822702,
 0.00074277044041082263,
 0.00036728777922689915,
 0.00011865171109093353,
 0.0073869116604328156,
 0.0036432864144444466,
 0.013848555274307728,
 0.0026235701516270638,
 0.0061208130791783333,
 0.074659951031208038,
 0.00023010998847894371,
 0.0010885572992265224,
 0.0019785368349403143,
 0.01424625888466835,
 0.0059181284159421921,
 0.028597814962267876,
 0.026400191709399223,
 0.017249686643481255,
 0.0014537405222654343,
 0.009897453710436821,
 0.028339488431811333,
 0.012139542028307915,
 0.029326183721423149,
 0.0035466828849166632,
 0.0016987600829452276,
 0.0012922005262225866,
 0.0018069201614707708,
 0.0010061913635581732,
 0.0028131993021816015,
 0.0034155675675719976,
 0.0027186700608581305,
 0.0012218186166137457,
 0.001976711442694068,
 0.061668798327445984,
 0.034943029284477234,
 0.0051121995784342289,
 0.0033064172603189945,
 0.00152360531501472,
 0.010900437831878662,
 0.0074116727337241173,
 0.0056010028347373009,
 0.0037734874058514833,
 0.00026480038650333881,
 0.0020501979161053896,
 0.00050929863937199116,
 0.00092792464420199394,
 0.0039188857190310955,
 0.006652116309851408,
 0.0018542630132287741,
 0.093283340334892273,
 0.10585097968578339,
 0.072786256670951843,
 -0.05875881016254425,
 0.11531548202037811,
 0.043680235743522644,
 0.19103269279003143,
 0.011735245585441589,
 0.17753557860851288,
 0.0022277086973190308,
 0.00089564156951382756,
 -0.00088545697508379817,
 0.00051531550707295537,
 -0.00046582537470385432,
 0.00078057852806523442,
 0.043550360947847366,
 0.0057346527464687824,
 0.14040374755859375,
 1.0130332708358765,
 1.3634963035583496,
 1.4262427091598511,
 6.8024158477783203,
 1.0329034328460693,
 1.8375755548477173,
 1.2911521196365356,
 1.5159057378768921,
 1.069514274597168,
 0.0086323181167244911,
 0.0044170776382088661,
 0.011881486512720585,
 0.013349429704248905,
 -0.010608657263219357,
 0.038454778492450714,
 0.00041957836947403848,
 0.0025827672798186541,
 0.0046467198990285397,
 0.14402297139167786,
 0.005705343559384346,
 0.0085844863206148148,
 0.016995416954159737,
 0.013749824836850166,
 0.0083989966660737991,
 0.020901905372738838,
 0.0010043474612757564,
 0.0015479157445952296,
 0.00099288101773709059,
 0.0012612211285158992,
 0.00069241772871464491,
 0.00056411873083561659,
 0.0014742257772013545,
 0.00098801206331700087,
 0.0014022606192156672,
 0.00087468873243778944,
 0.0025119280908256769,
 0.0074019753374159336,
 0.12028818577528,
 0.001312966225668788,
 0.003213721327483654,
 0.0043179569765925407,
 0.0021978197619318962,
 0.00043893689871765673,
 0.00039761225343681872,
 0.0042526754550635815,
 0.0062162908725440502,
 -1.9167431673849933e-05,
 1.9776414774241857e-05,
 2.5632538381614722e-05,
 2.3725833671051078e-05,
 0.019988346844911575,
 0.035915780812501907,
 0.049676347523927689,
 0.052563238888978958,
 0.024176169186830521,
 0.013807941228151321,
 0.057191777974367142,
 0.018295098096132278,
 0.00084485107799991965,
 0.00051167694618925452,
 ...}

In [263]:
xaxis_band='g'

isEXP= (diff['typ'] == 'EXP') | (diff['typ'] == 'SIMP') 
isDEV= (diff['typ'] == 'DEV')

fig,axes= plt.subplots(5,1,figsize=(5,12))
plt.subplots_adjust(hspace=0.5)
bin_minmax= dict(g_mag=(21.5,23.5),
                 delta_rhalf=(-10,10),
                 delta_e1=(-1,1),
                 delta_e2=(-1,1),
                 fracflux_sum=(-0.2,1.5)
                )
for ax,xkey in zip(axes,
                   ['g_mag','delta_rhalf','fracflux_sum',
                    'anymask_sum','allmask_sum']):
    for keep,label,color,ls in zip([isEXP,isDEV],
                                ['EXP','DEV'],
                                'bg',
                                ['-','--']):
        ax.scatter(diff[xkey][keep],diff['avg_num_std'][keep],
                   edgecolor=color,s=10,c='none',lw=2.,alpha=1,
                   label=label)
        if bin_minmax.get(xkey,None):
            binned= plots.bin_up(diff[xkey][keep],diff['avg_num_std'][keep],
                                 bin_minmax=bin_minmax[xkey],nbins=30)
            for perc in ['q50']: #,'q25','q75']:
                ax.plot(binned['binc'],binned[perc],c='k',ls=ls)
            ax.set_xlim(bin_minmax[xkey])
    ax.set_xlabel(xkey)

for row in range(5):
    axes[row].set_ylim(-30,30)
leg=axes[0].legend(loc='upper left',bbox_to_anchor=(1,1))
axes[1].set_ylabel(r'Average[ $\Delta\, Flux\,/\,\sigma$ ] (Tractor - Truth)')


Out[263]:
<matplotlib.text.Text at 0x139cf7198>

In [269]:
for keep,label,color,ls in zip([isEXP,isDEV],
                            ['EXP','DEV'],
                            'bg',
                            ['-','--']):
    plt.scatter(diff['delta_rhalf'][keep],diff['avg_num_std'][keep],
               edgecolor=color,s=10,c='none',lw=2.,alpha=0.2,
               label=label)
plt.xlim(-1,1)
plt.ylim(-10,10)


Out[269]:
(-10, 10)

In [271]:
sns.distplot(fwhm_or_rhalf[isRec][isEXP]) # - dat.rhalf[isRec]


Out[271]:
<matplotlib.axes._subplots.AxesSubplot at 0x13a4f47b8>

In [247]:
sns.distplot(diff['delta_rhalf'][isEXP])
sns.distplot(diff['delta_rhalf'][isDEV])
plt.xlim(-10,10)


Out[247]:
(-10, 10)

Compare to straigth truth and measured quanities


In [181]:
d={}

for key in ['ra','dec']:
    d[key]= dat.get(key)[isRec] 
for key in 'xy':
    d[key]= dat.get(key)[isRec]
# More complicated quantities
d['avg_num_std']= np.mean([(dat.get('tractor_flux_'+band)[isRec] - dat.get(band+'flux')[isRec])*\
                             np.sqrt(dat.get('tractor_flux_ivar_'+band)[isRec])
                            for band in 'grz'],axis=0)
assert(len(d['avg_num_std']) == len(dat[isRec]))
#for band in 'grz':
#    diff['num_stddev_'+band]= (dat.get('tractor_flux_'+band)[isRec] - dat.get(band+'flux')[isRec])*\
#                               np.sqrt(dat.get('tractor_flux_ivar_'+band)[isRec])

d['rhalf']= dat.rhalf[isRec]
d['e1']= dat.e1[isRec]
d['e2']= dat.e1[isRec]
# Scale
for key in ['ra','dec']:
    d[key]*= 3600 # arcsec
# Add Hue
d['typ']= tractor_type[isRec]

for key in d.keys():
    if not key in ['avg_num_std']:
        d[key]= np.array(d[key]).byteswap().newbyteorder()

d= pd.DataFrame(d)

In [179]:
d.columns


Out[179]:
Index(['avg_num_std', 'dec', 'e1', 'e2', 'ra', 'rhalf', 'typ', 'x', 'y'], dtype='object')

In [182]:
cols=['avg_num_std','rhalf','typ','e1','e2']
sns.pairplot(d[cols], hue="typ")


Out[182]:
<seaborn.axisgrid.PairGrid at 0x13092c630>

delta Flux/err_estim vs. mag, with q25,50,75 lines


In [70]:
i= dat.obiwan_mask == 1
#truth= plots.flux2mag(dat.gflux[i]/dat.mw_transmission_g[i])
#meas= plots.flux2mag(dat.tractor_flux_g[i]/dat.tractor_mw_transmission_g[i])

fig,ax= plt.subplots(3,1,figsize=(5,8))
plt.subplots_adjust(hspace=0.2)
for iax,band in enumerate('grz'):
    x= plots.flux2mag(dat.get(band+'flux')[i]/\
                      dat.get('mw_transmission_'+band)[i])
    y= (dat.get('tractor_flux_'+band)[i] - dat.get(band+'flux')[i])*\
        np.sqrt(dat.get('tractor_flux_ivar_'+band)[i])
    ax[iax].scatter(x,y,edgecolor='b',
                    s=10,c='none',lw=1.,alpha=0.5,
                    label='%s' % band)
    binned= plots.bin_up(x,y, bin_minmax=(16,25),nbins=30)
    for perc in ['q25','q50','q75']:
        ax[iax].plot(binned['binc'],binned[perc],c='r')

for iax,band in enumerate('grz'):
    ax[iax].legend(loc='upper right')
    ax[iax].set_ylim(-5,5)
ax[1].set_ylabel(r'$\Delta\, Flux\,/\,\sigma$ (Tractor - Truth)')
ax[0].set_title('Sky causing offset?')
ax[2].set_xlabel('mag (AB)')


Out[70]:
<matplotlib.text.Text at 0x120ae4d68>

delta Flux/err_estim vs. mag for a Single band 4 panels for PSF, SIMP or REX, EXP, COMP


In [110]:
band='g'

isRec= dat.obiwan_mask == 1
# TYPES= 'psf simp exp dev comp rex'.split(' ')
tractor_type= np.char.strip(dat.tractor_type)
# TYPES= set(tractor_type)
# print(TYPES)
TYPES= 'psf simp exp dev'.upper().split(' ')
# print(types)
isType={}
for typ in TYPES:
    isType[typ]= tractor_type == typ
#isType=dict(typ= tractor_type == typ
#            for typ in set(tractor_type))
#truth= plots.flux2mag(dat.gflux[i]/dat.mw_transmission_g[i])
#meas= plots.flux2mag(dat.tractor_flux_g[i]/dat.tractor_mw_transmission_g[i])

fig,ax= plt.subplots(2,2,figsize=(10,6))
plt.subplots_adjust(hspace=0.2,wspace=0)
cnt=-1
for row in range(2):
    for col in range(2):
        cnt+=1
        typ= TYPES[cnt]
        i= (isRec) & (isType[typ])
        if len(dat[i]) > 0:
            x= plots.flux2mag(dat.get(band+'flux')[i]/\
                              dat.get('mw_transmission_'+band)[i])
            y= (dat.get('tractor_flux_'+band)[i] - dat.get(band+'flux')[i])*\
                np.sqrt(dat.get('tractor_flux_ivar_'+band)[i])
            ax[row,col].scatter(x,y,edgecolor='k',
                                s=10,c='none',lw=2.,alpha=1)
            binned= plots.bin_up(x,y, bin_minmax=(16,25),nbins=30)
            for perc in ['q25','q50','q75']:
                ax[row,col].plot(binned['binc'],binned[perc],c='r')
            
            plots.mytext(ax[row,col],0.01,0.9,typ,fontsize=15)
            ax[row,col].set_ylim(-10,10)

#leg=ax[0].legend(loc=(0,1.01),ncol=3,markerscale=3)
ax[1,0].set_ylabel(r'$\Delta\, Flux\,/\,\sigma$ (Tractor - Truth)')
for i in range(2):
    ax[1,i].set_xlabel('%s (AB)' % band)


q50 filled q25-75 of delta Flux/err_estim vs. mag for each band, 1 panel per PSF, SIMP or REX, EXP, DEV


In [112]:
plt.fill_between?

In [119]:
isRec= dat.obiwan_mask == 1
# TYPES= 'psf simp exp dev comp rex'.split(' ')
tractor_type= np.char.strip(dat.tractor_type)
# TYPES= set(tractor_type)
# print(TYPES)
TYPES= 'psf simp exp dev'.upper().split(' ')
# print(types)
isType={}
for typ in TYPES:
    isType[typ]= tractor_type == typ
#isType=dict(typ= tractor_type == typ
#            for typ in set(tractor_type))
#truth= plots.flux2mag(dat.gflux[i]/dat.mw_transmission_g[i])
#meas= plots.flux2mag(dat.tractor_flux_g[i]/dat.tractor_mw_transmission_g[i])

fig,ax= plt.subplots(2,2,figsize=(10,6))
plt.subplots_adjust(hspace=0.2,wspace=0)
cnt=-1
for row in range(2):
    for col in range(2):
        cnt+=1
        typ= TYPES[cnt]
        i= (isRec) & (isType[typ])
        if len(dat[i]) > 0:
            for band,color in zip('grz','bgr'):
                x= plots.flux2mag(dat.get(band+'flux')[i]/\
                                  dat.get('mw_transmission_'+band)[i])
                y= (dat.get('tractor_flux_'+band)[i] - dat.get(band+'flux')[i])*\
                    np.sqrt(dat.get('tractor_flux_ivar_'+band)[i])
    #             ax[row,col].scatter(x,y,edgecolor='k',
    #                                 s=10,c='none',lw=2.,alpha=1)
                binned= plots.bin_up(x,y, bin_minmax=(16,25),nbins=30)
                ax[row,col].plot(binned['binc'],binned['q50'],c=color,
                                 lw=2,label=band)
                ax[row,col].fill_between(binned['binc'],
                                         binned['q25'],binned['q75'],
                                         color=color,alpha=0.3)

            plots.mytext(ax[row,col],0.01,0.9,typ,fontsize=15)
            ax[row,col].set_ylim(-10,10)

leg=ax[0,1].legend(loc=(0.3,0.8),ncol=3,fontsize=13)
ax[1,0].set_ylabel(r'$\Delta\, Flux\,/\,\sigma$ (Tractor - Truth)')
for i in range(2):
    ax[1,i].set_xlabel('%s (AB)' % band)


delta Flux/err_estim vs. mag but ADD for all three bands, so if tractor wrong by 2 std dev in all bands would have a +6 on the plot, one panel for each PSF, SIMP or REX, EXP, COMP

have to choose band to plot mag of on the xaxis


In [126]:
xaxis_band='g'

isRec= dat.obiwan_mask == 1
# TYPES= 'psf simp exp dev comp rex'.split(' ')
tractor_type= np.char.strip(dat.tractor_type)
# TYPES= set(tractor_type)
# print(TYPES)
TYPES= 'psf simp exp dev'.upper().split(' ')
# print(types)
isType={}
for typ in TYPES:
    isType[typ]= tractor_type == typ
#isType=dict(typ= tractor_type == typ
#            for typ in set(tractor_type))
#truth= plots.flux2mag(dat.gflux[i]/dat.mw_transmission_g[i])
#meas= plots.flux2mag(dat.tractor_flux_g[i]/dat.tractor_mw_transmission_g[i])

fig,ax= plt.subplots(2,2,figsize=(10,6))
plt.subplots_adjust(hspace=0.2,wspace=0)
cnt=-1
for row in range(2):
    for col in range(2):
        cnt+=1
        typ= TYPES[cnt]
        i= (isRec) & (isType[typ])
        if len(dat[i]) > 0:
            x= plots.flux2mag(dat.get(xaxis_band+'flux')[i]/\
                                      dat.get('mw_transmission_'+xaxis_band)[i])
            y= np.mean([(dat.get('tractor_flux_'+band)[i] - dat.get(band+'flux')[i])*\
                         np.sqrt(dat.get('tractor_flux_ivar_'+band)[i])
                        for band in 'grz'],axis=0)
            assert(len(y) == len(dat[i]))
            ax[row,col].scatter(x,y,edgecolor='k',
                                s=10,c='none',lw=2.,alpha=1)
            binned= plots.bin_up(x,y, bin_minmax=(16,25),nbins=30)
            for perc in ['q25','q50','q75']:
                ax[row,col].plot(binned['binc'],binned[perc],c='r')
            
            plots.mytext(ax[row,col],0.01,0.9,typ,fontsize=15)
            ax[row,col].set_ylim(-10,10)

#leg=ax[0].legend(loc=(0,1.01),ncol=3,markerscale=3)
ax[1,0].set_ylabel(r'Average[ $\Delta\, Flux\,/\,\sigma$ ] (Tractor - Truth)')
for i in range(2):
    ax[1,i].set_xlabel('%s (AB)' % xaxis_band)


Ditto above except draw median lines for all TYPES on same panel, and different panel for xaxis_band in grz


In [132]:
isRec= dat.obiwan_mask == 1
# TYPES= 'psf simp exp dev comp rex'.split(' ')
tractor_type= np.char.strip(dat.tractor_type)
# TYPES= set(tractor_type)
# print(TYPES)
TYPES= 'psf simp exp dev'.upper().split(' ')
# print(types)
isType={}
for typ in TYPES:
    isType[typ]= tractor_type == typ
#isType=dict(typ= tractor_type == typ
#            for typ in set(tractor_type))
#truth= plots.flux2mag(dat.gflux[i]/dat.mw_transmission_g[i])
#meas= plots.flux2mag(dat.tractor_flux_g[i]/dat.tractor_mw_transmission_g[i])

fig,axes= plt.subplots(1,3,figsize=(10,5))
plt.subplots_adjust(wspace=0)
cnt=-1
for ax,xaxis_band in zip(axes,'grz'):
    for typ,color in zip(TYPES,'brgy'):
        i= (isRec) & (isType[typ])
        if len(dat[i]) > 0:
            x= plots.flux2mag(dat.get(xaxis_band+'flux')[i]/\
                                      dat.get('mw_transmission_'+xaxis_band)[i])
            y= np.mean([(dat.get('tractor_flux_'+band)[i] - dat.get(band+'flux')[i])*\
                         np.sqrt(dat.get('tractor_flux_ivar_'+band)[i])
                        for band in 'grz'],axis=0)
            assert(len(y) == len(dat[i]))
            
            binned= plots.bin_up(x,y, bin_minmax=(16,25),nbins=30)
            ax.plot(binned['binc'],binned['q50'],c=color,
                    lw=2,label=typ)
            ax.fill_between(binned['binc'],
                            binned['q25'],binned['q75'],
                            color=color,alpha=0.3)
            
    #plots.mytext(ax,0.01,0.9,typ,fontsize=15)
    ax.set_ylim(-10,10)
    ax.set_xlabel('%s (AB)' % xaxis_band)

leg=axes[-1].legend(loc='upper left',ncol=2)
axes[0].set_ylabel(r'Average[ $\Delta\, Flux\,/\,\sigma$ ] (Tractor - Truth)')
for i in [1,2]:
    axes[i].set_yticklabels([])



In [ ]:


In [121]:
np.mean([np.arange(10) for i in range(3)],axis=0)


Out[121]:
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])