def testGetPixelCountImage(bins=250, integrationTime=1):
    '''
    Do two runs of getPixelCountImage and compare the results
    to check the repeatability (i.e., test the degree of 
    effect of the random dithering in the wavelength handling.)
    
    INPUTS:
        bins - set the number of bins for the output histogram
        
    OUTPUTS:
        Displays the two images in ds9, as well as image1 divided
        by image2. Also shows the latter in a regular plot, as well
        as a histogram of the image1/image2 ratios over all pixels.
    '''
    
    obsfile = loadTestObsFile.loadTestObsFile()
    obsfile.setWvlCutoffs(4000,8000)
    
    #Get first image
    im1 = obsfile.getPixelCountImage(firstSec=0, integrationTime=30, weighted=True,
                                     fluxWeighted=False, getRawCount=False, 
                                     scaleByEffInt=False)['image']
    
    #Get supposedly identical image
    im2 = obsfile.getPixelCountImage(firstSec=0, integrationTime=30, weighted=True,
                                     fluxWeighted=False, getRawCount=False,
                                     scaleByEffInt=False)['image']
    
    utils.ds9Array(im1,frame=1)
    utils.ds9Array(im2,frame=2)
    
    divim = im1/im2
    
    utils.ds9Array(divim,frame=3)
    utils.plotArray(divim, colormap=pl.cm.hot, cbar=True, normMax=np.mean(divim)+2*np.std(divim))
    
    toHist = divim.flatten()
    toHist = toHist[np.isfinite(toHist)]
    pl.figure()
    pl.hist(toHist,bins=bins)
    pl.title('Ratio of image1/image2, wavelength range '+str(obsfile.wvlLowerLimit)
             +'-'+str(obsfile.wvlUpperLimit)+'Ang')
    pl.xlabel('Ratio')
    pl.ylabel('Number of pixels')
    
    print 'Mean image1/image2: ',np.mean(toHist)
    print 'Std. dev image1/image2: ',np.std(toHist)
    
    def display(
        self,
        normMin=None,
        normMax=None,
        expWeight=True,
        pclip=None,
        colormap=mpl.cm.hot,
        image=None,
        logScale=False,
        fileName=None,
        ds9=False,
        cbar=False,
        noAxis=False,
    ):
        """
        Display the current image. Currently just a short-cut to utils.plotArray,
        but needs updating to mark RA and Dec on the axes.
        
        NOTE: FOR NOW, PLOTTING AGAINST RA/DEC IS SWITCHED OFF, SINCE IT LOOKS LIKE THE IMAGE FLIP/ROTATION
        ASSUMED BY CALCULATERADEC.PY MAY BE WRONG. NEEDS SORTING OUT, BUT IN THE MEANTIME, JUST SHOW THE IMAGE
        THE RIGHT WAY ROUND, AND DON'T LABEL THE AXES.
        
        INPUTS:
            normMin, normMax: Minimum and maximum values for the color-scale stretch
            expWeight: if True, scale each virtual pixel by its exposure time
            pclip: Apply a percentile clip to the image at the lower [pclip] and upper [100-pclip]'th
                    percentiles (where pclip is in percent). Overrides normMin and normMax.
            colorMap: as for plotArray, can specify the matplotlib color map to use.
            image: if set to a 2D array, displays that array instead of the default image.
            logScale: if True, display the intensities on a log scale.
            fileName: if a string, save the plot to this filename. If anything else (inc. None),
                      display to screen.
            ds9: if True, send image to DS9 (in which case pretty much all the other parameters
                 are ignored).
            cbar: if True, add a colour bar (note you can end up with multiple color bars if you 
                    call this repeatedly though.)
            noAxis: if True, don't mark or label the axes.
            
        """

        showCoordsOnAxes = (
            False
        )  # For now, don't try, since it looks like image flip/rotation assumed by CalculateRaDec may be wrong.

        assert np.all(self.image[self.effIntTimes == 0] == 0)

        if expWeight:
            toDisplay = np.copy(self.image * self.expTimeWeights)
        else:
            toDisplay = np.copy(self.image)

        if ds9 is True:
            utils.ds9Array(toDisplay)
            return  # Don't need to do anything else in this case.

        if logScale is True:
            toDisplay = np.log10(toDisplay)

        if image is not None:
            toDisplay = np.copy(image)

        #####################
        # Rotate by 180deg so north is up and east is left - just a fudge for now, need to
        # sort this out properly.
        if showCoordsOnAxes is False:
            toDisplay = np.rot90(np.rot90(toDisplay))
        #####################

        if pclip:
            normMin = np.percentile(toDisplay[np.isfinite(toDisplay)], q=pclip)
            normMax = np.percentile(toDisplay[np.isfinite(toDisplay)], q=100.0 - pclip)

        # Display NaNs as zeros so it looks better
        toDisplay[np.isnan(toDisplay)] = 0

        # Find the coordinates of the centers of the virtual pixels in degrees
        # raMin = (self.gridRA[0:-1] + self.gridRA[1:])/2.0 / np.pi * 180.
        # dec = (self.gridDec[0:-1] + self.gridDec[1:])/2.0 / np.pi * 180.

        # utils.plotArray(toDisplay,cbar=True,normMin=normMin,normMax=normMax,
        #                colormap=colormap,plotFileName=fileName,
        #                showMe=(type(fileName) is not str))
        # fig = mpl.figure()
        # ax = fig.add_subplot(111)
        # ax.set_xticklabels(ax.get_xticklabels(),rotation=90)
        mpl.ticklabel_format(style="plain", useOffset=False)
        mpl.tick_params(direction="out")

        ### Use until we get image rotation/flip sorted out properly
        if showCoordsOnAxes is True:
            origin = "lower"
            extent = (180.0 / np.pi) * np.array([self.gridRA[0], self.gridRA[-1], self.gridDec[0], self.gridDec[-1]])
        else:
            origin = "lower"
            extent = None
        ###

        if noAxis is True:
            mpl.axis("off")  # Hopefully overrides any axis labeling that comes later. But haven't checked...

        mpl.imshow(toDisplay, vmin=normMin, vmax=normMax, extent=extent, origin=origin, cmap=colormap)
        # mpl.ticklabel_format(style='plain',useOffset=False)

        if showCoordsOnAxes is True:
            ax = mpl.gca()
            xtickBase = 10 ** (np.round(np.log10((self.gridRA[-1] - self.gridRA[0]) * 180.0 / np.pi / 10.0)))
            ytickBase = 10 ** (np.round(np.log10((self.gridDec[-1] - self.gridDec[0]) * 180.0 / np.pi / 10.0)))
            ax.xaxis.set_major_locator(mpl.MultipleLocator(base=xtickBase))
            ax.yaxis.set_major_locator(mpl.MultipleLocator(base=ytickBase))
            mpl.xticks(rotation=90)
            mpl.xlabel("R.A. (deg)")
            mpl.ylabel("Dec. (deg)")
        if cbar is True:
            mpl.colorbar()

        utils.showzcoord()
def divideObsFiles(fileName1='/Users/vaneyken/Data/UCSB/ARCONS/turkDataCopy/ScienceData/PAL2012/20121211/flat_20121212-134024.h5',
                   fileName2='/Users/vaneyken/Data/UCSB/ARCONS/turkDataCopy/ScienceData/PAL2012/20121211/flat_20121212-134637.h5',
                   firstSec=0, integrationTime=10., nbins=None):
    
    '''
    Divide the raw image from one obs file by another, and display and return the result.
    This works with raw counts, so the obs file need not be calibrated.
    
    INPUTS:
        fileName1, fileName2 -- names of two obs files to divide by each other, OR two ObsFile
                                objects can be passed directly.
        firstSec - time during the obs files at which to start integration of images (sec)
        integrationTime - time to integrate for to make the images (sec)
        nbins - number of bins for histogram plot (if None, makes a semi-reasonable guess)
        
    OUTPUTS:
        Displays the divided result to the screen and to ds9.
        Returs a tuple of image arrays:
            divided image, input image 1, input image 2, obsFile 1, obsFile 2
    '''

    if type(fileName1) is str:
        obsf1 = ObsFile.ObsFile(fileName1)
        fn1 = fileName1
    else:
        obsf1=fileName1       #Otherwise just assume it's an ObsFile instance.
        fn1=obsf1.fileName
        
    if type(fileName2) is str:
        obsf2 = ObsFile.ObsFile(fileName2)
        fn2 = fileName2
    else:
        obsf2=fileName2
        fn2=obsf2.fileName
    
    print 'Reading '+os.path.basename(fn1)
    pci1 = obsf1.getPixelCountImage(firstSec=firstSec,integrationTime=integrationTime,getRawCount=True)
    print 'Reading '+os.path.basename(fn2)
    pci2 = obsf2.getPixelCountImage(firstSec=firstSec,integrationTime=integrationTime,getRawCount=True)
    
    im1 = pci1['image']
    im2 = pci2['image']
    divIm = im1/im2
    
    med = np.median(divIm[~np.isnan(divIm)])
    #Approximate std. dev from median abs. dev. (more robust)
    sdev = astropy.stats.median_absolute_deviation(divIm[~np.isnan(divIm)]) *1.4826 
    badFlag = np.abs(divIm - med) > 3.0*sdev
    
    print 'Displaying'
    toDisplay = np.copy(divIm)
    toDisplay[np.isnan(toDisplay)]=0
    utils.plotArray(toDisplay, cbar=True, normMin=med-4.*sdev, normMax=med+4.*sdev, colormap=mpl.cm.hot, fignum=None)
    yy,xx = np.indices(np.shape(divIm))
    mpl.scatter(xx[badFlag], yy[badFlag], marker='o', c='r')
    utils.ds9Array(divIm)
    mpl.figure()
    if nbins is None: nbins=np.sqrt(np.sum(np.isfinite(divIm)))
    mpl.hist(divIm[np.isfinite(divIm)].flatten(),bins=nbins)
    
    print 'Median: ',med
    print 'Approx std. dev. (M.A.D * 1.4826): ',sdev
    print 'Done.'
    return divIm,im1,im2,obsf1,obsf2,badFlag