Ejemplo n.º 1
0
                crval = [0, 0]
            else:
                crval = [r0, d0]
            cdelt = np.array(json.loads(Parameters.get('Mapping','cdelt')))/60.

            minRa  = np.min(ra)
            maxRa  = np.max(ra)
            minDec = np.min(dec)
            maxDec = np.max(dec)

            if (crval[0] < minRa) | (crval[0] > maxRa) | (crval[1] < minDec) | (crval[1] > maxDec):
                print('WARNING: MAP CENTRE DOES NOT MATCH TELESCOPE POINTING CENTRE. CHECK COORDINATES')
                print('MEAN RA: {:.2f}, MEAN DEC: {:.2f}'.format(np.mean(ra), np.mean(dec)))
            

            wcs,_,_ = Mapping.DefineWCS(naxis, cdelt, crval)
            maps, hits = Mapping.MakeMaps(tod, ra, dec, wcs)
            dataout['hits']  = hits
            dataout['maps']  = maps
            dataout['naxis'] = np.array(naxis)
            dataout['cdelt'] = np.array(cdelt)
            dataout['crval'] = np.array(crval)


        sbStr = ''.join(str(e) for e in sidebands)
        hoStr = ''.join(str(e) for e in pixels)
        FileTools.WriteH5Py('{}/{}_{}_Horns{}_Sidebands{}.h5'.format(Parameters.get('Inputs', 'outputDir'), 
                                                                     Parameters.get('Inputs', 'outputname'),
                                                                     prefix,
                                                                     hoStr,
                                                                     sbStr), dataout)
Ejemplo n.º 2
0
def FitTOD(tod,
           ra,
           dec,
           obs,
           clon,
           clat,
           cpang,
           prefix='',
           destripe=False,
           mode='mode1',
           justOffsets=True,
           doPlots=True):
    # Beam solid angle aken from James' report on wiki Optics
    nubeam = np.array([26., 33., 40.])
    srbeam = np.array([2.1842e-6, 1.6771e-6, 1.4828e-6])
    pmdl = interp1d(nubeam, srbeam)  # straight interpolation

    nHorns = tod.shape[0]
    nSidebands = tod.shape[1]
    nChans = tod.shape[2]
    nSamps = tod.shape[3]

    if mode == 'mode1':
        nParams = 5
    elif mode == 'mode2':
        nParams = 6
    else:
        nParams = 0
        print('WARNING: No fitting method selected')

    # Define the pixel grid
    # Pixel coordinates on sky
    wcs, xr, yr = Mapping.DefineWCS(naxis, cdelt, crval)
    r = np.sqrt((xr)**2 + (yr)**2)

    # Pixel coordinates in image
    xpix, ypix = np.meshgrid(np.arange(xr.shape[0]),
                             np.arange(yr.shape[1]),
                             indexing='ij')
    backgroundPixels = np.sqrt((xpix - xr.shape[0] / 2.)**2 +
                               (ypix - xr.shape[1] / 2.)**2) > xr.shape[0] / 3

    # Calculate RMS from adjacent pairs
    rms = CalcRMS(tod)

    # Set up data containers
    crossings = np.zeros(nHorns)  # Crossing points
    time = np.arange(nSamps)  # Useful for interpolation

    if justOffsets:
        #P1 = np.zeros((nHorns, nParams))
        #P1e = np.zeros((nHorns,  nParams))
        #chis = np.zeros((nHorns))
        P1 = np.zeros((nHorns, nSidebands, nChans, nParams - 2))
        errors = np.zeros((nHorns, nSidebands, nChans, nParams - 2))
        Pestout = np.zeros((nHorns, nParams))
        Pstdout = np.zeros((nHorns, nParams))

    else:
        P1 = np.zeros((nHorns, nSidebands, nChans, nParams - 2))
        errors = np.zeros((nHorns, nSidebands, nChans, nParams - 2))
        Pestout = np.zeros((nHorns, nParams))
        Pstdout = np.zeros((nHorns, nParams))

    #fig = pyplot.figure(figsize=(16,16))
    for i in range(nHorns):

        # Rotate the RA/DEC to the source centre
        x, y = Pointing.Rotate(ra[i, :], dec[i, :], clon, clat, -cpang[i, :])

        r = np.sqrt((x)**2 + (y)**2)
        close = (r < 12.5 / 60.)
        if np.sum((r < 6. / 60.)) < 10:
            print('Source not observed')
            continue

        # Average the data into a single timestream
        print(tod.shape)
        if tod.shape[2] == 1:
            todTemp = tod[0, 0, 0, :]
        else:
            todTemp = np.mean(
                np.mean(tod[i, :, :], axis=0),
                axis=0)  # average all data to get location of peak in data:

        removeNaN(todTemp)

        rmsTemp = CalcRMS(todTemp)

        try:
            todBackground = RemoveBackground(todTemp,
                                             rmsTemp,
                                             close,
                                             sampleRate=50,
                                             cutoff=1.)
            todTemp -= todBackground
        except (ValueError, IndexError):
            todTemp -= np.median(todTemp)

        offsets = 0
        print(crval)
        m, hits = Mapping.MakeMapSimple(todTemp, x, y, wcs)
        resid = todTemp[:todTemp.size // 2 * 2:2] - todTemp[1:todTemp.size //
                                                            2 * 2:2]
        residmap, rh = Mapping.MakeMapSimple(resid,
                                             x[:(todTemp.size // 2) * 2:2],
                                             y[:(todTemp.size // 2) * 2:2],
                                             wcs)
        m = m / hits
        residmap = residmap / rh
        mapNoise = np.nanstd(residmap) / np.sqrt(2)

        m -= np.nanmedian(m)
        m[np.isnan(m)] = 0.

        ipix = Mapping.ang2pixWCS(wcs, x, y).astype('int')
        gd = (np.isnan(ipix) == False) & (ipix >= 0) & (ipix < m.size)
        # Get an estimate of the peak location
        x0, y0, xpix0, ypix0 = ImagePeaks(m, xr, yr, mapNoise)

        if isinstance(x0, type(None)):
            print('No peak found')
            continue

        # Just select the near data and updated peak location
        r = np.sqrt((x - x0)**2 + (y - y0)**2)
        close = (r < 12.5 / 60.)
        near = (r < 25. / 60.) & (r > 15 / 60.)
        far = (r > 30. / 60.)
        fitselect = (r < 10. / 60.) & (np.isnan(todTemp) == False)
        plotselect = (r < 45. / 60.)

        if np.sum(fitselect) < 20:
            continue

        fitdata = todTemp[fitselect]
        fitra = x[fitselect]
        fitdec = y[fitselect]

        if mode == 'mode2':
            P0 = [
                np.max(fitdata) - np.median(fitdata), 4. / 60. / 2.355,
                4. / 60. / 2.355, x0, y0,
                np.median(fitdata)
            ]

        print(P0, lnprior(P0))
        fout = leastsq(ErrorLstSq,
                       P0,
                       args=(fitra, fitdec, fitdata, 0, 0),
                       full_output=True)
        #P0 = fout[0]
        ndim, nwalkers = len(P0), 100

        #pos = np.zeros((nwalkers, ndim))
        #pos[:,0] = np.abs(P0[0])*1e-4*np.random.randn(nwalkers)
        #pos[:,1:3] = np.abs(P0[1:3])[np.newaxis,:]*1e-4*np.random.randn((nwalkers,2))
        ###pos[:,3:5] = np.abs(P0[3:5])[np.newaxis,:]+0.1*np.random.randn((nwalkers,2))
        #pos[:,5] =  np.abs(P0[5])*1e-4*np.random.randn(nwalkers)
        #pos = pos.T

        pos = [
            np.array(P0) + 1e-4 * np.random.randn(ndim)
            for iwalker in range(nwalkers)
        ]
        sampler = emcee.EnsembleSampler(nwalkers,
                                        ndim,
                                        lnprob,
                                        args=(fitra, fitdec, fitdata, rmsTemp))
        sampler.run_mcmc(pos, 1200)
        samples = sampler.chain[:, 500:sampler.chain.shape[1]:3, :].reshape(
            (-1, ndim))
        print(samples.shape)
        Pest = np.mean(samples, axis=0)
        Pstd = np.std(samples, axis=0)
        #Pest = fout[0]
        chi2 = np.sum((fitdata - Gauss2d2FWHM(Pest, fitra, fitdec, 0, 0))**2 /
                      rmsTemp**2) / (fitdata.size - len(Pest))
        print(np.std(samples, axis=0))
        if doPlots:
            pyplot.plot(fitdata, label='data')
            pyplot.plot(Gauss2d2FWHM(Pest, fitra, fitdec, 0, 0), label='fit')
            pyplot.legend(loc='upper right')
            pyplot.ylabel('T (K)')
            pyplot.xlabel('Sample')
            pyplot.text(0.05,
                        0.9,
                        r'$\chi^2$=' + '{:.2f}'.format(chi2),
                        transform=pyplot.gca().transAxes)
            pyplot.title('Horn {:d} obs {}'.format(i + 1, prefix))
            pyplot.savefig('PeakFitPlots/PeakFits_Horn{:d}_{}.png'.format(
                i + 1, prefix),
                           bbox_inches='tight')
            pyplot.clf()
            fig = corner.corner(samples)
            pyplot.title('Horn {:d} obs {}'.format(i + 1, prefix))
            pyplot.savefig('PeakFitPlots/Corner_Horn{:d}_{}.png'.format(
                i + 1, prefix),
                           bbox_inches='tight')
            pyplot.clf()
            del fig
    # pyplot.figure()
    #pyplot.plot(samples[:,0])
    #pyplot.show()
        if justOffsets:
            #P1[i,:] = Pest
            #P1e[i,:] = np.std(samples, axis=0)
            Pestout[i, :] = Pest
            Pstdout[i, :] = Pstd
            #chis[i] = chi2
            continue
        else:
            Pestout[i, :] = Pest
            Pstdout[i, :] = Pstd
        print(x0, y0)
        siga, sigb = Pest[1:3]
        x0, y0 = Pest[3:5]
        print(x0, y0)

        for j in range(nSidebands):

            for k in range(nChans):

                try:
                    todBackground = RemoveBackground(tod[i, j, k, :],
                                                     rms[i, j, k],
                                                     close,
                                                     sampleRate=50,
                                                     cutoff=0.1)
                except (IndexError, ValueError):
                    todBackground = np.median(tod[i, j, k, :])

                tod[i, j, k, :] -= todBackground
                fitdata = tod[i, j, k, fitselect]
                fitra = x[fitselect]
                fitdec = y[fitselect]

                amax = np.argmax(fitdata)

                if mode == 'mode1':
                    P0 = [
                        np.max(fitdata) - np.median(fitdata), 4. / 60. / 2.355,
                        x0, y0,
                        np.median(fitdata)
                    ]
                    fout = leastsq(ErrorLstSq,
                                   P0,
                                   args=(fitra, fitdec, fitdata, 0, 0),
                                   full_output=True)
                    fbootmean, fbootstd = Bootstrap(P0, fitdata, fitra, fitdec,
                                                    ErrorLstSq)
                    fitModel = Gauss2d
                elif mode == 'mode2':
                    P0 = [
                        np.max(fitdata) - np.median(fitdata), Pest[1], Pest[2],
                        np.median(fitdata)
                    ]
                    fout = leastsq(ErrorLstSq2FWHM,
                                   P0,
                                   args=(fitra, fitdec, fitdata, x0, y0),
                                   full_output=True)
                    fbootmean, fbootstd = Bootstrap(P0, fitdata, fitra, fitdec,
                                                    ErrorLstSq2FWHM)
                    fitModel = Gauss2d2FWHMFixed
                else:
                    print('Warning: No fitting method selected')

                if isinstance(fout[1], type(None)):
                    continue

                #fout = np.mean(samples,axis=0),
                P1[i, j, k, :] = fout[0]
                errors[i, j, k, :] = fbootstd
                #pyplot.plot(fitdata-fitModel(fout[0], fitra, fitdec, x0,y0), label='data')
                #pyplot.legend(loc='upper right')
                #pyplot.ylabel('T (K)')
                #pyplot.xlabel('Sample')
                #pyplot.text(0.05,0.9, r'$\chi^2$='+'{:.2f}'.format(chi2), transform=pyplot.gca().transAxes)
                #pyplot.title('Horn {:d} obs {}'.format(i+1, prefix))
                #pyplot.show()

            #pyplot.errorbar(np.arange(P1.shape[2]), P1[i,j,:,1]*60, yerr=errors[i,j,:,1]*60)
            #pyplot.show()

        cross = np.argmax(
            fitModel(np.median(P1[i, 0, :, :], axis=0), x, y, x0, y0))
        print(cross, nHorns)
        crossings[i] = cross
    if justOffsets:
        return P1, errors, Pestout, Pstdout, crossings  #  P1, P1e, chis
    else:
        return P1, errors, Pestout, Pstdout, crossings
Ejemplo n.º 3
0
def FitTOD(tod,
           ra,
           dec,
           clon,
           clat,
           cpang,
           prefix='',
           normalize=True,
           plotDir=None):
    """
    args:
    tod   - 
    ra    - 
    dec   - 
    clon  -
    clat  -
    cpang -

    kwargs:
    prefix      -
    destripe    -
    normalize   -
    justOffsets -
    """

    # Define the pixel grid
    # Pixel coordinates on sky
    wcs, xr, yr = Mapping.DefineWCS(naxis, cdelt, crval)
    r = np.sqrt((xr)**2 + (yr)**2)

    # Pixel coordinates in image
    xpix, ypix = np.meshgrid(np.arange(xr.shape[0]),
                             np.arange(yr.shape[1]),
                             indexing='ij')

    # Calculate RMS from adjacent pairs
    rms = CalcRMS(tod)

    # Rotate the RA/DEC to the source centre
    x, y = Pointing.Rotate(ra, dec, clon, clat, -cpang)

    r = np.sqrt((x)**2 + (y)**2)
    close = (r < 3.)  # Check if source is even with 3 degrees of field centre
    if np.sum((r < 6. / 60.)) < 10:
        print('Source not observed')
        return badval

    # Filter background or at least subtract a mean level
    try:
        todBackground = RemoveBackground(tod,
                                         rms,
                                         x,
                                         y,
                                         sampleRate=50,
                                         cutoff=1.)
        tod -= todBackground
    except (ValueError, IndexError):
        tod -= np.nanmedian(tod)

    # Create map of data centred on 0,0
    ms, hits = Mapping.MakeMapSimple(tod, x, y, wcs)
    m = ms / hits

    # Calculate the pair subtracted TOD to creat a residual map
    residTod = tod[:tod.size // 2 * 2:2] - tod[1:tod.size // 2 * 2:2]
    residmap, rh = Mapping.MakeMapSimple(residTod, x[:(tod.size // 2) * 2:2],
                                         y[:(tod.size // 2) * 2:2], wcs)
    residmap = residmap / rh
    mapNoise = np.nanstd(residmap) / np.sqrt(2)

    m -= np.nanmedian(m)
    m[np.isnan(m)] = 0.

    # Get an estimate of the peak location
    x0, y0, xpix0, ypix0 = ImagePeaks(m, xr, yr, mapNoise)

    if isinstance(x0, type(None)):
        print('No peak found')
        return badval

    # Just select the near data and updated peak location
    # Probably should add some way of not having these be hardcoded...
    r = np.sqrt((x - x0)**2 + (y - y0)**2)
    close = (r < 12.5 / 60.)
    near = (r < 25. / 60.) & (r > 15 / 60.)
    far = (r > 30. / 60.)
    fitselect = (r < 10. / 60.) & (np.isnan(tod) == False)
    plotselect = (r < 45. / 60.)

    if np.sum(fitselect) < 20:
        return badval

    fitdata = tod[fitselect]
    fitra = x[fitselect]
    fitdec = y[fitselect]

    # Initial guesses for fit
    P0 = [
        np.max(fitdata) - np.median(fitdata), 4. / 60. / 2.355,
        4. / 60. / 2.355, x0, y0,
        np.median(fitdata)
    ]

    # Run mcmc fit:
    ndim, nwalkers = len(P0), 100
    pos = [
        np.array(P0) + 1e-4 * np.random.randn(ndim)
        for iwalker in range(nwalkers)
    ]
    sampler = emcee.EnsembleSampler(nwalkers,
                                    ndim,
                                    lnprob,
                                    args=(fitra, fitdec, fitdata, rms))
    sampler.run_mcmc(pos, 1200)
    samples = sampler.chain[:, 500:sampler.chain.shape[1]:3, :].reshape(
        (-1, ndim))
    Pest = np.mean(samples, axis=0)
    Pstd = np.std(samples, axis=0)

    chi2 = np.sum((fitdata - Gauss2d2FWHM(Pest, fitra, fitdec, 0, 0))**2 /
                  rms**2) / (fitdata.size - len(Pest))
    if not isinstance(plotDir, type(None)):
        pyplot.plot(fitdata, label='data')
        pyplot.plot(Gauss2d2FWHM(Pest, fitra, fitdec, 0, 0), label='fit')
        pyplot.legend(loc='upper right')
        pyplot.ylabel('T (K)')
        pyplot.xlabel('Sample')
        pyplot.text(0.05,
                    0.9,
                    r'$\chi^2$=' + '{:.2f}'.format(chi2),
                    transform=pyplot.gca().transAxes)
        pyplot.title(' {}'.format(prefix))
        pyplot.savefig('{}/PeakFits_{}.png'.format(plotDir, prefix),
                       bbox_inches='tight')
        pyplot.clf()
        #fig = corner.corner(samples)
        #pyplot.title('{}'.format(prefix))
        #pyplot.savefig('{}/Corner_{}.png'.format(plotDir, prefix), bbox_inches='tight')
        #pyplot.clf()
        #del fig

    # Normalise by rms
    if normalize:
        ms /= Pest[0]
    # Output fits + sample of peak crossing
    cross = np.argmax(Gauss2d2FWHM(Pest, x, y, 0, 0))

    return Pest, Pstd, cross, ms, hits, Gauss2d2FWHM(
        [1., Pest[1], Pest[2], Pest[3], Pest[4], 0], xr, yr, 0, 0) * outweight
Ejemplo n.º 4
0
def FitTOD(tod, ra, dec, obs, clon, clat, prefix='', destripe=False):
    # Beam solid angle aken from James' report on wiki Optics
    nubeam = np.array([26., 33., 40.])
    srbeam = np.array([2.1842e-6, 1.6771e-6, 1.4828e-6])
    pmdl = interp1d(nubeam, srbeam) # straight interpolation

    nHorns = tod.shape[0]
    nSidebands = tod.shape[1]
    nChans = tod.shape[2]
    nSamps = tod.shape[3]
    nParams = 5 + 0# 2


    wcs, xr, yr = Mapping.DefineWCS(naxis, cdelt, crval)

    # Crossing indices
    crossings = np.zeros(nHorns)


    # Calculate RMS from adjacent pairs
    splitTOD = (tod[:,:,:,:(nSamps//2) * 2:2] - tod[:,:,:,1:(nSamps//2)*2:2])
    rms = np.std(splitTOD,axis=3)/np.sqrt(2)

    t = np.arange(nSamps)
    P1 = np.zeros((nHorns, nSidebands, nChans, nParams+1))
    errors = np.zeros((nHorns, nSidebands, nChans, nParams))

    fig = pyplot.figure(figsize=(16,16))
    # Rotate the ra/dec
    width = 4.
    pixwidth = 2./60.
    nbins = int(width/pixwidth)
    xygrid = [np.linspace(-width/2, width/2,nbins+1), np.linspace(-width/2, width/2.,nbins+1)]
    xgrid, ygrid = np.meshgrid(np.linspace(-width/2, width/2,nbins)+pixwidth/2., np.linspace(-width/2, width/2.,nbins) + pixwidth/2.)
    for i in  range( nHorns):
        x, y = Pointing.Rotate(ra[i,:], dec[i,:], clon, clat, 0)
        
        # Bin the map up, apply a filter to remove spikes, to give first guess at pixel centre.
        hmap = np.histogram2d(y,x, xygrid)[0]
        todTemp = np.median(np.median(tod[i,:,:,:],axis=0),axis=0)
        rmsTemp = np.std(todTemp[1:todTemp.size//2 *2:2] - todTemp[:todTemp.size//2 * 2:2])/np.sqrt(2)
        smap = np.histogram2d(y,x, xygrid, weights = todTemp)[0]
        xpix = (x+width/2)//pixwidth 
        ypix = (y+width/2)//pixwidth
        #pyplot.plot(xpix, ypix, 'o')
        #pyplot.figure()
        #pyplot.plot(x, y, 'o')
        #pyplot.show()

        if destripe:
            pixels = (ypix + nbins*xpix).astype(int)
            offset = 300
            gd = (pixels > 0) & (pixels < nbins*nbins-1)
            m, offsets = Mapping.Destripe(todTemp[gd], pixels[gd], obs[gd], offset, nbins*nbins)
            m = np.reshape(m, (nbins, nbins)).T 
            #m = smap/hmap
        else:
            #h, wx, wy = np.histogram2d(x,y, (xygrid[0], xygrid[1]))
            #s, wx, wy = np.histogram2d(x,y, (xygrid[0], xygrid[1]), weights=todTemp)
            #m = s/h
            offsets  =0
            m, hits = Mapping.MakeMapSimple(todTemp, x, y, wcs)
            m = m/hits

        m -= np.nanmedian(m)
        #m /= rmsTemp
        m[np.isnan(m)] = 0.

        #pyplot.plot(ra[i,:], todTemp-offsets,'.')
        #pyplot.figure()
        #pyplot.plot(dec[i,:], todTemp-offsets,'.')
        #pyplot.show()


        r = np.sqrt((xgrid)**2 + (ygrid)**2)   
        
        d1 = ImagePeaks(m, r, 4)
        # if len(coords1) > 0:
        #     ximax, yimax = coords1[0]
        # else:
        #     m = median_filter(m, size=(2,2))
        # Remove background?
        xgrid2,ygrid2 = np.meshgrid(np.linspace(-d1.shape[0]/2, d1.shape[0]/2, d1.shape[0]), np.linspace(-d1.shape[1]/2, d1.shape[1]/2, d1.shape[1]))
        background = np.sqrt((xgrid2 - 0)**2 + (ygrid2 - 0)**2) > 25
        print(d1.shape, xgrid.shape)
        d1[background] = 0
        
        ximax, yimax = np.unravel_index(np.argmax(d1), m.shape)
        print(ximax, yimax, np.max(d1))
        #pyplot.imshow(m)
        #pyplot.plot(yimax, ximax,'ow')
        #pyplot.figure()
        #pyplot.imshow(d1)
        #pyplot.plot(yimax, ximax,'ow')
        #pyplot.show()

        # +/- 180
        x[x > 180] -= 360

        #pyplot.plot(x,y)
        #pyplot.figure()
        #pyplot.plot(az[i,:], el[i,:])
        #pyplot.show()

        #xbins = np.linspace(-4, 4, 60*8+1)
        #ybins = np.linspace(-4, 4, 60*8+1)

        # Just select the near data
        y0,x0 = -xr[ximax,yimax], yr[ximax,yimax]
        
        print(x0, y0)
        
        #print(x0, y0)
        #pyplot.figure(figsize=(6,6))
        #pyplot.plot(yr.flatten(),m.flatten(),'-')
        #pyplot.axvline(y0,color='r')
        #pyplot.show()


        background = np.sqrt((x - x0)**2 + (y - y0)**2) > 30./60.
        
        

        #x0, y0 = 0, 0
        #pyplot.plot(x,tod[0,0,0,:])
        #pyplot.axvline(x0)
        #pyplot.axvline(x[np.argmax(tod[0,0,0,:])],color='r')
        #pyplot.figure()
        #pyplot.plot(tod[0,0,0,:])
        #pyplot.show()
        r = np.sqrt((x-x0)**2 + (y-y0)**2)
        close = (r < 12.5/60.)
        near  = (r < 25./60.) & (r > 15/60.)
        far   = (r > 15./60.)
        fitselect = (r < 20./60.)
        time = np.arange(tod.shape[-1])
        #pyplot.plot(time[:], tod[0,0,0,:])
        #pyplot.plot(time[fitselect], tod[0,0,0,fitselect])
        #pyplot.show()
        #extent = [-naxis[0]/2. * cdelt[0], naxis[0]/2. * cdelt[0], 
        #          -naxis[1]/2. * cdelt[1], naxis[1]/2. * cdelt[1]]

        #pyplot.figure(figsize=(6,6))
        
        #m2 = m*0
        #r2 = np.sqrt((xr-x0)**2 + (yr-y0)**2)
        
        #m2 = (r2 < 10./60.)
        #pyplot.imshow(m.T,extent=extent,origin='lower')
        #pyplot.scatter(x0,y0, marker='o',color='r')
        #pyplot.figure()
        #pyplot.imshow(m2.T,extent=extent,origin='lower')
        #pyplot.scatter(x0,y0, marker='o',color='r')
        #pyplot.show()
        

        #pyplot.plot(time[:],todTemp[:],'.')
        #pyplot.plot(time[fitselect],todTemp[fitselect],'.')
        #pyplot.show()

        plotselect = (r < 120./60.)
        for j in range(nSidebands):
            
            for k in range(nChans):
                
                rmdl = np.poly1d(np.polyfit(time[background], tod[i,j,k,background]-offsets,11))
                todBackground =RemoveBackground(tod[i,j,k,:], rms[i,j,k], close, sampleRate=50, cutoff=1.)
                
                if destripe:
                    m, offsets = Mapping.Destripe(tod[i,j,k,gd], pixels[gd], obs[gd], offset, nbins*nbins)
                    m = np.reshape(m, (nbins,nbins)).T
                else:
                    m, hits = Mapping.MakeMapSimple(tod[i,j,k,:], x, y, wcs)
                    m = m/hits


                #tod[i,j,k,:] = tod[i,j,k,:] -offsets #-(rmdl(ra[i,:])+dmdl(dec[i,:]))
                tod[i,j,k,:] -= todBackground#np.median(tod[i,j,k,:])
                fitdata = tod[i,j,k,fitselect]
                fitra = x[fitselect]
                fitdec= y[fitselect]

                amax = np.argmax(fitdata)

                P0 = [np.max(fitdata) -np.median(fitdata) ,
                      4./60./2.355,
                      4./60./2.355,
                      np.median(fitdata),
                      x0,
                      y0,
                      0.,
                      0., 0.]#,0.,0., 0., 0.]
                P0 = [np.max(fitdata) -np.median(fitdata) ,
                      4./60./2.355,
                      x0,
                      y0,
                      np.median(fitdata),
                      0., 0.]#,0.,0., 0., 0.]
                P0 = [np.max(fitdata) -np.median(fitdata) ,
                      4./60./2.355,
                      x0,
                      y0,
                      np.median(fitdata)]#,0.,0., 0., 0.]


                #P1[i,j,k,:nParams], cov_x, info, mesg, s = leastsq(Error, P0, args=(fitra, fitdec, fitdata, 0,0), full_output=True)
                #fout = fmin(ErrorFmin, P0, maxfun=3000, args=(fitra, fitdec, fitdata, 0,0), full_output=True)
                #fout = leastsq(ErrorLstSq, P0, args=(fitra, fitdec, fitdata, 0,0), full_output=True)
                                
                ndim, nwalkers = len(P0), 100
                pos = [np.array(P0) + 1e-4*np.random.randn(ndim) for iwalker in range(nwalkers)]
                sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprobNoGrad, args=(fitra, fitdec, fitdata, rms[i,j,k]))
                sampler.run_mcmc(pos, 1200)
                samples = sampler.chain[:, 500:sampler.chain.shape[1]:3, :].reshape((-1, ndim))
                
                fout = np.mean(samples,axis=0), 
                P1[i,j,k,:nParams] = fout[0]
                print(fout[0])
                print (P0)
                print(x0, y0)
                #import corner
                #pyplot.clf()
                #fig = corner.corner(samples)
                #pyplot.show()
                
                P2 = P1[i,j,k,:nParams]*1.
                P2[0] = 0.

                ntod = Gauss2dNoGrad(P1[i,j,k,:nParams], x, y, 0,0)
                nulltod = Gauss2dNoGrad(P2, x, y, 0.,0.)
                otod = tod[i,j,k,:]
                omaps, hits = Mapping.MakeMapSimple(otod, x, y, wcs)
                nmaps, hits = Mapping.MakeMapSimple(ntod, x, y, wcs)
                nulls, hits = Mapping.MakeMapSimple(nulltod, x, y, wcs)


                xgrid, ygrid = np.meshgrid(np.arange(naxis[0]), np.arange(naxis[1]))
                xgrid = (xgrid-naxis[0]/2.)
                ygrid = (ygrid-naxis[1]/2.)
                rgrid = np.sqrt(xgrid**2 + ygrid**2)
                getchi = (rgrid < 5)
                nearChi = (rgrid > 7.5) & (rgrid < 15)

                maprms = np.nanstd((nmaps[nearChi]-omaps[nearChi])/hits[nearChi])
                rmap = (omaps[getchi]-nmaps[getchi])/hits[getchi]
                mapChi = np.nansum((rmap-np.mean(rmap))**2/maprms**2)/(nParams-1.)
                mapOrig = np.nansum(((omaps[getchi]-nulls[getchi])/hits[getchi])**2/maprms**2)/(nParams-1.)

                
                origChi = np.sum((tod[i,j,k,plotselect] -  Gauss2dNoGrad(P2, x[plotselect], y[plotselect], 0.,0.))**2/rms[i,j,k]**2)/(nParams-1.)
                reducedChi = np.sum((tod[i,j,k,plotselect] -  Gauss2dNoGrad(P1[i,j,k,:nParams], x[plotselect], y[plotselect], 0.,0.))**2/rms[i,j,k]**2)/(nParams-1.)
                #print('CHI2', origChi, reducedChi, mapChi, mapOrig, reducedChi/origChi)
                P1[i,j,k,nParams] = rms[i,j,k]


                if (k >= 0):
                    #r2 = np.sqrt((x-P1[i,j,k,2])**2 + (y-P1[i,j,k,3])**2)
                    #plotselect = (r2 < 15./60.)

                    ax = fig.add_subplot(3,1,1)
                    todPlot = tod[i,j,k,plotselect]
                    todPlot -= np.median(todPlot)
                    pyplot.plot(todPlot-Gauss2dNoGrad(P1[i,j,k,:nParams], x[plotselect], y[plotselect], 0,0))
                    pyplot.title('Horn {}, Sideband {}, Avg. Channel {} \n {}'.format(i,j,k, prefix))
                    pyplot.xlabel('Sample')
                    pyplot.ylabel('Detector Units')
                    pyplot.text(0.9,0.9,r'$rms$ = '+'{:.3f}'.format(rms[i,j,k]), ha='right', transform=ax.transAxes) 
                    ax = fig.add_subplot(3,1,2)
                    pyplot.plot(todPlot)

                    P3 = P1[i,j,k,:nParams]*1.
                    P3[3] = 0
                    P3[7:8] = 0
                    p3Model = Gauss2dNoGrad(P3, x[plotselect], y[plotselect], 0,0)
                    pyplot.plot(Gauss2dNoGrad(P1[i,j,k,:nParams], x[plotselect], y[plotselect], 0,0))#p3Model - np.nanmedian(p3Model))
                    pyplot.plot(Gauss2dNoGrad(P2, x[plotselect], y[plotselect], 0,0))

                    pyplot.xlabel('Sample')
                    pyplot.ylabel('Detector Units')
                    pyplot.text(0.9,0.9,r'$\chi^2$ = '+'{:.3f}'.format(mapChi), ha='right', transform=ax.transAxes) 
                    
                    
                    extent = [-naxis[0]/2. * cdelt[0], naxis[0]/2. * cdelt[0], 
                              -naxis[1]/2. * cdelt[1], naxis[1]/2. * cdelt[1]]
                    ax = fig.add_subplot(3,3,7)
                    ax.imshow(m, aspect='auto', extent=extent)
                    ax.scatter(P1[i,j,k,2], P1[i,j,k,3], marker='o',color='r')
                    ax = fig.add_subplot(3,3,8)
                    ax.imshow(nmaps/hits, extent=extent)
                    ax.scatter(P1[i,j,k,2], P1[i,j,k,3], marker='o',color='r')

                    ax = fig.add_subplot(3,3,9)
                    ax.imshow(nmaps/hits-m, extent=extent)
                    ax.scatter(P1[i,j,k,2], P1[i,j,k,3], marker='o',color='r')

                    #pyplot.tight_layout(True)
                    #pyplot.show()
                    pyplot.savefig('TODResidPlots/TODResidual_{}_H{}_S{}_C{}.png'.format(prefix, i,j,k), bbox_inches='tight')
                    pyplot.clf()
        cross = np.argmax(Gauss2dNoGrad(np.median(P1[i,0,:,:nParams],axis=0), x, y, 0,0))
        print( cross, nHorns)
        crossings[i] = cross
    return P1, errors, crossings