estimators.py 10.7 KB
Newer Older
Matthieu Tristram's avatar
Matthieu Tristram committed
1
"""
Matthieu Tristram's avatar
Matthieu Tristram committed
2
Set of routines generating the estimators for xQML code
Matthieu Tristram's avatar
Matthieu Tristram committed
3 4 5 6
"""
from __future__ import division

import numpy as np
Matthieu Tristram's avatar
Matthieu Tristram committed
7 8 9
import _libcov as clibcov
import timeit
import threading
Matthieu Tristram's avatar
Matthieu Tristram committed
10 11


Matthieu Tristram's avatar
Matthieu Tristram committed
12
#
Matthieu Tristram's avatar
Matthieu Tristram committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
def Pl(ds_dcb):
    """
    Reshape ds_dcb (nspec, nbins) into Pl (nspec * nbins)

    Parameters
    ----------
    ds_dcb : ndarray of floats
        Normalize Legendre polynomials (2l + 1)/2pi * pl

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

    Example
    ----------
    >>> thePl = Pl(np.arange(16).reshape((2,2,2,2)))
    >>> print(thePl) # doctest: +NORMALIZE_WHITESPACE
    [[[ 0  1]
      [ 2  3]]
    <BLANKLINE>
     [[ 4  5]
      [ 6  7]]
    <BLANKLINE>
     [[ 8  9]
      [10 11]]
    <BLANKLINE>
     [[12 13]
      [14 15]]]
    """
    nnpix = np.shape(ds_dcb)[-1]
    return np.copy(ds_dcb).reshape(2 * (np.shape(ds_dcb)[1]), nnpix, nnpix)

Matthieu Tristram's avatar
Matthieu Tristram committed
46
#
Matthieu Tristram's avatar
Matthieu Tristram committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
def CorrelationMatrix(Clth, Pl, ellbins, polar=True, temp=False, corr=False):
    """
    Compute correlation matrix S = sum_l Pl*Cl

    Parameters
    ----------
    Clth : 1D array of float
        Fiducial spectra
    Pl : ndarray of floats
        Rescaled normalize Legendre polynomials dS_dCb
    ellbins : array of integers
        Bins lower bound
    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)

    Returns
    ----------
    S : 2D square matrix of float (npix, npix)
        Pixel covariance matrix

    Example
    ----------
    >>> Pl = np.arange(10).reshape(2,-1)
    >>> Clth = np.arange(40).reshape(4,-1)
    >>> ellbins = np.arange(2,10,1)
    >>> S = CorrelationMatrix(Clth, Pl, ellbins)
    >>> print(S) # doctest: +NORMALIZE_WHITESPACE
    [[   0  280  560  840 1120]
     [1400 1680 1960 2240 2520]]
    """
    if corr:
        xx = ['TT', 'EE', 'BB', 'TE', 'EB', 'TB']
        ind = [0, 1, 2, 3, 4, 5]
    else:
        xx = ['TT', 'EE', 'BB', 'TE']
        ind = [0, 1, 2, 3]

    if not temp:
        allStoke = ['Q', 'U']
        if corr:
            xx = ['EE', 'BB', 'EB']
            ind = [1, 2, 5]
        else:
            xx = ['EE', 'BB']
            ind = [1, 2]
    if not polar:
        allStoke = ['I']
        xx = ['TT']
        ind = [0]

    clth = Clth[ind][:, 2: int(ellbins[-1])].flatten()
    S = np.sum(Pl * clth[:, None, None], 0)
    return S


Matthieu Tristram's avatar
Matthieu Tristram committed
106
def El(invCAA, invCBB, Pl, thread=False, verbose=False):
Matthieu Tristram's avatar
Matthieu Tristram committed
107 108
    """
    Compute El = CAA^-1.Pl.CBB^-1
Matthieu Tristram's avatar
Matthieu Tristram committed
109
    (Note: El is not symmetric for cross)
Matthieu Tristram's avatar
Matthieu Tristram committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

    Parameters
    ----------
    invCAA : square matrix array of float
        Inverse pixel covariance matrix of dataset A
    invCBB : square matrix array of float
        Inverse pixel covariance matrix of dataset B
    Pl : ndarray of floats
        Rescaled normalize Legendre polynomials dS/dCl

    Returns
    ----------
    El : array of float (shape(Pl))
        Quadratic parameter matrices such that yl = dA.El.dB.T

    Example
    ----------
    >>> Pl = np.arange(12).reshape(3,2,2)
    >>> invCAA = np.array([[1,2],[2,3]])
    >>> invCBB = np.array([[4,3],[3,6]])
    >>> print(El(invCAA, invCBB, Pl))
    [[[ 37  54]
      [ 57  84]]
    <BLANKLINE>
     [[121 162]
      [197 264]]
    <BLANKLINE>
     [[205 270]
      [337 444]]]

    """

Matthieu Tristram's avatar
Matthieu Tristram committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    tstart = timeit.default_timer()
    nl = len(Pl)
    npix = len(Pl[0])

    if thread:
        #Note: longer than with list...
        El = np.ndarray( np.shape(Pl))
        def CPC( l):
            El[l] = np.dot(np.dot(invCAA, Pl[l]), invCBB)
        procs = []
        for l in range(nl):
            proc = threading.Thread(target=CPC,args=(l,))
            procs.append(proc)

        for proc in procs:
            proc.start()
        for proc in procs:
            proc.join()

    else:
        El = [np.dot(np.dot(invCAA, P), invCBB) for P in Pl]

    if verbose:
        print( "Construct El (nl=%d): %.1f sec" % (nl,timeit.default_timer()-tstart))
Matthieu Tristram's avatar
Matthieu Tristram committed
166

Matthieu Tristram's avatar
Matthieu Tristram committed
167 168 169
    return El


Matthieu Tristram's avatar
Matthieu Tristram committed
170 171

def CrossWindowFunction(El, Pl, openMP=False, thread=False, verbose=False):
Matthieu Tristram's avatar
Matthieu Tristram committed
172
    """
Matthieu Tristram's avatar
Matthieu Tristram committed
173
    Compute mode-mixing matrix (Tegmark's window matrix)
Matthieu Tristram's avatar
Matthieu Tristram committed
174
    Wll = Trace[invCAA.Pl.invCBB.Pl] = Trace[El.Pl]
Matthieu Tristram's avatar
Matthieu Tristram committed
175
    Use the trick with matrices: Trace[A.B] = sum(A x B^T) (where . is the matrix product and x the elementwise mult)
Matthieu Tristram's avatar
Matthieu Tristram committed
176
    
Matthieu Tristram's avatar
Matthieu Tristram committed
177 178 179 180 181 182
    Parameters
    ----------
    El : ndarray of floats
        Quadratic parameter matrices such that yl = dA.El.dB.T
    Pl : ndarray of floats
        Rescaled normalize Legendre polynomials dS/dCl
Matthieu Tristram's avatar
Matthieu Tristram committed
183
    
Matthieu Tristram's avatar
Matthieu Tristram committed
184 185 186 187 188 189 190 191 192 193 194 195 196 197
    Returns
    ----------
    Wll : 2D square matrix array of floats
        Mode-mixing matrix of dimension (nspec * nbins)

    Example
    ----------
    >>> Pl = np.arange(12).reshape(3,2,2)
    >>> El = np.arange(12,24).reshape(3,2,2)
    >>> print(CrossWindowFunction(El, Pl))
    [[ 86 302 518]
     [110 390 670]
     [134 478 822]]
    """
Matthieu Tristram's avatar
Matthieu Tristram committed
198
    nl = len(El)
Matthieu Tristram's avatar
Matthieu Tristram committed
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 226 227 228 229

    tstart = timeit.default_timer()

    if openMP:
        #pb of precision (sum of +/- big numbers)
        Wll = np.ndarray( nl*nl)
        clibcov.CrossWindow( np.asarray(El), Pl, Wll)
        Wll = Wll.reshape(nl,nl)
    elif thread:
        #gain a factor 2.5 on npix=600
        Wll = np.ndarray( (nl, nl))
        def EP( l1, l2):
            Wll[l1,l2] = np.sum( El[l1]*Pl[l2])
        procs = []
        for l1 in range(nl):
            for l2 in range(nl):                
                proc = threading.Thread(target=EP, args=(l1,l2,))
                procs.append(proc)

        for proc in procs:
                proc.start()
        for proc in procs:
                proc.join()
        
    else:
        # No transpose because P symm
        Wll = np.asarray( [np.sum(E * P) for E in El for P in Pl] ).reshape(nl,nl)

    if verbose:
        print( "Construct Wll (nl=%d): %.1f sec" % (nl,timeit.default_timer()-tstart))

Matthieu Tristram's avatar
Matthieu Tristram committed
230 231 232
    return Wll


Matthieu Tristram's avatar
Matthieu Tristram committed
233

Matthieu Tristram's avatar
Matthieu Tristram committed
234 235
def CrossWindowFunctionLong(invCAA, invCBB, Pl):
    """
Matthieu Tristram's avatar
Matthieu Tristram committed
236
    Compute mode-mixing matrix (Tegmark's window matrix)
Matthieu Tristram's avatar
Matthieu Tristram committed
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
    Wll = Trace[invCAA.Pl.invCBB.Pl] = Trace[El.Pl]

    Parameters
    ----------
    invCAA : square matrix array of float
        Inverse pixel covariance matrix of dataset A
    invCBB : square matrix array of float
        Inverse pixel covariance matrix of dataset B
    Pl : ndarray of floats
        Rescaled normalize Legendre polynomials dS/dCl

    Returns
    ----------
    Wll : 2D square matrix array of floats
        Mode-mixing matrix of dimension (nspec * nbins, nspec * nbins)

    Example
    ----------
    >>> Pl = np.arange(12).reshape(3,2,2)
    >>> invCAA = np.array([[1,2],[2,3]])
    >>> invCBB = np.array([[4,3],[3,6]])
    >>> print(CrossWindowFunctionLong(invCAA, invCBB, Pl))
    [[  420  1348  2276]
     [ 1348  4324  7300]
     [ 2276  7300 12324]]
    """
    lmax = len(Pl)
    lrange = np.arange((lmax))
    # Pas de transpose car symm
Matthieu Tristram's avatar
Matthieu Tristram committed
266
    Wll = np.asarray(
Matthieu Tristram's avatar
Matthieu Tristram committed
267
        [np.sum(np.dot(np.dot(invCAA, Pi), invCBB) * Pj) for Pi in Pl for Pj in Pl]
Matthieu Tristram's avatar
Matthieu Tristram committed
268
        ).reshape(lmax, lmax)
Matthieu Tristram's avatar
Matthieu Tristram committed
269 270 271
    return Wll


Matthieu Tristram's avatar
Matthieu Tristram committed
272

Matthieu Tristram's avatar
Matthieu Tristram committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
def CrossGisherMatrix(El, CAB):
    """
    Compute matrix GAB = Trace[El.CAB.El.CAB]

    Parameters
    ----------
    CAB : 2D square matrix array of floats
        Pixel covariance matrix between dataset A and B
    El : ndarray of floats
        Quadratic parameter matrices such that yl = dA.El.dB.T

    Returns
    ----------
    GAB : 2D square matrix array of floats

     Example
    ----------
    >>> El = np.arange(12).reshape(3,2,2)
    >>> CAB = np.array([[1,2],[2,3]])
    >>> print(CrossGisherMatrix(El, CAB))
    [[ 221  701 1181]
     [ 701 2205 3709]
     [1181 3709 6237]]
    """
Matthieu Tristram's avatar
Matthieu Tristram committed
297 298
    nl = len(El)

Matthieu Tristram's avatar
Matthieu Tristram committed
299
    El_CAB = [np.dot(CAB, E) for E in El]
Matthieu Tristram's avatar
Matthieu Tristram committed
300
    GAB = [np.sum(Ei * Ej.T) for Ei in El_CAB for Ej in El_CAB]
Matthieu Tristram's avatar
Matthieu Tristram committed
301
    
Matthieu Tristram's avatar
Matthieu Tristram committed
302 303
    return np.asarray(GAB).reshape(nl,nl)

Matthieu Tristram's avatar
Matthieu Tristram committed
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


def CrossGisherMatrixLong(El, CAB):
    """
    Compute matrix GAB = Trace[El.CAB.El.CAB]

    Parameters
    ----------
    CAB : 2D square matrix array of floats
        Pixel covariance matrix between dataset A and B
    El : ndarray of floats
        Quadratic parameter matrices such that yl = dA.El.dB.T

    Returns
    ----------
    GAB : 2D square matrix array of floats

    Example
    ----------
    >>> El = np.arange(12).reshape(3,2,2)
    >>> CAB = np.array([[1,2],[2,3]])
    >>> print(CrossGisherMatrixLong(El, CAB))
    [[ 221  701 1181]
     [ 701 2205 3709]
     [1181 3709 6237]]

    """
    lmax = len(El)
    lrange = np.arange(lmax)
Matthieu Tristram's avatar
Matthieu Tristram committed
333 334
    GAB = [np.sum(np.dot(CAB, El[il]) * np.dot(CAB, El[jl]).T) for il in lrange for jl in lrange]
    return np.asarray(GAB).reshape(lmax, lmax)
Matthieu Tristram's avatar
Matthieu Tristram committed
335 336 337 338 339 340 341 342 343 344 345 346 347 348


def yQuadEstimator(dA, dB, El):
    """
    Compute pre-estimator 'y' such that Cl = Fll^-1 . yl

    Parameters
    ----------
    dA : array of floats
        Pixels dataset A
    dB : array of floats
        Pixels dataset B
    El : ndarray of floats
        Quadratic parameter matrices such that yl = dA.El.dB.T
Matthieu Tristram's avatar
Matthieu Tristram committed
349
    
Matthieu Tristram's avatar
Matthieu Tristram committed
350 351 352 353 354 355 356 357
    Returns
    ----------
    >>> dA = np.arange(12)
    >>> dB = np.arange(12,24)
    >>> El = np.arange(3*12**2).reshape(3,12,12)
    >>> print(yQuadEstimator(dA, dB, El))
    [1360788 3356628 5352468]
    """
Matthieu Tristram's avatar
Matthieu Tristram committed
358
    y = np.asarray([dA.dot(E).dot(dB) for E in El])
Matthieu Tristram's avatar
Matthieu Tristram committed
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
    return y


def ClQuadEstimator(invW, y):
    """
    Compute estimator 'Cl' such that Cl = Fll^-1 . yl

    Parameters
    ----------
    invW : 2D square matrix array of floats
        Inverse mode-mixing matrix Wll'^-1

    Returns
    ----------
    Cl : array of floats
        Unbiased estimated spectra

    Example
    ----------
    >>> invW = np.array([[1,2], [2,4]])
    >>> yl = np.array([3,7])
    >>> print(ClQuadEstimator(invW, yl))
    [17 34]
    """
    Cl = np.dot(invW, y)
    return Cl


def biasQuadEstimator(NoiseN, El):
    """
    Compute bias term bl such that Cl = Fll^-1 . ( yl + bias)

    Parameters
    ----------
    NoiseN : ???
        ???

    Returns
    ----------
    ???
    """

Matthieu Tristram's avatar
Matthieu Tristram committed
401
    return [np.sum(NoiseN * E) for E in El]
Matthieu Tristram's avatar
Matthieu Tristram committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429


def CovAB(invWll, GAB):
    """
    Compute analytical covariance matrix Cov(Cl, Cl_prime)

    Parameters
    ----------
    invWll : 2D square matrix of floats
        Inverse of the mode-mixing matrix Wll'=Tr[El.Pl']

    Returns
    ----------
    covAB : 2D square matrix array of floats
        Analytical covariance of estimate spectra

    Example
    ----------
    >>> invW = np.array([[1,2], [2,4]])
    >>> GAB = np.array([[5,3], [3,2]])
    >>> print(CovAB(invW, GAB))
    [[ 26  52]
     [ 52 104]]
    """
    covAB = np.dot(np.dot(invWll, GAB), invWll.T) + invWll
    return covAB


Matthieu Tristram's avatar
Matthieu Tristram committed
430

Matthieu Tristram's avatar
Matthieu Tristram committed
431 432 433 434
if __name__ == "__main__":
    """
    Run the doctest using

Matthieu Tristram's avatar
Matthieu Tristram committed
435
    python estimators.py
Matthieu Tristram's avatar
Matthieu Tristram committed
436 437 438 439 440 441 442

    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")
Matthieu Tristram's avatar
Matthieu Tristram committed
443
    doctest.testmod()