Ejemplo n.º 1
0
def test_mpi_read():

    comm = MPI.COMM_WORLD

    assert is_power2(
        comm.size), "Run with a number of MPI processes which is power of 2"

    nside = 64
    npix = hp.nside2npix(nside)

    num_local_pixels = npix // comm.size

    if comm.size == 1:
        pixel_indices = None
        comm = None
    else:
        pixel_indices = np.arange(comm.rank * num_local_pixels,
                                  (comm.rank + 1) * num_local_pixels,
                                  dtype=np.int)

    pysm_model = "s3,d7,f1,c1,a2"

    sky_config = build_sky_config(pysm_model, nside, pixel_indices, comm)

    sky = pysm.Sky(sky_config, mpi_comm=comm)

    instrument_bpass = {
        'use_smoothing': False,
        'nside': nside,
        'add_noise': False,
        'use_bandpass': True,
        'channels': [(np.linspace(20, 25, 10), np.ones(10))],
        'channel_names': ['channel_1'],
        'output_units': 'uK_RJ',
        'output_directory': './',
        'output_prefix': 'test',
        'noise_seed': 1234,
        'pixel_indices': pixel_indices
    }

    instrument = pysm.Instrument(instrument_bpass)
    local_map = instrument.observe(sky, write_outputs=False)

    # Run PySM again locally on each process on the full map

    sky_config = build_sky_config(pysm_model, nside)

    sky = pysm.Sky(sky_config, mpi_comm=comm)

    instrument_bpass["pixel_indices"] = None

    instrument = pysm.Instrument(instrument_bpass)
    complete_map = instrument.observe(sky, write_outputs=False)

    if pixel_indices is None:
        pixel_indices = np.arange(npix)

    np.testing.assert_array_almost_equal(local_map[0],
                                         complete_map[0][:, :, pixel_indices])
Ejemplo n.º 2
0
def simulation(nside):
    print '########Simulating#######'
    c1_config = models("c1", nside)       
    s1_config = models("s1", nside)
    d1_config = models("d1", nside)
    f1_config = models("f1", nside)
    a1_config = models("a1", nside)
    sky_config = {
        'synchrotron' : s1_config,
        'dust' : d1_config,
        'freefree' : f1_config,
        'cmb' : c1_config,
        'ame' : a1_config
    }
    sky = pysm.Sky(sky_config) 
    
    global wn, cmb_MASKED, coefficients,mask,cmb
    nu = np.array([30., 44., 70., 95., 150., 217., 353., 545., 857.]) 
    coefficients = convert_units("uK_RJ", "uK_CMB", nu)
     
    #dust = sky.dust(nu);synchrotron = sky.synchrotron(nu);freefree = sky.freefree(nu)
    #cmb = sky.cmb(nu); ame = sky.ame(nu)
    #np.save('../simulation/Nside = 1024/dust_map.npy',convert_unit(dust)); np.save('../simulation/Nside = 1024/synchro_map.npy',convert_unit(synchrotron));
    #np.save('../simulation/Nside = 1024/9_fre/cmb_map.npy',convert_unit(cmb)); #np.save('../simulation/Nside = 1024/freefree_map.npy',convert_unit(freefree));
    #np.save('../simulation/Nside = 1024/ame_map.npy',convert_unit(ame))
    
    total = sky.signal()(nu)
    #total = (total - cmb)*0.7 + cmb         #decrease the foreground 
    np.save('../simulation/Nside = 1024/9_fre/total_map.npy',convert_unit(total))
Ejemplo n.º 3
0
    def test_Sigma_synchrotron(self):
        NSIDE = 8
        MODEL = 's0'
        INSTRUMENT = 'litebird'
        SIGNAL_TO_NOISE = 20
        sky = pysm.Sky(get_sky(NSIDE, MODEL))
        instrument = pysm.Instrument(get_instrument(INSTRUMENT, NSIDE))
        components = [cm.Synchrotron(100.)]
        ref = []
        for component in components:
            ref += component.defaults

        with suppress_stdout():
            freq_maps, noise_maps = instrument.observe(sky,
                                                       write_outputs=False)

        signal = freq_maps[:, 0, 0]
        noise = np.std(noise_maps[:, 0], axis=-1)
        maps = signal / np.dot(signal, noise) * SIGNAL_TO_NOISE
        maps = maps[:, np.newaxis] + noise_maps[:, 0]
        res = basic_comp_sep(components,
                             instrument,
                             maps,
                             nside=hp.get_nside(maps))
        white = (res.x[0] - ref[0]) / res.Sigma[0, 0]**0.5
        _, p = kstest(white, 'norm')
        assert p > 0.01
Ejemplo n.º 4
0
    def test_Sigma_dust_one_parameter(self):
        NSIDE = 8
        MODEL = 'd0'
        INSTRUMENT = 'litebird'
        SIGNAL_TO_NOISE = 10
        sky = pysm.Sky(get_sky(NSIDE, MODEL))
        instrument = pysm.Instrument(get_instrument(INSTRUMENT, NSIDE))
        components = [cm.Dust(100., temp=20.)]
        ref = []
        for component in components:
            ref += component.defaults

        with suppress_stdout():
            freq_maps, noise_maps = instrument.observe(sky,
                                                       write_outputs=False)

        signal = freq_maps[:, 0, 0]
        noise = noise_maps[:, 0]
        signal_ver = signal / np.dot(signal, signal)**0.5
        noise_std = np.std([np.dot(n, signal_ver) for n in noise.T])
        maps = signal_ver * noise_std * SIGNAL_TO_NOISE
        maps = maps[:, np.newaxis] + noise

        res = basic_comp_sep(components,
                             instrument,
                             maps,
                             nside=hp.get_nside(maps))
        white = (res.x[0] - ref[0]) / res.Sigma[0, 0]**0.5
        _, p = kstest(white, 'norm')
        assert p > 0.01
Ejemplo n.º 5
0
    def setUp(self):
        self.nside = 1024
        sigma_T = 4.
        sigma_P = np.sqrt(2.) * sigma_T
        self.instrument_config = {
            'frequencies': np.array([23.]),
            'sens_I': np.array([sigma_T]),
            'sens_P': np.array([sigma_P]),
            'nside': self.nside,
            'noise_seed': 1234,
            'use_bandpass': False,
            'add_noise': True,
            'output_units': 'uK_CMB',
            'use_smoothing': False,
            'output_directory': os.path.dirname(os.path.abspath(__file__)),
            'output_prefix': 'test',
        }
        s1 = models("s1", self.nside)
        s1[0]['A_I'] = np.zeros(hp.nside2npix(self.nside))
        s1[0]['A_Q'] = np.zeros(hp.nside2npix(self.nside))
        s1[0]['A_U'] = np.zeros(hp.nside2npix(self.nside))
        sky_config = {'synchrotron': s1}
        self.sky = pysm.Sky(sky_config)

        pix2amin = np.sqrt(4. * np.pi * (180. / np.pi * 60.)**2 /
                           float(hp.nside2npix(self.nside)))

        self.expected_T_std = sigma_T / pix2amin
        self.expected_P_std = sigma_P / pix2amin
        self.test_file = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "test_nu0023p00GHz_noise_nside%04d.fits" % self.nside)
Ejemplo n.º 6
0
    def test_noise_write_partialsky(self):
        local_instrument_config = self.instrument_config.copy()
        npix = 20000
        local_instrument_config["pixel_indices"] = np.arange(npix,
                                                             dtype=np.int)
        instrument = pysm.Instrument(local_instrument_config)
        s1 = models("s1",
                    self.nside,
                    pixel_indices=local_instrument_config["pixel_indices"])
        s1[0]['A_I'] = np.zeros(npix)
        s1[0]['A_Q'] = np.zeros(npix)
        s1[0]['A_U'] = np.zeros(npix)
        sky_config = {'synchrotron': s1}
        partial_sky = pysm.Sky(sky_config)
        instrument.observe(partial_sky)
        # use masked array to handle partial sky
        T, Q, U = hp.ma(
            pysm.read_map(self.test_file, self.nside, field=(0, 1, 2)))
        T_std = np.ma.std(T)
        Q_std = np.ma.std(Q)
        U_std = np.ma.std(U)

        np.testing.assert_almost_equal(T_std, self.expected_T_std, decimal=2)
        np.testing.assert_almost_equal(Q_std, self.expected_P_std, decimal=2)
        np.testing.assert_almost_equal(U_std, self.expected_P_std, decimal=2)
Ejemplo n.º 7
0
    def test_Sigma_dust_sync_betas_temp(self):
        NSIDE = 8
        MODEL = 'd0s0'
        INSTRUMENT = 'litebird'
        SIGNAL_TO_NOISE = 10000
        UNITS = 'uK_CMB'
        sky = pysm.Sky(get_sky(NSIDE, MODEL))
        instrument = pysm.Instrument(
            get_instrument(INSTRUMENT, NSIDE, units=UNITS))
        components = [
            cm.Dust(150., temp=20., units=UNITS),
            cm.Synchrotron(150., units=UNITS)
        ]
        ref = []
        for component in components:
            ref += component.defaults
        ref = np.array(ref)

        with suppress_stdout():
            freq_maps, noise_maps = instrument.observe(sky,
                                                       write_outputs=False)

        signal = freq_maps[:, 0, 0]  # Same signal for all the pixels
        noise = noise_maps[:, 0]
        signal_ver = signal / np.dot(signal, signal)**0.5
        noise_std = np.std([np.dot(n, signal_ver) for n in noise.T])
        maps = signal_ver * noise_std * SIGNAL_TO_NOISE
        maps = maps[:, np.newaxis] + noise

        res = basic_comp_sep(components, instrument, maps, nside=NSIDE)
        diff = (res.x.T - ref)
        postS = np.mean(diff[..., None] * diff[..., None, :], axis=0)
        S = res.Sigma.T[0]
        aac(postS, S, rtol=1. / NSIDE)
Ejemplo n.º 8
0
    def test_dependence_on_nu0_RJ(self):
        NSIDE = 8
        MODEL = 'c1s0'
        INSTRUMENT = 'litebird'
        sky = pysm.Sky(get_sky(NSIDE, MODEL))
        instrument = pysm.Instrument(
            get_instrument(INSTRUMENT, NSIDE, units='uK_RJ'))
        components100 = [
            cm.CMB(units='K_RJ'),
            cm.Synchrotron(100., units='K_RJ')
        ]
        components10 = [
            cm.CMB(units='K_RJ'),
            cm.Synchrotron(10., units='K_RJ')
        ]

        with suppress_stdout():
            freq_maps, _ = instrument.observe(sky, write_outputs=False)

        res100 = basic_comp_sep(components100, instrument, freq_maps)
        res10 = basic_comp_sep(components10, instrument, freq_maps)
        aac(res100.Sigma, res10.Sigma)
        aac(res100.x, res10.x)
        aac(res100.s[0], res10.s[0])
        aac(res100.s[1], res10.s[1] * 10**res10.x[0])
Ejemplo n.º 9
0
def get_foreground_spectrum(nside,
                            nu_u,
                            mask_file="HFI_Mask_GalPlane-apo2_2048_R2.00.fits",
                            mask_field=2):
    nu = nu_u.to(u.GHz).value
    l_max = nside * 3
    sky_config = {
        'dust': pysm.nominal.models('d0', nside),
        'synchrotron': pysm.nominal.models('s0', nside)
    }
    sky = pysm.Sky(sky_config)
    dust_signal = sky.dust(nu)
    synchrotron_signal = sky.synchrotron(nu)

    mask = np.array(
        hp.ud_grade(
            hp.read_map(mask_file, field=mask_field).astype(np.bool), nside))

    proper_dust_masked = hp.ma(dust_signal)
    proper_dust_masked.mask = np.logical_not(mask)

    proper_sync_masked = hp.ma(synchrotron_signal)
    proper_sync_masked.mask = np.logical_not(mask)

    cl_dust_masked = np.array([
        hp.anafast(proper_dust_masked, lmax=l_max).T[l, :] * l * (l + 1) /
        (2 * np.pi) for l in range(l_max)
    ])
    cl_synchrotron_masked = np.array([
        hp.anafast(proper_sync_masked, lmax=l_max).T[l, :] * l * (l + 1) /
        (2 * np.pi) for l in range(l_max)
    ])

    return {'dust': cl_dust_masked, 'synchrotron': cl_synchrotron_masked}
Ejemplo n.º 10
0
def test_dust_model(model_tag, freq):

    # for 'd6' model fix the random seed and skip buggy 353 GHz
    if model_tag == "d6":
        if freq == 353:
            return
        np.random.seed(123)

    model = pysm.Sky(preset_strings=[model_tag], nside=64)

    model_number = {"d0": 1, "d1": 1, "d2": 6, "d3": 9, "d6": 12}[model_tag]
    expected_output = pysm.read_map(
        "pysm_2_test_data/check{}therm_{}p0_64.fits".format(
            model_number, freq),
        64,
        unit="uK_RJ",
        field=(0, 1, 2),
    )

    # for some models we do not have tests, we compare with output from a simular model
    # and we increase tolerance, mostly just to exercise the code.
    rtol = {"d0": 0.9}.get(model_tag, 1e-5)

    assert_quantity_allclose(expected_output,
                             model.get_emission(freq * units.GHz),
                             rtol=rtol)
Ejemplo n.º 11
0
def cmb_plot():
    import pkg_resources
    pysm_ver = pkg_resources.get_distribution("pysm").version
    print('Currently using PySm version: %s ' % pysm_ver)
    nside = 64
    sky_config = {
        'synchrotron': models("s1", nside),
        'dust': models("d1", nside),
        'freefree': models("f1", nside),
        'cmb': models("c1", nside),
        'ame': models("a1", nside),
    }
    # initialise Sky
    sky = pysm.Sky(sky_config)
    cmb = sky.cmb(nu=23.)

    fig = plt.figure(figsize=(6, 4))
    hp.mollview(cmb[0], min=-30, max=30, title=r'CMB', sub=(111))
    plt.show()
    plt.close()
    total = sky.signal()(100.)
    fig = plt.figure(figsize=(6, 4))
    hp.mollview(total[0], min=10, max=200, title=r'CMB + DUST', sub=(111))
    plt.show()
    plt.close()
Ejemplo n.º 12
0
 def compute_galaxy(self):
     """ Method to compute the Galactic foregrounds for the given model.
     This essentially just calls pysm for the given set of component
     models.
     """
     # get the PySM Sky object
     gal = pysm.Sky(self.skymodel['config'](self.nside))
     # observe the sky at the given set of frequencies
     return gal.signal()(self.instrument['nus'])
Ejemplo n.º 13
0
def gal(nside, fwhm=None):
    """ Create image of Galaxy in synchrotron and dust at
    150 GHz.
    """
    s1 = pysm.nominal.models('s1', nside)
    d1 = pysm.nominal.models('d1', nside)
    sky = pysm.Sky({'synchrotron': s1, 'dust': d1})
    c = pysm.common.K_RJ2Jysr(150.) / pysm.common.K_CMB2Jysr(150.)
    return hp.smoothing(sky.signal()(150.), fwhm=fwhm) * c
Ejemplo n.º 14
0
Archivo: pysm.py Proyecto: zonca/toast
 def init_sky(self, pysm_sky_config):
     if pysm is None:
         raise RuntimeError('pysm not available')
     autotimer = timing.auto_timer(type(self).__name__)
     initialized_sky_config = {}
     for name, model_id in pysm_sky_config.items():
         initialized_sky_config[name] = \
             pysm.nominal.models(model_id, self._nside, self._local_pixels,
                                 mpi_comm=self._comm)
     return pysm.Sky(initialized_sky_config, mpi_comm=self._comm)
Ejemplo n.º 15
0
    def __init__(self, skyconfig, d, instrument):
        """
        Parameters:
        skyconfig  : a skyconfig dictionary to pass to (as expected by) `PySM`
        d          : input dictionary from which the parameters are read
        instrument : a `PySM` instrument describing the instrument

        For more details about `PySM` see its documentation at the floowing link:
        https://pysm-public.readthedocs.io/en/latest/index.html
        """
        self.skyconfig = skyconfig
        self.dictionary = d
        self.instrument = instrument
        self.sky = pysm.Sky(skyconfig)
Ejemplo n.º 16
0
def test_synchrotron_model(model, freq):

    synchrotron = pysm.Sky(preset_strings=[model], nside=64)

    model_number = {"s1": 2, "s2": 7, "s3": 10}[model]
    synch = pysm.read_map(
        "pysm_2_test_data/check{}synch_{}p0_64.fits".format(model_number, freq),
        64,
        unit=pysm.units.uK_RJ,
        field=(0, 1, 2),
    ).reshape((1, 3, -1))

    assert_quantity_allclose(
        synch, synchrotron.get_emission(freq << pysm.units.GHz), rtol=1e-5
    )
Ejemplo n.º 17
0
def test_model(model, freq):

    model = pysm.Sky(preset_strings=[model], nside=64)

    model_number = 3
    expected_map = pysm.read_map(
        "pysm_2_test_data/check{}spinn_{}p0_64.fits".format(model_number, freq),
        64,
        unit=pysm.units.uK_RJ,
        field=0,
    ).reshape((1, 1, -1))

    assert_quantity_allclose(
        expected_map, model.get_emission(freq << pysm.units.GHz), rtol=1e-5
    )
Ejemplo n.º 18
0
def test_dust_model(model_tag, freq):

    model = pysm.Sky(preset_strings=[model_tag], nside=64)

    model_number = {"d1": 1, "d2": 6, "d3": 9}[model_tag]
    expected_output = pysm.read_map(
        "pysm_2_test_data/check{}therm_{}p0_64.fits".format(model_number, freq),
        64,
        unit="uK_RJ",
        field=(0, 1, 2),
    ).reshape((1, 3, -1))

    assert_quantity_allclose(
        expected_output, model.get_emission(freq * units.GHz), rtol=1e-5
    )
Ejemplo n.º 19
0
def test_highfreq_dust_model(model_tag, freq):

    model = pysm.Sky(preset_strings=[model_tag], nside=64)

    expected_output = pysm.read_map(
        "pysm_2_test_data/check_{}_{}_uK_RJ_64.fits".format(model_tag, freq),
        64,
        unit="uK_RJ",
        field=(0, 1, 2),
    )

    rtol = 1e-5

    assert_quantity_allclose(
        expected_output, model.get_emission(freq * units.GHz), rtol=rtol
    )
Ejemplo n.º 20
0
def test_cmb_lensed(model_tag, freq):

    # The PySM test was done with a different seed than the one
    # baked into the preset models
    pysm.sky.PRESET_MODELS["c1"]["cmb_seed"] = 1234
    model = pysm.Sky(preset_strings=[model_tag], nside=64)

    model_number = 5
    expected_output = pysm.read_map(
        "pysm_2_test_data/check{}cmb_{}p0_64.fits".format(model_number, freq),
        64,
        unit="uK_RJ",
        field=(0, 1, 2),
    )

    assert_quantity_allclose(expected_output,
                             model.get_emission(freq * u.GHz),
                             rtol=1e-5)
Ejemplo n.º 21
0
    def setUp(self):
        NSIDE = 16
        MODEL = 'c1d0s0f1'
        INSTRUMENT = 'litebird'
        X0_FACTOR = 0.99
        sky = pysm.Sky(get_sky(NSIDE, MODEL))
        self.instrument = pysm.Instrument(get_instrument(INSTRUMENT, NSIDE))
        with suppress_stdout():
            self.freq_maps, self.noise = self.instrument.observe(
                sky, write_outputs=False)

        self.components = [cm.CMB(), cm.Dust(200.), cm.Synchrotron(100.)]
        freefree = cm.PowerLaw(100.)
        freefree.defaults = [-2.14]  # Otherwise it is the same as Synchrotron
        self.components.append(freefree)
        self.input = []
        for component in self.components:
            self.input += component.defaults
            component.defaults = [d * X0_FACTOR for d in component.defaults]
Ejemplo n.º 22
0
    def __init__(self, skyconfig, d, instrument, out_dir, out_prefix):
        """
        Parameters:
        skyconfig  : a skyconfig dictionary to pass to (as expected by) `PySM`
        d          : input dictionary, from which the following Parameters are read
        instrument : a `PySM` instrument describing the instrument
        out_dir    : default path where the sky maps will be saved
        out_prefix : default world for the output files

        For more details about `PySM` see the `PySM` documentation at the floowing link: 
        https://pysm-public.readthedocs.io/en/latest/index.html
        """
        self.skyconfig = skyconfig
        self.nside = d['nside']
        self.dictionary = d
        self.instrument = instrument
        self.output_directory = out_dir
        self.output_prefix = out_prefix
        self.sky = pysm.Sky(skyconfig)
Ejemplo n.º 23
0
def test_synchrotron_model(model, freq):

    synchrotron = pysm.Sky(preset_strings=[model], nside=64)

    model_number = {"s0": 2, "s1": 2, "s2": 7, "s3": 10}[model]
    synch = pysm.read_map(
        "pysm_2_test_data/check{}synch_{}p0_64.fits".format(
            model_number, freq),
        64,
        unit=pysm.units.uK_RJ,
        field=(0, 1, 2),
    )

    # for some models we do not have tests, we compare with output from a simular model
    # and we increase tolerance, mostly just to exercise the code.
    rtol = {"s0": 5}.get(model, 1e-5)

    assert_quantity_allclose(synch,
                             synchrotron.get_emission(freq << pysm.units.GHz),
                             rtol=rtol)
Ejemplo n.º 24
0
 def init_sky(self, pysm_sky_config, pysm_precomputed_cmb_K_CMB):
     if pysm is None:
         raise RuntimeError("pysm not available")
     if pysm_precomputed_cmb_K_CMB is not None:
         raise NotImplementedError(
             "pysm_precomputed_cmb_K_CMB is not currently supported")
         # cmb = {
         #     "model": "pre_computed",
         #     "nside": self._nside,
         #     "pixel_indices": self._pixel_indices,
         # }
         # # PySM expects uK_CMB
         # cmb["A_I"], cmb["A_Q"], cmb["A_U"] = (
         #     np.array(
         #         pysm.read_map(
         #             pysm_precomputed_cmb_K_CMB,
         #             self._nside,
         #             field=(0, 1, 2),
         #             pixel_indices=self._pixel_indices,
         #             mpi_comm=self._comm,
         #         )
         #     )
         #     * 1e6
         # )
         # initialized_sky_config["cmb"] = [cmb]
         # # remove cmb from the pysm string
         # pysm_sky_config.pop("cmb", None)
     if self.map_dist is None:
         self.map_dist = (None
                          if self._comm is None else pysm.MapDistribution(
                              pixel_indices=self._pixel_indices,
                              nside=self._nside,
                              mpi_comm=self._comm,
                          ))
     return pysm.Sky(
         nside=self._nside,
         preset_strings=pysm_sky_config,
         component_objects=self.pysm_component_objects,
         map_dist=self.map_dist,
         output_unit=self._units,
     )
Ejemplo n.º 25
0
def get_sky(nside, tag='c1d0s0'):
    """ Get a pre-defined PySM sky

    Parameters
    ----------
    nside: int
        healpix nside of the sky templates
    tag: string
        See the `pysm documentation
        <https://pysm3.readthedocs.io/en/latest/models.html#models>`_
        for a complete list of available options.
        Default is 'c1d0s0', i.e. cmb (c1), dust with constant temperature and
        spectral index (d0), and synchrotron with constant spectral index (s0).

    Returns
    -------
    sky: pysm.Sky
        See the `pysm documentation
        <https://pysm3.readthedocs.io/en/latest/api/pysm.Sky.html#pysm.Sky>`_
    """
    preset_strings = [tag[i:i+2] for i in range(0, len(tag), 2)]
    return pysm.Sky(nside, preset_strings=preset_strings)
Ejemplo n.º 26
0
 def init_sky(self, pysm_sky_config, pysm_precomputed_cmb_K_CMB):
     if pysm is None:
         raise RuntimeError('pysm not available')
     autotimer = timing.auto_timer(type(self).__name__)
     initialized_sky_config = {}
     if pysm_precomputed_cmb_K_CMB is not None:
         cmb = \
             {
                 'model': 'pre_computed',
                 'nside': self._nside,
                 'pixel_indices': self._local_pixels
             }
         # PySM expects uK_CMB
         cmb['A_I'], cmb['A_Q'], cmb['A_U'] = np.array(pysm.read_map(
                 pysm_precomputed_cmb_K_CMB, self._nside, field=(0,1,2),
                 pixel_indices=self._local_pixels, mpi_comm=self._comm)) * 1e6
         initialized_sky_config["cmb"] = [cmb]
         # remove cmb from the pysm string
         pysm_sky_config.pop("cmb", None)
     for name, model_id in pysm_sky_config.items():
         initialized_sky_config[name] = \
             pysm.nominal.models(model_id, self._nside, self._local_pixels,
                                 mpi_comm=self._comm)
     return pysm.Sky(initialized_sky_config, mpi_comm=self._comm)
Ejemplo n.º 27
0
import pysm
import numpy as np
import healpy as hp
import matplotlib.pyplot as plt

if __name__ == "__main__":
    nside = 16
    bpass = [(np.linspace(140.0, 170.0, 10), np.ones(10))]
    freqs = np.linspace(1, 500, 100.0)

    sky = pysm.Sky(nside, preset_strings=["d6"])
    sky.correlation_length = 1.0
    sky_d1 = pysm.Sky(nside, preset_strings=["d1"])
    # hp.mollview(sky.get_emission(150.)[0, 0], title="model d4", norm='log')
    # plt.show()

    signal = sky.get_emission(freqs)
    signal_d1 = sky_d1.get_emission(freqs)
    fig, ax = plt.subplots(1, 1)
    print(signal.shape)
    ax.loglog(freqs, signal[:, 1, 0])
    ax.set_yscale("linear")
    plt.show()

    # get either individual model, or sky with group of components
    mbb = pysm.preset_models("d1", nside)
    sky = pysm.Sky(nside, preset_strings=["d1"])

    # the three main functions to be used (haven't added noise yet)
    out_delta = sky.get_emission(bpass[0][0].mean())
    out_bpass = sky.apply_bandpass(bpass)
Ejemplo n.º 28
0
import numpy as np
import pysm
import pysm.units as u

from mpi4py import MPI

nside = 32

map_dist = pysm.MapDistribution(pixel_indices=None,
                                nside=nside,
                                mpi_comm=MPI.COMM_WORLD)

sky = pysm.Sky(nside=nside,
               preset_strings=["d1", "s1", "f1", "a1"],
               map_dist=map_dist)

m = sky.get_emission(freq=np.arange(50, 55) * u.GHz,
                     weights=np.array([0.1, 0.3, 0.5, 0.3, 0.1]))[0]

print(map_dist.mpi_comm.rank, m.shape, m.min(), m.max())

m_smoothed = pysm.apply_smoothing_and_coord_transform(m,
                                                      fwhm=1 * u.deg,
                                                      map_dist=map_dist)

print(map_dist.mpi_comm.rank, m_smoothed.shape, m_smoothed.min(),
      m_smoothed.max())
Ejemplo n.º 29
0
        for d in range(1, 3):  #7
            d1_config = models("d%s" % d, nside)

            for a in range(2, 3):  #2
                a1_config = models("a%s" % a, nside)
                c1_config = models("c1", 128)

                sky_config = {
                    'synchrotron': s1_config,
                    'dust': d1_config,
                    #                                 'freefree' : f1_config,
                    'cmb': models("c1", nside),
                    'ame': a1_config,
                }
                sky = pysm.Sky(sky_config)
                synchrotron = (convert_unit(sky.synchrotron(nu)))
                dust = (convert_unit(sky.dust(nu)))
                ame = convert_unit(sky.ame(nu))
                cmb = convert_unit(sky.cmb(nu))
                total = (convert_unit(sky.signal()(nu)) - cmb)

                total_Bmap = []
                dust_Bmap = []
                sync_Bmap = []
                ame_Bmap = []
                cmb_Bmap = []
                for i in range(len(nu)):
                    total_Bmap.append(B_map(total[i]))
                    dust_Bmap.append(B_map(dust[i]))
                    sync_Bmap.append(B_map(synchrotron[i]))
Ejemplo n.º 30
0
args = parser.parse_args()

outfile = args.output
if outfile is None:
    outfile = "input_sky_band-{:.1f}-{:.1f}_beam-{:.1f}_n{:02d}-{}.fits".format(
        args.bandcenter_ghz,
        args.bandwidth_ghz,
        args.beam_arcmin,
        args.nside,
        args.coord,
    )

print("Working on {}".format(outfile))

print("  Construct Sky...", flush=True)
sky = pysm.Sky(nside=args.nside, preset_strings=["d1", "s1", "f1", "a1"])

freqs = (np.array([
    args.bandcenter_ghz - 0.5 * args.bandwidth_ghz,
    args.bandcenter_ghz,
    args.bandcenter_ghz + 0.5 * args.bandwidth_ghz,
]) * u.GHz)

print("  Get Emission...", flush=True)
map_data = sky.get_emission(freqs)

if args.coord == "G":
    print("  Smoothing...", flush=True)
    smoothed = pysm.apply_smoothing_and_coord_transform(map_data,
                                                        fwhm=args.beam_arcmin *
                                                        u.arcmin)