Пример #1
0
 def Method1():
     l = np.arange(lmax + 1)
     m = l.copy()
     #----------------------------------------
     # Vij(m), for beamlm ('AlmDS')
     idxBp = self.LM2Index('AlmDS', lmax, l, -m, '2D')[0]
     # Vij^{*}(-m)
     idxBn = self.LM2Index('AlmDS', lmax, l, m, '2D')[0]
     valid = 1 - Invalid(idxBp).mask  # 01, not TrueFalse
     ''' row-l, col-m '''
     #----------------------------------------
     idxBp = Invalid(idxBp, 0).data.astype(int)
     idxBn = Invalid(idxBn, 0).data.astype(int)
     ''' row-l, col-m '''
     #----------------------------------------
     m = m[None, :]
     alm4pinv1 = (-1)**m * alm[idxBp] * valid
     alm4pinv2 = np.conj(alm[idxBn]) * valid
     alm4pinv = np.array([alm4pinv1, alm4pinv2])
     # alm4pinv.shape =(2, l(lmax+1), m(lmax+1))
     #                  => [0]:for m>=0,  [1]:for m<=0
     #----------------------------------------
     if (flat):  # healpy order
         alm4pinv = alm4pinv.T[valid.T > 0.5].T
     return alm4pinv
Пример #2
0
    def ArrayRotation(self, bound, array, **kwargs):
        '''
		bound:
			True | False

		For 1D/2D/3D array
		array[0,0,0] is the original point
		ax: axis-0 of array: array.shape[0]
		ay: axis-1 of array: array.shape[1]
		az: axis-2 of array: array.shape[2]
		'''
        from jizhipy.Array import Invalid
        import numpy as np
        shape0 = array.shape
        r = max(shape0) * 2**0.5 / 2 + 2
        for i in range(len(shape0)):
            d = int(r - shape0[i] / 2)
            if (i == 0): halfshape = (d, ) + shape0[1:]
            elif (i == 1): halfshape = (shape0[0], d, shape0[2])
            elif (i == 2): halfshape = shape0[:-1] + (d, )
            half = np.nan + np.zeros(halfshape)
            array = np.concatenate([half, array, half], i)
        shape = array.shape
        #----------------------------------------
        xyzAfter = [array * 0. for i in range(3)]
        axis = 0
        for xyz in xyzAfter:
            if (len(shape) >= 1 and axis == 0):
                for i in range(1, shape[0]):
                    xyz[i] = i
            elif (len(shape) >= 1 and axis == 1):
                for i in range(1, shape[1]):
                    xyz[:, i] = i
            elif (len(shape) >= 1 and axis == 2):
                for i in range(1, shape[2]):
                    xyz[:, :, i] = i
            axis += 1
        xyzBefore = self.xyzRotationPoint(xyzAfter, **kwargs)
        #----------------------------------------
        xyzBefore = xyzBefore.astype(int)
        n = xyzBefore[-1]
        for i in range(-2, -len(shape) - 1, -1):
            n += xyzBefore[i] * np.prod(shape[:i + 1])
        array = array.flatten(n.astype(int)).reshape(shape)
        #----------------------------------------
        mask = Invalid(array, None).mask
        n = []
        for i in range(len(shape)):
            s = range(len(shape)).remove(i)
            if (bound): tf = mask.prod(axis=s)
            else: tf = mask.sum(axis=s)
            n.append(np.arange(tf.size)[tf > 0])
        for i in range(len(n)):
            if (i == 0): array = array[n[i]]
            elif (i == 1): array = array[:, n[i]]
            elif (i == 2): array = array[:, :, n[i]]
        return array
Пример #3
0
def _DoMultiprocess_Ylm(iterable):
    import scipy.special as spsp
    from jizhipy.Array import Invalid
    import numpy as np
    m, l, phi, theta = iterable[1]
    ylm = np.zeros(m.size, np.dtype(iterable[2]))
    for i in range(m.size):
        ylmi = spsp.sph_harm(m[i], l[i], phi[i], theta[i])
        if (Invalid(ylmi).mask == True): break
        ylm[i] = ylmi.take(0)
    return ylm
Пример #4
0
def _DoMultiprocess_Ylm_special(iterable):
    import scipy.special as spsp
    from jizhipy.Array import Invalid
    import numpy as np
    m, l = iterable[1]
    theta, phi, dtypename = iterable[2]
    ylm = np.zeros((m.size, ) + phi.shape, np.dtype(dtypename))
    for i in range(m.size):
        ylmi = spsp.sph_harm(m[i], l[i], np.pi / 1.5, np.pi / 2.5)
        if (Invalid(ylmi).mask == True): continue
        ylmi = spsp.sph_harm(m[i], l[i], phi, theta)
        ylm[i] = ylmi
    return ylm
Пример #5
0
    def Smoothing(self, hpmap, fwhm, verbose=False):
        '''
		hpmap:
			np.array(), with or without np.nan/np.inf
			np.ma.MaskedArray()
		'''
        from jizhipy.Array import Invalid
        import healpy as hp
        import numpy as np
        hpmap = Invalid(hpmap, True)
        hpmap, mask = hpmap.data, hpmap.mask
        hpmap = hp.smoothing(hpmap, fwhm, verbose=verbose)
        hpmap[mask] = np.nan
        return hpmap
Пример #6
0
def Graticule(hpmapORdlat=None, dlon=None, **kwargs):
    '''
	(1) Graticule( dlat, dlon ):
			dlat, dlon in degree

	(2) Graticule( hpmap ):
			hpmap is healpix map
		Example:
			a = np.log10(jp.GSM2016(example=True))
			nside = hp.get_nside(a)
			hp.mollview(a, title='diffuse')
			b = np.zeros(12*nside**2)
			theta, phi = np.array(hp.pix2ang(nside, np.arange(12*nside**2)))*180/np.pi
			b[(89.5<theta)*(theta<90.5)] = 1
			b=jp.CoordTrans.HealpixRotation(b, ax=40)[-1]
			jp.Plt.Graticule(b, color='r', ls='--', lw=3)
			plt.show(), exit()

	(3) Graticule( border=True, **kwargs )
			plot border
	'''
    import matplotlib.pyplot as plt
    import numpy as np
    import healpy as hp
    from jizhipy.Basic import IsType
    from jizhipy.Array import Invalid
    from jizhipy.Plot import GetSize, Scf, Sca, Zoom, Axes
    fig0, ax0 = plt.gcf(), plt.gca()
    if ('border' in kwargs.keys()):
        theta_border = np.arange(0, 181) * np.pi / 180
        border = bool(kwargs['border'])
        kwargs.pop('border')
    else:
        border = False
    #----------------------------------------
    if (IsType.isnum(hpmapORdlat) and IsType.isnum(dlon)):
        kwargs['verbose'] = False
        hp.graticule(hpmapORdlat, dlon, **kwargs)
        if (border):
            ax0.projplot(theta_border,
                         theta_border * 0 - np.pi,
                         direct=True,
                         color='k',
                         ls='-',
                         lw=2)
            ax0.projplot(theta_border,
                         theta_border * 0 + 0.9999 * np.pi,
                         direct=True,
                         color='k',
                         ls='-',
                         lw=2)
        return ax0
    #----------------------------------------
    elif (hpmapORdlat is not None):
        figsize, axsize = GetSize(fig0, ax0)
        fig = plt.figure(figsize=(figsize['width'], figsize['height']))
        hpmap = hp.mollview(hpmapORdlat,
                            fig=fig.number,
                            return_projected_map=True)
        plt.close(fig)
        del fig
        hpmap = Invalid(hpmap)
        hpmap.data[hpmap.mask] = 0
        hpmap = hpmap.data
        #----------------------------------------
        drow = (1. * axsize['top'] - axsize['bottom']) / hpmap.shape[0]
        dcol = (1. * axsize['right'] - axsize['left']) / hpmap.shape[1]
        x, y = [], []
        for i in range(1, hpmap.shape[1]):
            b = hpmap[:, i]
            n = np.arange(b.size)[b > 0.5]
            if (n.size > 0):
                x.append(axsize['left'] + dcol * i)
                y.append(axsize['bottom'] + drow * n.mean())
        Scf(fig0)
        Sca(ax0)
        Zoom(axsize)
        plt.plot(x, y, **kwargs)
        plt.xlim(axsize['left'], axsize['right'])
        plt.ylim(axsize['bottom'], axsize['top'])
        Axes.Frameoff()
        plt.sca(ax0)
        if (border):
            ax0.projplot(theta_border,
                         theta_border * 0 - np.pi,
                         direct=True,
                         color='k',
                         ls='-',
                         lw=2)
            ax0.projplot(theta_border,
                         theta_border * 0 + 0.9999 * np.pi,
                         direct=True,
                         color='k',
                         ls='-',
                         lw=2)
        return ax0
    #----------------------------------------
    elif (border):
        key = kwargs.keys()
        if ('color' not in key): kwargs['color'] = 'k'
        if ('lw' not in key and 'linewidth' not in key): kwargs['lw'] = 2
        ax0.projplot(theta_border,
                     theta_border * 0 - np.pi,
                     direct=True,
                     **kwargs)
        ax0.projplot(theta_border,
                     theta_border * 0 + 0.9999 * np.pi,
                     direct=True,
                     **kwargs)
        return ax0
Пример #7
0
    def Bins(self, array, nbins, weight=None, wmax2a=None, nsigma=None):
        '''
		nbins:
			(1) ==list/ndarray with .size==3
				** nbins, bmin, bmax = bins
				nbins: number of bins
				bmin, bmax: min and max of bins, NOT use the whole bin
			(2) ==int_number:
				** Then use weight and wmax2a
				Give the total number of the bins, in this case, x.size=bins+1, xc.size=bins

		nsigma:
			float | None
			When generate the bins, won't use the whole range of array, set nsigma, will use |array| <= nsigma*array.std()

		weight:
			** Use this only when bins==int_number
			'G?', 'K?' | None | ndarray with size=bins
			(1) ==None: each bin has the same weight => uniform bins
			(2) ==ndarray: give weights to each bins
			(3) =='G?': 
					'?' should be an value, for example, 'G1', 'G2.3', 'G5.4', 'G12', use Gaussian weight, and obtain it from np.linspace(-?, +?, bins)
			    =='K?': 
					'?' should be an value, for example, 'K1', 'K2.3', 'K5.4', 'K12', use modified Bessel functions of the second kind, and obtain it from np.linspace(-?, +?, bins)

		wmax2a:
			Use it when weight is not None
			float | None
			(1) ==float: weight.max() corresponds to which bin, the bin which value wmax2a is in
		'''
        import numpy as np
        from jizhipy.Basic import IsType
        from jizhipy.Array import Invalid, Asarray
        from jizhipy.Math import Gaussian
        #---------------------------------------------
        array = Asarray(array)
        if (nsigma is not None):
            mean, sigma = array.mean(), array.std()
            array = array[(mean - nsigma * sigma <= array) *
                          (array <= mean + nsigma * sigma)]
        amin, amax = array.min(), array.max()
        #---------------------------------------------
        if (Asarray(nbins).size == 3): nbins, bmin, bmax = nbins
        else: bmin, bmax = amin, amax
        #---------------------------------------------
        # First uniform bins
        bins = np.linspace(bmin, bmax, nbins + 1)
        bstep = bins[1] - bins[0]
        #---------------------------------------------
        # weight
        if (weight is not None):
            if (IsType.isstr(weight)):
                w, v = str(weight[0]).lower(), abs(float(weight[1:]))
                if (v == 0): v = 1
                x = np.linspace(-v, v, nbins)
                if (w == 'k'):
                    import scipy.special as spsp
                    weight = spsp.k0(abs(x))
                    weight = Invalid(weight)
                    weight.data[weight.mask] = 2 * weight.max()
                else:  # Gaussian
                    weight = Gaussian.GaussianValue1(x, 0, 0.4)
            #--------------------
            # wmax2a
            if (wmax2a is not None):
                nmax = int(round(np.where(weight == weight.max())[0].mean()))
                nb = abs(bins - wmax2a)
                nb = np.where(nb == nb.min())[0][0]
                for i in range(bins.size - 1):
                    if (bins[i] <= wmax2a < bins[i + 1]):
                        nb = i
                        break
                d = abs(nmax - nb)
                if (nmax < nb): weight = np.append(weight[-d:], weight[:-d])
                elif (nmax > nb): weight = np.append(weight[d:], weight[:d])
            #--------------------
            weight = weight[:nbins]
            if (weight.size < nbins):
                weight = np.concatenate([weight] +
                                        (nbins - weight.size) * [weight[-1:]])
            weight = weight.max() - weight + weight.min()
            weight /= weight.sum()
            weight = weight.cumsum()
            #--------------------
            c = bins[0] + (bmax - bmin) * weight
            bins[1:-1] = c[:-1]
            #--------------------
            bins = list(bins)
            n = 1
            while (n < len(bins)):
                if (bins[n] - bins[n - 1] < bstep / 20.):
                    bins = bins[:n] + bins[n + 1:]
                else:
                    n += 1
            bins = Asarray(bins)
        #---------------------------------------------
        return bins
Пример #8
0
    def LM2Index(self, which, lmax, l, m, order=None, symmetry=True):
        '''
		Usage:
			See MapMaking.py

		lmax:
			int, must be one
	
		l, m: 
			Can be one or 1D array
	
		order:
			'2D': return 2D matrix with np.nan
			None: remove np.nan and return 1D(flatten) ndarray
			'l': return 1D array ordered by l from small to large
			'm': return 1D array ordered by m from small to large
			'i': return 1D array ordered by index from small to large
	
		which == 'Alm' : 
			if (self.fgsymm) : index = (m*lmax - m*(m-1)/2 + l)
			else : 
				if (m >= 0)   : index = (m*lmax - m*(m-1)/2 + l)
				else : 
					m = -m
					index = (m-1)*self.lmax-m*(m-1)/2+l+self.offnm-1
	
		which == 'AlmDS' : 
			index = l*(l+1) + m
	
		return:
			[index, morder, lorder]
			'2D': index.shape=(l.size, m.size), lorder=l[:,None], morder=m[None,:]
			Others: 1D with index.size==lorder.size==morder.size
		'''
        import numpy as np
        from jizhipy.Array import Asarray, Invalid, Sort
        from jizhipy.Basic import Raise
        l, m = Asarray(l).flatten(), Asarray(m).flatten()
        if (l[l > lmax].size > 0):
            Raise(
                Exception, 'l=[' + str(l.min()) + ', ..., ' + str(l.max()) +
                '] > lmax=' + str(lmax))
        if (abs(m)[abs(m) > lmax].size > 0):
            Raise(
                Exception, 'm=[' + str(m.min()) + ', ..., ' + str(m.max()) +
                '] > lmax=' + str(lmax))
        #--------------------------------------------------
        #--------------------------------------------------
        if (str(which).lower() == 'alm'):
            if (symmetry):
                index = lmax * m[None, :] - m[None, :] * (m[None, :] -
                                                          1) / 2. + l[:, None]
            else:
                morder = np.append(
                    np.arange(m.size)[m >= 0],
                    np.arange(m.size)[m < 0])
                mpos, mneg = m[m >= 0], abs(m[m < 0])
                indexpos = lmax * mpos[None, :] - mpos[None, :] * (
                    mpos[None, :] - 1) / 2. + l[:, None]
                indexneg = lmax * (mneg[None, :] - 1) - mneg[None, :] * (
                    mneg[None, :] - 1) / 2. + l[:, None] + self.offnm - 1
                index = np.append(indexpos, indexneg, 1)
                indexpos = indexneg = mpos = mneg = 0  #@
                index = index[:, morder]
            #--------------------------------------------------
        elif (str(which).lower() == 'almds'):
            index = l[:, None] * (l[:, None] + 1) + m[None, :] + 0.
        #--------------------------------------------------
        #--------------------------------------------------
        for i in range(l.size):
            index[i, abs(m) > l[i]] = np.nan
        #--------------------------------------------------
        if (order == '2D'): return [index, m[None, :], l[:, None]]
        #--------------------------------------------------
        lorder = (index * 0 + 1) * l[:, None]
        morder = (index * 0 + 1) * m[None, :]
        lorder = Invalid(lorder, False).astype(int)
        morder = Invalid(morder, False).astype(int)
        index = Invalid(index, False).astype(int)
        #--------------------------------------------------
        if (order is not None):
            if (str(order).lower() == 'i'): along = '[0,:]'
            elif (str(order).lower() == 'l'): along = '[1,:]'
            elif (str(order).lower() == 'm'): along = '[2,:]'
            index = np.array([index, lorder, morder])
            index, lorder, morder = Sort(index, along)
        if (index.size == 1):
            index, lorder, morder = index[0], lorder[0], morder[0]
        return [index, morder, lorder]
Пример #9
0
def RemoveSource(inmap,
                 lb0,
                 lb1,
                 fwhm,
                 times=2,
                 same=False,
                 onebyone=True,
                 verbose=False):
    '''
	return:
		 (npix_source, inmap[npix_source])

	Remove bright source from the healpix map

	inmap:
		input healpix map, 1D

	lb0:
		[degree], the center of the sources to be removed
		l is longitude, b is latitude (theta=90-b)
		(1) 2D: l0, b0 = lb0[:,0], lb0[:,1]
		(2) .size==2: l0, b0 = lb0

	lb1:
		[degree], the center of the pixels which are used to fill the hole from sources removing
		lb1.shape == lb0.shape

	fwhm:
		[degree]
		isnum | islist
		fwhm size of the sources

	times:
		fwhm*times to smooth the filling pixels	

	same:
		(1) ==False: fill the hole of sources by the same shape regions centering at lb1
		(2) ==True: use one value at lb1 to fill the hole for each sources

	onebyone:
		(1) ==True: handle the sources one by one, the result must be correct, but slower
		(2) ==False: hand all sources together at once. The result is correct when all holes don't overlap. If they overlap, the result may be not correct
	'''
    import numpy as np
    import healpy as hp
    from jizhipy.Array import Invalid
    from jizhipy.Process import ProgressBar
    from jizhipy.Basic import IsType
    if (verbose is True): pstr = 'jizhipy.RemoveSource:'
    elif (verbose == '123'): pstr, verbose = '    ', True
    if (same): onebyone = True
    lb0, lb1 = np.array(lb0, float) * np.pi / 180, np.array(
        lb1, float) * np.pi / 180
    if (lb0.size == 2):
        lb0 = lb0.flatten()[None, :]
        lb1 = lb1.flatten()[None, :]
    if (IsType.isnum(fwhm)): fwhm = fwhm + np.zeros(len(lb0))
    fwhm = np.array(fwhm) * np.pi / 180
    same, onebyone = bool(same), bool(onebyone)
    inmap = np.array(inmap)
    nside = hp.get_nside(inmap)

    #--------------------------------------------------
    def OneByOne(lb0, lb1, fwhm, nside, same):
        l0, b0 = lb0
        l1, b1 = lb1
        # center of source
        n0 = hp.ang2pix(nside, np.pi / 2 - b0, l0)
        n1 = hp.ang2pix(nside, np.pi / 2 - b1, l1)
        # source's region
        a0 = np.zeros(12 * nside**2)
        a0[n0] = 1000
        a0 = hp.smoothing(a0, fwhm, verbose=False)
        a0 /= a0.max()
        pix = np.arange(12 * nside**2)
        pix0 = pix[a0 > 0.4]
        if (same): pix1 = n1 + 0 * pix0
        else:
            a1 = a0.copy()
            a1[n1] = 1000
            a1 = hp.smoothing(a1, fwhm, verbose=False)
            a1 = a1 / a1.max()
            pix1 = pix[a1 > 0.4][:pix0.size]
            if (pix1.size < pix0.size):
                pix1 = np.append(pix1, pix1[(pix1.size - pix0.size):][::-1])
        return np.array([pix0, pix1])

    #--------------------------------------------------
    if (onebyone):
        if (verbose): progressbar = ProgressBar(pstr, len(lb0))
        pix = []
        for i in range(len(lb0)):
            if (verbose): progressbar.Progress()
            pix.append(OneByOne(lb0[i], lb1[i], fwhm[i], nside, same))
        pix = np.concatenate(pix, 1)
    else:
        pix = OneByOne(lb0.T, lb1.T, fwhm.mean(), nside, same)
    #--------------------------------------------------
    inmap[pix[0]] = inmap[pix[1]]
    inmap = Invalid(inmap, True).data
    inmap = hp.smoothing(inmap, fwhm.mean() * times, verbose=False)
    return (pix[0], inmap[pix[0]])
Пример #10
0
def _Multiprocess_Smooth(iterable):
    '''
	nlr:
	If reduceshape==False, large times will make the left and right edge worse and worse
	(1) ==None: append first/last element
	(2) ==True: set nlr=[len(array)/100, len(array)/100]
	(3) ==[int, int]: set nlr=[int, int]
	(4) isnum (float or int): as the outside value
	(5) =='periodic': append right end to the left head, left head to right end
	(6) ==False
	(7) =='mirror': append mirror
	'''
    import numpy as np
    from jizhipy.Optimize import Interp1d
    import matplotlib.pyplot as plt
    from jizhipy.Array import Invalid
    array = iterable[1].T  # smooth along axis-0
    weight, nla, nra, sigma, nlr, case, fft = iterable[2]
    N0, N1 = array.shape
    #---------------------------------------------
    if (case == 1):  # nlr=None, append the first/last element
        aleft = np.zeros((nla, N1), array.dtype)
        if (nla != 0): aleft = aleft + array[:1]
        aright = np.zeros((nra, N1), array.dtype) + array[-1:]
    #---------------------------------------------
    elif (case in [2, 3]):  # nlr=True | (nl,nr), interp1d
        nlr = np.array(nlr, int)
        nlr[nlr > int(len(array) / 2)] = int(len(array) / 2)
        nlr[nlr < 2] = 2
        aleft0 = np.array([
            array[:int(nlr[0] / 2)].mean(0),
            array[int(nlr[0] / 2):nlr[0]].mean(0)
        ])
        xl0 = np.array([nlr[0] / 4., nlr[0] * 3 / 4.])
        aright0 = np.array([
            array[-nlr[1]:-int(nlr[1] / 2)].mean(0),
            array[-int(nlr[1] / 2):].mean(0)
        ])
        xr0 = np.array([-nlr[1] * 3 / 4., -nlr[1] / 4.]) + len(array)
        xl = np.arange(-nla, 0)
        xr = np.arange(N0, N0 + nra)
        aleft, aright = [], []
        for i in range(N1):
            if (nla == 0): aleft.append(np.zeros([0, N1], array.dtype))
            else: aleft.append(Interp1d(xl0, aleft0[:, i], xl))
            aright.append(Interp1d(xr0, aright0[:, i], xr))
        aleft, aright = np.array(aleft).T, np.array(aright).T
    #---------------------------------------------
    elif (case in [4, 6]):  # nlr=isnum | False
        aleft = nlr + np.zeros((nla, N1), array.dtype)
        aright = nlr + np.zeros((nra, N1), array.dtype)
    #---------------------------------------------
    elif (case == 5):  # nlr='periodic'
        if (nla == 0): aleft = np.zeros((nla, N1), array.dtype)
        else: aleft = array[-nla:]
        aright = array[:nra]
    elif (case == 7):  # nlr='mirror'
        if (nla == 0): aleft = np.zeros((nla, N1), array.dtype)
        else: aleft = array[:nla][::-1]
        aright = array[-nra:][::-1]
    #---------------------------------------------
    #---------------------------------------------
    if (not fft):
        array = np.concatenate([aleft, array, aright], 0)
        if (sigma is True): arrstd = array * 0
        n1, n2, n = nla, len(array) - nra, len(weight)
        arr = array * 0
        weight = weight[:, None]  # 2D
        if (case != 6): w = weight
        for i in range(n1, n2):
            a = array[i - nla:i - nla + n]
            if (case == 6):
                tf = (1 - Invalid(a[:, 0]).mask).astype(bool)
                if (tf.sum() < tf.size):
                    w = weight.copy()
                    w, a = w[tf], a[tf]
                    w /= w.sum()
                else:
                    w = weight
            arr[i] = (a * w).sum(0)
            if (sigma is True): arrstd[i] = ((a - arr[i]) * w).std(0)
        arr = arr[n1:n2]
        if (sigma is True):
            arrstd = arrstd[n1:n2]
            arr = np.concatenate([arr, arrstd], 0)
    #---------------------------------------------
    #---------------------------------------------
    else:
        from jizhipy.Math import Convolve
        if (case != 6):
            array = np.concatenate([aleft, array, aright], 0)
            n1, n2 = nla, len(array) - nra
        if (sigma is True): arrstd = array * 0
        n = weight.size - array.shape[0]
        nl, nr = int(abs(n) / 2), int(abs(n) - abs(n) / 2)
        if (n > 0): weight = weight[nl:-nr]
        elif (n < 0):
            weight = np.concatenate([np.zeros(nl), weight, np.zeros(nr)])
        for i in range(array.shape[1]):
            array[:, i] = Convolve(array[:, i], weight, 'linear')
        if (case != 6):
            array = array[n1:n2]
            if (sigma is True): arrstd = arrstd[n1:n2]
        arr = array
    #---------------------------------------------
    #---------------------------------------------
    return arr
Пример #11
0
    def Healpix2Flat(self,
                     lon=None,
                     lat=None,
                     dlon=None,
                     dlat=None,
                     Nlon=None,
                     Nlat=None,
                     hpmap=None,
                     nside=None,
                     ordering='RING'):
        '''
		npix, rehpmap = Healpix2Flat( hpmap=inhpmap )
		rehpmap == inhpmap[npix]

	(1) Healpix2Flat(lon, lat, dlon, dlat, Nlon, Nlat, hpmap)
	(2) Healpix2Flat(lon, lat, None, dlat, None, Nlat, hpmap)
	(3) Healpix2Flat(lon, lat, dlon, dlat, Nlon, Nlat, nside)
	(4) Healpix2Flat(lon, lat, None, dlat, None, Nlat, nside)
	(5) Healpix2Flat(hpmap): Nrow*Ncol = 4*12*nside**2
	(6) Healpix2Flat(nside)
	(7) Healpix2Flat( hpmap=remap, nside= ):
			give 2D flat map, return healpixmap
	return: npix | (npix, hpmap[npix])
		****** Order of maps:
			hp.mollview(): 
				left -> right (RA) : 180 -> 0 -> -180
				bottom -> top (Dec): -90 -> 0 -> 90

			plt.pcolormesh():
				left -> right (RA) : 180 -> 0 -> -180
				bottom -> top (Dec): -90 -> 0 -> 90

			np.array( hpmap[npix] ):
				col[0] -> col[N-1] (RA) : 180 -> 0 -> -180
				row[0] -> row[N-1] (Dec): -90 -> 0 -> 90

				(RA+180, Dec-90)  ...  (RA-180, Dec-90)
				(RA+180, Dec-80)  ...  (RA-180, Dec-80)
		array =	                  ... 
				(RA+180, Dec+90)  ...  (RA-180, Dec+90)
		****************************************


		lon, lat:
			in degree
			lon=RA or l, lat=Dec or b
			Center of the region

		dlon, dlat:
			in degree
			size of the region
			(1) dlon !=None, dlat !=None
			(2) dlon ==None, dlat !=None

		Nlon, Nlat:
			if (is None) : N = 2*int((12*nside**2)**0.5)
			if (is str): 
				'2'  : N = 2   * int((12*nside**2)**0.5)
				'5.3': N = 5.3 * int((12*nside**2)**0.5)

		hpmap, nside:
			One of them must be !=None

		return: npix | (npix, hpmap[npix])

		NOTE THAT maybe not all npix are valid, use 
			mask = Invalid(theta).mask
		'''
        import numpy as np
        import healpy as hp
        from jizhipy.Astro import Beam
        from jizhipy.Array import Invalid
        from jizhipy.Basic import IsType
        if (lon is None and lat is None and nside is not None
                and hpmap is not None and len(hpmap.shape) == 2):
            # case 7
            NDec, NRA = hpmap.shape
            Dec0, RA0 = -np.pi / 2, np.pi
            dDec, dRA = np.pi / NDec, -2 * np.pi / NRA
            theta, phi = hp.pix2ang(nside, np.arange(12 * nside**2))
            theta = np.pi / 2 - theta
            phi[phi > np.pi] -= 2 * np.pi
            ntheta, nphi = ((theta - Dec0) /
                            dDec).astype(int), ((phi - RA0) / dRA).astype(int)
            n = NRA * ntheta + nphi
            hpmap = hpmap.flatten()[n]
            return [n, hpmap]
        #---------------------------------------------
        #---------------------------------------------
        if (hpmap is None):
            hpmap, isnside = np.arange(12 * nside**2), True
        else:
            nside, isnside = hp.get_nside(hpmap), False
        nest = False if (str(ordering).lower() == 'ring') else True
        #---------------------------------------------
        # Flat full sky
        if (lon is None and lat is None):
            N0 = 2 * int(12**0.5 * nside)
            if (Nlon is None): Nlon = N0
            elif (IsType.isstr(Nlon)): Nlon = int(float(Nlon) * N0)
            if (Nlat is None): Nlat = N0
            elif (IsType.isstr(Nlat)): Nlat = int(float(Nlat) * N0)
            theta = np.linspace(0, np.pi, Nlat)
            phi = np.linspace(-np.pi, np.pi, Nlon)
            theta = theta[:, None] + 0 * phi[None, :]
            phi = phi[None, :] + 0 * theta
            npix = hp.ang2pix(nside, theta, phi, nest=nest)
            npix = npix[::-1, ::-1]
            if (isnside): return npix
            else: return [npix, hpmap[npix]]
        #--------------------------------------------------
        #--------------------------------------------------
        elif (lon is not None and lat is not None and dlon
              is not None):  # Healpix2Flat(lon, lat, dlon, dlat, Nlon, Nlat)
            lon, lat, dlon, dlat = np.array([lon, lat, dlon, dlat
                                             ]) * np.pi / 180  # rad
            if (Nlat is None): Nlat = Nlon
            # left -> right (RA) : 180 -> 0 -> -180
            # bottom -> top (Dec): -90 -> 0 -> 90
            lat = np.linspace(lat - dlat / 2, lat + dlat / 2, Nlat)
            lat[lat > np.pi / 2] = np.pi - lat[lat > np.pi / 2]
            lat[lat < -np.pi / 2] = -np.pi - lat[lat < -np.pi / 2]
            lon = np.linspace(lon - dlon / 2, lon + dlon / 2, Nlon)
            lon %= 2 * np.pi
            lon[lon > np.pi] -= 2 * np.pi
            if ((lon[:-1] - lon[1:]).sum() < 0): lon = lon[::-1]
            lon = lon[None, :] + 0 * lat[:, None]
            lat = lat[:, None] + 0 * lon
            npix = hp.ang2pix(nside, np.pi / 2 - lat, lon)
            if (isnside): return npix
            else: return [npix, hpmap[npix]]
        #--------------------------------------------------
        #--------------------------------------------------
        elif (lon is not None and lat is not None
              and dlon is None):  # Healpix2Flat(lon, lat, dlat, Nlat)
            thetawidth, Npix = dlat * np.pi / 180, Nlat
            theta, phi = Beam.ThetaPhiMatrix(
                thetawidth, Npix)  # rad, np.nan may in theta,phi
            #---------------------------------------------
            mask = Invalid(theta).mask
            theta[mask], phi[mask] = 0, 0
            thetar, phir = self.thetaphiRotation([theta, phi],
                                                 ax=-(90 - lat),
                                                 az=-(lon + 90))
            npix = hp.ang2pix(nside, thetar, phir, nest=nest)
            npix = npix[::-1, ::-1]
            #---------------------------------------------
            if (isnside):
                npix[mask] = -1
                return npix
            else:
                rehpmap = hpmap[npix]
                rehpmap[mask] = np.nan
                npix[mask] = -1
                return [npix, rehpmap]