Example #1
0
def create_acquisition_operator_REC(pointing, parameters):
    s = QubicScene(nside=parameters['nside'], kind='IQU')
    ## number of sub frequencies to build the TOD
    Nf = int(parameters['nf_sub_build'])
    band = parameters['band']
    relative_bandwidth = parameters['relative_bandwidth']
    Nbfreq_in, nus_edge_in, nus_in, deltas_in, Delta_in, Nbbands_in = compute_freq(
        band, relative_bandwidth, Nf)
    # Polychromatic instrument model
    q = QubicMultibandInstrument(
        filter_nus=nus_in * 1e9,
        filter_relative_bandwidths=deltas_in / nus_in,
        #TD = parameters['TD'],
        ripples=parameters['ripples']
    )  # The peaks of the synthesized beam are modeled with "ripples"
    ### Operators for Maps Reconstruction ################################################
    Nsb = parameters['nf_sub_rec']
    Nbfreq, nus_edge, nus, deltas, Delta, Nbbands = compute_freq(
        band, relative_bandwidth, Nsb)
    arec = QubicMultibandAcquisition(
        q,
        pointing,
        s,
        nus_edge,
        effective_duration=parameters['effective_duration'])
    ######################################################################################
    return arec
Example #2
0
def create_acquisition_operator_REC(pointing,
                                    d,
                                    nf_sub_rec,
                                    verbose=False,
                                    instrument=None):
    # scene
    s = qubic.QubicScene(d)
    if d['nf_sub'] == 1:
        if verbose:
            print('Making a QubicInstrument.')
        q = qubic.QubicInstrument(d)
        # one subfreq for recons
        _, nus_edge, _, _, _, _ = qubic.compute_freq(
            d['filter_nu'] / 1e9, nf_sub_rec, d['filter_relative_bandwidth'])
        arec = qubic.QubicAcquisition(q, pointing, s, d)

        return arec
    else:
        if instrument is None:
            if verbose:
                print('Making a QubicMultibandInstrument.')
            q = qubic.QubicMultibandInstrument(d)
        else:
            q = instrument
        # number of sub frequencies for reconstruction
        _, nus_edge, _, _, _, _ = qubic.compute_freq(
            d['filter_nu'] / 1e9, nf_sub_rec, d['filter_relative_bandwidth'])
        # Operator for Maps Reconstruction
        arec = qubic.QubicMultibandAcquisition(q, pointing, s, d, nus_edge)
        return arec
Example #3
0
def foreground_signal(dictionaries, sky_configuration, sky = 'T',
	seed = None, verbose = False):
	
	"""
	Averaging manually the maps into a band if nf_sub != nfrecon, otherwise, foreground are computed 
		in nf_recon sub-bands


	Assumes . dictionaries[:]['nf_sub'] == dictionaries[:]['nf_recon']
			. all regions and frequencies uses same sky configuration. 

	Parameters: 
		dictionaries: 
			array of dictionaries. #dicts = #regions + #bands_needed
		sky_configuration:
			dictionary with PySM format to build foregrounds
		sky: 
			'T' or 'P' for temperature or polarization study
		seed: 
			fix seed for simulations
	"""

	# Generate foregrounds
	##### QubicSkySim instanciation
	seed = seed

	QubicSkyObject = []
	foreground_maps = np.zeros((len(dictionaries), dictionaries[0]['nf_recon'], 12 * dictionaries[0]['nside'] ** 2, 3))
	for ic, idict in enumerate(dictionaries):

		QubicSkyObject.append(qss.Qubic_sky(sky_configuration, idict))

		if idict['nf_sub'] != idict['nf_recon']:
			_, nus_edge_in, nus_in, _, _, _ = qubic.compute_freq(idict['filter_nu'] / 1e9, 
														   idict['nf_sub'],
														   idict['filter_relative_bandwidth'])
			_, nus_edge_out, nus_out, _, _, _ = qubic.compute_freq(idict['filter_nu'] / 1e9,  
																   idict['nf_recon'],
																   idict['filter_relative_bandwidth'])
	
			if verbose: print('Computing maps averaging')
			# Generate convolved sky of dust without noise 
			dust_map_in = QubicSkyObject[ic].get_fullsky_convolved_maps(FWHMdeg = None, verbose = False)
			if verbose: print('=== Done {} map ===='.format(idict['filter_nu'] / 1e9, regions[ic//len(regions)][0]))
		
			for i in range(idict['nf_recon']):
				inband = (nus_in > nus_edge_out[i]) & (nus_in < nus_edge_out[i + 1])
				foreground_maps[ic, ...] = np.mean(dust_map_in[inband, ...], axis=0)    

		elif idict['nf_sub'] == idict['nf_recon']:
			# Now averaging maps into reconstruction sub-bands maps
			foreground_maps[ic] = QubicSkyObject[ic].get_fullsky_convolved_maps(FWHMdeg = None, verbose = False)

	return foreground_maps
Example #4
0
def create_input_sky(d, skypars):
    Nf = int(d['nf_sub'])
    band = d['filter_nu'] / 1e9
    filter_relative_bandwidth = d['filter_relative_bandwidth']
    _, _, nus_in, _, _, Nbbands_in = qubic.compute_freq(
        band, filter_relative_bandwidth, Nf)
    # seed
    if d['seed']:
        np.random.seed(d['seed'])
        # Generate the input CMB map
        sp = qubic.read_spectra(skypars['r'])
        cmb = np.array(
            hp.synfast(sp, d['nside'], new=True, pixwin=True, verbose=False)).T
        # Generate the dust map
        coef = skypars['dust_coeff']
        ell = np.arange(1, 3 * d['nside'])
        fact = (ell * (ell + 1)) / (2 * np.pi)
        spectra_dust = [
            np.zeros(len(ell)), coef * (ell / 80.)**(-0.42) / (fact * 0.52),
            coef * (ell / 80.)**(-0.42) / fact,
            np.zeros(len(ell))
        ]
        dust = np.array(
            hp.synfast(spectra_dust,
                       d['nside'],
                       new=True,
                       pixwin=True,
                       verbose=False)).T

        # Combine CMB and dust. As output we have N 3-component maps of sky.
        x0 = cmb_plus_dust(cmb, dust, Nbbands_in, nus_in, d['kind'])
        return x0
Example #5
0
    def __init__(self, skyconfig, d):

        Nf = d['nf_sub']
        band = d['filter_nu'] / 1e9
        filter_relative_bandwidth = d['filter_relative_bandwidth']
        _, _, central_nus, _, _, _ = qubic.compute_freq(
            band, Nf, filter_relative_bandwidth)
        names = [np.str(np.round(cn, 2)) for cn in central_nus]
        names = [n.replace('.', 'p') for n in names]
        instrument = pysm.Instrument({
            'nside': d['nside'],
            'frequencies': central_nus,  # GHz
            'use_smoothing': False,
            'beams': np.ones_like(central_nus),  # arcmin 
            'add_noise': False,
            'noise_seed': 0,
            'sens_I': np.ones_like(central_nus),
            'sens_P': np.ones_like(central_nus),
            'use_bandpass': False,
            'channel_names': names,
            'channels': np.ones_like(central_nus),
            'output_units': 'uK_RJ',
            'output_directory': "./",
            'output_prefix': "qubic",
            'pixel_indices': None
        })

        sky.__init__(self, skyconfig, d, instrument)
Example #6
0
    def __init__(self, skyconfig, d, output_directory="./", output_prefix="qubic_sky"):
        self.Nfin = int(d['nf_sub'])
        self.Nfout = int(d['nf_recon'])
        self.filter_relative_bandwidth = d['filter_relative_bandwidth']
        self.filter_nu = int(d['filter_nu'] / 1e9)
        _, nus_edge_in, central_nus, deltas, _, _ = qubic.compute_freq(self.filter_nu,
                                                                       self.Nfin,
                                                                       self.filter_relative_bandwidth)
        self.qubic_central_nus = central_nus
        # THESE LINES HAVE TO BE CONFIRMED/IMPROVED in future since fwhm = lambda / (P Delta_x)
        # is an approximation for the resolution
        if d['config'] == 'FI':
            self.fi2td = 1
        elif d['config'] == 'TD':
            P_FI = 22  # horns in the largest baseline in the FI
            P_TD = 8  # horns in the largest baseline in the TD
            self.fi2td = (P_FI - 1) / (P_TD - 1)
        #
        self.qubic_resolution_nus = d['synthbeam_peak150_fwhm'] * 150 / self.qubic_central_nus * self.fi2td
        self.qubic_channels_names = ["{:.3s}".format(str(i)) + "_GHz" for i in self.qubic_central_nus]

        instrument = {'nside': d['nside'], 'frequencies': central_nus,  # GHz
                      'use_smoothing': False, 'beams': np.ones_like(central_nus),  # arcmin
                      'add_noise': False,  # If True `sens_I` and `sens_Q` are required
                      'noise_seed': 0.,  # Not used if `add_noise` is False
                      'sens_I': np.ones_like(central_nus),  # Not used if `add_noise` is False
                      'sens_P': np.ones_like(central_nus),  # Not used if `add_noise` is False
                      'use_bandpass': False,  # If True pass banpasses  with the key `channels`
                      'channel_names': self.qubic_channels_names,  # np.ones_like(central_nus),
                      'channels': np.ones_like(central_nus), 'output_units': 'uK_RJ',
                      'output_directory': output_directory, 'output_prefix': output_prefix,
                      'pixel_indices': None}

        sky.__init__(self, skyconfig, d, instrument, output_directory, output_prefix)
Example #7
0
def create_acquisition_operator_REC(pointing, d, nf_sub_rec):
    # Polychromatic instrument model
    q = qubic.QubicMultibandInstrument(d)
    # scene
    s = qubic.QubicScene(d)
    # number of sub frequencies for reconstruction
    _, nus_edge, _, _, _, _ = qubic.compute_freq(
        d['filter_nu'] / 1e9, nf_sub_rec, d['filter_relative_bandwidth'])
    # Operator for Maps Reconstruction
    arec = qubic.QubicMultibandAcquisition(q, pointing, s, d, nus_edge)
    return arec
Example #8
0
def reconstruct_maps(TOD, d, pointing, nf_sub_rec, x0=None):
    _, nus_edge, nus, _, _, _ = qubic.compute_freq(
        d['filter_nu'] / 1e9, nf_sub_rec, d['filter_relative_bandwidth'])
    arec = create_acquisition_operator_REC(pointing, d, nf_sub_rec)
    cov = arec.get_coverage()
    maps_recon = arec.tod2map(TOD, cov=cov, tol=d['tol'], maxiter=1500)
    if x0 is None:
        return maps_recon, cov, nus, nus_edge
    else:
        _, maps_convolved = arec.get_observation(x0)
        maps_convolved = np.array(maps_convolved)
        return maps_recon, cov, nus, nus_edge, maps_convolved
Example #9
0
 def get_simple_sky_map(self):
     """
     Create as many skies as the number of input frequencies. Instrumental
     effects are not considered. For this use the `get_sky_map` method.
     Return a vector of shape (number_of_input_subfrequencies, npix, 3)
     """
     sky_signal = self.sky.signal()
     Nf = int(self.dictionary['nf_sub'])
     band = self.dictionary['filter_nu'] / 1e9
     filter_relative_bandwidth = self.dictionary['filter_relative_bandwidth']
     _, _, nus_in, _, _, Nbbands_in = qubic.compute_freq(band, Nf, filter_relative_bandwidth)
     return np.rollaxis(sky_signal(nu=nus_in), 2, 1)
Example #10
0
def create_acquisition_operator_TOD(pointing, d):
    # Polychromatic instrument model
    q = qubic.QubicMultibandInstrument(d)
    # scene
    s = qubic.QubicScene(d)
    # number of sub frequencies to build the TOD
    _, nus_edge_in, _, _, _, _ = qubic.compute_freq(
        d['filter_nu'] / 1e9, d['filter_relative_bandwidth'],
        d['nf_sub'])  # Multiband instrument model
    # Multi-band acquisition model for TOD fabrication
    atod = qubic.QubicMultibandAcquisition(q, pointing, s, d, nus_edge_in)
    return atod
Example #11
0
    def get_simple_sky_map(self):
        """
        Create as many skies as the number of input frequencies.
        Instrumental effects are not considered.
        Return a vector of shape (number_of_input_subfrequencies, npix, 3)
        """
        _, nus_edge, nus_in, _, _, Nbbands_in = qubic.compute_freq(self.filter_nu, self.Nfin,
                                                                   self.filter_relative_bandwidth)

        sky = np.zeros((self.Nfin, self.npix, 3))

        ##### This is the old code by JCH - It has been replaced by what Edgar Jaber has proposed
        ##### see his presentation on Git: qubic/scripts/ComponentSeparation/InternshipJaber/teleconf_03122020.pdf
        # for i in range(Nf):
        #     # ###################### This is puzzling part here: ############################
        #     # # See Issue on PySM Git: https://github.com/healpy/pysm/issues/49
        #     # ###############################################################################
        #     # # #### THIS IS WHAT WOULD MAKE SENSE BUT DOES NOT WORK ~ 5% on maps w.r.t. input
        #     # # nfreqinteg = 5
        #     # # nus = np.linspace(nus_edge[i], nus_edge[i + 1], nfreqinteg)
        #     # # freqs = utils.check_freq_input(nus)
        #     # # convert_to_uK_RJ = (np.ones(len(freqs), dtype=np.double) * u.uK_CMB).to_value(
        #     # # u.uK_RJ, equivalencies=u.cmb_equivalencies(freqs))
        #     # # #print('Convert_to_uK_RJ :',convert_to_uK_RJ)
        #     # # weights = np.ones(nfreqinteg) * convert_to_uK_RJ
        #     # ###############################################################################
        #     # ###### Works OK but not clear why...
        #     # ###############################################################################
        #     # nfreqinteg = 5
        #     # nus = np.linspace(nus_edge[i], nus_edge[i + 1], nfreqinteg)
        #     # filter_uK_CMB = np.ones(len(nus), dtype=np.double)
        #     # filter_uK_CMB_normalized = utils.normalize_weights(nus, filter_uK_CMB)
        #     # weights = 1. / filter_uK_CMB_normalized
        #     # ###############################################################################

        #     # ### Integrate through band using filter shape defined in weights
        #     # themaps_iqu = self.sky.get_emission(nus * u.GHz, weights=weights)
        #     # sky[i, :, :] = np.array(themaps_iqu.to(u.uK_CMB, equivalencies=u.cmb_equivalencies(nus_in[i] * u.GHz))).T
        #     # ratio = np.mean(self.input_cmb_maps[0,:]/sky[i,:,0])
        #     # print('Ratio to initial: ',ratio)

        # #### Here is the new code from Edgar Jaber
        for i in range(self.Nfin):
            nfreqinteg = 5
            freqs = np.linspace(nus_edge[i], nus_edge[i + 1], nfreqinteg)
            weights = np.ones(nfreqinteg)
            sky[i, :, :] = (
                    self.sky.get_emission(freqs * u.GHz, weights) * utils.bandpass_unit_conversion(freqs * u.GHz,
                                                                                                   weights,
                                                                                                   u.uK_CMB)).T

        return sky
Example #12
0
def get_corrections(nf_sub, nf_recon, band=150, relative_bandwidth=0.25):
    """
    The reconstructed subbands have different widths.
    Here, we compute the corrections you can applied to
    the variances and covariances to take this into account.

    Parameters
    ----------
    nf_sub : int
        Number of input subbands
    nf_recon : int
        Number of reconstructed subbands
    band : int
        QUBIC frequency band, in GHz. 150 by default
        Typical values: 150, 220.
    relative_bandwidth : float
        Ratio of the difference between the edges of the
        frequency band over the average frequency of the band
        Typical value: 0.25

    Returns
    ----------
    corrections : list
        Correction coefficients for each subband.
    correction_mat : array of shape (3xnf_recon, 3xnf_recon)
        Matrix containing the corrections.
        It can be multiplied term by term to a covariance matrix.

    """
    nb = nf_sub // nf_recon  # Number of input subbands in each reconstructed subband

    _, nus_edge, nus, deltas, Delta, _ = qubic.compute_freq(band, nf_sub, relative_bandwidth)

    corrections = []
    for isub in range(nf_recon):
        # Compute wide of the sub-band
        sum_delta_i = deltas[isub * nb: isub * nb + nb].sum()
        corrections.append(Delta / sum_delta_i)

    correction_mat = np.empty((3 * nf_recon, 3 * nf_recon))
    for i in range(3 * nf_recon):
        for j in range(3 * nf_recon):
            freq_i = i // nf_recon
            freq_j = j // nf_recon
            sum_delta_i = deltas[freq_i * nb: freq_i * nb + nb].sum()
            sum_delta_j = deltas[freq_j * nb: freq_j * nb + nb].sum()
            correction_mat[i, j] = Delta / np.sqrt(sum_delta_i * sum_delta_j)

    return corrections, correction_mat
Example #13
0
 def get_simple_sky_map(self):
     """
     Create as many skies as the number of the qubic sub-frequencies. 
     Instrumental effects are not considered. For this purpose use the 
     `get_sky_map` method.
     Return a vector of shape (number_of_input_subfrequencies, npix, 3)
     """
     sky_signal = self.sky.signal()
     Nf = self.dictionary['nf_sub']
     band = self.dictionary['filter_nu'] / 1e9
     filter_relative_bandwidth = self.dictionary[
         'filter_relative_bandwidth']
     _, _, central_nus, _, _, _ = qubic.compute_freq(
         band, filter_relative_bandwidth, Nf)
     return np.rollaxis(sky_signal(nu=central_nus), 2, 1)
Example #14
0
def reconstruct_maps(TOD, parameters, pointing, x0=None):
    band = parameters['band']
    relative_bandwidth = parameters['relative_bandwidth']
    Nsb = int(parameters['nf_sub_rec'])
    Nbfreq, nus_edge, nus, deltas, Delta, Nbbands = compute_freq(
        band, relative_bandwidth, Nsb)
    arec = create_acquisition_operator_REC(pointing, parameters)
    maps_recon = arec.tod2map(TOD, tol=parameters['tol'], maxiter=100000)
    cov = arec.get_coverage()
    if x0 is None:
        return maps_recon, cov, nus, nus_edge
    else:
        TOD_useless, maps_convolved = arec.get_observation(x0)
        TOD_useless = 0
        maps_convolved = np.array(maps_convolved)
        return maps_recon, cov, nus, nus_edge, maps_convolved
Example #15
0
def reconstruct_maps(TOD, d, pointing, nf_sub_rec, x0=None):
    _, nus_edge, nus, _, _, _ = qubic.compute_freq(d['filter_nu'] / 1e9, nf_sub_rec, d['filter_relative_bandwidth'])
    arec = create_acquisition_operator_REC(pointing, d, nf_sub_rec)
    cov = arec.get_coverage()
    maps_recon, nit, error = arec.tod2map(TOD, d, cov=cov)
    if not d['verbose']:
        print('niterations = {}, error = {}'.format(nit, error))
    if x0 is None:
        return maps_recon, cov, nus, nus_edge
    else:
        if d['nf_sub'] == 1:
            _, maps_convolved = arec.get_observation(x0[0], noiseless = d['noiseless'])
        else:
            _, maps_convolved = arec.get_observation(x0, noiseless = d['noiseless'])
        maps_convolved = np.array(maps_convolved)
        return maps_recon, cov, nus, nus_edge, maps_convolved
Example #16
0
def get_sub_freqs_and_resolutions(dico_fast_simulator):
    """
    Give the frequency sub-bands and corresponding angular resolutions around f = 150 or 220 GHz.

    :param dico_fast_simulator: instrument dictionary containing frequency band and nbr of sub-bands wanted
    :return: Tuple (freqs, fwhms) containing the list of the central frequencies
        and the list of resolutions (in degrees).
    """
    band = dico_fast_simulator['filter_nu'] / 1e9
    n = int(dico_fast_simulator['nf_recon'])
    filter_relative_bandwidth = dico_fast_simulator[
        'filter_relative_bandwidth']
    _, _, nus_in, _, _, _ = qubic.compute_freq(
        band, Nfreq=n, relative_bandwidth=filter_relative_bandwidth)
    # nus_in are in GHz so we use inverse scaling of resolution with frequency
    # we know the fwhm at 150 GHz so the factor is 150 / (target frequency)
    return nus_in, dico_fast_simulator['synthbeam_peak150_fwhm'] * 150 / nus_in
Example #17
0
def get_tod(d, p, x0):
    # Polychromatic instrument model
    q = qubic.QubicMultibandInstrument(d)

    # Scene
    s = qubic.QubicScene(d)

    # Number of sub frequencies to build the TOD
    _, nus_edge_in, _, _, _, _ = qubic.compute_freq(
        d['filter_nu'] / 1e9, d['filter_relative_bandwidth'], d['nf_sub'])

    # Multi-band acquisition operator
    a = qubic.QubicMultibandAcquisition(q, p, s, d, nus_edge_in)

    tod, _ = a.get_observation(x0, noiseless=True)

    return q, tod
Example #18
0
def make_covTD(d):
	"""
	Usually coverage map is provided in a separate file. But if not the case, this method can compute a coverage map
	Parameters:
	d: Qubic dictionary
	Return:
	cov: coverage map in a.QubicMultibandAcquisition shape (nfreq, npix).
	"""

	pointing = qubic.get_pointing(d)
	q= qubic.QubicMultibandInstrument(d)
	s= qubic.QubicScene(d)
	nf_sub_rec = d['nf_recon']
	_, nus_edge, nus, _, _, _ = qubic.compute_freq(d['filter_nu'] / 1e9, 
												   nf_sub_rec, d['filter_relative_bandwidth'])
	arec = qubic.QubicMultibandAcquisition(q, pointing, s, d, nus_edge)
	cov = arec.get_coverage()
	return cov
Example #19
0
def create_input_sky(d, skypars):
    """

    Parameters
    ----------
    d : file .dict
    skypars : dictionary
        Contains the dust coeff and r

    Returns
    -------
    x0 : a sky with 3 components I, Q, U
    """
    Nf = int(d['nf_sub'])
    band = d['filter_nu'] / 1e9
    filter_relative_bandwidth = d['filter_relative_bandwidth']
    _, _, nus_in, _, _, Nbbands_in = qubic.compute_freq(
        band, Nf, filter_relative_bandwidth)
    # seed
    if d['seed']:
        np.random.seed(d['seed'])
        # Generate the input CMB map
        sp = qubic.read_spectra(skypars['r'])
        cmb = np.array(
            hp.synfast(sp, d['nside'], new=True, pixwin=True, verbose=False)).T
        # Generate the dust map
        ell = np.arange(1, 3 * d['nside'])
        spectra_dust = dust_spectra(ell, skypars)
        # coef = skypars['dust_coeff']
        # fact = (ell * (ell + 1)) / (2 * np.pi)
        # spectra_dust = [np.zeros(len(ell)),
        #                 coef * (ell / 80.) ** (-0.42) / (fact * 0.52),
        #                 coef * (ell / 80.) ** (-0.42) / fact,
        #                 np.zeros(len(ell))]
        dust = np.array(
            hp.synfast(spectra_dust,
                       d['nside'],
                       new=True,
                       pixwin=True,
                       verbose=False)).T

        # Combine CMB and dust. As output we have N 3-component maps of sky.
        x0 = cmb_plus_dust(cmb, dust, Nbbands_in, nus_in, d['kind'])
        return x0
Example #20
0
def create_acquisition_operator_TOD(pointing, d, verbose=False):
    # scene
    s = qubic.QubicScene(d)
    if d['nf_sub'] == 1:
        if verbose:
            print('Making a QubicInstrument.')
        q = qubic.QubicInstrument(d)
        return qubic.QubicAcquisition(q, pointing, s, d)
    else:
        # Polychromatic instrument model
        if verbose:
            print('Making a QubicMultibandInstrument.')
        q = qubic.QubicMultibandInstrument(d)
        # number of sub frequencies to build the TOD
        _, nus_edge_in, _, _, _, _ = qubic.compute_freq(
            d['filter_nu'] / 1e9,
            d['nf_sub'],  # Multiband instrument model
            d['filter_relative_bandwidth'])
        # Multi-band acquisition model for TOD fabrication
        return qubic.QubicMultibandAcquisition(q, pointing, s, d, nus_edge_in)
Example #21
0
    def __init__(self, skyconfig, d, output_directory="./", output_prefix="qubic_sky"):
        _, nus_edge_in, central_nus, deltas, _, _ = qubic.compute_freq(d['filter_nu'] / 1e9, d['nf_sub'],
                                                                       # Multiband instrument model
                                                                       d['filter_relative_bandwidth'])
        self.qubic_central_nus = central_nus
        self.qubic_resolution_nus = 61.347409 / self.qubic_central_nus
        self.qubic_channels_names = ["{:.3s}".format(str(i)) + "_GHz" for i in self.qubic_central_nus]

        instrument = pysm.Instrument({'nside': d['nside'], 'frequencies': central_nus,  # GHz
                                      'use_smoothing': False, 'beams': np.ones_like(central_nus),  # arcmin
                                      'add_noise': False,  # If True `sens_I` and `sens_Q` are required
                                      'noise_seed': 0.,  # Not used if `add_noise` is False
                                      'sens_I': np.ones_like(central_nus),  # Not used if `add_noise` is False
                                      'sens_P': np.ones_like(central_nus),  # Not used if `add_noise` is False
                                      'use_bandpass': False,  # If True pass banpasses  with the key `channels`
                                      'channel_names': self.qubic_channels_names,  # np.ones_like(central_nus),
                                      'channels': np.ones_like(central_nus), 'output_units': 'uK_RJ',
                                      'output_directory': output_directory, 'output_prefix': output_prefix,
                                      'pixel_indices': None})

        sky.__init__(self, skyconfig, d, instrument, output_directory, output_prefix)
Example #22
0
def get_tod(d, p, x0, closed_horns=None):
    """

    Parameters
    ----------
    d : dictionnary
    p : pointing
    x0 : sky
    closed_horns : array
        index of closed horns

    Returns
    -------
    Returns an instrument with closed horns and TOD
    """
    # Polychromatic instrument model
    q = qubic.QubicMultibandInstrument(d)
    # q = qubic.QubicInstrument(d)
    if closed_horns is not None:
        for i in range(d['nf_sub']):
            for h in closed_horns:
                q[i].horn.open[h] = False

    # Scene
    s = qubic.QubicScene(d)

    # Number of sub frequencies to build the TOD
    _, nus_edge_in, _, _, _, _ = qubic.compute_freq(
        d['filter_nu'] / 1e9, d['nf_sub'], d['filter_relative_bandwidth'])

    # Multi-band acquisition operator
    a = qubic.QubicMultibandAcquisition(q, p, s, d, nus_edge_in)
    # a = qubic.QubicPolyAcquisition(q, p, s, d)

    tod = a.get_observation(x0, convolution=False, noiseless=True)

    return q, tod
Example #23
0
def create_input_sky(parameters):
    Nf = int(parameters['nf_sub_build'])
    band = parameters['band']
    relative_bandwidth = parameters['relative_bandwidth']
    Nbfreq_in, nus_edge_in, nus_in, deltas_in, Delta_in, Nbbands_in = compute_freq(
        band, relative_bandwidth, Nf)
    # seed
    if parameters['seed']:
        np.random.seed(parameters['seed'])
    # Generate the input CMB map
    sp = read_spectra(0)
    cmb = np.array(
        hp.synfast(sp,
                   parameters['nside'],
                   new=True,
                   pixwin=True,
                   verbose=False)).T
    # Generate the dust map
    coef = parameters['dust_coeff']
    ell = np.arange(1, 3 * parameters['nside'])
    fact = (ell * (ell + 1)) / (2 * np.pi)
    spectra_dust = [
        np.zeros(len(ell)), coef * (ell / 80.)**(-0.42) / (fact * 0.52),
        coef * (ell / 80.)**(-0.42) / fact,
        np.zeros(len(ell))
    ]
    dust = np.array(
        hp.synfast(spectra_dust,
                   parameters['nside'],
                   new=True,
                   pixwin=True,
                   verbose=False)).T

    # Combine CMB and dust. As output we have N 3-component maps of sky.
    x0 = cmb_plus_dust(cmb, dust, Nbbands_in, nus_in)
    return x0
Example #24
0
def reconstruct_maps(TOD,
                     d,
                     pointing,
                     nf_sub_rec,
                     x0=None,
                     verbose=False,
                     instrument=None,
                     forced_tes_sigma=None):
    _, nus_edge, nus, _, _, _ = qubic.compute_freq(
        d['filter_nu'] / 1e9, nf_sub_rec, d['filter_relative_bandwidth'])
    arec = create_acquisition_operator_REC(pointing,
                                           d,
                                           nf_sub_rec,
                                           verbose=verbose,
                                           instrument=instrument)
    print('len(arec) = {}'.format(len(arec)))
    if forced_tes_sigma is not None:
        for i in range(len(arec)):
            arec[i].forced_sigma = forced_tes_sigma
            print('In SpectroImLib:reconstruct_maps: arec.forced_sigma{} = {}'.
                  format(i, arec[i].forced_sigma))
    cov = arec.get_coverage()
    maps_recon, nit, error = arec.tod2map(TOD, d, cov=cov)
    if not d['verbose']:
        print('niterations = {}, error = {}'.format(nit, error))
    if x0 is None:
        return maps_recon, cov, nus, nus_edge
    else:
        if d['nf_sub'] == 1:
            _, maps_convolved = arec.get_observation(x0[0],
                                                     noiseless=d['noiseless'])
        else:
            _, maps_convolved = arec.get_observation(x0,
                                                     noiseless=d['noiseless'])
        maps_convolved = np.array(maps_convolved)
        return maps_recon, cov, nus, nus_edge, maps_convolved
nside = 256
# Observe a patch at the galactic north pole
center_gal = 0, 90
center = gal2equ(center_gal[0], center_gal[1])

band = 150
tol = 1e-4

# Compute frequencies at which we sample the TOD.
# As input we set 150 [GHz] - the central frequency of the band and
# the relative bandwidth -- 0.25.
# The bandwidth is assumed to be uniform.
# The number of frequencies is set by an optional parameter Nfreq, 
# which is, by default, 15 for 150 GHz band
# and 20 for 220 GHz band.
Nbfreq, nus_edge, nus, deltas, Delta, Nbbands = compute_freq(band, 0.25)

# Use random pointings for the test
p = create_random_pointings(center, 1000, 10)

# Polychromatic instrument model
q = QubicMultibandInstrument(filter_nus=nus * 1e9,
                             filter_relative_bandwidths=nus / deltas,
                             ripples=True) # The peaks of the synthesized beam are modeled with "ripples"

s = QubicScene(nside=nside, kind='IQU')

# Polychromatic acquisition model
a = QubicPolyAcquisition(q, p, s, effective_duration=2)

sp = read_spectra(0)
hp.gnomview(maps_ud[2,-1,:,0], reso = 15,#hold = True, 
			notext = False, title = 'G patch ', sub = (121),
			max = 0.4*np.max(maps_ud[2,-1,:,0]), 
			unit = r'$\mu$K',
			rot = centers[2])
hp.projscatter(hp.pix2ang(nside_new, pixG_ud), marker = '*', color = 'r', s = 200)
hp.gnomview(maps_ud[1,-1,:,0], reso = 15, title = 'Q patch ',
			unit = r'$\mu$K', sub = (122),
			rot = centerQ)
hp.projscatter(hp.pix2ang(nside_new, pixQ_ud), marker = '*', color = 'r', s = 200)
hp.graticule(dpar = 10, dmer = 20, alpha = 0.6, verbose = False)
plt.show()

print("# Preparing for run MCMC ")
_, nus150, nus_out150, _, _, _ = qubic.compute_freq(dictionaries[0]['filter_nu'] / 1e9,  
							dictionaries[0]['nf_recon'],
							dictionaries[0]['filter_relative_bandwidth'])
_, nus220, nus_out220, _, _, _ = qubic.compute_freq(dictionaries[1]['filter_nu'] / 1e9,  
							dictionaries[1]['nf_recon'],
							dictionaries[1]['filter_relative_bandwidth'])
nus_out = [nus_out150, nus_out220, nus_out150, nus_out220]
pixs_ud = [pixQ_ud, pixQ_ud, pixG_ud, pixG_ud]
pixs_red = [pixQ_red, pixQ_red, pixG_red, pixG_red]
nus_edge = [nus150, nus220, nus150, nus220]

study = "dust+synch"
if study == "dust":
	FuncModel = fsed.ThermDust_Planck353
	p0 = np.array([1e3,3])
elif study == "synch":
	FuncModel = fsed.Synchrotron_storja
Example #27
0
nside = 256
# Observe a patch at the galactic north pole
center_gal = 0, 90
center = gal2equ(center_gal[0], center_gal[1])

band = 150
tol = 1e-4

# Compute frequencies at which we sample the TOD.
# As input we set 150 [GHz] - the central frequency of the band and
# the relative bandwidth -- 0.25.
# The bandwidth is assumed to be uniform.
# The number of frequencies is set by an optional parameter Nfreq, 
# which is, by default, 15 for 150 GHz band
# and 20 for 220 GHz band.
Nbfreq, nus_edge, nus, deltas, Delta, Nbbands = compute_freq(band, 0.25)

# Use random pointings for the test
p = create_random_pointings(center, 1000, 10)

# Polychromatic instrument model
q = QubicMultibandInstrument(filter_nus=nus * 1e9,
                             filter_relative_bandwidths=nus / deltas,
                             ripples=True) # The peaks of the synthesized beam are modeled with "ripples"

s = QubicScene(nside=nside, kind='IQU')

# Polychromatic acquisition model
a = QubicPolyAcquisition(q, p, s, effective_duration=2)

sp = read_spectra(0)
Example #28
0
subq = q.detector_subset(dets)

# Reading a sky map
m0=hp.fitsfunc.read_map('CMB_test.fits', field=(0,1,2))

x0=np.zeros((d['nf_sub'],len(m0[0]),len(m0)))
for j in range(len(m0)):
    for i in range(d['nf_sub']):
        x0[i,:,j]=m0[j]

# field center in galactic coordinates
center_gal = qubic.equ2gal(d['RA_center'], d['DEC_center'])

# Choosing the subfrequencies for map acquisition
Nbfreq_in, nus_edge_in, nus_in, deltas_in, Delta_in, Nbbands_in =\
  qubic.compute_freq(d['filter_nu']/1e9, d['filter_relative_bandwidth'],
                     d['nf_sub']) # Multiband instrument model

# Map acquisition for the full and reduced instruments
a = qubic.QubicMultibandAcquisition(q, p, s, d, nus_edge_in)
suba = qubic.QubicMultibandAcquisition(subq, p, s, d, nus_edge_in)


t = time()
# Time lines construction
TOD, maps_convolved= a.get_observation(x0, noiseless=True)
subTOD= suba.get_observation(np.array(maps_convolved), convolution=False,
                                 noiseless=True)
print 'TOD time =', time()-t

# Choosing the subfrequencies for map reconstruction
nf_sub_rec = 2
center = gal2equ(center_gal[0], center_gal[1])

band = 150
tol = 1e-4

# Compute frequencies at which we sample the TOD.
# As input we set 150 [GHz] - the central frequency of the band and
# the relative bandwidth -- 0.25.
# The bandwidth is assumed to be uniform.
# The number of frequencies is set by an optional parameter Nfreq, 
# which is, by default, 15 for 150 GHz band
# and 20 for 220 GHz band.
# Here we use only Nf=5 frequencies
Nf = 5
relative_bandwidth = 0.25
Nbfreq, nus_edge, nus, deltas, Delta, Nbbands = compute_freq(band, relative_bandwidth, 5)

# Use random pointings
p = create_random_pointings(center, 1000, 10)

# Polychromatic instrument model
q = QubicMultibandInstrument(filter_nus=nus * 1e9,
                             filter_relative_bandwidths=nus / deltas,
                             ripples=True) # The peaks of the synthesized beam are modeled with "ripples"

s = QubicScene(nside=nside, kind='IQU')

# Multi-band acquisition model
# Nsb=2 sub-bands to reconstruct the CMB
Nsb = 2
Nbfreq, nus_edge, nus_, deltas_, Delta_, Nbbands_ = compute_freq(band, relative_bandwidth, Nsb)
Example #30
0
for freq in xrange(nbands):
	for i in xrange(2):
		for pitch in xrange(7):
			std[pitch, freq, i] = np.std(residus[pitch][:,freq,:,i+1])
	std_meanQU = np.mean(std, axis=2) / np.sqrt(nbands)
	plt.plot(pitch_std, std_meanQU[:,freq], 'o', label='subband ' + str(freq+1) + '/' + str(nbands))
	# plt.plot(pitch_mean, std[:,i], '.', label=stokes[i+1])
	plt.xlim(-0.5, 31)
	plt.xlabel('pitch std')
	plt.ylabel('std_Residus / sqrt(nbands)')
	plt.legend(numpoints=1, loc=4)
	plt.title('Q an U std residus averaged and corrected by sqrt(nbands)')
	
#Calcul de la correction
Nfreq = 12
_, nus_edge, nus, deltas, Delta, _ = qubic.compute_freq(band=150, relative_bandwidth=0.25, Nfreq=Nfreq)
print(Delta)
print(deltas)
plot(nus, deltas, 'o')

#si on les import tous
plt.figure('pitch_test_I=0_std_residus_corrected2')
for nbands in [1,2,3,4]:
	plt.subplot(2,2,nbands)
	std = np.empty((7, nbands, 2))
	for freq in xrange(nbands):
		for i in xrange(2):
			for pitch in xrange(7):
				res = pitch*4+nbands-1
				#print(res)
				std[pitch, freq, i] = np.std(residus[res][:,freq,:,i+1])
Example #31
0
source = m0 * 0
source[id] = 1
arcToRad = np.pi / (180 * 60.)
source = hp.sphtfunc.smoothing(source, fwhm=30 * arcToRad)
x0[:, :, component] = source
hp.mollview(x0[0, :, component])
plt.show()

if p.fix_az:
    center = (fix_azimuth['az'], fix_azimuth['el'])
else:
    center = qubic.equ2gal(d['RA_center'], d['DEC_center'])

# Make TOD
Nbfreq_in, nus_edge_in, nus_in, deltas_in, Delta_in, Nbbands_in = qubic.compute_freq(d['filter_nu'] / 1e9,
                                                                                     d['nf_sub'],
                                                                                     d['filter_relative_bandwidth'])
a = qubic.QubicMultibandAcquisition(q, p, s, d, nus_edge_in)

TOD = a.get_observation(x0, noiseless=True, convolution=False)

plt.plot(TOD[0, :])
plt.xlabel('pointing index')
plt.ylabel('TOD')
plt.show()

# Map making
if alaImager:
    nf_sub_rec = 1
    d['synthbeam_kmax'] = 0
    if oneComponent: