Example #1
0
def test_pv_invert_many_plot(rdict):
    plt = setuplot()
    plt.figure(1)
    plt.clf()
    plt.hist(rdict['rms'],20)
    plt.xlabel(r'Order increase')
    plt.ylabel('Number')
    plt.title('test')
    plt.show()
Example #2
0
def dc4_plot_exposures(serun, overplot=True, prompt=False, typ='png', data=None):

    import astro_util
    plt = setuplot('Agg')

    plt.rcParams['figure.figsize'] = 8.5,11
    plt.clf()


    fpath = deswl.files.wlse_collated_path(serun, 'gal', ftype='rec', 
                                           region=[1,2,3,4])
    fields=['ra','dec','expname','ccd']
    if data is None:
        data=esutil.io.read(fpath, verbose=True, fields=fields, norecfile=True)

    if overplot:
        outdir=os.path.dirname(fpath)
        outdir=os.path.join(outdir, 'plots')
        if not os.path.exists(outdir):
            os.makedirs(outdir)
        outfile=os.path.basename(fpath).replace('.rec', '-pos.'+typ)
        outfile=os.path.join(outdir, outfile)
        stdout.write("Will write image: %s\n" % outfile)


    stdout.write("shifting ra\n")
    sra=astro_util.shiftra(data['ra'])

    stdout.write("Getting ranges\n")
    minra=sra.min()
    maxra=sra.max()
    midra=(maxra+minra)/2.

    mindec=data['dec'].min()
    maxdec=data['dec'].max()
    middec=(maxdec+mindec)/2.


    from mpl_toolkits.basemap import Basemap
    #map = Basemap(projection='moll', lon_0=0)
    map = Basemap(projection='cass', 
                  llcrnrlon=-33, llcrnrlat=mindec,
                  urcrnrlon=-18, urcrnrlat=-5,
                  lon_0 = midra, lat_0=middec)


    #xrange=map(minra, maxra)
    #yrange=map(mindec,maxdec)


    #i=raw_input('hit a key: ')
    #plt.xlim(xrange[0], xrange[1])
    #plt.ylim(yrange[0], yrange[1])

    #stdout.write("Writing figure: %s\n" % outfile)
    #plt.savefig(outfile, dpi=100, bbox_inches='tight',pad_inches=0.5)
    #return

    stdout.write('Getting exposure names\n')
    enames = numpy_util.unique(data['expname'],values=True)

    stdout.write('Plotting exposures\n')

    ntot=len(enames)
    i=0
    for ename in sorted(enames):
        stdout.write('%s/%s %s\n' % (i,ntot,ename))
        i += 1
        w, = numpy.where( data['expname'] == ename )
        if w.size > 0:

            x, y = map(sra[w], data['dec'][w])
            if overplot:
                plt.plot( x, y, '.',markersize=2)
            else:
                plt.clf()
                plt.plot( x, y, '.',color='tan',markersize=2)

                ax=plt.axes()
                plt.text(0.85,0.9,ename,
                           horizontalalignment='center',
                           verticalalignment='center',
                           transform=ax.transAxes,fontsize=18)


                for ccd in range(1,63):
                    w2,=numpy.where(data['ccd'][w] == ccd)
                    if w2.size > 0:
                        w2=w[w2]

                        m=x.mean()
                        my=y.mean()

                        plt.text( mx, my, str(ccd), 
                                   fontsize=14, 
                                   weight='extra bold',
                                   horizontalalignment='center', 
                                   verticalalignment='center')



            if prompt:
                x=raw_input('hit a key: ')
                if x == 'q':
                    return



    #merid=numpy.arange(0.0, 365., 5.)
    #para =numpy.arange(-90., 95., 5.)
    merid=numpy.arange(0.0, 365., 5.)
    para =numpy.arange(-90., 95., 5.)

    merid_label=numpy.ones(merid.size)
    para_label=numpy.ones(para.size)
    stdout.write("drawing meridians\n")
    map.drawmeridians(merid, labels=[0,0,0,1], labelstyle='+/-')#, yoffset=-0.05)
    stdout.write("drawing parallels\n")
    map.drawparallels(para,labels=[1,0,0,0], labelstyle='+/-')#, xoffset=0.05)

    #plt.xlabel('RA')
    #plt.ylabel('DEC')

    if overplot:
        stdout.write("Writing figure: %s\n" % outfile)
        plt.savefig(outfile, 
                      dpi=100, 
                      transparent=False,
                      bbox_inches='tight',pad_inches=0.5)
Example #3
0
def plot_shearxy_byccd(serun, region, 
                       example_wcs_byccd=None, outfile=None, typ='pdf'):
    """
    Take the input data, split by ccd, and plot each separately.  The x,y
    are converted to a ra,dec type system that preserved the layout of
    the camera.  We don't use the actual ra/dec here because we want to
    be able to combine multiple exposures on the same plot.
    """

    from numpy import arctan2, pi

    fpath=deswl.files.wlse_collated_path(serun,'gal',ftype='rec',region=region)
    data = esutil.io.read(fpath, verbose=True)
    if data.size == 0:
        stdout.write("No objects in region: %s\n" % region)
        return


    outdir=os.path.dirname(fpath)
    outdir=os.path.join(outdir, 'plots')
    if not os.path.exists(outdir):
        os.makedirs(outdir)
    outfile=os.path.basename(fpath).replace('.rec', '-shear-byccd.'+typ)
    outfile=os.path.join(outdir, outfile)
    stdout.write("Will write image: %s\n" % outfile)


    plt=setuplot('Agg')
    plt.clf()
    if example_wcs_byccd is None:
        example_wcs_byccd = get_exposure_wcs_example()

    h,rev = esutil.stat.histogram(data['ccd'], rev=True, min=1,max=62)

    allstats = []
    #for ccd in range(1,63):

    running_shear1=0.0
    running_shear2=0.0
    running_shear_weight=0.0
    for iccd in range(len(h)):
        if rev[iccd] != rev[iccd+1]:
            w = rev[ rev[iccd]:rev[iccd+1] ]

            ccd = data['ccd'][w[0]]

            stdout.write('\tccd=%s\n' % ccd)

            # no copy is made here!
            stats = stats_shearxy(data[w], nx=3, ny=3)

            ccd_wcs = example_wcs_byccd[ccd]
            xx,yy = ccd_wcs.image2sky(stats['mx'],stats['my'])

            xx -= 337.3
            yy += 15.0
            stats['mx'] = xx
            stats['my'] = yy

            allstats.append(stats)

            weights = 1.0/(stats['mshear1_err']**2 + stats['mshear2_err']**2)
            s1 = stats['mshear1']*weights
            s2 = stats['mshear2']*weights
            s1sum=s1.sum()
            s2sum=s2.sum()
            wsum = weights.sum()

            running_shear1 += s1sum
            running_shear2 += s2sum
            running_shear_weight += wsum

            thise1 = s1sum/wsum
            thise2 = s2sum/wsum
            thisangle = 0.5*arctan2(thise2, thise1)*180./pi
            stdout.write("\t\t<e1>=%s\n" % thise1 )
            stdout.write("\t\t<e2>=%s\n" % thise2 )
            stdout.write("\t\t<angle>=%s\n" % thisangle )


            #plt.plot(xx,yy,'.',markersize=1)

    #plt.show()

    stats = numpy_util.combine_arrlist(allstats)

    mshear1 = running_shear1/running_shear_weight
    mshear2 = running_shear2/running_shear_weight
    mangle = 0.5*arctan2(mshear2, mshear1)*180.0/pi
    mshear = numpy.sqrt( mshear1**2 + mshear2**2 )

    mangle_err = stats['mangle'].std()/numpy.sqrt(stats['mangle'].size)

    print "mins:",stats['mshear1'].min(), stats['mshear2'].min(), \
            stats['mshear'].min()
    print "maxs:",stats['mshear1'].max(), stats['mshear2'].max(), \
            stats['mshear'].max()
    stdout.write("overall averages: \n\tshear1: "
                 "%s\n\tshear2: %s\n\tangle: %s\n" % (mshear1, mshear2,mangle))
    stdout.write('\tangle error approximately %s\n' % mangle_err)

    # x component of the "vector" version
    u = stats['mshear']*numpy.cos(stats['mangle'])#*10000
    # y component of the "vector" version
    v = stats['mshear']*numpy.sin(stats['mangle'])#*10000

    # scale=1 means a vector of length 1 will cover essentially
    # all the plot.  I want them slightly smaller, so I'm using
    # scale=1.5
    scale=1.5
    ax=plt.axes()
    from matplotlib.ticker import MultipleLocator as ml
    ax.xaxis.set_minor_locator(ml(0.1))
    ax.yaxis.set_minor_locator(ml(0.1))
    #plt.quiver(stats['mx'], stats['my'], u, v,headwidth=0,
    #             scale=scale, pivot='middle')

    whiskers(plt, stats['mx'], stats['my'], u, v)


    xtext=336.0 - 337.3
    whiskers(plt, 336.18-337.3, -14.1+15.0, 0.05, 0.0, color='blue')
    plt.text(xtext, -14.1+15, "0.05", verticalalignment='center')


    ystart=-15.6 + 15
    ystep=-0.08
    istep = 0
    ytext=ystart+istep*ystep

    plt.text(xtext, ytext, r"$\langle \gamma_1 \rangle=%0.3f$" % mshear1,
               verticalalignment='center')
    istep+=1
    ytext=ystart+istep*ystep
    plt.text(xtext, ytext, r"$\langle \gamma_2 \rangle=%0.3f$" % mshear2,
               verticalalignment='center')
    istep+=1
    ytext=ystart+istep*ystep
    plt.text(xtext,ytext,r"$\langle \theta \rangle=%0.2f^{\circ}$" % mangle,
               verticalalignment='center')


    # plot a whisker representing the average
    istep+=1
    ytext=ystart+istep*ystep
    svec1 = mshear*numpy.cos( mangle*pi/180. )
    svec2 = mshear*numpy.sin( mangle*pi/180. )
    plt.text(xtext, ytext, r"$\langle \gamma \rangle=%0.3f$" % mshear, 
               verticalalignment='center')
    istep+=1
    ytext=ystart+istep*ystep
    whiskers(plt, 336.225-337.3, ytext, svec1, svec2, color='red')


    label = 'region%s' % region
    ax=plt.axes()
    plt.text(0.90, 0.9, label, 
               horizontalalignment='center', 
               verticalalignment='center', 
               transform=ax.transAxes, 
               fontsize=18)
    # this is so the arrows have the right angle

    plt.axis('equal')
    plt.ylim(-16.1+15.0,-13.9+15.0)

    if outfile is not None:
        stdout.write("Writing file: %s\n" % outfile)
        plt.savefig(outfile, bbox_inches='tight', pad_inches=0.2)
    else:
        plt.show()

    #print 'mean shear: ',stats['mshear']
    return example_wcs_byccd
Example #4
0
def test_invert(sip=False, invert=False, distort=True, 
                dofacrange=False, doorange=False):
    """
    Test the inversion routine in wcsutil
    """

    indir=os.path.expanduser("~/data/astrometry/image")
    plotdir=os.path.join(indir,'plots')
    if sip:
        imname=os.path.join(indir, 'newheader.fits')
        fend = '-sip'
    else:
        imname=os.path.join(indir, "BCS2304-5436Og.070914_0304.088_04.fits")
        fend = '--pv'
    
    catext=2

    sys.stdout.write("Image file: %s\n" % imname)

    hdr = pyfits.getheader(imname)

    wcs = wcsutil.WCS(hdr)

    if invert:
        if not dofacrange and not doorange:
            if sip:
                wcs.InvertSipDistortion()
            else:
                wcs.InvertPVDistortion()
        elif dofacrange:
            n = 20
            rms = numpy.zeros(n, dtype='f8')
            facs = list( range(1,n+1) )

            i=0
            for fac in facs:
                rms[i] = wcs.InvertDistortion(fac=fac,verbose=False)
            sys.stdout.write('%s\n' % facs)
            sys.stdout.write('%s\n' % rms)

            plt = setuplot()
            plt.clf()
            plt.plot(facs,rms,'.')
        elif doorange:
            fname='test-order-inverse'+fend+'.pdf'
            fname=os.path.join(plotdir,fname)
            n=6
            order_increases= list( range(n) )
            rms = numpy.zeros(n, dtype='f8')
            i=0
            for oi in order_increases:
                rms[i] = wcs.InvertDistortion(order_increase=oi,verbose=False)
                i += 1
            sys.stdout.write('order increases: %s\n' % order_increases)
            sys.stdout.write('rms: %s\n' % rms)

            plt = setuplot()
            plt.clf()
            plt.plot(order_increases, rms,'-.')
            #plt.xlabel(r'$\mathrm{order increase}$')
            #plt.ylabel('$\mathrm{rms}~[pix]$')
            #plt.rc('text',usetex=True)
            #plt.rc('font',**{'family':'sans-serif','sans-serif':['computer modern roman']})
            #plt.rc('font',**{'family':'serif','sans-serif':['Times New Roman']})

            from matplotlib.ticker import MultipleLocator as ml
            ax = plt.axes()
            ax.xaxis.set_minor_locator(ml(0.1))
            ax.yaxis.set_minor_locator(ml(0.1))

            plt.xlabel(r'Order increase')
            plt.ylabel(r'rms $[pix]$')
            ax.set_yscale('log')
            sys.stdout.write('Saving figure: %s\n' % fname)
            plt.savefig(fname)
            fname=fname.replace('.pdf','.eps')
            sys.stdout.write('Saving figure: %s\n' % fname)
            plt.savefig(fname)
            fname=fname.replace('.eps','.ps')
            sys.stdout.write('Saving figure: %s\n' % fname)
            plt.savefig(fname)

    else:
        x = numpy.array([21.34, 1000.0, 1500.17], dtype='f8')
        y = numpy.array([11.21, 1000.0, 1113.92], dtype='f8')

        #wcs.InvertDistortion(order_increase=1)
        ra,dec = wcs.image2sky(x,y)
        xp,yp = wcs.sky2image(ra,dec, find=True)
        sys.stdout.write('x,y= %s\n' % (x,y) )
        sys.stdout.write('crval= %s\n' % wcs.crval)
        sys.stdout.write('predicted ra,dec= %s\n' % (ra,dec))
        sys.stdout.write('inverted xp,yp= %s\n' % (xp,yp))
        sys.stdout.write('difference= %s\n' % (x-xp,y-yp))
        sys.stdout.write('fractional difference= %s\n' % ( (x-xp)/x,(y-yp)/y ) )