Beispiel #1
0
def set_minor_ticks(ax, xloc=None, yloc=None):
    """
    By default minor ticks are not drawn in matplotlib.

    This function takes an axes instance (e.g. from axes or add_subplot) and
    adds minor ticks.  By default uses a simple algorithm to figure out where
    they should go based on the limits.  So best to call this program last
    right before saving the figure.

    Requires matplotlib
    """
    from math import log10, floor
    from matplotlib.ticker import MultipleLocator as ml

    ranges = ax.axis()
    if xloc is None:
        r=floor(log10(ranges[1]-ranges[0])-1)
        xloc = 10.0**r
    if yloc is None:
        r=floor(log10(ranges[3]-ranges[2])-1)
        yloc = 10.0**r

    ax.xaxis.set_minor_locator(ml(xloc))
    ax.yaxis.set_minor_locator(ml(yloc))
Beispiel #2
0
def set_minor_ticks(ax, xloc=None, yloc=None):
    """
    By default minor ticks are not drawn in matplotlib.

    This function takes an axes instance (e.g. from axes or add_subplot) and
    adds minor ticks.  By default uses a simple algorithm to figure out where
    they should go based on the limits.  So best to call this program last
    right before saving the figure.

    Requires matplotlib
    """
    from math import log10, floor
    from matplotlib.ticker import MultipleLocator as ml

    ranges = ax.axis()
    if xloc is None:
        r = floor(log10(ranges[1] - ranges[0]) - 1)
        xloc = 10.0**r
    if yloc is None:
        r = floor(log10(ranges[3] - ranges[2]) - 1)
        yloc = 10.0**r

    ax.xaxis.set_minor_locator(ml(xloc))
    ax.yaxis.set_minor_locator(ml(yloc))
Beispiel #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
Beispiel #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 ) )