Exemple #1
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
                         })
Exemple #2
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)
Exemple #3
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})
Exemple #4
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)
Exemple #5
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)
Exemple #6
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)
Exemple #7
0
    def test_distance_off(self, cosmo):
        """Test ``with_redshift`` with the distance off."""
        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)
Exemple #8
0
    def test_temperature_off(self, cosmo):
        """Test ``with_redshift`` with the temperature off."""
        z = 15 * cu.redshift

        # 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)
Exemple #9
0
    def test_hubble_off(self, cosmo):
        """Test ``with_redshift`` with Hubble off."""
        unit = u.km / u.s / u.Mpc
        z = 15 * cu.redshift

        # 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)
Exemple #10
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
    })
Exemple #11
0
    def test_hubble(self, cosmo):
        """Test Hubble equivalency component."""
        unit = u.km / u.s / u.Mpc
        default_cosmo = default_cosmology.get()
        z = 15 * cu.redshift
        H = cosmo.H(z)
        h = H.to_value(u.km / u.s / u.Mpc) / 100 * cu.littleh

        # 1) Default (without specifying the cosmology)
        with default_cosmology.set(cosmo):
            equivalency = cu.with_redshift(hubble=True)
            # H
            assert_quantity_allclose(z.to(unit, equivalency), H)
            assert_quantity_allclose(H.to(cu.redshift, equivalency), z)
            # little-h
            assert_quantity_allclose(z.to(cu.littleh, equivalency), h)
            assert_quantity_allclose(h.to(cu.redshift, equivalency), z)

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

        # 2) Specifying the cosmology
        equivalency = cu.with_redshift(cosmo, hubble=True)
        # H
        assert_quantity_allclose(z.to(unit, equivalency), H)
        assert_quantity_allclose(H.to(cu.redshift, equivalency), z)
        # little-h
        assert_quantity_allclose(z.to(cu.littleh, equivalency), h)
        assert_quantity_allclose(h.to(cu.redshift, equivalency), z)

        # Test `atzkw`
        # this is really just a test that 'atzkw' doesn't fail
        equivalency = cu.with_redshift(cosmo,
                                       hubble=True,
                                       atzkw={"ztol": 1e-10})
        assert_quantity_allclose(H.to(cu.redshift, equivalency), z)  # H
        assert_quantity_allclose(h.to(cu.redshift, equivalency), z)  # h
Exemple #12
0
def test_redshift_hubble():
    """Test :func:`astropy.cosmology.units.redshift_hubble`."""
    unit = u.km / u.s / u.Mpc
    cosmo = Planck13.clone(H0=100 * unit)
    default_cosmo = default_cosmology.get()
    z = 15 * cu.redshift
    H = cosmo.H(z)
    h = H.to_value(u.km/u.s/u.Mpc) / 100 * cu.littleh

    # 1) Default (without specifying the cosmology)
    with default_cosmology.set(cosmo):
        equivalency = cu.redshift_hubble()
        # H
        assert_quantity_allclose(z.to(unit, equivalency), H)
        assert_quantity_allclose(H.to(cu.redshift, equivalency), z)
        # little-h
        assert_quantity_allclose(z.to(cu.littleh, equivalency), h)
        assert_quantity_allclose(h.to(cu.redshift, equivalency), z)

    # showing the answer changes if the cosmology changes
    # this test uses the default cosmology
    equivalency = cu.redshift_hubble()
    assert_quantity_allclose(z.to(unit, equivalency), default_cosmo.H(z))
    assert default_cosmo.H(z) != H

    # 2) Specifying the cosmology
    equivalency = cu.redshift_hubble(cosmo)
    # H
    assert_quantity_allclose(z.to(unit, equivalency), H)
    assert_quantity_allclose(H.to(cu.redshift, equivalency), z)
    # little-h
    assert_quantity_allclose(z.to(cu.littleh, equivalency), h)
    assert_quantity_allclose(h.to(cu.redshift, equivalency), z)

    # Test `atzkw`
    equivalency = cu.redshift_hubble(cosmo, ztol=1e-10)
    assert_quantity_allclose(H.to(cu.redshift, equivalency), z)  # H
    assert_quantity_allclose(h.to(cu.redshift, equivalency), z)  # little-h
Exemple #13
0
def with_redshift(cosmology=None,
                  *,
                  distance="comoving",
                  hubble=True,
                  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`).

    distance : {'comoving', 'lookback', 'luminosity'} or None (optional, keyword-only)
        The type of distance equivalency to create or `None`.
        Default is 'comoving'.
    hubble : bool (optional, keyword-only)
        Whether to create a Hubble parameter <-> redshift equivalency, using
        ``Cosmology.H``. Default is `True`.
    Tcmb : bool (optional, keyword-only)
        Whether to create a CMB temperature <-> redshift equivalency, using
        ``Cosmology.Tcmb``. Default is `True`.

    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 distance / Hubble / temperature.

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

    >>> equivalency = cu.with_redshift(WMAP9)
    >>> z = 1100 * cu.redshift

    Redshift to (comoving) distance:

    >>> z.to(u.Mpc, equivalency)  # doctest: +FLOAT_CMP
    <Quantity 14004.03157418 Mpc>

    Redshift to the Hubble parameter:

    >>> z.to(u.km / u.s / u.Mpc, equivalency)  # doctest: +FLOAT_CMP
    <Quantity 1565637.40154275 km / (Mpc s)>

    >>> z.to(cu.littleh, equivalency)  # doctest: +FLOAT_CMP
    <Quantity 15656.37401543 littleh>

    Redshift to CMB temperature:

    >>> z.to(u.K, equivalency)
    <Quantity 3000.225 K>
    """
    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

    # Hubble <-> Redshift
    if hubble:
        equivs.extend(redshift_hubble(cosmology, **atzkw))

    # CMB Temperature <-> Redshift
    if Tcmb:
        equivs.extend(redshift_temperature(cosmology, **atzkw))

    # Distance <-> Redshift, but need to choose which distance
    if distance is not None:
        equivs.extend(redshift_distance(cosmology, kind=distance, **atzkw))

    # -----------
    return u.Equivalency(
        equivs, "with_redshift", {
            'cosmology': cosmology,
            'distance': distance,
            'hubble': hubble,
            'Tcmb': Tcmb
        })
Exemple #14
0
def redshift_hubble(cosmology=None, **atzkw):
    """Convert quantities between redshift and Hubble parameter and little-h.

    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 Hubble parameter and little-h unit.

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

    >>> z = 1100 * cu.redshift
    >>> equivalency = cu.redshift_hubble(WMAP9)  # construct equivalency

    >>> z.to(u.km / u.s / u.Mpc, equivalency)  # doctest: +FLOAT_CMP
    <Quantity 1565637.40154275 km / (Mpc s)>

    >>> z.to(cu.littleh, equivalency)  # doctest: +FLOAT_CMP
    <Quantity 15656.37401543 littleh>
    """
    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_hubble(z):
        """Redshift to Hubble parameter."""
        return cosmology.H(z)

    def hubble_to_z(H):
        """Hubble parameter to redshift."""
        return z_at_value(cosmology.H, H << (u.km / u.s / u.Mpc), **atzkw)

    def z_to_littleh(z):
        """Redshift to :math:`h`-unit Quantity."""
        return z_to_hubble(z).to_value(u.km / u.s / u.Mpc) / 100 * littleh

    def littleh_to_z(h):
        """:math:`h`-unit Quantity to redshift."""
        return hubble_to_z(h * 100)

    return u.Equivalency(
        [(redshift, u.km / u.s / u.Mpc, z_to_hubble, hubble_to_z),
         (redshift, littleh, z_to_littleh, littleh_to_z)], "redshift_hubble",
        {'cosmology': cosmology})