示例#1
0
文件: mapPCG.py 项目: amaurea/flipper
 def setWeights(self):
     """
     @brief sets the weights for all maps
     """
     trace.issue("flipper.pcg", 3, "pcg: setting weights")
     self.clearMaps()
     for ts in self.datasets.values():
         tod = ts
         self.projectTODToMaps(tod)
     for mapName in self.maps.keys():
         self.weights[mapName] = numpy.array(self.maps[mapName].weight).copy()
示例#2
0
 def apply(self,ltMap):
     discDiffMap = discDifference(self.radius,ltMap,\
                                  discKern1=self.discKern1,\
                                  discKern3=self.discKern3)
     trace.issue("flipper.prewhitener",5,"Applying disc differencing with R=%f arcmin"%self.radius)
     
     discDiffMap.data[:] += self.addBackFraction*ltMap.data[:]
     if self.smoothingFWHM>0.:
         trace.issue("flipper.prewhitener",5,"Smoothing with FWHM: %f arcmin"%self.smoothingFWHM)
         discDiffMap = discDiffMap.convolveWithGaussian(self.smoothingFWHM)
     return discDiffMap
示例#3
0
 def applyFilter(self):
     """
     @brief Filter the TOD. Performs the pcg (1-C)^TN^{-1}(1-C) step.
     """
     trace.issue("flipper.pcg", 2, "Filtering %s" % self.tod.name)
     self.removeCorrelations(
     )  # don't need to repeat 1-C b/c (1-C)^T(1-C) = 1-C
     if self.params['filterNoise']:
         trace.issue("flipper.pcg", 3, "Noise Filtering")
         self.noiseFilter()
     if not (self.params['useNoiseInCorr']): self.removeCorrelations()
示例#4
0
文件: mapPCG.py 项目: amaurea/flipper
 def applyFilter(self):
     """
     @brief Filter the TOD. Performs the pcg (1-C)^TN^{-1}(1-C) step.
     """
     trace.issue("flipper.pcg", 2, "Filtering %s" % self.tod.name)
     self.removeCorrelations()  # don't need to repeat 1-C b/c (1-C)^T(1-C) = 1-C
     if self.params["filterNoise"]:
         trace.issue("flipper.pcg", 3, "Noise Filtering")
         self.noiseFilter()
     if not (self.params["useNoiseInCorr"]):
         self.removeCorrelations()
示例#5
0
 def setWeights(self):
     """
     @brief sets the weights for all maps
     """
     trace.issue("flipper.pcg", 3, "pcg: setting weights")
     self.clearMaps()
     for ts in self.datasets.values():
         tod = ts
         self.projectTODToMaps(tod)
     for mapName in self.maps.keys():
         self.weights[mapName] = numpy.array(
             self.maps[mapName].weight).copy()
示例#6
0
文件: mtm.py 项目: mattyowl/flipper
    def generatePower(self):

        #empty place-holder for final power spectrum
        p2d = fftTools.powerFromLiteMap(self.map)
        p2d.powerMap[:] = 0.

        #Best guess power
        tempMap = self.map.copy()
        tempMap2 = self.map2.copy()
        tempMap.data[:, :] *= self.mask.data[:, :]
        tempMap2.data[:, :] *= self.mask.data[:, :]
        p2dBest = fftTools.powerFromLiteMap(tempMap,
                                            tempMap2,
                                            applySlepianTaper=True)  #00 taper

        del tempMap, tempMap2

        #place-holder for total weights
        totWeight = numpy.zeros([self.map.Ny, self.map.Nx])

        num_iter = self.Niter
        if self.Niter == 0:
            num_iter = 1

        for k in range(num_iter):
            trace.issue('mtm', 2, 'Iteration ...%02d' % k)
            weights = self._getWeights(p2dBest)
            p2d.powerMap[:] = 0.
            totWeight[:] = 0.
            for i in range(self.Ntap):
                for j in range(self.Ntap):

                    tempMap = self.map.copy()
                    tempMap2 = self.map2.copy()
                    tempMap.data[:, :] *= self.tapers[:, :, i,
                                                      j] * self.mask.data[:, :]
                    tempMap2.data[:, :] *= self.tapers[:, :, i,
                                                       j] * self.mask.data[:, :]
                    p2dRunning = fftTools.powerFromLiteMap(tempMap, tempMap2)
                    p2d.powerMap[:, :] += self.eigs[
                        i, j] * weights[:, :, i,
                                        j]**2 * p2dRunning.powerMap[:, :]
                    totWeight[:, :] += self.eigs[i, j] * weights[:, :, i, j]**2
                    del tempMap
                    del tempMap2
                    del p2dRunning

            p2d.powerMap[:] /= totWeight[:]
            p2dBest.powerMap[:] = p2d.powerMap[:]  #new best guess

        return p2d
示例#7
0
文件: mtm.py 项目: mattyowl/flipper
    def generatePower(self):

        #empty place-holder for final power spectrum
        p2d = fftTools.powerFromLiteMap(self.map)
        p2d.powerMap[:] = 0.

        #Best guess power
        tempMap = self.map.copy()
        tempMap2 = self.map2.copy()
        tempMap.data[:,:] *= self.mask.data[:,:]
        tempMap2.data[:,:] *= self.mask.data[:,:]
        p2dBest = fftTools.powerFromLiteMap(tempMap,tempMap2,applySlepianTaper=True) #00 taper
        
        del tempMap, tempMap2
        
        #place-holder for total weights
        totWeight = numpy.zeros([self.map.Ny,self.map.Nx]) 
        
        num_iter = self.Niter
        if self.Niter == 0:
            num_iter = 1

        for k in  range(num_iter):
            trace.issue('mtm',2,'Iteration ...%02d'%k)
            weights = self._getWeights(p2dBest)
            p2d.powerMap[:] = 0.
            totWeight[:] = 0.
            for i in range(self.Ntap):
                for j in range(self.Ntap):
                                    
                    tempMap = self.map.copy()
                    tempMap2 = self.map2.copy()
                    tempMap.data[:,:] *= self.tapers[:,:,i,j]*self.mask.data[:,:]
                    tempMap2.data[:,:] *= self.tapers[:,:,i,j]*self.mask.data[:,:]
                    p2dRunning = fftTools.powerFromLiteMap(tempMap,tempMap2)
                    p2d.powerMap[:,:] += self.eigs[i,j]*weights[:,:,i,j]**2*p2dRunning.powerMap[:,:]
                    totWeight[:,:] += self.eigs[i,j]*weights[:,:,i,j]**2
                    del tempMap
                    del tempMap2
                    del p2dRunning
                    
                    
            p2d.powerMap[:] /= totWeight[:]
            p2dBest.powerMap[:] = p2d.powerMap[:] #new best guess
            

        return p2d
示例#8
0
 def addTOD(self, tod, projDict, filter=None):
     """
     @brief add a tod and associated projectors to the pcg
     @param tod the TOD.TOD to  add to the pcg
     @param projDict a dictionary with map name keys and projector values
     """
     self.ntod += 1
     self.datasets[tod.name] = tod
     for mn in projDict.keys():
         self.proj[self._createProjKey(tod.name, mn)] = projDict[mn]
     if filter != None:
         self.filters[tod.name] = filter
         self.filters[tod.name].applyFilter()
         print "filta ", tod.name, self.filters[tod.name]
     elif filter == None and self.filterClass != None:
         trace.issue("flipper.pcg", 3,
                     "Estimating noise for %s." % tod.name)
         data = tod.data.copy()
         mapsZero = True
         for mapName in self.getMapNamesForTOD(tod.name):
             if self.x[mapName].max() > 0. or self.x[mapName].min() < 0.:
                 mapsZero = False
         if not mapsZero:
             trace.issue("flipper.pcg", 3,
                         "Subtracting initial maps from %s." % tod.name)
             # Remove maps from data before estimating noise filters
             tod.data[:] *= -1
             self.loadMaps(weight=False)
             self.projectMapsToTOD(tod)
             tod.data[:] *= -1
         #now estimate filters
         self.filters[tod.name] = self.filterClass(tod, self.filterParams)
         tod.data[:] = data[:]
         del data
         self.filters[tod.name].setTOD(tod)
         self.filters[tod.name].applyFilter()
         self.filters[tod.name].setTOD(None)
     else:
         self.filters[tod.name] = None
     self.clearMaps()
     self.projectTODToMaps(tod)
     mapNames = self.getMapNamesForTOD(tod.name)
     for mapName in mapNames:
         map2numpy(self.maps[mapName], self.b[mapName], accum=True)
示例#9
0
文件: mapPCG.py 项目: amaurea/flipper
 def addTOD(self, tod, projDict, filter=None):
     """
     @brief add a tod and associated projectors to the pcg
     @param tod the TOD.TOD to  add to the pcg
     @param projDict a dictionary with map name keys and projector values
     """
     self.ntod += 1
     self.datasets[tod.name] = tod
     for mn in projDict.keys():
         self.proj[self._createProjKey(tod.name, mn)] = projDict[mn]
     if filter != None:
         self.filters[tod.name] = filter
         self.filters[tod.name].applyFilter()
         print "filta ", tod.name, self.filters[tod.name]
     elif filter == None and self.filterClass != None:
         trace.issue("flipper.pcg", 3, "Estimating noise for %s." % tod.name)
         data = tod.data.copy()
         mapsZero = True
         for mapName in self.getMapNamesForTOD(tod.name):
             if self.x[mapName].max() > 0.0 or self.x[mapName].min() < 0.0:
                 mapsZero = False
         if not mapsZero:
             trace.issue("flipper.pcg", 3, "Subtracting initial maps from %s." % tod.name)
             # Remove maps from data before estimating noise filters
             tod.data[:] *= -1
             self.loadMaps(weight=False)
             self.projectMapsToTOD(tod)
             tod.data[:] *= -1
         # now estimate filters
         self.filters[tod.name] = self.filterClass(tod, self.filterParams)
         tod.data[:] = data[:]
         del data
         self.filters[tod.name].setTOD(tod)
         self.filters[tod.name].applyFilter()
         self.filters[tod.name].setTOD(None)
     else:
         self.filters[tod.name] = None
     self.clearMaps()
     self.projectTODToMaps(tod)
     mapNames = self.getMapNamesForTOD(tod.name)
     for mapName in mapNames:
         map2numpy(self.maps[mapName], self.b[mapName], accum=True)
示例#10
0
 def testIsotropyInAnnuli(self,binningFile,cutByMask=False):
     """
     @brief tests the isotropy in each annulus specfied by the binningFIle (see _testIsotropyInAnnulus)
     @param binningFile An ascii file with columns binLower, binUpper, binCenter (nBins on the first line)
     @param  cutByMask If set to True, multiply the annulus by the k-space mask before adding pixels (see createKspaceMask).
     @return binLowerBound,binUpperBound,BinCenter,BinnedValue,BinWeight
     """
     
     binLower,binUpper,binCenter = readBinningFile(binningFile)
     nBins = binLower.size
     trace.issue("fftTools",0, "nBins= %d"%nBins)
     
     
     binMean = numpy.zeros(nBins)
     binWeight = numpy.zeros(nBins)
     
     for i in xrange(nBins):
         (binMean[i],binWeight[i]) = self._testIsotropyInAnnulus(binLower[i],binUpper[i],cutByMask=cutByMask)
         
     return binLower,binUpper,binCenter,binMean,binWeight
示例#11
0
def liteMapFromFits(file, extension=0):
    """
    @brief Reads in a FITS file and creates a liteMap object out of it.
    @param extension specify the FITS HDU where the map image is stored
    """
    ltmap = liteMap()
    hdulist = pyfits.open(file)
    header = hdulist[extension].header
    trace.issue("flipper.liteMap", 3, "Map header \n %s" % header)

    ltmap.data = hdulist[extension].data.copy()

    [ltmap.Ny, ltmap.Nx] = ltmap.data.shape

    wcs = astWCS.WCS(file, extensionName=extension)
    ltmap.wcs = wcs.copy()
    ltmap.header = ltmap.wcs.header
    ltmap.x0, ltmap.y0 = wcs.pix2wcs(0, 0)
    ltmap.x1, ltmap.y1 = wcs.pix2wcs(ltmap.Nx - 1, ltmap.Ny - 1)

    # [ltmap.x0,ltmap.x1,ltmap.y0,ltmap.y1] = wcs.getImageMinMaxWCSCoords()
    if ltmap.x0 > ltmap.x1:
        ltmap.pixScaleX = (
            numpy.abs(ltmap.x1 - ltmap.x0)
            / ltmap.Nx
            * numpy.pi
            / 180.0
            * numpy.cos(numpy.pi / 180.0 * 0.5 * (ltmap.y0 + ltmap.y1))
        )
    else:
        ltmap.pixScaleX = (
            numpy.abs((360.0 - ltmap.x1) + ltmap.x0)
            / ltmap.Nx
            * numpy.pi
            / 180.0
            * numpy.cos(numpy.pi / 180.0 * 0.5 * (ltmap.y0 + ltmap.y1))
        )

    ltmap.pixScaleY = numpy.abs(ltmap.y1 - ltmap.y0) / ltmap.Ny * numpy.pi / 180.0
    # print 0.5*(ltmap.y0+ltmap.y1)
    ltmap.area = ltmap.Nx * ltmap.Ny * ltmap.pixScaleX * ltmap.pixScaleY * (180.0 / numpy.pi) ** 2
    # print numpy.cos(numpy.pi/180.*0.5*(ltmap.y0+ltmap.y1))
    trace.issue("flipper.liteMap", 1, "Reading file %s" % file)
    trace.issue("flipper.liteMap", 1, "Map dimensions (Ny,Nx) %d %d" % (ltmap.Ny, ltmap.Nx))
    trace.issue(
        "flipper.liteMap",
        1,
        "pixel scales Y, X (degrees) %f %f" % (ltmap.pixScaleY * 180.0 / numpy.pi, ltmap.pixScaleX * 180.0 / numpy.pi),
    )

    return ltmap
示例#12
0
def liteMapFromDataAndWCS(data, wcs):
    """
    @brief Given a numpy array: data and a astLib.astWCS instance: wcs creates a liteMap
    
    """
    ltmap = liteMap()

    ltmap.data = data.copy()

    [ltmap.Ny, ltmap.Nx] = ltmap.data.shape
    ltmap.wcs = wcs.copy()
    ltmap.header = ltmap.wcs.header

    # [ltmap.x0,ltmap.x1,ltmap.y0,ltmap.y1] = wcs.getImageMinMaxWCSCoords()
    ltmap.x0, ltmap.y0 = wcs.pix2wcs(0, 0)
    ltmap.x1, ltmap.y1 = wcs.pix2wcs(ltmap.Nx - 1, ltmap.Ny - 1)

    if ltmap.x0 > ltmap.x1:
        ltmap.pixScaleX = (
            numpy.abs(ltmap.x1 - ltmap.x0)
            / ltmap.Nx
            * numpy.pi
            / 180.0
            * numpy.cos(numpy.pi / 180.0 * 0.5 * (ltmap.y0 + ltmap.y1))
        )
    else:
        ltmap.pixScaleX = (
            numpy.abs((360.0 - ltmap.x1) + ltmap.x0)
            / ltmap.Nx
            * numpy.pi
            / 180.0
            * numpy.cos(numpy.pi / 180.0 * 0.5 * (ltmap.y0 + ltmap.y1))
        )
    ltmap.pixScaleY = numpy.abs(ltmap.y1 - ltmap.y0) / ltmap.Ny * numpy.pi / 180.0

    # print 0.5*(ltmap.y0+ltmap.y1)
    ltmap.area = ltmap.Nx * ltmap.Ny * ltmap.pixScaleX * ltmap.pixScaleY * (180.0 / numpy.pi) ** 2
    # print numpy.cos(numpy.pi/180.*0.5*(ltmap.y0+ltmap.y1))
    trace.issue("flipper.liteMap", 1, "Reading file %s" % file)
    trace.issue("flipper.liteMap", 1, "Map dimensions (Ny,Nx) %d %d" % (ltmap.Ny, ltmap.Nx))
    trace.issue(
        "flipper.liteMap",
        1,
        "pixel scales Y, X (degrees) %f %f" % (ltmap.pixScaleY * 180.0 / numpy.pi, ltmap.pixScaleX * 180.0 / numpy.pi),
    )

    return ltmap
示例#13
0
文件: mapPCG.py 项目: amaurea/flipper
    def setup(self):
        """
        @brief initialize all PCG vectors and preconditioners
        Execute after you've added your maps and tods.
        """
        # Compute weight maps and
        self.setWeights()

        # If we're on a cluster, accumulate the b map
        if self.doMPI:
            trace.issue("flipper.pcg", 3, "pcg: Reducing b and weights")
            for mapName in self.maps.keys():
                mbMPI.reduceArray(self.b[mapName], self.root)
                mbMPI.reduceArray(self.weights[mapName], self.root)
                if self.root == MPI.WORLD.rank:
                    self.maps[mapName].weight[:][:] = self.weights[mapName][:][:]

        # setup and apply preconditioners
        if not self.doMPI or self.root == MPI.WORLD.rank:
            trace.issue("flipper.pcg", 3, "pcg: masking initial maps with the weight maps")
            for mapName in self.maps.keys():
                self.x[mapName][numpy.where(self.weights[mapName] == 0)] = 0.0
            self.loadMaps()
            trace.issue("flipper.pcg", 3, "pcg: setting up preconditioners.")
            for mapName in self.maps.keys():
                if self.pcParams[mapName] != None:
                    self.preconditioners[mapName] = preconditioner.preconditionerList()
                    for pcDict in self.pcParams[mapName]:
                        try:
                            self.preconditioners[mapName].append(
                                apply(eval(pcDict["func"]), [self.maps[mapName]], pcDict["keywords"])
                            )
                        except:
                            trace.issue("flipper.pcg", 0, "pcg: Invalid preconditioner specification for %s" % mapName)
                            raise

            trace.issue("flipper.pcg", 3, "pcg: Applying preconditioners to b.")
            for mapName in self.maps.keys():
                if self.preconditioners[mapName] != None:
                    self.preconditioners[mapName].applyPreconditioner(self.b[mapName])

        # setup priors
        if not self.doMPI or self.root == MPI.WORLD.rank:
            trace.issue("flipper.pcg", 3, "pcg: Creating map priors")
            for mapName in self.maps.keys():
                if self.priorParams[mapName] != None:
                    self.priors[mapName] = prior.priorList()
                    for priorDict in self.priorParams[mapName]:
                        try:
                            self.priors[mapName].append(
                                apply(eval(priorDict["class"]), [self.maps[mapName]], pcDict["keywords"])
                            )
                        except:
                            trace.issue("flipper.pcg", 0, "pcg: Invalid prior specification for %s" % mapName)
                            raise

        # get Ax  (stor in q)
        trace.issue("flipper.pcg", 3, "pcg: Applying inverse covariance to initial map")
        computeAx = False
        for mapVector in self.x.values():
            if mapVector.max() != 0.0 or mapVector.min() != 0.0:
                computeAx = True
        if computeAx:
            self.applyInverseCovariance(self.x, self.q)
        else:
            trace.issue("flipper.pcg", 3, "All initial maps are 0.: not computing M^TN^{-1}Mx_0.")

        if self.doMPI:
            mbMPI.reduceArray(self.q[mapName], self.root)

        if not self.doMPI or self.root == MPI.WORLD.rank:

            for mapName in self.maps.keys():
                if self.preconditioners[mapName] != None:  # Q M^T N^-1 M x + Q K^-1 x
                    if self.q[mapName].max() != 0 or self.q[mapName].min() != 0.0:
                        self.preconditioners[mapName].applyPreconditioner(self.q[mapName])

            for mapName in self.maps.keys():
                self.r[mapName] = self.b[mapName] - self.q[mapName]
                self.p[mapName] = self.r[mapName].copy()

        if self.doMPI:
            for mapName in self.maps.keys():
                mbMPI.broadcastArray(self.p[mapName], self.root)
示例#14
0
def addLiteMapsWithSpectralWeighting(liteMap1, liteMap2, kMask1Params=None, kMask2Params=None, signalMap=None):
    """
    @brief add two maps, weighting in Fourier space
    Maps must be the same size.
    @param kMask1Params mask params for liteMap1 (see fftTools.power2D.createKspaceMask)
    @param kMask2Params mask params for liteMap2 (see fftTools.power2D.createKspaceMask)
    @param signalMap liteMap with best estimate of signal to use when estimating noise weighting
    @return new map
    """
    # Get fourier weights
    trace.issue("liteMap", 0, "Computing Weights")
    # np1 = fftTools.noisePowerFromLiteMaps(liteMap1, liteMap2, applySlepianTaper = False)
    # np2 = fftTools.noisePowerFromLiteMaps(liteMap2, liteMap1, applySlepianTaper = False)
    data1 = copy.copy(liteMap1.data)
    data2 = copy.copy(liteMap2.data)
    if signalMap != None:
        liteMap1.data[:] = (liteMap1.data - signalMap.data)[:]
        liteMap2.data[:] = (liteMap2.data - signalMap.data)[:]
    np1 = fftTools.powerFromLiteMap(liteMap1)  # , applySlepianTaper = True)
    np2 = fftTools.powerFromLiteMap(liteMap2)  # ), applySlepianTaper = True)
    print "testing", liteMap1.data == data1
    liteMap1.data[:] = data1[:]
    liteMap2.data[:] = data2[:]

    n1 = np1.powerMap

    n2 = np2.powerMap
    #     n1[numpy.where( n1<n1.max()*.002)] = n1.max()*.001
    #     n2[numpy.where( n2<n2.max()*.002)] = n2.max()*.001

    w1 = 1 / n1
    w2 = 1 / n2

    m1 = numpy.median(w1)
    m2 = numpy.median(w2)
    w1[numpy.where(abs(w1) > 4 * m1)] = 4 * m1
    w2[numpy.where(abs(w2) > 4 * m2)] = 4 * m2

    # w1[:] = 1.
    # w2[:] = 1.
    # pylab.hist(w1.ravel())
    # pylab.savefig("hist1.png")
    # pylab.clf()
    yrange = [4, 5000]
    np1.powerMap = w1
    # np1.plot(pngFile="w1.png", log=True, zoomUptoL=8000, yrange = yrange)
    np2.powerMap = w2
    # np2.plot(pngFile="w2.png", log=True, zoomUptoL=8000, yrange = yrange)

    if kMask1Params != None:
        np1.createKspaceMask(**kMask1Params)
        w1 *= np1.kMask

    if kMask2Params != None:
        np2.createKspaceMask(**kMask2Params)
        w2 *= np2.kMask
    pylab.clf()

    invW = 1.0 / (w1 + w2)
    invW[numpy.where(numpy.isnan(invW))] = 0.0
    invW[numpy.where(numpy.isinf(invW))] = 0.0

    trace.issue("liteMap", 3, "NaNs in inverse weight: %s" % str(numpy.where(numpy.isnan(invW))))
    trace.issue("liteMap", 3, "Infs in inverse weight: %s" % str(numpy.where(numpy.isinf(invW))))

    trace.issue("liteMap", 2, "Adding Maps")
    f1 = fftTools.fftFromLiteMap(liteMap1, applySlepianTaper=False)
    f2 = fftTools.fftFromLiteMap(liteMap2, applySlepianTaper=False)
    kTot = (f1.kMap * w1 + f2.kMap * w2) * invW
    trace.issue("liteMap", 3, "NaNs in filtered transform: %s" % str(numpy.where(numpy.isnan(kTot))))
    f1.kMap = kTot
    finalMap = liteMap1.copy()
    finalMap.data[:] = 0.0
    finalMap.data = f1.mapFromFFT()
    return finalMap
示例#15
0
    def setup(self):
        """
        @brief initialize all PCG vectors and preconditioners
        Execute after you've added your maps and tods.
        """
        # Compute weight maps and
        self.setWeights()

        # If we're on a cluster, accumulate the b map
        if self.doMPI:
            trace.issue("flipper.pcg", 3, "pcg: Reducing b and weights")
            for mapName in self.maps.keys():
                mbMPI.reduceArray(self.b[mapName], self.root)
                mbMPI.reduceArray(self.weights[mapName], self.root)
                if self.root == MPI.WORLD.rank:
                    self.maps[mapName].weight[:][:] = self.weights[
                        mapName][:][:]

        # setup and apply preconditioners
        if not self.doMPI or self.root == MPI.WORLD.rank:
            trace.issue("flipper.pcg", 3,
                        "pcg: masking initial maps with the weight maps")
            for mapName in self.maps.keys():
                self.x[mapName][numpy.where(self.weights[mapName] == 0)] = 0.
            self.loadMaps()
            trace.issue("flipper.pcg", 3, "pcg: setting up preconditioners.")
            for mapName in self.maps.keys():
                if self.pcParams[mapName] != None:
                    self.preconditioners[
                        mapName] = preconditioner.preconditionerList()
                    for pcDict in self.pcParams[mapName]:
                        try:
                            self.preconditioners[mapName].append( apply(eval(pcDict['func']), \
                                  [self.maps[mapName]]  , pcDict['keywords']) )
                        except:
                            trace.issue("flipper.pcg", 0, "pcg: Invalid preconditioner specification for %s" %\
                                mapName)
                            raise

            trace.issue("flipper.pcg", 3,
                        "pcg: Applying preconditioners to b.")
            for mapName in self.maps.keys():
                if self.preconditioners[mapName] != None:
                    self.preconditioners[mapName].applyPreconditioner(
                        self.b[mapName])

        # setup priors
        if not self.doMPI or self.root == MPI.WORLD.rank:
            trace.issue("flipper.pcg", 3, "pcg: Creating map priors")
            for mapName in self.maps.keys():
                if self.priorParams[mapName] != None:
                    self.priors[mapName] = prior.priorList()
                    for priorDict in self.priorParams[mapName]:
                        try:
                            self.priors[mapName].append( apply(eval(priorDict['class']), \
                                    [self.maps[mapName]]  , pcDict['keywords']) )
                        except:
                            trace.issue("flipper.pcg", 0, "pcg: Invalid prior specification for %s" %\
                                    mapName)
                            raise

        # get Ax  (stor in q)
        trace.issue("flipper.pcg", 3,
                    "pcg: Applying inverse covariance to initial map")
        computeAx = False
        for mapVector in self.x.values():
            if mapVector.max() != 0. or mapVector.min() != 0.:
                computeAx = True
        if computeAx:
            self.applyInverseCovariance(self.x, self.q)
        else:
            trace.issue(
                "flipper.pcg", 3,
                "All initial maps are 0.: not computing M^TN^{-1}Mx_0.")

        if self.doMPI:
            mbMPI.reduceArray(self.q[mapName], self.root)

        if not self.doMPI or self.root == MPI.WORLD.rank:

            for mapName in self.maps.keys():
                if self.preconditioners[
                        mapName] != None:  # Q M^T N^-1 M x + Q K^-1 x
                    if self.q[mapName].max() != 0 or self.q[mapName].min(
                    ) != 0.:
                        self.preconditioners[mapName].applyPreconditioner(
                            self.q[mapName])

            for mapName in self.maps.keys():
                self.r[mapName] = self.b[mapName] - self.q[mapName]
                self.p[mapName] = self.r[mapName].copy()

        if self.doMPI:
            for mapName in self.maps.keys():
                mbMPI.broadcastArray(self.p[mapName], self.root)
示例#16
0
    def loadDataFromHealpixMap(self, hpm, interpolate=False, hpCoords="J2000"):
        """
        @brief copy data from a Healpix map (from healpy), return a lite map
        @param hpm healpy map
        @param interpolate use interpolation when copying 
        @param hpCoords coordinates of hpm (e.g., "J2000"(RA, Dec) or "GALACTIC")

        Assumes that liteMap is in J2000 RA Dec. The Healpix map must contain the liteMap.
        """
        inds = numpy.indices([self.Nx, self.Ny])
        x = inds[0].ravel()
        y = inds[1].ravel()
        skyLinear = numpy.array(self.pixToSky(x, y))
        ph = skyLinear[:, 0]
        th = skyLinear[:, 1]
        thOut = []
        phOut = []
        if hpCoords != "J2000":
            for i in xrange(len(th)):
                crd = astCoords.convertCoords("J2000", hpCoords, ph[i], th[i], 0.0)
                phOut.append(crd[0])
                thOut.append(crd[1])
            thOut = numpy.array(thOut)
            phOut = numpy.array(phOut)
        else:
            thOut = th
            phOut = ph
        trace.issue("flipper.liteMap", 3, "theta (min, max): %f, %f" % (th.min(), th.max()))
        trace.issue("flipper.liteMap", 3, "phi (min, max): %f, %f" % (ph.min(), ph.max()))
        trace.issue("flipper.liteMap", 3, "phiOut (min, max): (%f, %f)  " % (phOut.min(), phOut.max()))
        trace.issue("flipper.liteMap", 3, "thetaOut (min, max): (%f, %f)  " % (thOut.min(), thOut.max()))
        phOut *= numpy.pi / 180
        thOut = 90.0 - thOut  # polar angle is 0 at north pole
        thOut *= numpy.pi / 180
        trace.issue("flipper.liteMap", 3, "phiOut rad (min, max): (%f, %f)  " % (phOut.min(), phOut.max()))
        trace.issue("flipper.liteMap", 3, "thetaOut rad (min, max): (%f, %f)  " % (thOut.min(), thOut.max()))
        if interpolate:
            self.data[y, x] = healpy.get_interp_val(hpm, thOut, phOut)
        else:
            ind = healpy.ang2pix(healpy.get_nside(hpm), thOut, phOut)
            trace.issue("flipper.liteMap", 3, "healpix indices (min,max): %d, %d" % (ind.min(), ind.max()))
            self.data[:] = 0.0
            self.data[[y, x]] = hpm[ind]
示例#17
0
def fftFromLiteMap(liteMap, applySlepianTaper=False, nresForSlepian=3.0, threads=1):
    """
    Create an fft2D object from a liteMap.
    
    Parameters
    ----------
    liteMap : liteMap.liteMap 
        The map object whose fft is being taken.
    applySlepianTaper : bool, optional 
        If ``True``, apply the lowest order taper (to minimize edge-leakage).
        Default is ``False``.
    nresForSlepian : float, optional 
        If ``applySlepianTaper`` = ``True``, this specifies the resolution of 
        the taper to use. Default is 3.0.
    threads : int, optional
        Number of threads to use in pyFFTW calculations. Default is 1.
        
    Returns
    -------
    ft : fftTools.fft2D
        The fft2D object corresponding the input liteMap.
    """
    ft = fft2D()
        
    ft.Nx = liteMap.Nx
    ft.Ny = liteMap.Ny
    trace.issue("flipper.fftTools", 1, "Taking FFT of map with (Ny, Nx)= (%f, %f)" %(ft.Ny,ft.Nx))
    
    ft.pixScaleX = liteMap.pixScaleX 
    ft.pixScaleY = liteMap.pixScaleY
    
    lx =  2*numpy.pi*fftfreq(ft.Nx, d=ft.pixScaleX)
    ly =  2*numpy.pi*fftfreq(ft.Ny, d=ft.pixScaleY)
    
    ix = numpy.mod(numpy.arange(ft.Nx*ft.Ny), ft.Nx)
    iy = numpy.arange(ft.Nx*ft.Ny)/ft.Nx
    
    modLMap        = numpy.zeros([ft.Ny, ft.Nx])
    modLMap[iy,ix] = numpy.sqrt(lx[ix]**2 + ly[iy]**2)
    ft.modLMap  =  modLMap
    
    ft.lx = lx
    ft.ly = ly
    ft.ix = ix
    ft.iy = iy
    ft.thetaMap = numpy.zeros([ft.Ny, ft.Nx])
    ft.thetaMap[iy[:], ix[:]] = numpy.arctan2(ly[iy[:]], lx[ix[:]])
    ft.thetaMap *= 180./numpy.pi
    
    mp = liteMap.data.copy()
    taper = mp.copy()*0. + 1.0

    if (applySlepianTaper):
        try:
            f = open(taperDir + os.path.sep + 'taper_Ny%d_Nx%d_Nres%3.1f' %(ft.Ny, ft.Nx, nresForSlepian))
            taper = pickle.load(f)
            f.close()
        except:
            taper = slepianTaper00(ft.Nx, ft.Ny,nresForSlepian)
            f = open(taperDir + os.path.sep + 'taper_Ny%d_Nx%d_Nres%3.1f'%(ft.Ny, ft.Nx, nresForSlepian), mode="w")
            pickle.dump(taper,f)
            f.close()
    
    if have_pyFFTW: 
        ft.kMap = fft2(mp*taper, threads=threads)
    else:
        ft.kMap = fft2(mp*taper)
    del mp, modLMap, lx, ly
    return ft