示例#1
0
def tomo_map(data, Nside=2048, starsel='all', part='all', distcut=360):
    """
    Make healpix map for the given Nside for the tomography data

    Parameters:
    -----------
    - data, ndarray.    All of the data array.
    - Nside, integer.   The resolution of the map to make, default is 2048

    Return:
    -------
    - p_map, array.     Array with the fractional polarization, p=sqrt(q^2+u^2)
    - q_map, array.     Array with the fractional q=Q/I polarization.
    - u_map, array.     Array with the fractional u=U/I polarization.
    - sigma_p, array.   Array with the uncertainty of p
    - sigma_q, array.   Array with the uncertainty of q.
    - sigma_u, array.   Array with the uncertainty of u.
    - pix, array.       The pixels where there exist data.
    """

    # Select stars
    if starsel == 'all':
        print('Use all areas')
        pass
    elif starsel == '1cloud':
        ii = select_stars(103.9, 21.97, 0.16)  # 1-cloud region
        data = data[ii, :]
        #ii = np.where(in 1 cloud)[0]     # 1 cloud region
    elif starsel == '2cloud':
        ii = select_stars(104.08, 22.31, 0.16)  # 2 cloud region
        data = data[ii, :]

    print(np.shape(data))
    jj = np.where(data[:, 11] > 360)[0]
    cut_intr = np.logical_and(data[:, 4] <= 0, data[:, 4])
    data = data[cut_intr, :]  # use stars with negative evpa
    print(np.shape(data))

    if part == 'LVC':
        if len(distcut) == 2:
            print('min and max distance for LVC', distcut)
            clean = np.logical_and(data[:,11] > distcut[0],\
                                   data[:,11] < distcut[1])
        else:
            print('LVC for dist >', distcut)
            clean = np.logical_and(data[:, 11] > distcut[0], data[:, 11])
    else:
        clean = np.logical_and(data[:, 11] > distcut[0], data[:, 11])

    data = data[clean, :]  # remove close stars, use r > 360 pc
    print(np.shape(data))
    # remove pol.angle outliers:
    mean = np.mean(data[:, 4])  #*180/np.pi
    sigma3 = 2.5 * np.std(data[:, 4])  #*180/np.pi
    clean_3sigma = np.logical_and(data[:, 4],
                                  data[:, 4] - data[:, 5] < mean + sigma3)
    data = data[clean_3sigma, :]
    print(np.shape(data))
    #s2n = data[:,2]/data[:,3] >= 3
    #data = data[s2n,:]
    #print(np.shape(data), '-')

    # convert to galactic coordinates:
    l, b = tools.convert2galactic(data[:, 0], data[:, 1])
    theta = np.pi / 2. - b * np.pi / 180.
    phi = l * np.pi / 180.
    #print(np.min(theta), np.max(theta))
    print(np.shape(data))

    # get pixel numbers
    pix = hp.pixelfunc.ang2pix(Nside, theta, phi, nest=False)

    # make cut regarding IVC, have only stars not affected by the IVC
    print('Remove stars affected by the IVC')
    if part != 'none':
        IVC_cut = tools.IVC_cut(pix, data[:,11], distcut[0], Nside=Nside,\
                                clouds=part)
        data = data[IVC_cut, :]
        pix = pix[IVC_cut]
    else:
        pass

    #cut_max_d = np.logical_and(data[:,11] < 1000, data[:,11])
    #data = data[cut_max_d,:]
    #pix = pix[cut_max_d]

    #sys.exit()

    # Debias p, since > 0.
    pmas = tools.MAS(data[:, 2], data[:, 3])

    # polariasation rotation (IAU convention):
    # compute pol. in galactic coordinates of q and u.
    print('Rotate polarisation angle from equitorial to galactic.')
    q_gal, u_gal, theta_gal = tools.rotate_pol(data[:,0], data[:,1],\
                                               pmas, data[:,6],\
                                               data[:,8], data[:,4])
    sq_gal, su_gal = tools.error_polangle(pmas, data[:,3],\
                                          theta_gal, np.radians(data[:,5]))

    # correct for extinction:
    #correction = tools.extinction_correction(l, b, data[:,10])
    #q_gal = q_gal*correction
    #u_gal = u_gal*correction
    q_err = sq_gal  #*correction
    u_err = su_gal  #*correction

    psi = 0.5 * np.arctan2(-u_gal, q_gal)

    # Create maps
    Npix = hp.nside2npix(Nside)
    p_map = np.full(Npix, hp.UNSEEN)
    q_map = np.full(Npix, hp.UNSEEN)
    u_map = np.full(Npix, hp.UNSEEN)
    r_map = np.full(Npix, hp.UNSEEN)
    psi_map = np.full(Npix, hp.UNSEEN)
    sigma_p = np.full(Npix, hp.UNSEEN)
    sigma_q = np.full(Npix, hp.UNSEEN)
    sigma_u = np.full(Npix, hp.UNSEEN)
    sigma_psi = np.full(Npix, hp.UNSEEN)
    err_psi = np.full(Npix, hp.UNSEEN)

    print(len(np.unique(pix)), len(pix))
    uniqpix = np.unique(pix)
    index = []
    for k, i in enumerate(uniqpix):
        ind = np.where(pix == i)[0]

        q, qerr = tools.weightedmean(q_gal[ind], q_err[ind])
        u, uerr = tools.weightedmean(u_gal[ind], u_err[ind])
        p, perr = tools.weightedmean(pmas[ind], data[ind, 3])
        #psi2, psierr = tools.weightedmean(psi[ind]*180/np.pi, data[ind,5])

        p_map[i] = p  #np.mean(data[ind, 2])
        q_map[i] = q  #np.mean(q_gal[ind])
        u_map[i] = u  #np.mean(u_gal[ind])

        sigma_p[i] = perr  #tools.sigma_x(data[ind, 3], len(ind))
        sigma_q[
            i] = qerr  #+ np.std(q_gal[ind]) #tools.sigma_x(q_err[ind], len(ind))#
        sigma_u[
            i] = uerr  #+ np.std(u_gal[ind]) #tools.sigma_x(u_err[ind], len(ind))#
        a = np.std(u_gal[ind])  #tools.sigma_x(u_err[ind], len(ind))

        sigma_psi[i] = tools.sigma_x(data[ind, 5], len(ind))  #np.std(psi[ind])
        r_map[i] = np.mean(data[ind, 10])

    #
    print(u_map[uniqpix])
    #sys.exit()
    return (p_map, q_map, u_map, [sigma_p, sigma_q, sigma_u,
                                  sigma_psi], r_map, pix)
示例#2
0
def pix2star_tomo(data, Nside, starsel='all'):
    """
    Method where the pixels are asigned to a star. Remove stars closer 
    than 360 pc, since not polarised.
    """
    # Select stars
    if starsel == 'all':
        print('Use all areas')
        pass
    elif starsel == '1cloud':
        ii = select_stars(103.9, 21.97, 0.16)  # 1-cloud region
        data = data[ii, :]
        #ii = np.where(in 1 cloud)[0]     # 1 cloud region
    elif starsel == '2cloud':
        ii = select_stars(104.08, 22.31, 0.16)  # 2 cloud region
        data = data[ii, :]
    print(np.shape(data))

    jj = np.where(data[:, 11] > 360)[0]
    clean = np.logical_and(data[:, 11] > 360, data[:, 11])
    #print(clean)
    data = data[clean, :]  # remove close stars, use r > 360 pc
    # remove pol.angle outliers:
    mean = np.mean(data[:, 4])  #*180/np.pi
    sigma3 = 2.5 * np.std(data[:, 4])  #*180/np.pi
    clean_3sigma = np.logical_and(data[:, 4],
                                  data[:, 4] - data[:, 5] < mean + sigma3)
    data = data[clean_3sigma, :]

    #jj = np.where(data[:,10] > 360)[0]
    #data = data[jj,:] # remove close stars, use r > 360 pc
    print(Nside, np.shape(data))
    #sys.exit()

    # convert to galactic coordinates:
    l, b = tools.convert2galactic(data[:, 0], data[:, 1])
    theta = np.pi / 2. - b * np.pi / 180.  # in healpix
    phi = l * np.pi / 180.

    # get pixel numbers
    pix = hp.pixelfunc.ang2pix(Nside, theta, phi, nest=False)

    # clean for IVC:
    IVC_cut = tools.IVC_cut(pix,
                            data[:, 11],
                            distcut=900,
                            Nside=Nside,
                            clouds='LVC')
    data = data[IVC_cut, :]
    theta = theta[IVC_cut]
    phi = phi[IVC_cut]

    # Debias p, since > 0.
    pmas = tools.MAS(data[:, 2], data[:, 3])
    # polariasation rotation (IAU convention):
    print('Rotate polarisation angle from equitorial to galactic.')
    q_gal, u_gal, evpa = tools.rotate_pol(data[:,0], data[:,1], data[:,2],\
                                    data[:,6],data[:,8], data[:,4])
    #q_err, u_err, evpa0 = tools.rotate_pol(data[:,0], data[:,1], data[:,3],\
    #                                data[:,7], data[:,9], data[:,4])
    sq_gal, su_gal = tools.error_polangle(pmas, data[:,3],\
                                          evpa, np.radians(data[:,5]))
    #print(len(q_gal), len(u_gal), len(evpa), '.')
    # correct for extinction:
    #correction = tools.extinction_correction(l, b, data[:,10])
    #q_gal = q_gal*correction
    #u_gal = u_gal*correction
    j = np.where(u_gal == np.max(u_gal))[0]
    #print(j, u_gal[j], l[j], b[j], data[j,10], data[j,4])
    #print(np.mean(u_gal), np.mean(data[:,4]))
    q_err = sq_gal  #*correction
    u_err = su_gal  #*correction

    #q_err = data[:,7]
    #u_err = data[:,9]

    p_gal = np.sqrt(q_gal**2 + u_gal**2)
    sigma = [data[:, 3], q_err, u_err]
    r = data[:, 10]
    pix_stars = hp.ang2pix(Nside, theta, phi)
    #print(pix_stars)
    #print(len(pix_stars), len(u_gal))
    return (p_gal, q_gal, u_gal, sigma, r, pix_stars)
示例#3
0
def main(planckfile, dustfile, tomofile, colnames, names, pol, res,\
        part='all'):
    """
    The main function of the program. Do all the calling to the functions used 
    to calculate the comparison between the Tomography data and Planck         
    polarisation data. Want to smooth to uK_cmb.                               
                                                                               
    Parameters:                                                                
    -----------                                                                
    - planckfile, string.   Name of the planck file to compare with.           
    - dustfile, string.     Name of the dust intensity file.                   
    - tomofile, string.     The name of the tomography file.                   
    - colnames, list.       List of the column names of the tomography file.   
    - names, list.          List with the column names in the smoothed planck  
                            maps, with polarisation first then dust intensity. 
    - pol, bool.            Which Stokes parameter to evaluate.                
                                                                               
    Return:                                                                    
    -------
    """

    # read smoothed planck maps.
    print('load planck 353GHz data')
    # read_smooth_maps(filename, name, shape)
    IQU_smaps = smooth.read_smooth_maps(planckfile, names[0], 3)
    dust_smap = smooth.read_smooth_maps(dustfile, names[1], 1)[0]
    T_smap = IQU_smaps[0]
    Q_smap = IQU_smaps[1]
    U_smap = IQU_smaps[2]

    Nside = hp.get_nside(T_smap)
    print('Using Nside={}'.format(Nside))

    #sys.exit()
    # load tomography data:
    data = load.load_tomographydata(tomofile, colnames)
    print('Data loaded, using Nside={}'.format(Nside))

    p, q, u, sigma, r_map, pix = load.pix2star_tomo(data,\
                                                    Nside, part)
    u = -u  # to Healpix convention
    mask = pix
    print(len(mask))
    # Modify length of submillimeter polarisation arrays:
    Ts = T_smap[mask]
    Qs = Q_smap[mask]
    Us = U_smap[mask]
    dust = dust_smap[mask]
    # modify the smoothing
    u_smap = smooth.smooth_tomo_map(u, mask, Nside, res)
    q_smap = smooth.smooth_tomo_map(q, mask, Nside, res)
    p_smap = smooth.smooth_tomo_map(p, mask, Nside, res)
    u = u_smap[mask]
    q = q_smap[mask]
    p = p_smap[mask]
    print('Tomography maps smoothed')
    #print(np.mean(q_smap[mask]), np.mean(dust_smap[mask]))
    dPsi = np.full(len(u), hp.UNSEEN)
    #sys.exit()

    l, b = tools.convert2galactic(data[:, 0], data[:, 1])
    lon = np.mean(l)
    lat = np.mean(b)
    print(lon, lat)

    # calculate Delta psi:
    print(len(Qs), len(q), len(Us), len(u))
    print('Calculate Delta psi:')
    psi = tools.delta_psi(Qs, q, Us, u)

    # Calculate ratio Ps/pv:
    unit1 = 287.45  # MJy/sr/Kcmb
    unit2 = unit1 * 1e-6
    print('Calculate Ps/pv:')
    Ps = np.sqrt(Qs**2 + Us**2)
    print('Ps/pv=', np.mean(Ps / p) * unit2, np.std(Ps / p) * unit2)
    print(np.mean(Ts / p) * unit2)
    print('--------')

    planck = [Qs, Us, dust]
    tomo = [q, u, sigma]
    return (planck, tomo, r_map, mask)
示例#4
0
def main(tomofile, colnames, planckfile, dustfile, Ppol=False, Qpol=False,\
        Upol=False, write=False, read=False, ud_grade=True, newNside=512, res=15):
    """
    The main function of the program. Do all the calling to the functions used
    to calculate the comparison between the Tomography data and Planck
    polarisation data. Want to smooth to uK_cmb.

    Parameters:
    -----------
    - tomofile, string.     The name of the tomography file.
    - colnames, list.       List of the column names of the tomography file.
    - planckfile, string.   Name of the planck file to compare with.
    - dustfile, string.     Name of the dust intensity file.

    Return:
    -------
    """

    data = load.load_tomographydata(tomofile, colnames)
    print(data[0, :])

    p_map, q_map, u_map, sigma, r_map, pix = load.tomo_map(data)

    u_map = -u_map
    mask = np.unique(pix)
    #print(q_map[mask]**2 + u_map[mask]**2)
    l, b = tools.convert2galactic(data[:, 0], data[:, 1])

    lon = np.mean(l)
    lat = np.mean(b)
    print(lon, lat)
    print('pixel size, arcmin:', hp.pixelfunc.nside2resol(2048, arcmin=True))
    print('pixel size, radian:', hp.pixelfunc.nside2resol(2048))
    #sys.exit()

    names = ['pqu_tomo', 'IQU_planck', 'I_dust']
    # write smoothed maps
    if write is True:
        # load planck
        print('load planck 353GHz data')
        T, P, Q, U = load.load_planck_map(planckfile, p=True)
        d353 = load.load_planck_map(dustfile)
        dust353 = tools.Krj2Kcmb(d353)
        T = T * 1e6
        P = P * 1e6
        Q = Q * 1e6
        U = U * 1e6
        # if ud_grade is true, need new_nside, smoothing resloution
        if ud_grade is True:
            Nside = newNside
            #p_map, q_map, u_map, sigma, r_map, pix = load.tomo_map(data, Nside=Nside)
            print(newNside, 'Down grade maps')
            new_maps = tools.ud_grade_maps([U, u_map],
                                           mask,
                                           new_Nside=newNside)

            hp.mollview(new_maps[0])
            hp.mollview(new_maps[1])
            plt.show()
        else:
            pass

        print('Write smoothed maps to file')
        sys.exit()
        smooth.Write_smooth_map([p_map, q_map, u_map, T, Q, U, dust353],\
                                ['tomo','IQU', 'dust'], Nside=Nside, res=res)
        # ['pqu_tomo', 'IQU_planck', 'I_dust'] used to be
        #Write_smooth_map([p_map], ['p_tomo2'], iterations=3)

        sys.exit()
    #
    # Read in  smoothed maps
    if read is True:
        print('Load smoothed maps')
        smaps = smooth.read_smooth_maps(names)
        if smaps[-1] == 'all':
            T_smap = smaps[0] * 1e6
            Q_smap = smaps[1] * 1e6
            U_smap = smaps[2] * 1e6
            p_smap_sph, q_smap_sph, u_smap_sph = smaps[3:
                                                       6]  # spherical harmonic
            dust_smap = smaps[-2] * 1e6

        elif smaps[-1] == 'planck':
            T_smap, Q_smap, U_smap = smaps[0:3]

        elif smaps[-1] == 'tomo':
            p_smap_sph, q_smap_sph, u_smap_sph = smaps[0:
                                                       3]  # spherical harmonic

        elif smaps[-1] == 'dust':
            dust_smap = smaps[0] * 1e6

        print('smoothed maps loaded')
        #full_smaps = [T_smap, Q_smap, U_smap]
        #print(np.shape(smaps))
        #print(np.mean(dust_smap[mask]), np.mean(U_smap[mask]))
        chi = (0.5 * np.arctan(U_smap[mask] / Q_smap[mask]))
        chiQ = np.pi / 4 - (0.5 * np.arccos(Q_smap[mask] / T_smap[mask]))
        chiU = (0.5 * np.arctan(U_smap[mask] / T_smap[mask]))
        x = 0.5 * np.arctan2(U_smap[mask], Q_smap[mask])
        print('--', np.mean(chi) * 180 / np.pi, np.mean(x) * 180 / np.pi)
        """
        plt.figure()
        plt.hist(chi, bins=50)
        plt.title(r'$\chi$')
        plt.savefig('chi.png')
        plt.figure()
        plt.hist(chiQ, bins=50)
        plt.title(r'$\chi_U$')
        plt.savefig('chiQ.png')
        plt.figure()
        plt.hist(chiU, bins=50)
        plt.title(r'$\chi_U$')
        plt.savefig('chiU.png')
        plt.figure()
        plt.hist(chi-chiQ, bins=50)
        plt.title(r'$\chi-\chi_Q$')
        plt.savefig('chi_diff_Q.png')
        plt.figure()
        plt.hist(chi-chiU, bins=50)
        plt.title(r'$\chi - \chi_U$')
        plt.savefig('chi_diff_U.png')
        plt.figure()
        plt.hist(chiQ-chiU, bins=50)
        plt.title(r'$\chi_Q - \chi_U$')
        plt.savefig('chi_diff_QU.png')
        sys.exit()
        """
    else:
        print('Use non smoothed maps')
        # load planck
        print('load planck 353GHz data')
        T, P, Q, U = load.load_planck_map(planckfile, p=True)
        d353 = load.load_planck_map(dustfile)
        dust353 = tools.Krj2Kcmb(d353) * 1e6
        T = T * 1e6
        P = P * 1e6
        Q = Q * 1e6
        U = U * 1e6

        #hp.mollview(p_map)

    #
    """
    Work with smoothed maps reduced to given area of Tomography data
    """

    if Ppol == True:
        print('-- P polarisation --')
        p_smap = smooth.smooth_tomo_map(p_map, mask)
        if read is True:
            full_IQU = [T_smap, Q_smap, U_smap]
            tot_res, frac_res, dust = tools.map_analysis_function(p_smap, T_smap,\
                                                            dust_smap, mask)

        else:
            full_IQU = [T, Q, U]
            tot_res, frac_res, dust = tools.map_analysis_function(p_map, T,\
                                                            dust353, mask)

        return (tot_res, frac_res, dust, lon, lat, full_IQU, mask, r_map)

    elif Qpol == True:
        print('-- Q polarisation --')
        q_smap = smooth.smooth_tomo_map(q_map, mask)
        if read is True:
            full_IQU = [T_smap, Q_smap, U_smap]
            tot_res, frac_res, dust = tools.map_analysis_function(q_smap, Q_smap,\
                                                            dust_smap, mask)
        else:
            full_IQU = [T, Q, U]
            tot_res, frac_res, dust = tools.map_analysis_function(q_map, Q,\
                                                            dust353, mask)

        return (tot_res, frac_res, dust, lon, lat, full_IQU, mask, r_map)

    elif Upol == True:
        print('-- U polarisation --')
        u_smap = smooth.smooth_tomo_map(u_map, mask)
        if read is True:
            full_IQU = [T_smap, Q_smap, U_smap]
            tot_res, frac_res, dust = tools.map_analysis_function(u_smap, U_smap,\
                                                            dust_smap, mask)

        else:
            full_IQU = [T, Q, U]
            tot_res, frac_res, dust = tools.map_analysis_function(u_map, U,\
                                                            dust353, mask)
        #hp.mollview(tot_res[1])
        #plt.show()
        return (tot_res, frac_res, dust, lon, lat, full_IQU, mask, r_map)
示例#5
0
def main(planckfile, dustfile, tomofile, colnames, names, pol, res,\
         part='all', distcut=None):
    """
    The main function of the program. Do all the calling to the functions used
    to calculate the comparison between the Tomography data and Planck
    polarisation data. Want to smooth to uK_cmb.

    Parameters:
    -----------
    - planckfile, string.   Name of the planck file to compare with.
    - dustfile, string.     Name of the dust intensity file.
    - tomofile, string.     The name of the tomography file.
    - colnames, list.       List of the column names of the tomography file.
    - names, list.          List with the column names in the smoothed planck
                            maps, with polarisation first then dust intensity.
    - pol, bool.            Which Stokes parameter to evaluate.

    Return:
    -------
    """
    if (pol == 'P') or (pol == 'Q') or (pol == 'U'):
        polarisation = True
    elif (pol == 'p') or (pol == 'q') or (pol == 'u') or (pol == 'qu'):
        polarisation = True
    else:
        polarisation = False

    print(pol, polarisation)

    if distcut is None:
        distcut = 900

    if (polarisation is True):
        # read smoothed planck maps. Units = uKcmb
        print('load planck 353GHz data')
        # read_smooth_maps(filename, name, shape)
        if len(names) == 3:
            IQU_smaps = smooth.read_smooth_maps(planckfile, names, 3)
        else:
            IQU_smaps = smooth.read_smooth_maps(planckfile, names[0], 3)
        #dust_smap = smooth.read_smooth_maps(dustfile, names[1], 1)[0]
        T_smap = IQU_smaps[0]
        Q_smap = IQU_smaps[1]
        U_smap = IQU_smaps[2]
        Nside = hp.get_nside(T_smap)

        band = planckfile.split('_')[2]
        if len(band) > 3:
            band = band[:3]
            if band == '15a':
                band = '353'

        if int(band) < 353:
            # load cmb intensity and subtract form polarization maps
            cmbfile = 'Data/IQU_Nside{}_CMB_10arcmin.h5'.format(Nside)
            cmbmaps = tools.Read_H5(cmbfile, 'IQU') * 1e6
            Q_cmb = cmbmaps[1, :]
            U_cmb = cmbmaps[1, :]
            Q_smap = Q_smap - Q_cmb
            U_smap = U_smap - U_cmb

        # load tomography data:
        data = load.load_tomographydata(tomofile, colnames)
        print('Data loaded, using Nside={}'.format(Nside))

        p_map, q_map, u_map, sigma, r_map, pix =\
                    load.tomo_map(data, Nside, part=part, distcut=distcut)
        u_map = -u_map  # to Healpix convention
        mask = np.unique(pix)

        u_smap = smooth.smooth_tomo_map(u_map, mask, Nside, res)
        q_smap = smooth.smooth_tomo_map(q_map, mask, Nside, res)
        p_smap = smooth.smooth_tomo_map(p_map, mask, Nside, res)
        print('Tomography maps smoothed')
        print(np.mean(q_smap[mask]), np.mean(Q_smap[mask]))
        dPsi = np.full(len(u_map), hp.UNSEEN)
        #sys.exit()

        l, b = tools.convert2galactic(data[:, 0], data[:, 1])
        theta, phi = hp.pix2ang(Nside, pix)
        lon = np.mean(phi) * 180 / np.pi
        lat = 90 - np.mean(theta) * 180 / np.pi
        print(lon, lat)

        x = 0.5 * np.arctan2(U_smap[mask], Q_smap[mask])
        x_v = 0.5 * np.arctan2(u_smap[mask], q_smap[mask])

        print('-- Q,U polarisation --')
        print('Return: tomo, planck, dust, mask, dpsi, fullIQU, [lon,lat], r')
        psi, psi_v, psi_s = tools.delta_psi(Q_smap[mask], q_smap[mask],\
                                            U_smap[mask], u_smap[mask])
        #, plot=True, name=Nside
        dPsi[mask] = psi  # deg
        full_IQU = [T_smap, Q_smap, U_smap]  # uKcmb
        tomo = [q_smap, u_smap, p_smap, sigma[1], sigma[2], sigma[0]]  # .
        planck = [Q_smap, U_smap]  # uKcmb
        coord = [lon, lat, l, b]  # [deg,rad]
        angles = [dPsi[mask], psi_v, psi_s, sigma[3]]  # deg
        return (tomo, planck, coord, full_IQU, mask, r_map, angles)
示例#6
0
def main(planckfile, dustfile, tomofile, colnames, names, pol, res,\
         part='all', distcut=None):
    """
    The main function of the program. Do all the calling to the functions used
    to calculate the comparison between the Tomography data and Planck
    polarisation data. Want to smooth to uK_cmb.

    Parameters:
    -----------
    - planckfile, string.   Name of the planck file to compare with.
    - dustfile, string.     Name of the dust intensity file.
    - tomofile, string.     The name of the tomography file.
    - colnames, list.       List of the column names of the tomography file.
    - names, list.          List with the column names in the smoothed planck
                            maps, with polarisation first then dust intensity.
    - pol, bool.            Which Stokes parameter to evaluate.

    Return:
    -------
    """
    if (pol == 'P') or (pol == 'Q') or (pol == 'U'):
        polarisation = True
    elif (pol == 'p') or (pol == 'q') or (pol == 'u') or (pol == 'qu'):
        polarisation = True
    else:
        polarisation = False

    print(pol, polarisation)

    if distcut is None:
        distcut = 900

    if (polarisation is True):
        # read smoothed planck maps.
        print('load planck 353GHz data')
        # read_smooth_maps(filename, name, shape)
        IQU_smaps = smooth.read_smooth_maps(planckfile, names[0], 3)
        dust_smap = smooth.read_smooth_maps(dustfile, names[1], 1)[0]
        T_smap = IQU_smaps[0]
        Q_smap = IQU_smaps[1]
        U_smap = IQU_smaps[2]

        Nside = hp.get_nside(T_smap)
        print('Using Nside={}'.format(Nside))
        print(planckfile)
        band = planckfile.split('_')[2]
        if len(band) > 3:
            band = band[:3]
            if band == '15a':
                band = '353'
        print(band)

        if int(band) < 353:
            # load cmb intensity and subtract form polarization maps
            cmbfile = 'Data/IQU_Nside{}_CMB_10arcmin.h5'.format(Nside)
            cmbmaps = tools.Read_H5(cmbfile, 'IQU') * 1e6
            Q_cmb = cmbmaps[1, :]
            U_cmb = cmbmaps[1, :]
            Q_smap = Q_smap - Q_cmb
            U_smap = U_smap - U_cmb

        print(np.mean(Q_smap), np.mean(U_smap))
        #sys.exit()
        # load tomography data:
        data = load.load_tomographydata(tomofile, colnames)
        print('Data loaded, using Nside={}'.format(Nside))

        p_map, q_map, u_map, sigma, r_map, pix =\
                    load.tomo_map(data, Nside, part=part, distcut=distcut)
        u_map = -u_map  # to Healpix convention
        mask = np.unique(pix)
        print(len(mask))
        u_smap = smooth.smooth_tomo_map(u_map, mask, Nside, res)
        q_smap = smooth.smooth_tomo_map(q_map, mask, Nside, res)
        p_smap = smooth.smooth_tomo_map(p_map, mask, Nside, res)
        print('Tomography maps smoothed')
        print(np.mean(q_smap[mask]), np.mean(dust_smap[mask]),
              np.mean(Q_smap[mask]))
        dPsi = np.full(len(u_map), hp.UNSEEN)
        #sys.exit()

        l, b = tools.convert2galactic(data[:, 0], data[:, 1])
        theta, phi = hp.pix2ang(Nside, pix)
        lon = np.mean(phi) * 180 / np.pi
        lat = 90 - np.mean(theta) * 180 / np.pi
        print(lon, lat)

        x = 0.5 * np.arctan2(U_smap[mask], Q_smap[mask])
        #x[x<0.] += np.pi
        #x[x>=np.pi] -= np.pi

        x_v = 0.5 * np.arctan2(u_smap[mask], q_smap[mask])
        #psi_v[psi_v<0] += np.pi
        #psi_v[psi_v>=np.pi] -= np.pi
        print('Polarization angles of planck (mean, min, max) [deg]:')
        print(
            np.mean(x) * 180 / np.pi,
            np.min(x) * 180 / np.pi,
            np.max(x) * 180 / np.pi)
        print(
            np.mean(x_v) * 180 / np.pi,
            np.min(x_v) * 180 / np.pi,
            np.max(x_v) * 180 / np.pi)
        #print(np.mean(x+np.pi/2-psi_v))
        if (pol == 'P') or (pol == 'p'):
            print('-- P polarisation --')

            psi, psi_v, psi_s = tools.delta_psi(Q_smap[mask], q_smap[mask],\
                                                U_smap[mask],u_smap[mask])\
            #, plot=True, name='smooth2')

            dPsi[mask] = psi
            full_IQU = [T_smap, Q_smap, U_smap]
            tot_res, frac_res, dust = tools.map_analysis_function(p_smap, T_smap,\
                                                            dust_smap, mask, Nside)

            return (tot_res, frac_res, dust, [lon, lat], full_IQU, mask, r_map,
                    dPsi)

        elif (pol == 'Q') or (pol == 'q'):
            print('-- Q polarisation --')
            psi, psi_v, psi_s = tools.delta_psi(Q_smap[mask], q_smap[mask], U_smap[mask],\
                                    u_smap[mask], plot=True)

            dPsi[mask] = psi
            full_IQU = [T_smap, Q_smap, U_smap]
            tot_res, frac_res, dust = tools.map_analysis_function(q_smap, Q_smap,\
                                                            dust_smap, mask, Nside)
            return (tot_res, frac_res, dust, [lon, lat], full_IQU, mask, r_map,
                    dPsi)

        elif (pol == 'U') or (pol == 'u'):
            print('-- U polarisation --')
            print(len(u_smap))
            psi, psi_v, psi_s = tools.delta_psi(Q_smap[mask], q_smap[mask],\
                                                U_smap[mask],u_smap[mask], plot=True)

            dPsi[mask] = psi
            full_IQU = [T_smap, Q_smap, U_smap]
            tot_res, frac_res, dust = tools.map_analysis_function(u_smap, U_smap,\
                                                            dust_smap, mask, Nside)

            return (tot_res, frac_res, dust, [lon, lat], full_IQU, mask, r_map,
                    dPsi)

        elif (pol == 'QU') or (pol == 'qu'):
            print('-- Q,U polarisation --')
            print(
                'Return: tomo, planck, dust, mask, dpsi, fullIQU, [lon,lat], r'
            )
            psi, psi_v, psi_s = tools.delta_psi(Q_smap[mask], q_smap[mask],\
                                                U_smap[mask], u_smap[mask])
            #, plot=True, name=Nside)

            dPsi[mask] = psi
            full_IQU = [T_smap, Q_smap, U_smap]
            tomo = [q_smap, u_smap, p_smap, sigma[1], sigma[2], sigma[0]]
            planck = [Q_smap, U_smap]
            coord = [lon, lat]
            angles = [dPsi[mask], psi_v, psi_s, sigma[3]]
            return (tomo, planck, dust_smap, coord, full_IQU, mask, r_map,
                    angles)

    else:
        # use unsmoothe maps
        print('Use non smoothed maps')
        # load planck
        print('load planck 353GHz data')

        #T, P, Q, U = load.load_planck_map(planckfile, p=True)
        data = load.load_planck_map(planckfile, p=True)
        d353 = load.load_planck_map(dustfile)
        sys.exit()
        dust353 = tools.Krj2Kcmb(d353) * 1e6
        T = T * 1e6
        P = P * 1e6
        Q = Q * 1e6
        U = U * 1e6
        Nside = hp.get_nside(T_smap)

        data = load.load_tomographydata(tomofile, colnames)
        p_map, q_map, u_map, sigma, r_map, pix = load.tomo_map(data, Nside)
        u_map = -u_map  # to Healpix convention
        mask = np.unique(pix)

        l, b = tools.convert2galactic(data[:, 0], data[:, 1])
        lon = np.mean(l)
        lat = np.mean(b)

        dPsi = np.full(len(u_map), hp.UNSEEN)

        if Ppol == True:
            print('-- P polarisation --')
            psi = tools.delta_psi(Q[mask], q_map[mask], U[mask],\
                                    u_map[mask], plot=True)
            dPsi[mask] = psi
            full_IQU = [T, Q, U]
            tot_res, frac_res, dust = tools.map_analysis_function(p_map, T,\
                                                            dust353, mask)
            return (tot_res, frac_res, dust, [lon, lat], full_IQU, mask, r_map,
                    dPsi)

        elif Qpol == True:
            print('-- Q polarisation --')
            psi = tools.delta_psi(Q[mask], q_map[mask], U[mask],\
                                    u_map[mask], plot=True)
            dPsi[mask] = psi
            full_IQU = [T, Q, U]
            tot_res, frac_res, dust = tools.map_analysis_function(q_map, Q,\
                                                            dust353, mask)
            return (tot_res, frac_res, dust, [lon, lat], full_IQU, mask, r_map,
                    dPsi)

        if Upol == True:
            print('-- U polarisation --')
            psi = tools.delta_psi(Q[mask], q_map[mask], U[mask],\
                                    u_map[mask], plot=True)
            dPsi[mask] = psi
            full_IQU = [T, Q, U]
            tot_res, frac_res, dust = tools.map_analysis_function(u_map, U,\
                                                            dust353, mask)
            return (tot_res, frac_res, dust, [lon, lat], full_IQU, mask, r_map,
                    dPsi)