Python astropy.units.cm() Examples

The following are 30 code examples of astropy.units.cm(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module astropy.units , or try the search function .
Example #1
Source File: dm_models.py    From astromodels with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def evaluate(self, x, mass, channel, sigmav, J):

        if isinstance(x, astropy_units.Quantity):

            # We need to convert to GeV
            xx = x.to(astropy_units.MeV)

        else:

            # We can assume that the input is in keV

            keVtoGeV = 1E-6

            xx = np.multiply(x, keVtoGeV)  # xm expects gamma ray energies in MeV

        xm = np.log10(np.divide(xx, mass))

        phip = 1. / (8. * np.pi) * np.power(mass, -2) * (sigmav * J)  # units of this should be 1 / cm**2
        dn = self._dn_interp((mass, xm))  # note this is unitless (dx = d(xm))
        dn[xm > 0] = 0

        return np.multiply(phip, np.divide(dn, x)) 
Example #2
Source File: test_geometry.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_guess_area():
    x = u.Quantity([0, 1, 2], u.cm)
    y = u.Quantity([0, 0, 0], u.cm)
    n_pixels = len(x)

    geom = CameraGeometry(
        "test",
        pix_id=np.arange(n_pixels),
        pix_area=None,
        pix_x=x,
        pix_y=y,
        pix_type="rect",
    )

    assert np.all(geom.pix_area == 1 * u.cm ** 2)

    geom = CameraGeometry(
        "test",
        pix_id=np.arange(n_pixels),
        pix_area=None,
        pix_x=x,
        pix_y=y,
        pix_type="hexagonal",
    )
    assert u.allclose(geom.pix_area, 2 * np.sqrt(3) * (0.5 * u.cm) ** 2) 
Example #3
Source File: test_column.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_qtable_column_conversion():
    """
    Ensures that a QTable that gets assigned a unit switches to be Quantity-y
    """
    qtab = table.QTable([[1, 2], [3, 4.2]], names=['i', 'f'])

    assert isinstance(qtab['i'], table.column.Column)
    assert isinstance(qtab['f'], table.column.Column)

    qtab['i'].unit = 'km/s'
    assert isinstance(qtab['i'], u.Quantity)
    assert isinstance(qtab['f'], table.column.Column)

    # should follow from the above, but good to make sure as a #4497 regression test
    assert isinstance(qtab['i'][0], u.Quantity)
    assert isinstance(qtab[0]['i'], u.Quantity)
    assert not isinstance(qtab['f'][0], u.Quantity)
    assert not isinstance(qtab[0]['f'], u.Quantity)

    # Regression test for #5342: if a function unit is assigned, the column
    # should become the appropriate FunctionQuantity subclass.
    qtab['f'].unit = u.dex(u.cm/u.s**2)
    assert isinstance(qtab['f'], u.Dex) 
Example #4
Source File: test_ccddata.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_arithmetic_overload_differing_units():
    a = np.array([1, 2, 3]) * u.m
    b = np.array([1, 2, 3]) * u.cm
    ccddata = CCDData(a)

    # TODO: Could also be parametrized.
    res = ccddata.add(b)
    np.testing.assert_array_almost_equal(res.data, np.add(a, b).value)
    assert res.unit == np.add(a, b).unit

    res = ccddata.subtract(b)
    np.testing.assert_array_almost_equal(res.data, np.subtract(a, b).value)
    assert res.unit == np.subtract(a, b).unit

    res = ccddata.multiply(b)
    np.testing.assert_array_almost_equal(res.data, np.multiply(a, b).value)
    assert res.unit == np.multiply(a, b).unit

    res = ccddata.divide(b)
    np.testing.assert_array_almost_equal(res.data, np.divide(a, b).value)
    assert res.unit == np.divide(a, b).unit 
Example #5
Source File: test_hillas.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_single_pixel():
    x = y = np.arange(3)
    x, y = np.meshgrid(x, y)

    geom = CameraGeometry(
        camera_name="testcam",
        pix_id=np.arange(9),
        pix_x=x.ravel() * u.cm,
        pix_y=y.ravel() * u.cm,
        pix_type="rectangular",
        pix_area=1 * u.cm ** 2,
    )

    image = np.zeros((3, 3))
    image[1, 1] = 10
    image = image.ravel()

    hillas = hillas_parameters(geom, image)

    assert hillas.length.value == 0
    assert hillas.width.value == 0
    assert np.isnan(hillas.psi) 
Example #6
Source File: test_representation.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_cartesian_cylindrical_roundtrip():

    s1 = CartesianRepresentation(x=np.array([1., 2000.]) * u.kpc,
                                 y=np.array([3000., 4.]) * u.pc,
                                 z=np.array([5., 600.]) * u.cm)

    s2 = CylindricalRepresentation.from_representation(s1)

    s3 = CartesianRepresentation.from_representation(s2)

    s4 = CylindricalRepresentation.from_representation(s3)

    assert_allclose_quantity(s1.x, s3.x)
    assert_allclose_quantity(s1.y, s3.y)
    assert_allclose_quantity(s1.z, s3.z)

    assert_allclose_quantity(s2.rho, s4.rho)
    assert_allclose_quantity(s2.phi, s4.phi)
    assert_allclose_quantity(s2.z, s4.z) 
Example #7
Source File: test_geometry.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_find_neighbor_pixels():
    """ test basic neighbor functionality """
    n_pixels = 5
    x, y = u.Quantity(
        np.meshgrid(np.linspace(-5, 5, n_pixels), np.linspace(-5, 5, n_pixels)), u.cm
    )

    geom = CameraGeometry(
        "test",
        pix_id=np.arange(n_pixels),
        pix_area=u.Quantity(4, u.cm ** 2),
        pix_x=x.ravel(),
        pix_y=y.ravel(),
        pix_type="rectangular",
    )

    neigh = geom.neighbors
    assert set(neigh[11]) == {16, 6, 10, 12} 
Example #8
Source File: model.py    From grizli with MIT License 6 votes vote down vote up
def trace_table(self):
        """
        Table of trace parameters.  Trace is unit-indexed.
        """
        dtype = np.float32

        tab = utils.GTable()
        tab.meta['CONFFILE'] = os.path.basename(self.beam.conf.conf_file)

        tab['wavelength'] = np.cast[dtype](self.beam.lam*u.Angstrom)
        tab['trace'] = np.cast[dtype](self.beam.ytrace + self.beam.sh_beam[0]/2 - self.beam.ycenter)

        sens_units = u.erg/u.second/u.cm**2/u.Angstrom/(u.electron/u.second)
        tab['sensitivity'] = np.cast[dtype](self.beam.sensitivity*sens_units)

        return tab 
Example #9
Source File: test_quantity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_complicated_operation(self):
        """ Perform a more complicated test """
        from astropy.units import imperial

        # Multiple units
        distance = u.Quantity(15., u.meter)
        time = u.Quantity(11., u.second)

        velocity = (distance / time).to(imperial.mile / u.hour)
        assert_array_almost_equal(
            velocity.value, 3.05037, decimal=5)

        G = u.Quantity(6.673E-11, u.m ** 3 / u.kg / u.s ** 2)
        new_q = ((1. / (4. * np.pi * G)).to(u.pc ** -3 / u.s ** -2 * u.kg))

        # Area
        side1 = u.Quantity(11., u.centimeter)
        side2 = u.Quantity(7., u.centimeter)
        area = side1 * side2
        assert_array_almost_equal(area.value, 77., decimal=15)
        assert area.unit == u.cm * u.cm 
Example #10
Source File: test_quantity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_quantity_value_views():
    q1 = u.Quantity([1., 2.], unit=u.meter)
    # views if the unit is the same.
    v1 = q1.value
    v1[0] = 0.
    assert np.all(q1 == [0., 2.] * u.meter)
    v2 = q1.to_value()
    v2[1] = 3.
    assert np.all(q1 == [0., 3.] * u.meter)
    v3 = q1.to_value('m')
    v3[0] = 1.
    assert np.all(q1 == [1., 3.] * u.meter)
    v4 = q1.to_value('cm')
    v4[0] = 0.
    # copy if different unit.
    assert np.all(q1 == [1., 3.] * u.meter) 
Example #11
Source File: test_geometry.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_calc_pixel_neighbors_square_diagonal():
    """
    check that neighbors for square-pixel cameras are what we expect,
    namely that the diagonals are included if requested.
    """
    x, y = np.meshgrid(np.arange(20), np.arange(20))

    cam = CameraGeometry(
        camera_name="test",
        pix_id=np.arange(400),
        pix_type="rectangular",
        pix_x=u.Quantity(x.ravel(), u.cm),
        pix_y=u.Quantity(y.ravel(), u.cm),
        pix_area=u.Quantity(np.ones(400), u.cm ** 2),
    )

    cam._neighbors = cam.calc_pixel_neighbors(diagonal=True)
    assert set(cam.neighbors[21]) == {0, 1, 2, 20, 22, 40, 41, 42} 
Example #12
Source File: test_hdf5.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_units():
    class WithUnits(Container):
        inverse_length = Field(5 / u.m, "foo")
        time = Field(1 * u.s, "bar", unit=u.s)
        grammage = Field(2 * u.g / u.cm ** 2, "baz", unit=u.g / u.cm ** 2)

    c = WithUnits()

    with tempfile.NamedTemporaryFile() as f:
        with HDF5TableWriter(f.name, "data") as writer:
            writer.write("units", c)

        with tables.open_file(f.name, "r") as f:

            assert f.root.data.units.attrs["inverse_length_UNIT"] == "m-1"
            assert f.root.data.units.attrs["time_UNIT"] == "s"
            assert f.root.data.units.attrs["grammage_UNIT"] == "cm-2 g" 
Example #13
Source File: test_quantities.py    From marvin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def datacube():
    """Produces a simple 3D array for datacube testing."""

    flux = numpy.tile([numpy.arange(1, 1001, dtype=numpy.float32)],
                      (100, 1)).T.reshape(1000, 10, 10)
    ivar = (1. / (flux / 100))**2
    mask = numpy.zeros(flux.shape, dtype=numpy.int)
    wave = numpy.arange(1, 1001)

    redcorr = numpy.ones(1000) * 1.5

    mask[50:100, 5, 5] = 2**10
    mask[500:600, 3, 3] = 2**4

    scale = 1e-3

    datacube = DataCube(flux, wave, ivar=ivar, mask=mask, redcorr=redcorr, scale=scale,
                        unit=u.erg / u.s / (u.cm ** 2) / u.Angstrom / spaxel_unit,
                        pixmask_flag='MANGA_DRP3PIXMASK')

    yield datacube 
Example #14
Source File: test_quantities.py    From marvin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def spectrum():
    """Produces a simple 1D array for datacube testing."""

    flux = numpy.arange(1, 1001, dtype=numpy.float32)
    ivar = (1. / (flux / 100))**2
    mask = numpy.zeros(flux.shape, dtype=numpy.int)
    wave = numpy.arange(1, 1001)

    mask[50:100] = 2**10
    mask[500:600] = 2**4

    scale = 1e-3

    datacube = Spectrum(flux, wave, ivar=ivar, mask=mask, scale=scale,
                        unit=u.erg / u.s / (u.cm ** 2) / u.Angstrom / spaxel_unit,
                        pixmask_flag='MANGA_DRP3PIXMASK')

    yield datacube 
Example #15
Source File: test_quantities_parameters.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_parameter_change_unit():
    """
    Test that changing the unit on a parameter does not work. This is an
    ambiguous operation because it's not clear if it means that the value should
    be converted or if the unit should be changed without conversion.
    """

    g = Gaussian1D(1, 1 * u.m, 0.1 * u.m)

    # Setting a unit on a unitless parameter should not work
    with pytest.raises(ValueError) as exc:
        g.amplitude.unit = u.Jy
    assert exc.value.args[0] == ("Cannot attach units to parameters that were "
                                 "not initially specified with units")

    # But changing to another unit should not, even if it is an equivalent unit
    with pytest.raises(ValueError) as exc:
        g.mean.unit = u.cm
    assert exc.value.args[0] == ("Cannot change the unit attribute directly, "
                                 "instead change the parameter to a new quantity") 
Example #16
Source File: apec.py    From astromodels with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def evaluate(self, x, NH, redshift):

            if isinstance(x, astropy_units.Quantity):

                _unit = astropy_units.cm ** 2
                _y_unit = astropy_units.dimensionless_unscaled
                _x = x.value

            else:

                _unit = 1.0
                _y_unit = 1.0

                _x = x

            xsect_interp = self._cached_interp(_x * (1 + redshift))

            spec = np.exp(-NH * xsect_interp * _unit) * _y_unit

            return spec


    # TbAbs class 
Example #17
Source File: test_physical_models.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_blackbody_overflow():
    """Test Planck function with overflow."""
    photlam = u.photon / (u.cm ** 2 * u.s * u.AA)
    wave = [0.0, 1000.0, 100000.0, 1e55]  # Angstrom
    temp = 10000.0  # Kelvin
    bb = BlackBody(temperature=temp * u.K, scale=1.0)
    with pytest.warns(
            AstropyUserWarning,
            match=r'Input contains invalid wavelength/frequency value\(s\)'):
        with np.errstate(all="ignore"):
            bb_lam = bb(wave) * u.sr
    flux = bb_lam.to(photlam, u.spectral_density(wave * u.AA)) / u.sr

    # First element is NaN, last element is very small, others normal
    assert np.isnan(flux[0])
    with np.errstate(all="ignore"):
        assert np.log10(flux[-1].value) < -134
    np.testing.assert_allclose(
        flux.value[1:-1], [0.00046368, 0.04636773], rtol=1e-3
    )  # 0.1% accuracy in PHOTLAM/sr
    with np.errstate(all="ignore"):
        flux = bb(1.0 * u.AA)
    assert flux.value == 0 
Example #18
Source File: test_parameter.py    From astromodels with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_set_units():

    p = Parameter('test_parameter',1.0, unit=u.keV)

    p.value = 3.0 * u.MeV

    assert p.value == 3000.0

    with pytest.raises(u.UnitConversionError):

        p.value = 3.0 * u.cm

    with pytest.raises(CannotConvertValueToNewUnits):

        p.unit = u.cm

    with pytest.raises(CannotConvertValueToNewUnits):

        p.unit = u.dimensionless_unscaled

    p.unit = u.MeV

    assert p.unit == u.MeV

    p.display() 
Example #19
Source File: apec.py    From astromodels with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def evaluate(self, x, NH, redshift):

            if isinstance(x, astropy_units.Quantity):

                _unit = astropy_units.cm ** 2
                _y_unit = astropy_units.dimensionless_unscaled
                _x = x.value

            else:

                _unit = 1.0
                _y_unit = 1.0

                _x = x

            xsect_interp = self._cached_interp(_x * (1 + redshift))

            spec = np.exp(-NH * xsect_interp * _unit) * _y_unit

            return spec 
Example #20
Source File: test_blackbody.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_blackbody_overflow():
    """Test Planck function with overflow."""
    photlam = u.photon / (u.cm**2 * u.s * u.AA)
    wave = [0, 1000.0, 100000.0, 1e55]  # Angstrom
    temp = 10000.0  # Kelvin
    with pytest.warns(
            AstropyUserWarning,
            match=r'Input contains invalid wavelength/frequency value\(s\)'):
        with np.errstate(all='ignore'):
            bb_lam = blackbody_lambda(wave, temp) * u.sr
    flux = bb_lam.to(photlam, u.spectral_density(wave * u.AA)) / u.sr

    # First element is NaN, last element is very small, others normal
    assert np.isnan(flux[0])
    assert np.log10(flux[-1].value) < -134
    np.testing.assert_allclose(
        flux.value[1:-1], [3.38131732e+16, 3.87451317e+15],
        rtol=1e-3)  # 0.1% accuracy in PHOTLAM/sr

    with np.errstate(all='ignore'):
        flux = blackbody_lambda(1, 1e4)
    assert flux.value == 0 
Example #21
Source File: test_cosmology.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_critical_density():
    from astropy.constants import codata2014

    # WMAP7 but with Omega_relativistic = 0
    # These tests will fail if astropy.const starts returning non-mks
    #  units by default; see the comment at the top of core.py.
    # critical_density0 is inversely proportional to G.
    tcos = core.FlatLambdaCDM(70.4, 0.272, Tcmb0=0.0)
    fac = (const.G / codata2014.G).to(u.dimensionless_unscaled).value
    assert allclose(tcos.critical_density0 * fac,
                    9.309668456020899e-30 * (u.g / u.cm**3))
    assert allclose(tcos.critical_density0,
                    tcos.critical_density(0))
    assert allclose(
        tcos.critical_density([1, 5]) * fac,
        [2.70352772e-29, 5.53739080e-28] * (u.g / u.cm**3))
    assert allclose(
        tcos.critical_density([1., 5.]) * fac,
        [2.70352772e-29, 5.53739080e-28] * (u.g / u.cm**3)) 
Example #22
Source File: test_nddata.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_param_unit():
    with pytest.raises(ValueError):
        NDData(np.ones((5, 5)), unit="NotAValidUnit")
    NDData([1, 2, 3], unit='meter')
    # Test conflicting units (quantity as data)
    q = np.array([1, 2, 3]) * u.m
    nd = NDData(q, unit='cm')
    assert nd.unit != q.unit
    assert nd.unit == u.cm
    # (masked quantity)
    mq = np.ma.array(np.array([2, 3])*u.m, mask=False)
    nd2 = NDData(mq, unit=u.s)
    assert nd2.unit == u.s
    # (another NDData as data)
    nd3 = NDData(nd, unit='km')
    assert nd3.unit == u.km 
Example #23
Source File: test_nduncertainty.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_init_fake_with_fake(UncertClass):
    uncert = np.arange(5).reshape(5, 1)
    fake_uncert1 = UncertClass(uncert)
    fake_uncert2 = UncertClass(fake_uncert1)
    assert_array_equal(fake_uncert2.array, uncert)
    assert fake_uncert2.array is not uncert
    # Without making copies
    fake_uncert1 = UncertClass(uncert, copy=False)
    fake_uncert2 = UncertClass(fake_uncert1, copy=False)
    assert_array_equal(fake_uncert2.array, fake_uncert1.array)
    assert fake_uncert2.array is fake_uncert1.array
    # With a unit
    uncert = np.arange(5).reshape(5, 1) * u.adu
    fake_uncert1 = UncertClass(uncert)
    fake_uncert2 = UncertClass(fake_uncert1)
    assert_array_equal(fake_uncert2.array, uncert.value)
    assert fake_uncert2.array is not uncert.value
    assert fake_uncert2.unit is u.adu
    # With a unit and an explicit unit-parameter
    fake_uncert2 = UncertClass(fake_uncert1, unit=u.cm)
    assert_array_equal(fake_uncert2.array, uncert.value)
    assert fake_uncert2.array is not uncert.value
    assert fake_uncert2.unit is u.cm 
Example #24
Source File: test_regression.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_regression_6697():
    """
    Test for regression of a bug in get_gcrs_posvel that introduced errors at the 1m/s level.

    Comparison data is derived from calculation in PINT
    https://github.com/nanograv/PINT/blob/master/pint/erfautils.py
    """
    pint_vels = CartesianRepresentation(*(348.63632871, -212.31704928, -0.60154936), unit=u.m/u.s)
    location = EarthLocation(*(5327448.9957829, -1718665.73869569,  3051566.90295403), unit=u.m)
    t = Time(2458036.161966612, format='jd')
    obsgeopos, obsgeovel = location.get_gcrs_posvel(t)
    delta = (obsgeovel-pint_vels).norm()
    assert delta < 1*u.cm/u.s 
Example #25
Source File: test_blackbody.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_fit(self):

        fitter = LevMarLSQFitter()

        b = BlackBody1D(3000 * u.K)

        wav = np.array([0.5, 5, 10]) * u.micron
        fnu = np.array([1, 10, 5]) * u.Jy

        b_fit = fitter(b, wav, fnu)

        assert_quantity_allclose(b_fit.temperature, 2840.7438339457754 * u.K)
        assert_quantity_allclose(b_fit.bolometric_flux, 6.821837075583734e-08 * u.erg / u.cm**2 / u.s) 
Example #26
Source File: test_quantities_model.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_uses_quantity():
    """
    Test Quantity
    """
    g = Gaussian1D(mean=3 * u.m, stddev=3 * u.cm, amplitude=3 * u.Jy)

    assert g.uses_quantity

    g = Gaussian1D(mean=3, stddev=3, amplitude=3)

    assert not g.uses_quantity

    g.mean = 3 * u.m

    assert g.uses_quantity 
Example #27
Source File: imp.py    From heliopy with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, probe):
        _check_probe(probe, ['8'])
        self.probe = probe

        self.units = OrderedDict(
            [('sw_flag', u.dimensionless_unscaled),
             ('x_gse', u.R_earth), ('y_gse', u.R_earth),
             ('z_gse', u.R_earth), ('y_gsm', u.R_earth),
             ('z_gsm', u.R_earth), ('Nm', u.dimensionless_unscaled),
             ('<|B|>', u.nT), ('|<B>|', u.nT), ('<B_lat>', u.nT),
             ('<B_long>', u.nT), ('Bx_gse', u.nT), ('By_gse', u.nT),
             ('Bz_gse', u.nT), ('By_gsm', u.nT), ('Bz_gsm', u.nT),
             ('sigma|B|', u.nT), ('sigma B', u.nT),
             ('sigma B_x', u.nT), ('sigma B_y', u.nT),
             ('sigma B_z', u.nT),
             ('plas_reg', u.dimensionless_unscaled),
             ('Npp', u.dimensionless_unscaled),
             ('v_fit', u.km / u.s), ('vx_fit_gse', u.km / u.s),
             ('vy_fit_gse', u.km / u.s), ('vz_fit_gse', u.km / u.s),
             ('vlong_fit', u.deg), ('vlat_fit', u.deg),
             ('np_fit', u.cm**-3), ('Tp_fit', u.K),
             ('v_mom', u.km / u.s), ('vx_mom_gse', u.km / u.s),
             ('vy_mom_gse', u.km / u.s), ('vz_mom_gse', u.km / u.s),
             ('vlong_mom', u.deg), ('vlat_mom', u.deg),
             ('np_mom', u.cm**-3), ('Tp_mom', u.K),
             ('FCp', u.dimensionless_unscaled),
             ('DWp', u.dimensionless_unscaled)]) 
Example #28
Source File: core.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def critical_density(self, z):
        """ Critical density in grams per cubic cm at redshift ``z``.

        Parameters
        ----------
        z : array_like
          Input redshifts.

        Returns
        -------
        rho : `~astropy.units.Quantity`
          Critical density in g/cm^3 at each input redshift.
        """

        return self._critical_density0 * (self.efunc(z)) ** 2 
Example #29
Source File: test_quantities_model.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_gaussian1d_bounding_box():
    g = Gaussian1D(mean=3 * u.m, stddev=3 * u.cm, amplitude=3 * u.Jy)
    bbox = g.bounding_box
    assert_quantity_allclose(bbox[0], 2.835 * u.m)
    assert_quantity_allclose(bbox[1], 3.165 * u.m) 
Example #30
Source File: test_cosmology.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_units():
    """ Test if the right units are being returned"""

    cosmo = core.FlatLambdaCDM(H0=70, Om0=0.27, Tcmb0=2.0)
    assert cosmo.comoving_distance(1.0).unit == u.Mpc
    assert cosmo._comoving_distance_z1z2(1.0, 2.0).unit == u.Mpc
    assert cosmo.comoving_transverse_distance(1.0).unit == u.Mpc
    assert cosmo._comoving_transverse_distance_z1z2(1.0, 2.0).unit == u.Mpc
    assert cosmo.angular_diameter_distance(1.0).unit == u.Mpc
    assert cosmo.angular_diameter_distance_z1z2(1.0, 2.0).unit == u.Mpc
    assert cosmo.luminosity_distance(1.0).unit == u.Mpc
    assert cosmo.lookback_time(1.0).unit == u.Gyr
    assert cosmo.lookback_distance(1.0).unit == u.Mpc
    assert cosmo.H0.unit == u.km / u.Mpc / u.s
    assert cosmo.H(1.0).unit == u.km / u.Mpc / u.s
    assert cosmo.Tcmb0.unit == u.K
    assert cosmo.Tcmb(1.0).unit == u.K
    assert cosmo.Tcmb([0.0, 1.0]).unit == u.K
    assert cosmo.Tnu0.unit == u.K
    assert cosmo.Tnu(1.0).unit == u.K
    assert cosmo.Tnu([0.0, 1.0]).unit == u.K
    assert cosmo.arcsec_per_kpc_comoving(1.0).unit == u.arcsec / u.kpc
    assert cosmo.arcsec_per_kpc_proper(1.0).unit == u.arcsec / u.kpc
    assert cosmo.kpc_comoving_per_arcmin(1.0).unit == u.kpc / u.arcmin
    assert cosmo.kpc_proper_per_arcmin(1.0).unit == u.kpc / u.arcmin
    assert cosmo.critical_density(1.0).unit == u.g / u.cm ** 3
    assert cosmo.comoving_volume(1.0).unit == u.Mpc ** 3
    assert cosmo.age(1.0).unit == u.Gyr
    assert cosmo.distmod(1.0).unit == u.mag