libcov.py 35.9 KB
Newer Older
Matthieu Tristram's avatar
Matthieu Tristram committed
1 2 3 4 5 6 7 8 9 10 11 12
"""
Set of routines to ...
"""
from __future__ import division

import timeit

import numpy as np
import healpy as hp
import math
from scipy import special

Matthieu Tristram's avatar
Matthieu Tristram committed
13
from .simulation import extrapolpixwin
Matthieu Tristram's avatar
Matthieu Tristram committed
14
from .xqml_utils import getstokes, progress_bar, GetBinningMatrix
Matthieu Tristram's avatar
Matthieu Tristram committed
15 16 17

import _libcov as clibcov

18 19

def compute_ds_dcb( ellbins, nside, ipok, bl, clth, Slmax, spec,
20
                    pixwin=True, verbose=False, MC=0, Sonly=False, openMP=True):
Matthieu Tristram's avatar
Matthieu Tristram committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
    """
    Compute the Pl = dS/dCl matrices.

    Parameters
    ----------
    ellbins : array of floats
        Lowers bounds of bins. Example : taking ellbins = (2, 3, 5) will
        compute the spectra for bins = (2, 3.5).
    nside : int
        Healpix map resolution
    ipok : array of ints
        Healpy pixels numbers considered
    bl : 1D array of floats
        Beam window function
    clth : 4D or 6D array of float
        Fiducial power spectra
    Slmax : int
        Maximum lmax computed for the pixel covariance pixel matrix
    spec : 1D array of string
        Spectra list
    pixwin : bool
        If True, multiplies the beam window function by the pixel
        window function. Default: True
44
    verbose : bool
Matthieu Tristram's avatar
Matthieu Tristram committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
        If True, displays timmer. Default: False
    MC : int
        If not 0, computes Pl using Monte-Carlo method from MC simulations.
        Default: False
    Sonly : bool
        If True, compute the signal matric only. Default: False


    Returns
    ----------
    Pl : ndarray of floats
        Normalize Legendre polynomials dS/dCl

    S :  2D array of floats
        Pixel signal covariance matrix S

    Example
    ----------
    >>> Pl, S = compute_ds_dcb(
Matthieu Tristram's avatar
Matthieu Tristram committed
64 65
    ... np.array([2,4,5,10]), 2, np.array([0,1,4,10,11]), np.arange(10),
    ... clth=np.arange(60).reshape(6,-1), Slmax=9,
Matthieu Tristram's avatar
Matthieu Tristram committed
66
    ... spec=["TT", "EE", "BB", "TE", "EB", "TB"],
67
    ... pixwin=True, verbose=False, MC=0, Sonly=False)
Matthieu Tristram's avatar
Matthieu Tristram committed
68
    >>> print(round(np.sum(Pl),5), round(np.sum(S),5))
Matthieu Tristram's avatar
Matthieu Tristram committed
69
    (1149.18805, 23675.10206)
Matthieu Tristram's avatar
Matthieu Tristram committed
70 71 72 73 74 75 76 77 78 79
    """
    if Slmax < ellbins[-1]-1:
        print("WARNING : Slmax < lmax")

    # ### define pixels
    rpix = np.array(hp.pix2vec(nside, ipok))
    allcosang = np.dot(np.transpose(rpix), rpix)
    allcosang[allcosang > 1] = 1.0
    allcosang[allcosang < -1] = -1.0

80
    tstart = timeit.default_timer()
Matthieu Tristram's avatar
Matthieu Tristram committed
81

82 83 84 85 86
    clth = np.asarray(clth)
    if len(clth) == 4:
        clth = np.concatenate((clth,clth[0:2]*0.))

    temp  = "TT" in spec
Matthieu Tristram's avatar
Matthieu Tristram committed
87
    polar = "EE" in spec or "BB" in spec
88
    corr  = "TE" in spec or "TB" in spec or "EB" in spec
Matthieu Tristram's avatar
Matthieu Tristram committed
89 90 91
    if Sonly:
        if MC:
            S = S_bins_MC(
92
                ellbins, nside, ipok, allcosang, bl, clth, Slmax, MC, spec,
93
                pixwin=pixwin, verbose=verbose)
Matthieu Tristram's avatar
Matthieu Tristram committed
94 95
        else:
            S = compute_S(
96
                ellbins, nside, ipok, allcosang, bl, clth, Slmax, spec,
97
                pixwin=pixwin, verbose=verbose)
Matthieu Tristram's avatar
Matthieu Tristram committed
98
        return S
99
    
Matthieu Tristram's avatar
Matthieu Tristram committed
100 101 102
    if MC:
        Pl, S = covth_bins_MC(
            ellbins, nside, ipok, allcosang, bl, clth, Slmax, MC,
103
            spec, pixwin=pixwin, verbose=verbose)
Matthieu Tristram's avatar
Matthieu Tristram committed
104
    elif openMP:
Matthieu Tristram's avatar
Matthieu Tristram committed
105
        fpixwin = extrapolpixwin(nside, Slmax, pixwin)
Matthieu Tristram's avatar
Matthieu Tristram committed
106 107
        bell = np.array([bl*fpixwin]*4)[:Slmax+1].ravel()
        stokes, spec, istokes, ispecs = getstokes(spec)
108 109
        ispec = np.zeros(6,int)
        ispec[ispecs] = 1
Matthieu Tristram's avatar
Matthieu Tristram committed
110 111 112
        nbins = (len(ellbins)-1)*len(spec)
        npix = len(ipok)*len(istokes)
        Pl = np.ndarray( nbins*npix**2)
113
        clibcov.dSdC( nside, len(istokes), ispec, ellbins, ipok, bell, Pl)
Matthieu Tristram's avatar
Matthieu Tristram committed
114
        Pl = Pl.reshape( nbins, npix, npix)
Matthieu Tristram's avatar
Matthieu Tristram committed
115
        P, Q, ell, ellval = GetBinningMatrix(ellbins, Slmax)
116
        S = SignalCovMatrix(Pl,np.array([P.dot(clth[isp,2:Slmax+1]) for isp in ispecs]).ravel())
Matthieu Tristram's avatar
Matthieu Tristram committed
117 118 119
    else:
        Pl, S = compute_PlS(
            ellbins, nside, ipok, allcosang, bl, clth, Slmax,
120
            spec=spec, pixwin=pixwin, verbose=verbose)
Matthieu Tristram's avatar
Matthieu Tristram committed
121

122 123
    if verbose:
        print( "Construct Pl (npix=%d): %.1f sec" % (len(ipok),timeit.default_timer()-tstart))
124
    
Matthieu Tristram's avatar
Matthieu Tristram committed
125 126 127
    return Pl, S


128

Matthieu Tristram's avatar
Matthieu Tristram committed
129

Matthieu Tristram's avatar
Matthieu Tristram committed
130
def SignalCovMatrix(Pl, model):
Matthieu Tristram's avatar
Matthieu Tristram committed
131 132 133 134 135 136 137 138 139
    """
    Compute correlation matrix S = sum_l Pl*Cl
    
    Parameters
    ----------
    clth : ndarray of floats
    Array containing fiducial CMB spectra (unbinned).
    """
    # Return scalar product btw Pl and the fiducial spectra.
Matthieu Tristram's avatar
Matthieu Tristram committed
140
    return np.sum(Pl * model[:, None, None], 0)
Matthieu Tristram's avatar
Matthieu Tristram committed
141 142 143 144




Matthieu Tristram's avatar
Matthieu Tristram committed
145 146
def compute_PlS(
        ellbins, nside, ipok, allcosang, bl, clth, Slmax,
147
        spec, pixwin=True, verbose=False):
Matthieu Tristram's avatar
Matthieu Tristram committed
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    """
    Computes Legendre polynomes Pl = dS/dCb and signal matrix S.

    Parameters
    ----------
    ellbins : array of floats
        Lowers bounds of bins. Example : taking ellbins = (2, 3, 5) will
        compute the spectra for bins = (2, 3.5).
    nside : int
        Healpix map resolution
    ipok : array of ints
        Healpy pixels numbers considered
    bl : 1D array of floats
        Beam window function
    clth : 4D or 6D array of float
        Fiducial power spectra
    Slmax : int
        Maximum lmax computed for the pixel covariance pixel matrix
    spec : 1D array of string
        Spectra list
    pixwin : bool
        If True, multiplies the beam window function by the pixel
        window function. Default: True
171
    verbose : bool
Matthieu Tristram's avatar
Matthieu Tristram committed
172 173 174 175 176 177 178 179 180 181 182 183
        If True, displays timmer. Default: False

    Returns
    ----------
    Pl : ndarray of floats
        Normalize Legendre polynomials dS/dCl

    S :  2D array of floats
        Pixel signal covariance matrix S

    Example
    ----------
Matthieu Tristram's avatar
Matthieu Tristram committed
184
    >>> Pl, S = compute_PlS(np.array([2,3,4,10]),4,ipok=np.array([0,1,3]),
Matthieu Tristram's avatar
Matthieu Tristram committed
185
    ... allcosang=np.linspace(0,1,15).reshape(3,-1), bl=np.arange(13),
Matthieu Tristram's avatar
Matthieu Tristram committed
186
    ... clth=np.arange(6*13).reshape(6,-1), Slmax=9,
187
    ... spec=["TT", "EE", "BB", "TE", "EB", "TB"], pixwin=True, verbose=False)
Matthieu Tristram's avatar
Matthieu Tristram committed
188
    >>> print(round(np.sum(Pl),5), round(np.sum(S),5))
Matthieu Tristram's avatar
Matthieu Tristram committed
189
    (-429.8591, -17502.8982)
Matthieu Tristram's avatar
Matthieu Tristram committed
190

Matthieu Tristram's avatar
Matthieu Tristram committed
191
    >>> Pl, S = compute_PlS(np.array([2,3,4,10]),4,ipok=np.array([0,1,3]),
Matthieu Tristram's avatar
Matthieu Tristram committed
192
    ... allcosang=np.linspace(0,1,15).reshape(3,-1), bl=np.arange(13),
Matthieu Tristram's avatar
Matthieu Tristram committed
193
    ... clth=np.arange(6*13).reshape(6,-1), Slmax=9,
194
    ... spec=["TT", "EE", "BB", "TE", "EB", "TB"], pixwin=False, verbose=False)
Matthieu Tristram's avatar
Matthieu Tristram committed
195
    >>> print(round(np.sum(Pl),5), round(np.sum(S),5))
Matthieu Tristram's avatar
Matthieu Tristram committed
196
    (-756.35517, -31333.69722)
Matthieu Tristram's avatar
Matthieu Tristram committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    """

    lmax = ellbins[-1]
    ell = np.arange(np.min(ellbins), np.max(ellbins) + 1)
    nbins = len(ellbins) - 1
    minell = np.array(ellbins[0:nbins])
    maxell = np.array(ellbins[1:nbins+1]) - 1
    ellval = (minell + maxell) * 0.5

    npi = ipok.size
    stokes, spec, istokes, ispecs = getstokes(spec)
    nspec = len(spec)
    nsto = len(stokes)
    temp = "TT" in spec
    polar = "EE" in spec or "BB" in spec
    TE = 'TE' in spec
    EB = 'EB' in spec
    TB = 'TB' in spec
    te = spec.index('TE') if TE else 0
    tb = spec.index('TB') if TB else 0
    eb = spec.index('EB') if EB else 0
    ponbins = nbins*temp
    ponpi = npi*temp
    tenbins = te*nbins
    tbnbins = tb*nbins
    ebnbins = eb*nbins

    rpix = np.array(hp.pix2vec(nside, ipok))
    ll = np.arange(Slmax+1)
Matthieu Tristram's avatar
Matthieu Tristram committed
226
    fpixwin = extrapolpixwin(nside, Slmax, pixwin)
Matthieu Tristram's avatar
Matthieu Tristram committed
227 228 229 230 231 232 233 234 235 236
    norm = (2*ll[2:]+1)/(4.*np.pi)*(fpixwin[2:]**2)*(bl[2:Slmax+1]**2)
    clthn = clth[:, 2: Slmax+1]
    masks = []
    for i in np.arange(nbins):
        masks.append((ll[2:] >= minell[i]) & (ll[2:] <= maxell[i]))
    masks = np.array(masks)

    Pl = np.zeros((nspec*nbins, nsto*npi, nsto*npi))
    S = np.zeros((nsto*npi, nsto*npi))

237
    tstart = timeit.default_timer()
Matthieu Tristram's avatar
Matthieu Tristram committed
238 239

    for i in np.arange(npi):
240
        if verbose:
241
            progress_bar(i, npi)
Matthieu Tristram's avatar
Matthieu Tristram committed
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
        for j in np.arange(i, npi):
            cos_chi = allcosang[i, j]
            if temp:
                pl = norm*pl0(cos_chi, Slmax)[2:]
                elem = np.sum((pl * clthn[0]))
                S[i, j] = elem
                S[j, i] = elem
                for b in np.arange(nbins):
                    elem = np.sum(pl[masks[b]])
                    Pl[b, i, j] = elem
                    Pl[b, j, i] = elem

            if polar:
                ii = i+ponpi
                jj = j+ponpi
                cij, sij = polrotangle(rpix[:, i], rpix[:, j])
                cji, sji = polrotangle(rpix[:, j], rpix[:, i])

                # Tegmark version
                Q22 = norm * F1l2(cos_chi, Slmax)
                # # /!\ signe - !
                R22 = -norm * F2l2(cos_chi, Slmax)

                # # Matt version
266 267 268 269
                # d2p2 = dlss(cos_chi, 2,  2, Slmax)
                # d2m2 = dlss(cos_chi, 2, -2, Slmax)
                # Q22 = norm * ( d2p2 + d2m2 )[2:]/2.
                # R22 = norm * ( d2p2 - d2m2 )[2:]/2.
Matthieu Tristram's avatar
Matthieu Tristram committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403

                if TE or TB:
                    # # Matt version
                    d20 = -dlss(cos_chi, 2,  0, Slmax)[2:]
                    P02 = norm * d20
                    # P02 = -norm * F1l0(cos_chi, Slmax)
                    elemA = 0
                    elemB = 0
                    elemC = 0
                    elemD = 0

                    if TE:
                        elemTE = np.sum(P02*clthn[3])
                        elemA += cji*elemTE
                        elemB -= sji*elemTE
                        elemC += cij*elemTE
                        elemD -= sij*elemTE

                    if TB:
                        elemTB = np.sum(P02*clthn[5])
                        elemA += sji*elemTB
                        elemB += cji*elemTB
                        elemC += sij*elemTB
                        elemD += cij*elemTB

                    S[i, jj] = elemA
                    S[i, jj+npi] = elemB
                    S[ii, j] = elemC
                    S[ii+npi, j] = elemD

                    S[jj, i] = elemA
                    S[jj+npi, i] = elemB
                    S[j, ii] = elemC
                    S[j, ii+npi] = elemD

                elem1 = np.sum((cij*cji*Q22 + sij*sji*R22)*clthn[1])
                elem2 = np.sum((-cij*sji*Q22 + sij*cji*R22)*clthn[1])
                elem3 = np.sum((sij*sji*Q22 + cij*cji*R22)*clthn[1])
                elem4 = np.sum((-sij*cji*Q22 + cij*sji*R22)*clthn[1])

                elem3 += np.sum((cij*cji*Q22 + sij*sji*R22)*clthn[2])
                elem4 -= np.sum((-cij*sji*Q22 + sij*cji*R22)*clthn[2])
                elem1 += np.sum((sij*sji*Q22 + cij*cji*R22)*clthn[2])
                elem2 -= np.sum((-sij*cji*Q22 + cij*sji*R22)*clthn[2])

                if EB:
                    elemEB = np.sum((Q22 - R22)*clthn[4])
                    elem1 += (cji*sij + sji*cij)*elemEB
                    elem2 += (-sji*sij + cji*cij)*elemEB
                    elem3 += (-sji*cij - cji*sij)*elemEB
                    elem4 += (cji*cij - sji*sij)*elemEB

                S[ii, jj] = elem1
                S[ii, jj+npi] = elem2
                S[ii+npi, jj+npi] = elem3
                S[ii+npi, jj] = elem4

                S[jj, ii] = elem1
                S[jj+npi, ii] = elem2
                S[jj+npi, ii+npi] = elem3
                S[jj, ii+npi] = elem4

                for b in np.arange(nbins):
                    elem1 = np.sum(( cij*cji*Q22+sij*sji*R22)[masks[b]])
                    elem2 = np.sum((-cij*sji*Q22+sij*cji*R22)[masks[b]])
                    elem3 = np.sum(( sij*sji*Q22+cij*cji*R22)[masks[b]])
                    elem4 = np.sum((-sij*cji*Q22+cij*sji*R22)[masks[b]])

                    # # EE ij then ji
                    Pl[ponbins + b, ii,     jj    ] = elem1
                    Pl[ponbins + b, ii,     jj+npi] = elem2
                    Pl[ponbins + b, ii+npi, jj+npi] = elem3
                    Pl[ponbins + b, ii+npi, jj    ] = elem4

                    Pl[ponbins + b, jj,     ii    ] = elem1
                    Pl[ponbins + b, jj+npi, ii    ] = elem2
                    Pl[ponbins + b, jj+npi, ii+npi] = elem3
                    Pl[ponbins + b, jj,     ii+npi] = elem4

                    # # BB ij then ji
                    Pl[ponbins + nbins+b, ii+npi, jj+npi] =  elem1
                    Pl[ponbins + nbins+b, ii+npi, jj    ] = -elem2
                    Pl[ponbins + nbins+b, ii,     jj    ] =  elem3
                    Pl[ponbins + nbins+b, ii,     jj+npi] = -elem4

                    Pl[ponbins + nbins+b, jj+npi, ii+npi] =  elem1
                    Pl[ponbins + nbins+b, jj,     ii+npi] = -elem2
                    Pl[ponbins + nbins+b, jj,     ii    ] =  elem3
                    Pl[ponbins + nbins+b, jj+npi, ii    ] = -elem4

                    if TE or TB:
                        elemA = np.sum(cji*P02[masks[b]])
                        elemB = np.sum(sji*P02[masks[b]])
                        elemC = np.sum(cij*P02[masks[b]])
                        elemD = np.sum(sij*P02[masks[b]])

                        if TE:
                            Pl[tenbins + b, i, jj    ] =  elemA
                            Pl[tenbins + b, i, jj+npi] = -elemB
                            Pl[tenbins + b, ii,     j] =  elemC
                            Pl[tenbins + b, ii+npi, j] = -elemD

                            Pl[tenbins + b, jj,     i] =  elemA
                            Pl[tenbins + b, jj+npi, i] = -elemB
                            Pl[tenbins + b, j,     ii] =  elemC
                            Pl[tenbins + b, j, ii+npi] = -elemD

                        if TB:
                            Pl[tbnbins + b, i, jj    ] = elemB
                            Pl[tbnbins + b, i, jj+npi] = elemA
                            Pl[tbnbins + b, ii, j    ] = elemD
                            Pl[tbnbins + b, ii+npi, j] = elemC

                            Pl[tbnbins + b, jj,     i] = elemB
                            Pl[tbnbins + b, jj+npi, i] = elemA
                            Pl[tbnbins + b, j,     ii] = elemD
                            Pl[tbnbins + b, j, ii+npi] = elemC

                    if EB:
                        Pl[ebnbins+b, ii,         jj] = -elem2-elem4
                        Pl[ebnbins+b, ii,     jj+npi] =  elem1-elem3
                        Pl[ebnbins+b, ii+npi, jj+npi] =  elem2+elem4
                        Pl[ebnbins+b, ii+npi,     jj] =  elem1-elem3

                        Pl[ebnbins+b, jj,         ii] = -elem2-elem4
                        Pl[ebnbins+b, jj+npi,     ii] =  elem1-elem3
                        Pl[ebnbins+b, jj+npi, ii+npi] =  elem2+elem4
                        Pl[ebnbins+b, jj,     ii+npi] =  elem1-elem3

    return Pl, S


def compute_S(
        ellbins, nside, ipok, allcosang, bl, clth, Slmax,
404
        spec, pixwin=True, verbose=False):
Matthieu Tristram's avatar
Matthieu Tristram committed
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    """
    Computes signal matrix S.

    Parameters
    ----------
    ellbins : array of floats
        Lowers bounds of bins. Example : taking ellbins = (2, 3, 5) will
        compute the spectra for bins = (2, 3.5).
    nside : int
        Healpix map resolution
    ipok : array of ints
        Healpy pixels numbers considered
    bl : 1D array of floats
        Beam window function
    clth : 4D or 6D array of float
        Fiducial power spectra
    Slmax : int
        Maximum lmax computed for the pixel covariance pixel matrix
    spec : 1D array of string
        Spectra list
    pixwin : bool
        If True, multiplies the beam window function by the pixel
        window function. Default: True
428
    verbose : bool
Matthieu Tristram's avatar
Matthieu Tristram committed
429 430 431 432 433 434 435 436 437
        If True, displays timmer. Default: False

    Returns
    ----------
    S :  2D array of floats
        Pixel signal covariance matrix S

    Example
    ----------
Matthieu Tristram's avatar
Matthieu Tristram committed
438 439 440
    >>> S = compute_S(np.array([2,3,4,10]),4,ipok=np.array([0,1,3]),
    ... allcosang=np.linspace(0,1,15).reshape(3,-1), bl=np.arange(10),
    ... clth=np.arange(6*13).reshape(6,-1), Slmax=9,
441
    ... spec=["TT", "EE", "BB", "TE", "EB", "TB"], pixwin=True, verbose=False)
Matthieu Tristram's avatar
Matthieu Tristram committed
442
    >>> print(round(np.sum(S),5))
Matthieu Tristram's avatar
Matthieu Tristram committed
443
    -17502.8982
Matthieu Tristram's avatar
Matthieu Tristram committed
444

Matthieu Tristram's avatar
Matthieu Tristram committed
445
    >>> S = compute_S(np.array([2,3,4,10]),4,ipok=np.array([0,1,3]),
Matthieu Tristram's avatar
Matthieu Tristram committed
446
    ... allcosang=np.linspace(0,1,15).reshape(3,-1), bl=np.arange(13),
Matthieu Tristram's avatar
Matthieu Tristram committed
447
    ... clth=np.arange(6*13).reshape(6,-1), Slmax=9,
448
    ... spec=["TT", "EE", "BB", "TE", "EB", "TB"], pixwin=False, verbose=False)
Matthieu Tristram's avatar
Matthieu Tristram committed
449
    >>> print(round(np.sum(S),5))
Matthieu Tristram's avatar
Matthieu Tristram committed
450
    -31333.69722
Matthieu Tristram's avatar
Matthieu Tristram committed
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    """

    lmax = ellbins[-1]
    ell = np.arange(np.min(ellbins), np.max(ellbins) + 1)
    nbins = len(ellbins) - 1
    minell = np.array(ellbins[0:nbins])
    maxell = np.array(ellbins[1:nbins+1]) - 1
    ellval = (minell + maxell) * 0.5

    npi = ipok.size
    stokes, spec, istokes, ispecs = getstokes(spec)
    nspec = len(spec)
    nsto = len(stokes)
    temp = "TT" in spec
    polar = "EE" in spec or "BB" in spec
    TE = 'TE' in spec
    EB = 'EB' in spec
    TB = 'TB' in spec
    te = spec.index('TE') if TE else 0
    tb = spec.index('TB') if TB else 0
    eb = spec.index('EB') if EB else 0
    ponbins = nbins*temp
    ponpi = npi*temp
    tenbins = te*nbins
    tbnbins = tb*nbins
    ebnbins = eb*nbins

    rpix = np.array(hp.pix2vec(nside, ipok))
    ll = np.arange(Slmax+1)
Matthieu Tristram's avatar
Matthieu Tristram committed
480 481
    fpixwin = extrapolpixwin(nside, Slmax, pixwin)
    norm = (2*ll[2:]+1)/(4.*np.pi)*(fpixwin[2:Slmax+1]**2)*(bl[2:Slmax+1]**2)
Matthieu Tristram's avatar
Matthieu Tristram committed
482 483 484
    clthn = clth[:, 2: Slmax+1]
    S = np.zeros((nsto*npi, nsto*npi))

485
    tstart = timeit.default_timer()
Matthieu Tristram's avatar
Matthieu Tristram committed
486
    for i in np.arange(npi):
487
        if verbose:
488
            progress_bar(i, npi)
Matthieu Tristram's avatar
Matthieu Tristram committed
489 490
        for j in np.arange(i, npi):
            if temp:
Matthieu Tristram's avatar
Matthieu Tristram committed
491
                pl = norm*pl0(allcosang[i, j], Slmax)[2:]
Matthieu Tristram's avatar
Matthieu Tristram committed
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
                elem = np.sum((pl * clthn[0]))
                S[i, j] = elem
                S[j, i] = elem

            if polar:
                ii = i+ponpi
                jj = j+ponpi
                cij, sij = polrotangle(rpix[:, i], rpix[:, j])
                cji, sji = polrotangle(rpix[:, j], rpix[:, i])
                cos_chi = allcosang[i, j]

                # Tegmark version
                Q22 = norm*F1l2(cos_chi, Slmax)
                # # /!\ signe - !
                R22 = -norm*F2l2(cos_chi, Slmax)

                # # Matt version
                # d20  = dlss(cos_chi, 2,  0, Slmax+1)
                # d2p2 = dlss(cos_chi, 2,  2, Slmax+1)
                # d2m2 = dlss(cos_chi, 2, -2, Slmax+1)
                # P02 = -d20[2:]
                # Q22 = ( d2p2 + d2m2 )[2:]/2.
                # R22 = ( d2p2 - d2m2 )[2:]/2.

                if TE or TB:
                    P02 = -norm*F1l0(cos_chi, Slmax)
                    elemA = 0
                    elemB = 0
                    elemC = 0
                    elemD = 0

                    if TE:
                        elemTE = P02*clthn[3]
                        elemA += np.sum(cji*elemTE)
                        elemB -= np.sum(sji*elemTE)
                        elemC += np.sum(cij*elemTE)
                        elemD -= np.sum(sij*elemTE)

                    if TB:
                        elemTB = P02*clthn[5]
                        elemA += np.sum(sji*elemTB)
                        elemB += np.sum(cji*elemTB)
                        elemC += np.sum(sij*elemTB)
                        elemD += np.sum(cij*elemTB)

                    S[i, jj] = elemA
                    S[i, jj+npi] = elemB
                    S[ii, j] = elemC
                    S[ii+npi, j] = elemD

                    S[jj, i] = elemA
                    S[jj+npi, i] = elemB
                    S[j, ii] = elemC
                    S[j, ii+npi] = elemD

                elem1 = np.sum((cij*cji*Q22 + sij*sji*R22)*clthn[1])
                elem2 = np.sum((-cij*sji*Q22 + sij*cji*R22)*clthn[1])
                elem3 = np.sum((sij*sji*Q22 + cij*cji*R22)*clthn[1])
                elem4 = np.sum((-sij*cji*Q22 + cij*sji*R22)*clthn[1])

                elem3 += np.sum((cij*cji*Q22 + sij*sji*R22)*clthn[2])
                elem4 -= np.sum((-cij*sji*Q22 + sij*cji*R22)*clthn[2])
                elem1 += np.sum((sij*sji*Q22 + cij*cji*R22)*clthn[2])
                elem2 -= np.sum((-sij*cji*Q22 + cij*sji*R22)*clthn[2])

                if EB:
                    elemEB = np.sum((Q22 - R22)*clthn[4])
                    elem1 += (cji*sij + sji*cij)*elemEB
                    elem2 += (-sji*sij + cji*cij)*elemEB
                    elem3 += (-sji*cij - cji*sij)*elemEB
                    elem4 += (cji*cij - sji*sij)*elemEB

                S[ii, jj] = elem1
                S[ii, jj+npi] = elem2
                S[ii+npi, jj+npi] = elem3
                S[ii+npi, jj] = elem4

                S[jj, ii] = elem1
                S[jj+npi, ii] = elem2
                S[jj+npi, ii+npi] = elem3
                S[jj, ii+npi] = elem4

    return S


def covth_bins_MC(
        ellbins, nside, ipok, allcosang, bl, clth, Slmax, nsimu,
579
        spec, pixwin=False, verbose=False):
Matthieu Tristram's avatar
Matthieu Tristram committed
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
    """
    Can be particularly slow on sl7.
    To be enhanced and extended to TT and correlations.

    Parameters
    ----------
    ellbins : array of floats
        Lowers bounds of bins. Example : taking ellbins = (2, 3, 5) will
        compute the spectra for bins = (2, 3.5).
    nside : int
        Healpix map resolution
    ipok : array of ints
        Healpy pixels numbers considered
    bl : 1D array of floats
        Beam window function
    clth : 4D or 6D array of float
        Fiducial power spectra
    Slmax : int
        Maximum lmax computed for the pixel covariance pixel matrix
    spec : 1D array of string
        Spectra list
    pixwin : bool
        If True, multiplies the beam window function by the pixel
        window function. Default: True
604
    verbose : bool
Matthieu Tristram's avatar
Matthieu Tristram committed
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
        If True, displays timmer. Default: False

    Returns
    ----------
    Pl : ndarray of floats
        Normalize Legendre polynomials dS/dCl

    S : 2D square matrix array of floats
        Pixel signal covariance matrix S

    Example
    ----------
    >>> import pylab
    >>> pylab.seed(0)
    >>> Pl, S = covth_bins_MC(np.array([2,3,4]), 4, ipok=np.array([0,1,3]),
    ... allcosang=np.linspace(0,1,13), bl=np.arange(13),
    ... clth=np.arange(4*13).reshape(4,-1), Slmax=11, nsimu=100,
622
    ... spec, pixwin=True, verbose=False)
Matthieu Tristram's avatar
Matthieu Tristram committed
623 624 625 626 627 628 629 630
    >>> print(round(np.sum(Pl),5), round(np.sum(S),5))
    (12.68135, 406990.12056)

    >>> import pylab
    >>> pylab.seed(0)
    >>> Pl, S = covth_bins_MC(np.array([2,3,4]), 4, ipok=np.array([0,1,3]),
    ... allcosang=np.linspace(0,1,13), bl=np.arange(13),
    ... clth=np.arange(4*13).reshape(4,-1), Slmax=11, nsimu=100,
631
    ... spec, pixwin=True, verbose=False)
Matthieu Tristram's avatar
Matthieu Tristram committed
632 633 634
    >>> print(round(np.sum(Pl),5), round(np.sum(S),5))
    (42.35592, 7414.01784)
    """
635 636

    polar = 'EE' in spec or 'BB' in spec
Matthieu Tristram's avatar
Matthieu Tristram committed
637 638 639 640 641 642 643 644 645 646
    if nsimu == 1:
        nsimu = (12 * nside**2) * 10 * (int(polar) + 1)

    lmax = ellbins[-1]
    ell = np.arange(np.min(ellbins), np.max(ellbins) + 1)
    nbins = len(ellbins) - 1
    minell = np.array(ellbins[0: nbins])
    maxell = np.array(ellbins[1: nbins + 1]) - 1
    ellval = (minell + maxell) * 0.5

647
    Stokes, spec, istokes, ispecs = getstokes(spec)
Matthieu Tristram's avatar
Matthieu Tristram committed
648 649
    nspec = len(spec)
    ll = np.arange(Slmax+1)
Matthieu Tristram's avatar
Matthieu Tristram committed
650
    fpixwin = extrapolpixwin(nside, Slmax, pixwin)
Matthieu Tristram's avatar
Matthieu Tristram committed
651 652 653 654 655
    masks = []
    for i in np.arange(nbins):
        masks.append((ll[:] >= minell[i]) & (ll[:] <= maxell[i]))
    masks = np.array(masks)
    npix = len(ipok)
656
    tstart = timeit.default_timer()
Matthieu Tristram's avatar
Matthieu Tristram committed
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
    norm = bl[0: Slmax + 1]**2 * fpixwin[0: Slmax + 1]**2

    if polar:
        ClthOne = np.zeros((nspec * (nbins), 6, (Slmax + 1)))
        for l in np.arange(2 * nbins):
            ClthOne[l, int(l / nbins + 1)] = masks[l % nbins] * norm
        if corr:
            print("not implemented")
            # break;
            for l in np.arange(2 * nbins, 3 * nbins):
                ClthOne[l, 1] = masks[l % nbins] * norm
                ClthOne[l, 2] = masks[l % nbins] * norm
                ClthOne[l, 4] = masks[l % nbins] * norm

        Pl = np.zeros((nspec * (nbins), 2 * npix, 2 * npix))
672
        tstart = timeit.default_timer()
Matthieu Tristram's avatar
Matthieu Tristram committed
673
        for l in np.arange((nspec * nbins)):
674
            if verbose:
675
                progress_bar(l, nspec * (nbins))
Matthieu Tristram's avatar
Matthieu Tristram committed
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704

            data = [
                np.array(
                    hp.synfast(
                        ClthOne[l], nside, lmax=Slmax, new=True, verbose=False)
                    )[1: 3, ipok].flatten() for s in np.arange(nsimu)]

            Pl[l] = np.cov(
                np.array(data).reshape(nsimu, 2 * npix), rowvar=False)

        Pl = Pl.reshape(nspec, nbins, 2 * npix, 2 * npix)
        S = np.cov(
            np.array([
                np.array(
                    hp.synfast(
                        clth[:, : Slmax + 1] * norm,
                        nside,
                        lmax=Slmax,
                        new=True,
                        verbose=False)
                    )[1:3, ipok].flatten() for s in np.arange(nsimu)]).reshape(
                        nsimu, 2*npix), rowvar=False)

    else:
        ClthOne = np.zeros((nbins, (Slmax + 1)))
        for l in np.arange((nbins)):
            ClthOne[l] = masks[l] * norm
        Pl = np.zeros(((nbins), npix, npix))
        for l in np.arange((nbins)):
705
            if verbose:
706
                progress_bar(l, nspec * (nbins))
Matthieu Tristram's avatar
Matthieu Tristram committed
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
            Pl[l] = np.cov(
                np.array([
                    hp.synfast(
                        ClthOne[l],
                        nside,
                        lmax=Slmax,
                        verbose=False
                        )[ipok] for s in np.arange(nsimu)]).reshape(
                            nsimu, npix), rowvar=False)

        Pl = Pl.reshape(1, nbins, npix, npix)
        S = np.cov(
            np.array([
                np.array(
                    hp.synfast(
                        clth[:, : Slmax + 1] * norm,
                        nside,
                        lmax=Slmax,
                        new=True,
                        verbose=False)
                    )[0, ipok].flatten() for s in np.arange(nsimu)]).reshape(
                        nsimu, npix), rowvar=False)

    stop = timeit.default_timer()
    return (Pl, S)


def S_bins_MC(
        ellbins, nside, ipok, allcosang, bl, clth, Slmax, nsimu,
736
        spec, pixwin=False, verbose=False):
Matthieu Tristram's avatar
Matthieu Tristram committed
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
    """
    Can be particularly slow on sl7 !
    To be enhanced and extended to TT and correlations

    Parameters
    ----------
    ellbins : array of floats
        Lowers bounds of bins. Example : taking ellbins = (2, 3, 5) will
        compute the spectra for bins = (2, 3.5).
    nside : int
        Healpix map resolution
    ipok : array of ints
        Healpy pixels numbers considered
    bl : 1D array of floats
        Beam window function
    clth : 4D or 6D array of float
        Fiducial power spectra
    Slmax : int
        Maximum lmax computed for the pixel covariance pixel matrix
    polar : bool
        If True, get Stokes parameters for polar. Default: True
    temp : bool
        If True, get Stokes parameters for temperature. Default: False
    corr : bool
        If True, get Stokes parameters for EB and TB. Default: False
    pixwin : bool
        If True, multiplies the beam window function by the pixel
        window function. Default: True
765
    verbose : bool
Matthieu Tristram's avatar
Matthieu Tristram committed
766 767 768 769 770 771 772 773
        If True, displays timmer. Default: False

    Returns
    ----------
    S :  2D array of floats
        Pixel signal covariance matrix S

    """
774
    polar = 'EE' in spec or 'BB' in spec
Matthieu Tristram's avatar
Matthieu Tristram committed
775 776 777 778 779 780 781 782
    if nsimu == 1:
        nsimu = (12 * nside**2) * 10 * (int(polar) + 1)
    lmax = ellbins[-1]
    ell = np.arange(np.min(ellbins), np.max(ellbins) + 1)
    nbins = len(ellbins) - 1
    minell = np.array(ellbins[0: nbins])
    maxell = np.array(ellbins[1: nbins + 1]) - 1
    ellval = (minell + maxell) * 0.5
783
    Stokes, spec, ind = getstokes(spec)
Matthieu Tristram's avatar
Matthieu Tristram committed
784 785
    nspec = len(spec)
    ll = np.arange(Slmax + 2)
Matthieu Tristram's avatar
Matthieu Tristram committed
786
    fpixwin = extrapolpixwin(nside, Slmax, pixwin)
Matthieu Tristram's avatar
Matthieu Tristram committed
787 788 789 790 791
    masks = []
    for i in np.arange(nbins):
        masks.append((ll[:] >= minell[i]) & (ll[:] <= maxell[i]))
    masks = np.array(masks)
    npix = len(ipok)
792
    tstart = timeit.default_timer()
Matthieu Tristram's avatar
Matthieu Tristram committed
793
    norm = bl[0: Slmax + 1]**2 * fpixwin[0: Slmax + 1]**2
Matthieu Tristram's avatar
Matthieu Tristram committed
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129

    if polar:
        ClthOne = np.zeros((nspec * (nbins), 6, (Slmax + 2)))
        for l in np.arange(2 * nbins):
            ClthOne[l, l / nbins + 1] = masks[l % nbins] * norm
        if corr:
            print("not implemented")
            # break;
            for l in np.arange(2*nbins, 3*nbins):
                ClthOne[l, 1] = masks[l % nbins]*norm
                ClthOne[l, 2] = masks[l % nbins]*norm
                # couille ici : -nbins*(l/nbins)]*norm
                ClthOne[l, 4] = masks[l % nbins]*norm

        S = np.cov(
            np.array(
                [np.array(hp.synfast(
                    clth[:, : Slmax + 2]*norm,
                    nside,
                    lmax=Slmax,
                    new=True,
                    verbose=False))[1:3, ipok].flatten()
                 for s in np.arange(nsimu)]).reshape(nsimu, 2 * npix),
            rowvar=False)

    else:
        ClthOne = np.zeros((nbins, (Slmax+2)))
        for l in np.arange((nbins)):
            ClthOne[l] = masks[l]*norm
        S = np.cov(
            np.array(
                [np.array(hp.synfast(
                    clth[:, : Slmax + 2] * norm,
                    nside,
                    lmax=Slmax,
                    new=True,
                    verbose=False))[0, ipok].flatten()
                 for s in np.arange(nsimu)]).reshape(nsimu, npix),
            rowvar=False)

    return S


def polrotangle(ri, rj):
    """
    Computes cosine and sine of twice the angle between pixels i and j.

    Parameters
    ----------
    ri : 3D array of floats
        Coordinates of vector corresponding to input pixels i following
        healpy.pix2vec(nside,ipix) output
    rj : 3D array of floats
        Coordinates of vector corresponding to input pixels j following
        healpy.pix2vec(nside,jpix) output

    Returns
    ----------
    cos2a : 1D array of floats
        Cosine of twice the angle between pixels i and j
    sin2a : 1D array of floats
        Sine of twice the angle between pixels i and j

    Example
    ----------
    >>> cos2a, sin2a = polrotangle([0.1,0.2,0.3], [0.4,0.5,0.6])
    >>> print(round(cos2a,5),round(sin2a,5))
    (0.06667, 0.37333)
    """
    z = np.array([0.0, 0.0, 1.0])

    # Compute ri^rj : unit vector for the great circle connecting i and j
    rij = np.cross(ri, rj)
    norm = np.sqrt(np.dot(rij, np.transpose(rij)))

    # case where pixels are identical or diametrically opposed on the sky
    if norm <= 1e-15:
        cos2a = 1.0
        sin2a = 0.0
        return cos2a, sin2a
    rij = rij / norm

    # Compute z^ri : unit vector for the meridian passing through pixel i
    ris = np.cross(z, ri)
    norm = np.sqrt(np.dot(ris, np.transpose(ris)))

    # case where pixels is at the pole
    if norm <= 1e-15:
        cos2a = 1.0
        sin2a = 0.0
        return cos2a, sin2a
    ris = ris / norm

    # Now, the angle we want is that
    # between these two great circles: defined by
    cosa = np.dot(rij, np.transpose(ris))

    # the sign is more subtle : see tegmark et de oliveira costa 2000 eq. A6
    rijris = np.cross(rij, ris)
    sina = np.dot(rijris, np.transpose(ri))

    # so now we have directly cos2a and sin2a
    cos2a = 2.0 * cosa * cosa - 1.0
    sin2a = 2.0 * cosa * sina

    return cos2a, sin2a


def dlss(z, s1, s2, lmax):
    """
    Computes the reduced Wigner D-function d^l_ss'

    Parameters
    ----------
    z : float
        Cosine of the angle between two pixels
    s1 : int
        Spin number 1
    s2 : int
        Spin number 2
    lmax : int
        Maximum multipole

    Returns
    ----------
    d : 1D array of floats
        ???

    Example
    ----------
    >>> d = dlss(0.1, 2,  2, 5)
    >>> print(round(sum(d),5))
    0.24351
    """
    d = np.zeros((lmax + 1))
    if s1 < abs(s2):
        print("error spins, s1<|s2|")
        return

    # Conv: sign = -1 if (s1 + s2) and 1 else 1
    sign = (-1)**(s1 - s2)
    fs1 = math.factorial(2.0 * s1)
    fs1ps2 = math.factorial(1.0 * s1 + s2)
    fs1ms2 = math.factorial(1.0 * s1 - s2)
    num = (1.0 + z)**(0.5 * (s1 + s2)) * (1.0 - z)**(0.5 * (s1 - s2))

    # Initialise the recursion (l = s1 + 1)
    d[s1] = sign / 2.0**s1 * np.sqrt(fs1 / fs1ps2 / fs1ms2) * num

    l1 = s1 + 1.0
    rhoSSL1 = np.sqrt((l1 * l1 - s1 * s1) * (l1 * l1 - s2 * s2)) / l1
    d[s1+1] = (2 * s1 + 1.0)*(z - s2 / (s1 + 1.0)) * d[s1] / rhoSSL1

    # Build the recursion for l > s1 + 1
    for l in np.arange(s1 + 1, lmax, 1):
        l1 = l + 1.0
        numSSL = (l * l * 1.0 - s1 * s1) * (l * l * 1.0 - s2 * s2)
        rhoSSL = np.sqrt(numSSL) / (l * 1.0)
        numSSL1 = (l1 * l1 - s1 * s1) * (l1 * l1 - s2 * s2)
        rhoSSL1 = np.sqrt(numSSL1) / l1

        numd = (2.0 * l + 1.0) * (z - s1 * s2 / (l * 1.0) / l1) * d[l]
        d[l+1] = (numd - rhoSSL * d[l-1]) / rhoSSL1
    return d


def pl0(z, lmax):
    """
    Computes the associated Legendre function of the first kind of order 0
    Pn(z) from 0 to lmax (inclusive).

    Parameters
    ----------
    z : float
        Cosine of the angle between two pixels
    lmax : int
        Maximum multipole

    Returns
    ----------
    Pn : 1D array of floats
    Legendre function

    Example
    ----------
    >>> thepl0 = pl0(0.1, 5)
    >>> print(round(sum(thepl0),5))
    0.98427
    """
    Pn = special.lpn(lmax, z)[0]
    return Pn


def pl2(z, lmax):
    """
    Computes the associated Legendre function of the first kind of order 2
    from 0 to lmax (inclusive)

    Parameters
    ----------
    z : float
        Cosine of the angle between two pixels
    lmax : int
        Maximum multipole

    Returns
    ----------
    Pn2 : 1D array of floats
    Legendre function

    Example
    ----------
    >>> thepl2 = pl2(0.1, 5)
    >>> print(round(sum(thepl2),5))
    -7.49183
    """
    Pn2 = special.lpmn(2, lmax, z)[0][2]
    return Pn2


# ####### F1 and F2 functions from Tegmark & De Oliveira-Costa, 2000  #########
def F1l0(z, lmax):
    """
    Compute the F1l0 function from Tegmark & De Oliveira-Costa, 2000

    Parameters
    ----------
    z : float
        Cosine of the angle between two pixels
    lmax : int
        Maximum multipole

    Returns
    ----------
    bla : 1D array of float
    F1l0 function from Tegmark & De Oliveira-Costa, 2000

    Example
    ----------
    >>> theF1l0= F1l0(0.1, 5)
    >>> print(round(sum(theF1l0),5))
    0.20392
    """
    if abs(z) == 1.0:
        return(np.zeros(lmax - 1))
    else:
        ell = np.arange(2, lmax + 1)
        thepl = pl0(z, lmax)
        theplm1 = np.append(0, thepl[:-1])
        thepl = thepl[2:]
        theplm1 = theplm1[2:]
        a0 = 2.0 / np.sqrt((ell - 1) * ell * (ell + 1) * (ell + 2))
        a1 = ell * z * theplm1 / (1 - z**2)
        a2 = (ell / (1 - z**2) + ell * (ell - 1) / 2) * thepl
        bla = a0 * (a1 - a2)
        return bla


def F1l2(z, lmax):
    """
    Compute the F1l2 function from Tegmark & De Oliveira-Costa, 2000

    Parameters
    ----------
    z : float
        Cosine of the angle between two pixels
    lmax : int
        Maximum multipole

    Returns
    ----------
    bla : 1D array of float
    F1l2 function from Tegmark & De Oliveira-Costa, 2000

    Example
    ----------
    >>> theF1l2= F1l2(0.1, 5)
    >>> print(round(sum(theF1l2),5))
    0.58396
    """
    if z == 1.0:
        return np.ones(lmax - 1) * 0.5
    elif z == -1.0:
        ell = np.arange(lmax + 1)
        return 0.5 * (-1)**ell[2:]
    else:
        ell = np.arange(2, lmax + 1)
        thepl2 = pl2(z, lmax)
        theplm1_2 = np.append(0, thepl2[:-1])
        thepl2 = thepl2[2:]
        theplm1_2 = theplm1_2[2:]
        a0 = 2.0 / ((ell - 1) * ell * (ell + 1) * (ell + 2))
        a1 = (ell + 2) * z * theplm1_2 / (1 - z**2)
        a2 = ((ell - 4) / (1 - z**2) + ell * (ell - 1) / 2) * thepl2
        bla = a0 * (a1 - a2)
        return bla


def F2l2(z, lmax):
    """
    Compute the F2l2 function from Tegmark & De Oliveira-Costa, 2000

    Parameters
    ----------
    z : float
        Cosine of the angle between two pixels
    lmax : int
        Maximum multipole

    Returns
    ----------
    ???

    Example
    ----------
    >>> theF2l2= F2l2(0.1, 5)
    >>> print(round(sum(theF2l2),5))
    0.34045
    """
    if z == 1.0:
        return -0.5 * np.ones(lmax - 1)
    elif z == -1.0:
        ell = np.arange(lmax + 1)
        return  0.5 * (-1)**ell[2:]
    else:
        ell = np.arange(2, lmax + 1)
        thepl2 = pl2(z, lmax)
        theplm1_2 = np.append(0, thepl2[:-1])
        thepl2 = thepl2[2:]
        theplm1_2 = theplm1_2[2:]
        a0 = 4.0 / ((ell - 1) * ell * (ell + 1) * (ell + 2) * (1 - z**2))
        a1 = (ell + 2) * theplm1_2
        a2 = (ell - 1) * z * thepl2
        bla = a0 * (a1 - a2)
        return bla

1130 1131


Matthieu Tristram's avatar
Matthieu Tristram committed
1132 1133 1134 1135
if __name__ == "__main__":
    """
    Run the doctest using

Matthieu Tristram's avatar
Matthieu Tristram committed
1136
    python libcov.py'
Matthieu Tristram's avatar
Matthieu Tristram committed
1137 1138 1139 1140 1141 1142 1143 1144

    If the tests are OK, the script should exit gracefuly, otherwise the
    failure(s) will be printed out.
    """
    import doctest
    if np.__version__ >= "1.14.0":
        np.set_printoptions(legacy="1.13")
    doctest.testmod()