예제 #1
0
def redshift_temperature(cosmology=None, **atzkw):
    """Convert quantities between redshift and CMB temperature.

    Care should be taken to not misinterpret a relativistic, gravitational, etc
    redshift as a cosmological one.

    Parameters
    ----------
    cosmology : `~astropy.cosmology.Cosmology`, str, or None, optional
        A cosmology realization or built-in cosmology's name (e.g. 'Planck18').
        If None, will use the default cosmology
        (controlled by :class:`~astropy.cosmology.default_cosmology`).
    **atzkw
        keyword arguments for :func:`~astropy.cosmology.z_at_value`

    Returns
    -------
    `~astropy.units.equivalencies.Equivalency`
        Equivalency between redshift and temperature.
    """
    from astropy.cosmology import default_cosmology, z_at_value

    # get cosmology: None -> default and process str / class
    cosmology = cosmology if cosmology is not None else default_cosmology.get()
    with default_cosmology.set(cosmology):  # if already cosmo, passes through
        cosmology = default_cosmology.get()

    def z_to_Tcmb(z):
        return cosmology.Tcmb(z)

    def Tcmb_to_z(T):
        return z_at_value(cosmology.Tcmb, T << u.K, **atzkw)

    return u.Equivalency([(redshift, u.K, z_to_Tcmb, Tcmb_to_z)],
                         "redshift_temperature", {'cosmology': cosmology})
예제 #2
0
def test_pipeline_cosmology():

    # Define function for testing pipeline cosmology
    from skypy.utils import uses_default_cosmology
    @uses_default_cosmology
    def return_cosmology(cosmology):
        return cosmology

    # Initial default_cosmology
    initial_default = default_cosmology.get()

    # Test pipeline correctly sets default cosmology from parameters
    # N.B. astropy cosmology class has not implemented __eq__ for comparison
    H0, Om0 = 70, 0.3
    config = {'parameters': {'H0': H0, 'Om0': Om0},
              'cosmology': (FlatLambdaCDM, ['$H0', '$Om0']),
              'test': (return_cosmology, ),
              }
    pipeline = Pipeline(config)
    pipeline.execute()
    assert type(pipeline['test']) == FlatLambdaCDM
    assert pipeline['test'].H0.value == H0
    assert pipeline['test'].Om0 == Om0

    # Test pipeline correctly updates cosmology from new parameters
    H0_new, Om0_new = 75, 0.25
    pipeline.execute({'H0': H0_new, 'Om0': Om0_new})
    assert type(pipeline['test']) == FlatLambdaCDM
    assert pipeline['test'].H0.value == H0_new
    assert pipeline['test'].Om0 == Om0_new

    # Check that the astropy default cosmology is unchanged
    assert default_cosmology.get() == initial_default
예제 #3
0
def redshift_distance(cosmology=None, kind="comoving", **atzkw):
    """Convert quantities between redshift and distance.

    Care should be taken to not misinterpret a relativistic, gravitational, etc
    redshift as a cosmological one.

    Parameters
    ----------
    cosmology : `~astropy.cosmology.Cosmology`, str, or None, optional
        A cosmology realization or built-in cosmology's name (e.g. 'Planck18').
        If None, will use the default cosmology
        (controlled by :class:`~astropy.cosmology.default_cosmology`).
    kind : {'comoving', 'lookback', 'luminosity'} or None, optional
        The distance type for the Equivalency.
        Note this does NOT include the angular diameter distance as this
        distance measure is not monotonic.
    **atzkw
        keyword arguments for :func:`~astropy.cosmology.z_at_value`

    Returns
    -------
    `~astropy.units.equivalencies.Equivalency`
        Equivalency between redshift and temperature.

    Examples
    --------
    >>> import astropy.units as u
    >>> import astropy.cosmology.units as cu
    >>> from astropy.cosmology import WMAP9

    >>> z = 1100 * cu.redshift
    >>> z.to(u.Mpc, cu.redshift_distance(WMAP9, kind="comoving"))  # doctest: +FLOAT_CMP
    <Quantity 14004.03157418 Mpc>
    """
    from astropy.cosmology import default_cosmology, z_at_value

    # get cosmology: None -> default and process str / class
    cosmology = cosmology if cosmology is not None else default_cosmology.get()
    with default_cosmology.set(cosmology):  # if already cosmo, passes through
        cosmology = default_cosmology.get()

    allowed_kinds = ('comoving', 'lookback', 'luminosity')
    if kind not in allowed_kinds:
        raise ValueError(f"`kind` is not one of {allowed_kinds}")

    method = getattr(cosmology, kind + "_distance")

    def z_to_distance(z):
        """Redshift to distance."""
        return method(z)

    def distance_to_z(d):
        """Distance to redshift."""
        return z_at_value(method, d << u.Mpc, **atzkw)

    return u.Equivalency([(redshift, u.Mpc, z_to_distance, distance_to_z)],
                         "redshift_distance", {
                             'cosmology': cosmology,
                             "distance": kind
                         })
예제 #4
0
def test_uses_default_cosmology():

    from astropy.cosmology import default_cosmology, WMAP9

    from skypy.utils import uses_default_cosmology

    @uses_default_cosmology
    def function_with_cosmology(cosmology):
        return cosmology

    assert function_with_cosmology() == default_cosmology.get()

    assert WMAP9 != default_cosmology.get()
    assert function_with_cosmology(WMAP9) == WMAP9
예제 #5
0
def test_schechter_lf():

    from pytest import raises
    from skypy.galaxies import schechter_lf
    from astropy import units

    # redshift and magnitude distributions are tested separately
    # only test that output is consistent here

    # parameters for the sampling
    z = np.linspace(0., 1., 100)
    M_star = -20
    phi_star = 1e-3
    alpha = -0.5
    m_lim = 30.
    sky_area = 1.0 * units.deg**2
    cosmo = default_cosmology.get()

    # sample redshifts and magnitudes
    z_gal, M_gal = schechter_lf(z, M_star, phi_star, alpha, m_lim, sky_area, cosmo)

    # check length
    assert len(z_gal) == len(M_gal)

    # turn M_star, phi_star, alpha into arrays
    z, M_star, phi_star, alpha = np.broadcast_arrays(z, M_star, phi_star, alpha)

    # sample s.t. arrays need to be interpolated
    # alpha array not yet supported
    with raises(NotImplementedError):
        z_gal, M_gal = schechter_lf(z, M_star, phi_star, alpha, m_lim, sky_area, cosmo)
예제 #6
0
def get_pc_per_arcsec(distance, cosmo=WMAP9):
    """

    Args:
        distance: float
            Distance in Mpc
        cosmo: astropy.cosmology
            Cosmology. Default is None: will then
            use the default_cosmology from astropy

    Returns:
        pc_per_arcsec: float
            Conversion parsec per arcsecond

    """
    from astropy.cosmology import default_cosmology
    from astropy.coordinates import Distance
    from astropy import units as u

    # Use default cosmology from astropy
    if cosmo is None:
        cosmo = default_cosmology.get()

    # Use astropy units
    dist = Distance(distance, u.Mpc)
    # get the corresponding redshift
    redshift = dist.compute_z(cosmo)
    # And nore the proper conversion
    kpc_per_arcmin = cosmo.kpc_proper_per_arcmin(redshift)
    return kpc_per_arcmin.to(u.pc / u.arcsec)
예제 #7
0
    def test_temperature(self, cosmo):
        """Test temperature equivalency component."""
        default_cosmo = default_cosmology.get()
        z = 15 * cu.redshift
        Tcmb = cosmo.Tcmb(z)

        # 1) Default (without specifying the cosmology)
        with default_cosmology.set(cosmo):
            equivalency = cu.with_redshift(Tcmb=True)
            assert_quantity_allclose(z.to(u.K, equivalency), Tcmb)
            assert_quantity_allclose(Tcmb.to(cu.redshift, equivalency), z)

        # showing the answer changes if the cosmology changes
        # this test uses the default cosmology
        equivalency = cu.with_redshift(Tcmb=True)
        assert_quantity_allclose(z.to(u.K, equivalency), default_cosmo.Tcmb(z))
        assert default_cosmo.Tcmb(z) != Tcmb

        # 2) Specifying the cosmology
        equivalency = cu.with_redshift(cosmo, Tcmb=True)
        assert_quantity_allclose(z.to(u.K, equivalency), Tcmb)
        assert_quantity_allclose(Tcmb.to(cu.redshift, equivalency), z)

        # Test `atzkw`
        # this is really just a test that 'atzkw' doesn't fail
        equivalency = cu.with_redshift(cosmo, Tcmb=True, atzkw={"ztol": 1e-10})
        assert_quantity_allclose(Tcmb.to(cu.redshift, equivalency), z)
예제 #8
0
def test_redshift_temperature():
    """Test :func:`astropy.cosmology.units.redshift_temperature`."""
    cosmo = Planck13.clone(Tcmb0=3 * u.K)
    default_cosmo = default_cosmology.get()
    z = 15 * cu.redshift
    Tcmb = cosmo.Tcmb(z)

    # 1) Default (without specifying the cosmology)
    with default_cosmology.set(cosmo):
        equivalency = cu.redshift_temperature()
        assert_quantity_allclose(z.to(u.K, equivalency), Tcmb)
        assert_quantity_allclose(Tcmb.to(cu.redshift, equivalency), z)

    # showing the answer changes if the cosmology changes
    # this test uses the default cosmology
    equivalency = cu.redshift_temperature()
    assert_quantity_allclose(z.to(u.K, equivalency), default_cosmo.Tcmb(z))
    assert default_cosmo.Tcmb(z) != Tcmb

    # 2) Specifying the cosmology
    equivalency = cu.redshift_temperature(cosmo)
    assert_quantity_allclose(z.to(u.K, equivalency), Tcmb)
    assert_quantity_allclose(Tcmb.to(cu.redshift, equivalency), z)

    # Test `atzkw`
    equivalency = cu.redshift_temperature(cosmo, ztol=1e-10)
    assert_quantity_allclose(Tcmb.to(cu.redshift, equivalency), z)
예제 #9
0
def with_H0(H0=None):
    """
    Convert between quantities with little-h and the equivalent physical units.

    Parameters
    ----------
    H0 : None or `~astropy.units.Quantity` ['frequency']
        The value of the Hubble constant to assume. If a
        `~astropy.units.Quantity`, will assume the quantity *is* ``H0``. If
        `None` (default), use the ``H0`` attribute from
        :mod:`~astropy.cosmology.default_cosmology`.

    References
    ----------
    For an illuminating discussion on why you may or may not want to use
    little-h at all, see https://arxiv.org/pdf/1308.4150.pdf
    """
    if H0 is None:
        from .realizations import default_cosmology

        H0 = default_cosmology.get().H0

    h100_val_unit = u.Unit(100 / (H0.to_value((u.km / u.s) / u.Mpc)) * littleh)

    return u.Equivalency([(h100_val_unit, None)], "with_H0", kwargs={"H0": H0})
예제 #10
0
    def __init__(self,
                 z_lens,
                 z_source,
                 kwargs_model,
                 cosmo_fiducial=None,
                 lens_model_kinematics_bool=None,
                 light_model_kinematics_bool=None,
                 kwargs_seeing={},
                 kwargs_aperture={},
                 anisotropy_model=None):

        if cosmo_fiducial is None:
            cosmo_fiducial = default_cosmology.get()
        self._z_lens = z_lens
        self._z_source = z_source
        self._cosmo_fiducial = cosmo_fiducial
        self._lens_cosmo = LensCosmo(z_lens=z_lens,
                                     z_source=z_source,
                                     cosmo=self._cosmo_fiducial)
        self.LensModel, self.SourceModel, self.LensLightModel, self.PointSource, extinction_class = class_creator.create_class_instances(
            all_models=True, **kwargs_model)
        super(TDCosmography, self).__init__(
            z_lens=z_lens,
            z_source=z_source,
            kwargs_model=kwargs_model,
            cosmo=cosmo_fiducial,
            lens_model_kinematics_bool=lens_model_kinematics_bool,
            light_model_kinematics_bool=light_model_kinematics_bool,
            kwargs_seeing=kwargs_seeing,
            kwargs_aperture=kwargs_aperture,
            anisotropy_model=anisotropy_model)
예제 #11
0
    def test_distance(self, kind):
        """Test distance equivalency."""
        cosmo = Planck13
        z = 15 * cu.redshift
        dist = getattr(cosmo, kind + "_distance")(z)

        default_cosmo = default_cosmology.get()
        assert default_cosmo != cosmo  # shows changing default

        # 1) without specifying the cosmology
        with default_cosmology.set(cosmo):
            equivalency = cu.with_redshift(distance=kind)
            assert_quantity_allclose(z.to(u.Mpc, equivalency), dist)

        # showing the answer changes if the cosmology changes
        # this test uses the default cosmology
        equivalency = cu.with_redshift(distance=kind)
        assert_quantity_allclose(z.to(u.Mpc, equivalency),
                                 getattr(default_cosmo, kind + "_distance")(z))
        assert not u.allclose(getattr(default_cosmo, kind + "_distance")(z), dist)

        # 2) Specifying the cosmology
        equivalency = cu.with_redshift(cosmo, distance=kind)
        assert_quantity_allclose(z.to(u.Mpc, equivalency), dist)
        assert_quantity_allclose(dist.to(cu.redshift, equivalency), z)

        # Test atzkw
        # this is really just a test that 'atzkw' doesn't fail
        equivalency = cu.with_redshift(cosmo, distance=kind, atzkw={"ztol": 1e-10})
        assert_quantity_allclose(dist.to(cu.redshift, equivalency), z)
예제 #12
0
    def __init__(self,
                 mass=u.Quantity(mass.default, mass.unit),
                 concentration=concentration.default,
                 redshift=redshift.default,
                 massfactor=("critical", 200),
                 cosmo=None,
                 **kwargs):
        # Set default cosmology
        if cosmo is None:
            # LOCAL
            from astropy.cosmology import default_cosmology

            cosmo = default_cosmology.get()

        # Set mass overdensity type and factor
        self._density_delta(massfactor, cosmo, redshift)

        # Establish mass units for density calculation (default solar masses)
        if not isinstance(mass, u.Quantity):
            in_mass = u.Quantity(mass, u.M_sun)
        else:
            in_mass = mass

        # Obtain scale radius
        self._radius_s(mass, concentration)

        # Obtain scale density
        self._density_s(mass, concentration)

        super().__init__(mass=in_mass,
                         concentration=concentration,
                         redshift=redshift,
                         **kwargs)
예제 #13
0
def with_redshift(cosmology=None, *, Tcmb=True, atzkw=None):
    """Convert quantities between measures of cosmological distance.

    Note: by default all equivalencies are on and must be explicitly turned off.
    Care should be taken to not misinterpret a relativistic, gravitational, etc
    redshift as a cosmological one.

    Parameters
    ----------
    cosmology : `~astropy.cosmology.Cosmology`, str, or None, optional
        A cosmology realization or built-in cosmology's name (e.g. 'Planck18').
        If None, will use the default cosmology
        (controlled by :class:`~astropy.cosmology.default_cosmology`).
    Tcmb : bool (optional, keyword-only)
        Whether to create a CMB temperature <-> redshift equivalency, using
        ``Cosmology.Tcmb``. Default is False.
    atzkw : dict or None (optional, keyword-only)
        keyword arguments for :func:`~astropy.cosmology.z_at_value`

    Returns
    -------
    `~astropy.units.equivalencies.Equivalency`
        With equivalencies between redshift and temperature.
    """
    from astropy.cosmology import default_cosmology, z_at_value

    # get cosmology: None -> default and process str / class
    cosmology = cosmology if cosmology is not None else default_cosmology.get()
    with default_cosmology.set(cosmology):  # if already cosmo, passes through
        cosmology = default_cosmology.get()

    atzkw = atzkw if atzkw is not None else {}
    equivs = []  # will append as built

    # -----------
    # CMB Temperature <-> Redshift

    if Tcmb:
        equivs.extend(redshift_temperature(cosmology, **atzkw))

    # -----------

    return u.Equivalency(equivs, "with_redshift", {
        'cosmology': cosmology,
        'Tcmb': Tcmb
    })
예제 #14
0
    def test_distance_default(self):
        """Test distance equivalency default."""
        z = 15 * cu.redshift
        d = default_cosmology.get().comoving_distance(z)

        equivalency = cu.with_redshift()
        assert_quantity_allclose(z.to(u.Mpc, equivalency), d)
        assert_quantity_allclose(d.to(cu.redshift, equivalency), z)
예제 #15
0
def test_growth():
    """
    Test a FlatLambdaCDM cosmology with omega_matter = 1.0
    and astropy default cosmology
    """

    redshift = np.linspace(0., 10., 101)
    cosmology_flat = FlatLambdaCDM(H0=70.0, Om0=1.0)

    fz = growth_factor(redshift, cosmology_flat)
    Dz = growth_function(redshift, cosmology_flat)
    Dzprime = growth_function_derivative(redshift, cosmology_flat)

    # Test growth factor
    assert redshift.shape == fz.shape,\
        "Length of redshift array and growth rate array do not match"
    assert isclose(fz[0], 1.0),\
        "Growth factor at redshift 0 is not close to 1.0"

    # Test growth function
    assert redshift.shape == Dz.shape,\
        "Length of redshift array and growth function array do not match"
    assert allclose(Dz, 1. / (1. + redshift)),\
        "Growth function is not close to the scale factor"

    # make sure that growth_function with scalar returns scalar
    Dz2 = growth_function(redshift[2], cosmology_flat)
    assert np.isscalar(
        Dz2), 'growth function with scalar did not produce scalar'
    assert Dz2 == Dz[
        2], 'growth function with scalar produced inconsistent result'

    # Test growth function derivative
    assert redshift.shape == Dzprime.shape,\
        "Length of redshift array and growth function array do not match"
    assert isclose(Dzprime[0], -1.0),\
        "Derivative of growth function at redshift 0 is not close to -1.0"

    # Test against precomputed values using astropy default cosmology
    default = default_cosmology.get()
    zvec = np.linspace(0.0, 1.0, 4)

    fz_default = growth_factor(zvec, default)
    Dz_default = growth_function(zvec, default)
    Dzprime_default = growth_function_derivative(zvec, default)

    precomputed_fz_default = np.array(
        [0.5255848, 0.69412802, 0.80439553, 0.87179376])
    precomputed_Dz_default = np.array(
        [0.66328939, 0.55638978, 0.4704842, 0.40368459])
    precomputed_Dzprime_default = np.array(
        [-0.34861482, -0.2896543, -0.22707323, -0.17596485])

    assert allclose(fz_default, precomputed_fz_default)
    assert allclose(Dz_default, precomputed_Dz_default)
    assert allclose(Dzprime_default, precomputed_Dzprime_default)
예제 #16
0
    def __init__(self, cosmo=None):
        """

        :param cosmo: astropy.cosmology instance
        """
        from astropy.cosmology import default_cosmology

        if cosmo is None:
            cosmo = default_cosmology.get()
        self.cosmo = cosmo
예제 #17
0
    def __init__(self, cosmo=None):
        """

        :param cosmo: instance of astropy.cosmology
        :return: Background class with instance of astropy.cosmology
        """
        from astropy.cosmology import default_cosmology

        if cosmo is None:
            cosmo = default_cosmology.get()
        self.cosmo = cosmo
예제 #18
0
    def __init__(self,
                 z_lens,
                 z_source,
                 kwargs_model,
                 cosmo_fiducial=None,
                 lens_model_kinematics_bool=None,
                 light_model_kinematics_bool=None,
                 kwargs_seeing={},
                 kwargs_aperture={},
                 anisotropy_model=None,
                 multi_observations=False,
                 kwargs_lens_eqn_solver={}):
        """

        :param z_lens: redshift of deflector
        :param z_source: redshift of source
        :param kwargs_model: model configurations (according to FittingSequence)
        :param cosmo_fiducial: fiducial cosmology used to compute angular diameter distances where required
        :param lens_model_kinematics_bool: (optional) bool list, corresponding to lens models being included into the
         kinematics modeling
        :param light_model_kinematics_bool: (optional) bool list, corresponding to lens light models being included
         into the kinematics modeling
        :param kwargs_seeing: seeing conditions (see observation class in Galkin)
        :param kwargs_aperture: aperture keyword arguments (see aperture class in Galkin)
        :param anisotropy_model: string, anisotropy model type
        :param multi_observations: bool, if True, interprets kwargs_aperture and kwargs_seeing as lists of multiple
         observations
        """

        if cosmo_fiducial is None:
            cosmo_fiducial = default_cosmology.get()
        self._z_lens = z_lens
        self._z_source = z_source
        self._cosmo_fiducial = cosmo_fiducial
        self._lens_cosmo = LensCosmo(z_lens=z_lens,
                                     z_source=z_source,
                                     cosmo=self._cosmo_fiducial)
        self.LensModel, self.SourceModel, self.LensLightModel, self.PointSource, extinction_class = class_creator.create_class_instances(
            all_models=True,
            **kwargs_model,
            kwargs_lens_eqn_solver=kwargs_lens_eqn_solver)
        super(TDCosmography, self).__init__(
            z_lens=z_lens,
            z_source=z_source,
            kwargs_model=kwargs_model,
            cosmo=cosmo_fiducial,
            lens_model_kinematics_bool=lens_model_kinematics_bool,
            light_model_kinematics_bool=light_model_kinematics_bool,
            kwargs_seeing=kwargs_seeing,
            kwargs_aperture=kwargs_aperture,
            anisotropy_model=anisotropy_model,
            multi_observations=multi_observations,
            kwargs_lens_eqn_solver=kwargs_lens_eqn_solver)
예제 #19
0
    def __init__(self,
                 z_source,
                 lens_model_list,
                 redshift_list,
                 cosmo=None,
                 **lensmodel_kwargs):
        """

        :param cosmo: instance of astropy.cosmology
        :return: Background class with instance of astropy.cosmology
        """
        if cosmo is None:
            from astropy.cosmology import default_cosmology
            cosmo = default_cosmology.get()
        self._cosmo_bkg = Background(cosmo)
        self._z_source = z_source
        if not len(lens_model_list) == len(redshift_list):
            raise ValueError(
                "The length of lens_model_list does not correspond to redshift_list"
            )
        self._lens_model_list = lens_model_list
        self._redshift_list = redshift_list
        if len(lens_model_list) < 1:
            self._sorted_redshift_index = []
        else:
            self._sorted_redshift_index = self._index_ordering(redshift_list)
        self._lens_model = SinglePlane(lens_model_list, **lensmodel_kwargs)
        z_before = 0
        self._T_ij_list = []
        self._T_z_list = []
        self._reduced2physical_factor = []
        for idex in self._sorted_redshift_index:
            z_lens = self._redshift_list[idex]
            if z_before == z_lens:
                delta_T = 0
            else:
                delta_T = self._cosmo_bkg.T_xy(z_before, z_lens)
            self._T_ij_list.append(delta_T)
            T_z = self._cosmo_bkg.T_xy(0, z_lens)
            self._T_z_list.append(T_z)
            factor = self._cosmo_bkg.D_xy(0, z_source) / self._cosmo_bkg.D_xy(
                z_lens, z_source)
            self._reduced2physical_factor.append(factor)
            z_before = z_lens
        delta_T = self._cosmo_bkg.T_xy(z_before, z_source)
        self._T_ij_list.append(delta_T)
        self._T_z_source = self._cosmo_bkg.T_xy(0, z_source)
        sum_partial = np.sum(self._T_ij_list)
        if np.abs(sum_partial - self._T_z_source) > 0.1:
            print(
                "Numerics in multi-plane compromised by too narrow spacing of too many redshift bins"
            )
예제 #20
0
    def execute(self, parameters={}):
        r'''Run a pipeline.

        This function runs a pipeline of functions to generate variables and
        the columns of a set of tables. It uses a Directed Acyclic Graph to
        determine a non-blocking order of execution that resolves any
        dependencies, see [1]_.

        Parameters
        ----------
        parameters : dict
            Updated parameter values for this execution.

        References
        ----------
        .. [1] https://networkx.github.io/documentation/stable/

        '''
        # update parameter state
        self.parameters.update(parameters)

        # initialise state object
        self.state = copy(self.parameters)

        # Initialise cosmology from config parameters or use astropy default
        if self.cosmology:
            self.state['cosmology'] = self.get_value(self.cosmology)
        else:
            self.state['cosmology'] = default_cosmology.get()

        # Execute pipeline setting state cosmology as the default
        with default_cosmology.set(self.state['cosmology']):

            # go through the jobs in dependency order
            for job in networkx.topological_sort(self.dag):
                if job in self.skip_jobs:
                    continue
                elif job in self.config:
                    settings = self.config.get(job)
                    self.state[job] = self.get_value(settings)
                else:
                    table, column = job.split('.')
                    settings = self.table_config[table][column]
                    names = [n.strip() for n in column.split(',')]
                    if len(names) > 1:
                        # Multi-column assignment
                        t = Table(self.get_value(settings), names=names)
                        self.state[table].add_columns(t.columns.values())
                    else:
                        # Single column assignment
                        self.state[table][column] = self.get_value(settings)
예제 #21
0
def test_schechter_lf_magnitude():
    from skypy.galaxy.luminosity import schechter_lf_magnitude
    from astropy.cosmology import default_cosmology
    import pytest

    # use default cosmology
    cosmo = default_cosmology.get()

    # Schechter function parameters for tests
    M_star = -20.5
    alpha = -1.3

    # sample 1000 galaxies at a fixed redshift of 1.0
    z = np.repeat(1.0, 1000)
    M = schechter_lf_magnitude(z, M_star, alpha, 30., cosmo)

    # get the distribution function
    log10_x_min = -0.4 * (30. - cosmo.distmod(1.0).value - M_star)
    x = np.logspace(log10_x_min, log10_x_min + 3, 1000)
    pdf = x**(alpha + 1) * np.exp(-x)
    cdf = np.concatenate([[0.],
                          np.cumsum(
                              (pdf[1:] + pdf[:-1]) / 2 * np.diff(np.log(x)))])
    cdf /= cdf[-1]

    # test the samples against the CDF
    D, p = kstest(10.**(-0.4 * (M - M_star)), lambda t: np.interp(t, x, cdf))
    assert p > 0.01, 'D = {}, p = {}'.format(D, p)

    # test for 1000 galaxies with Pareto redshift distribution
    z = np.random.pareto(3., size=1000)

    # for scalar parameters, sample galaxies with magnitude limit of 30
    M = schechter_lf_magnitude(z, M_star, alpha, 30., cosmo)

    # check that the output has the correct shape
    assert np.shape(M) == (1000, )

    # make sure magnitude limit was respected
    M_lim = 30. - cosmo.distmod(z).value
    assert np.all(M <= M_lim)

    # sample with array for alpha
    # not implemented at the moment
    with pytest.raises(NotImplementedError):
        M = schechter_lf_magnitude(z, M_star, np.broadcast_to(alpha, z.shape),
                                   30., cosmo)

    # sample with an explicit size
    schechter_lf_magnitude(1.0, M_star, alpha, 30., cosmo, size=100)
예제 #22
0
def test_magnitude_functions():

    from astropy.cosmology import default_cosmology

    from skypy.galaxy.luminosity import (absolute_to_apparent_magnitude,
                                         apparent_to_absolute_magnitude,
                                         distance_modulus, luminosity_in_band,
                                         luminosity_from_absolute_magnitude,
                                         absolute_magnitude_from_luminosity)

    cosmo = default_cosmology.get()

    # sample some redshifts
    z = np.random.uniform(0, 10, size=1000)

    # sample some absolute magnitudes
    M = np.random.uniform(15, 25, size=1000)

    # sample distance moduli
    DM = cosmo.distmod(z).value

    # compare with function
    np.testing.assert_allclose(distance_modulus(z), DM)

    # compute apparent magnitudes
    m = absolute_to_apparent_magnitude(M, DM)

    # compare with values
    np.testing.assert_allclose(m, M + DM)

    # go back to absolute magnitudes
    M_ = apparent_to_absolute_magnitude(m, DM)

    # compare with original values
    np.testing.assert_allclose(M_, M)

    # convert between absolute luminosity and magnitude
    assert np.isclose(luminosity_from_absolute_magnitude(-22), 630957344.5)
    assert np.isclose(absolute_magnitude_from_luminosity(630957344.5), -22)

    # convert with standard luminosities
    for ref, mag in luminosity_in_band.items():
        assert np.isclose(luminosity_from_absolute_magnitude(mag, ref), 1.0)
        assert np.isclose(absolute_magnitude_from_luminosity(1.0, ref), mag)

    # error when unknown reference is used
    with pytest.raises(KeyError):
        luminosity_from_absolute_magnitude(0., 'unknown')
    with pytest.raises(KeyError):
        absolute_magnitude_from_luminosity(1., 'unknown')
예제 #23
0
    def test_distance_off(self, cosmo):
        """Test ``with_redshift`` with the distance off."""
        default_cosmo = default_cosmology.get()
        z = 15 * cu.redshift

        # 1) Default (without specifying the cosmology)
        with default_cosmology.set(cosmo):
            equivalency = cu.with_redshift(distance=None)
            with pytest.raises(u.UnitConversionError, match="'redshift' and 'Mpc'"):
                z.to(u.Mpc, equivalency)

        # 2) Specifying the cosmology
        equivalency = cu.with_redshift(cosmo, distance=None)
        with pytest.raises(u.UnitConversionError, match="'redshift' and 'Mpc'"):
            z.to(u.Mpc, equivalency)
예제 #24
0
    def test_temperature_off(self, cosmo):
        """Test ``with_redshift`` with the temperature off."""
        default_cosmo = default_cosmology.get()
        z = 15 * cu.redshift
        Tcmb = cosmo.Tcmb(z)

        # 1) Default (without specifying the cosmology)
        with default_cosmology.set(cosmo):
            equivalency = cu.with_redshift(Tcmb=False)
            with pytest.raises(u.UnitConversionError, match="'redshift' and 'K'"):
                z.to(u.K, equivalency)

        # 2) Specifying the cosmology
        equivalency = cu.with_redshift(cosmo, Tcmb=False)
        with pytest.raises(u.UnitConversionError, match="'redshift' and 'K'"):
            z.to(u.K, equivalency)
예제 #25
0
    def __init__(self, cosmo=None, interp=False, **kwargs_interp):
        """

        :param cosmo: instance of astropy.cosmology
        :param interp: boolean, if True, uses interpolated cosmology to evaluate specific redshifts
        :param kwargs_interp: keyword arguments of CosmoInterp specifying the interpolation interval and maximum
         redshift
        :return: Background class with instance of astropy.cosmology
        """

        if cosmo is None:
            from astropy.cosmology import default_cosmology
            cosmo = default_cosmology.get()
        if interp:
            self.cosmo = CosmoInterp(cosmo, **kwargs_interp)
        else:
            self.cosmo = cosmo
예제 #26
0
    def test_hubble_off(self, cosmo):
        """Test ``with_redshift`` with Hubble off."""
        unit = u.km / u.s / u.Mpc
        default_cosmo = default_cosmology.get()
        z = 15 * cu.redshift
        H = cosmo.H(z)

        # 1) Default (without specifying the cosmology)
        with default_cosmology.set(cosmo):
            equivalency = cu.with_redshift(hubble=False)
            with pytest.raises(u.UnitConversionError, match="'redshift' and 'km / "):
                z.to(unit, equivalency)

        # 2) Specifying the cosmology
        equivalency = cu.with_redshift(cosmo, hubble=False)
        with pytest.raises(u.UnitConversionError, match="'redshift' and 'km / "):
            z.to(unit, equivalency)
예제 #27
0
    def __init__(self, z_source, lens_model_list, redshift_list, cosmo=None):
        """

        :param cosmo: instance of astropy.cosmology
        :return: Background class with instance of astropy.cosmology
        """
        from astropy.cosmology import default_cosmology

        if cosmo is None:
            cosmo = default_cosmology.get()
        self._cosmo_bkg = Background(cosmo)
        self._z_source = z_source
        if not len(lens_model_list) == len(redshift_list):
            raise ValueError("The length of lens_model_list does not correspond to redshift_list")
        self._lens_model_list = lens_model_list
        self._redshift_list = redshift_list
        self._sorted_redshift_index = self._index_ordering(redshift_list)
        self._lens_model = SinglePlane(lens_model_list)
예제 #28
0
    def __init__(self, lens_model_list, z_lens=None, z_source=None, lens_redshift_list=None, cosmo=None,
                 multi_plane=False, numerical_alpha_class=None, observed_convention_index=None, z_source_convention=None):
        """

        :param lens_model_list: list of strings with lens model names
        :param z_lens: redshift of the deflector (only considered when operating in single plane mode).
        Is only needed for specific functions that require a cosmology.
        :param z_source: redshift of the source: Needed in multi_plane option only,
        not required for the core functionalities in the single plane mode.
        :param lens_redshift_list: list of deflector redshift (corresponding to the lens model list),
        only applicable in multi_plane mode.
        :param cosmo: instance of the astropy cosmology class. If not specified, uses the default cosmology.
        :param multi_plane: bool, if True, uses multi-plane mode. Default is False.
        :param numerical_alpha_class: an instance of a custom class for use in NumericalAlpha() lens model
        (see documentation in Profiles/numerical_alpha)
        :param observed_convention_index: a list of lens indexes that correspond to observed positions on the sky, not
        physical positions
        :param z_source_convention: float, redshift of a source to define the reduced deflection angles of the lens
        models. If None, 'z_source' is used.
        """
        self.lens_model_list = lens_model_list
        self.z_lens = z_lens
        if z_source_convention is None:
            z_source_convention = z_source
        self.z_source = z_source
        self._z_source_convention = z_source_convention
        self.redshift_list = lens_redshift_list

        if cosmo is None:
            cosmo = default_cosmology.get()
        self.cosmo = cosmo
        self.multi_plane = multi_plane
        if multi_plane is True:
            if z_source is None:
                raise ValueError('z_source needs to be set for multi-plane lens modelling.')

            self.lens_model = MultiPlane(z_source, lens_model_list, lens_redshift_list, cosmo=cosmo,
                                         numerical_alpha_class=numerical_alpha_class,
                                         observed_convention_index=observed_convention_index,
                                         z_source_convention=z_source_convention)
        else:
            self.lens_model = SinglePlane(lens_model_list, numerical_alpha_class=numerical_alpha_class)
        if z_lens is not None and z_source is not None:
            self._lensCosmo = LensCosmo(z_lens, z_source, cosmo=cosmo)
예제 #29
0
    def compute_z(self, cosmology=None, **atzkw):
        """
        The redshift for this distance assuming its physical distance is
        a luminosity distance.

        Parameters
        ----------
        cosmology : `~astropy.cosmology.Cosmology` or None
            The cosmology to assume for this calculation, or `None` to use the
            current cosmology (see `astropy.cosmology` for details).
        **atzkw
            keyword arguments for :func:`~astropy.cosmology.z_at_value`

        Returns
        -------
        z : `~astropy.units.Quantity`
            The redshift of this distance given the provided ``cosmology``.

        Warnings
        --------
        This method can be slow for large arrays.
        The redshift is determined using :func:`astropy.cosmology.z_at_value`,
        which handles vector inputs (e.g. an array of distances) by
        element-wise calling of :func:`scipy.optimize.minimize_scalar`.
        For faster results consider using an interpolation table;
        :func:`astropy.cosmology.z_at_value` provides details.

        See Also
        --------
        :func:`astropy.cosmology.z_at_value`
            Find the redshift corresponding to a
            :meth:`astropy.cosmology.FLRW.luminosity_distance`.
        """
        from astropy.cosmology import z_at_value

        if cosmology is None:
            from astropy.cosmology import default_cosmology
            cosmology = default_cosmology.get()

        atzkw.setdefault("ztol", 1.e-10)
        return z_at_value(cosmology.luminosity_distance, self, **atzkw)
예제 #30
0
def test_littleh():
    """Test :func:`astropy.cosmology.units.with_H0`."""
    H0_70 = 70 * u.km / u.s / u.Mpc
    h70dist = 70 * u.Mpc / cu.littleh

    assert_quantity_allclose(h70dist.to(u.Mpc, cu.with_H0(H0_70)), 100 * u.Mpc)

    # make sure using the default cosmology works
    cosmodist = default_cosmology.get().H0.value * u.Mpc / cu.littleh
    assert_quantity_allclose(cosmodist.to(u.Mpc, cu.with_H0()), 100 * u.Mpc)

    # Now try a luminosity scaling
    h1lum = 0.49 * u.Lsun * cu.littleh ** -2
    assert_quantity_allclose(h1lum.to(u.Lsun, cu.with_H0(H0_70)), 1 * u.Lsun)

    # And the trickiest one: magnitudes.  Using H0=10 here for the round numbers
    H0_10 = 10 * u.km / u.s / u.Mpc
    # assume the "true" magnitude M = 12.
    # Then M - 5*log_10(h)  = M + 5 = 17
    withlittlehmag = 17 * (u.mag - u.MagUnit(cu.littleh ** 2))
    assert_quantity_allclose(withlittlehmag.to(u.mag, cu.with_H0(H0_10)), 12 * u.mag)
예제 #31
0
def thermodynamic_temperature(frequency, T_cmb=None):
    r"""Defines the conversion between Jy/sr and "thermodynamic temperature",
    :math:`T_{CMB}`, in Kelvins.  The thermodynamic temperature is a unit very
    commonly used in cosmology. See eqn 8 in [1]

    :math:`K_{CMB} \equiv I_\nu / \left(2 k \nu^2 / c^2  f(\nu) \right)`

    with :math:`f(\nu) = \frac{ x^2 e^x}{(e^x - 1 )^2}`
    where :math:`x = h \nu / k T`

    Parameters
    ----------
    frequency : `~astropy.units.Quantity` with spectral units
        The observed `spectral` equivalent `~astropy.units.Unit` (e.g.,
        frequency or wavelength)
    T_cmb :  `~astropy.units.Quantity` with temperature units or None
        The CMB temperature at z=0.  If `None`, the default cosmology will be
        used to get this temperature.

    Notes
    -----
    For broad band receivers, this conversion do not hold
    as it highly depends on the frequency

    References
    ----------
    .. [1] Planck 2013 results. IX. HFI spectral response
       https://arxiv.org/abs/1303.5070

    Examples
    --------
    Planck HFI 143 GHz::

        >>> from astropy import units as u
        >>> from astropy.cosmology import Planck15
        >>> freq = 143 * u.GHz
        >>> equiv = u.thermodynamic_temperature(freq, Planck15.Tcmb0)
        >>> (1. * u.mK).to(u.MJy / u.sr, equivalencies=equiv)  # doctest: +FLOAT_CMP
        <Quantity 0.37993172 MJy / sr>

    """
    nu = frequency.to(si.GHz, spectral())

    if T_cmb is None:
        from astropy.cosmology import default_cosmology
        T_cmb = default_cosmology.get().Tcmb0

    def f(nu, T_cmb=T_cmb):
        x = _si.h * nu / _si.k_B / T_cmb
        return x**2 * np.exp(x) / np.expm1(x)**2

    def convert_Jy_to_K(x_jybm):
        factor = (f(nu) * 2 * _si.k_B * si.K * nu**2 / _si.c**2).to_value(astrophys.Jy)
        return x_jybm / factor

    def convert_K_to_Jy(x_K):
        factor = (astrophys.Jy / (f(nu) * 2 * _si.k_B * nu**2 / _si.c**2)).to_value(si.K)
        return x_K / factor

    return Equivalency([(astrophys.Jy/si.sr, si.K, convert_Jy_to_K, convert_K_to_Jy)],
                       "thermodynamic_temperature", {'frequency': frequency, "T_cmb": T_cmb})
예제 #32
0
import healpy as hp
import numpy as np
from scipy.stats import norm
from scipy.special import gammaincinv
from scipy.special import gammaincc
import cosmolopy.magnitudes as mag
from astropy.utils.data import download_file
from astropy.cosmology import default_cosmology
cosmo = default_cosmology.get()

from observational_const import *
import sys

#parameters:
credzone = 0.99
nsigmas_in_d = 3
ngalaxtoshow = 200
airmass_thresholdp = 10
completenessp = 0.5
minGalaxies = 60

#schecter funtion parameters:
alpha = -1.07
MB_star = -20.7 ## random slide from https://www.astro.umd.edu/~richard/ASTRO620/LumFunction-pp.pdf but not really...?



def find_galaxy_list(map_path, airmass_threshold = airmass_thresholdp, completeness = completenessp, credzone = 0.99):

    #loading the map:
    prob, distmu, distsigma, distnorm = hp.read_map(map_path, field=[0, 1, 2, 3], verbose=False)