Python astropy.units.Hz() Examples

The following are 30 code examples of astropy.units.Hz(). 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: test_gsb.py    From baseband with GNU General Public License v3.0 6 votes vote down vote up
def test_timestamp_io(self, tmpdir, sample):
        """Tests GSBTimeStampIO in base.py."""
        with open(sample, 'rt') as fh:
            header0 = gsb.GSBHeader.fromfile(fh, verify=True)

        with gsb.open(sample, 'rt') as fh:
            header1 = fh.read_timestamp()
            assert header1 == header0
            current_pos = fh.tell()
            frame_rate = fh.get_frame_rate()
            assert abs(frame_rate - u.Hz / 0.251658240) < 1. * u.nHz
            assert fh.tell() == current_pos

        testfile = str(tmpdir.join('test.timestamp'))
        with gsb.open(testfile, 'wt') as fw:
            fw.write_timestamp(header=header1)
        with gsb.open(testfile, 'rt') as fh:
            header2 = fh.read_timestamp()
            assert header2 == header1

        # Check that extra arguments raise TypeError.
        with pytest.raises(TypeError):
            gsb.open(testfile, 'rt', raw='bla') 
Example #2
Source File: test_guppi.py    From baseband with GNU General Public License v3.0 6 votes vote down vote up
def test_partial_last_frame(self, tmpdir):
        """Test reading a file with an incomplete last frame."""
        # Read in sample file as a byte stream.
        with guppi.open(SAMPLE_FILE, 'rb') as fh:
            puppi_raw = fh.read()

        # Try reading a file with an incomplete payload.
        with guppi.open(str(tmpdir.join('puppi_partframe.raw')), 'wb') as fw:
            fw.write(puppi_raw[:len(puppi_raw) - 6091])
        nsample = 3*1024 - 2*64  # 3 frames minus 2 overlaps
        with guppi.open(str(tmpdir.join('puppi_partframe.raw')), 'rs') as fn:
            assert fn.shape == (nsample, 2, 4)
            assert np.abs(fn.stop_time
                          - fn.start_time - nsample / (250 * u.Hz)) < 1. * u.ns

        # Try reading a file with an incomplete header.
        with guppi.open(str(tmpdir.join('puppi_partframe.raw')), 'wb') as fw:
            fw.write(puppi_raw[:len(puppi_raw) - 17605])
        with guppi.open(str(tmpdir.join('puppi_partframe.raw')), 'rs') as fn:
            assert fn.shape == (nsample, 2, 4)
            assert np.abs(fn.stop_time
                          - fn.start_time - nsample / (250 * u.Hz)) < 1. * u.ns 
Example #3
Source File: base.py    From baseband with GNU General Public License v3.0 6 votes vote down vote up
def get_frame_rate(self):
        """Determine the number of frames per second.

        The frame rate is calculated from the time elapsed between the
        first two frames, as inferred from their time stamps.

        Returns
        -------
        frame_rate : `~astropy.units.Quantity`
            Frames per second.
        """
        with self.temporary_offset(0):
            header0 = self.find_header()
            self.seek(header0.frame_nbytes, 1)
            header1 = self.read_header()

        # Mark 4 specification states frames-lengths range from 1.25 ms
        # to 160 ms.
        tdelta = (header1.fraction[0] - header0.fraction[0]) % 1.
        return u.Quantity(1 / tdelta, u.Hz).round() 
Example #4
Source File: periodogram.py    From lightkurve with MIT License 6 votes vote down vote up
def __init__(self, frequency, power, nyquist=None, label=None,
                 targetid=None, default_view='frequency', meta={}):
        # Input validation
        if not isinstance(frequency, u.quantity.Quantity):
            raise ValueError('frequency must be an `astropy.units.Quantity` object.')
        if not isinstance(power, u.quantity.Quantity):
            raise ValueError('power must be an `astropy.units.Quantity` object.')
        # Frequency must have frequency units
        try:
            frequency.to(u.Hz)
        except u.UnitConversionError:
            raise ValueError('Frequency must be in units of 1/time.')
        # Frequency and power must have sensible shapes
        if frequency.shape[0] <= 1:
            raise ValueError('frequency and power must have a length greater than 1.')
        if frequency.shape != power.shape:
            raise ValueError('frequency and power must have the same length.')

        self.frequency = frequency
        self.power = power
        self.nyquist = nyquist
        self.label = label
        self.targetid = targetid
        self.default_view = self._validate_view(default_view)
        self.meta = meta 
Example #5
Source File: test_quantity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_quantity_conversion_equivalency_passed_on():
    class MySpectral(u.Quantity):
        _equivalencies = u.spectral()

        def __quantity_view__(self, obj, unit):
            return obj.view(MySpectral)

        def __quantity_instance__(self, *args, **kwargs):
            return MySpectral(*args, **kwargs)

    q1 = MySpectral([1000, 2000], unit=u.Hz)
    q2 = q1.to(u.nm)
    assert q2.unit == u.nm
    q3 = q2.to(u.Hz)
    assert q3.unit == u.Hz
    assert_allclose(q3.value, q1.value)
    q4 = MySpectral([1000, 2000], unit=u.nm)
    q5 = q4.to(u.Hz).to(u.nm)
    assert q5.unit == u.nm
    assert_allclose(q4.value, q5.value)

# Regression test for issue #2315, divide-by-zero error when examining 0*unit 
Example #6
Source File: test_quantity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_quantity_conversion_with_equiv():
    q1 = u.Quantity(0.1, unit=u.meter)
    v2 = q1.to_value(u.Hz, equivalencies=u.spectral())
    assert_allclose(v2, 2997924580.0)
    q2 = q1.to(u.Hz, equivalencies=u.spectral())
    assert_allclose(q2.value, v2)

    q1 = u.Quantity(0.4, unit=u.arcsecond)
    v2 = q1.to_value(u.au, equivalencies=u.parallax())
    q2 = q1.to(u.au, equivalencies=u.parallax())
    v3 = q2.to_value(u.arcminute, equivalencies=u.parallax())
    q3 = q2.to(u.arcminute, equivalencies=u.parallax())

    assert_allclose(v2, 515662.015)
    assert_allclose(q2.value, v2)
    assert q2.unit == u.au
    assert_allclose(v3, 0.0066666667)
    assert_allclose(q3.value, v3)
    assert q3.unit == u.arcminute 
Example #7
Source File: test_equivalencies.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_is_equivalent():
    assert u.m.is_equivalent(u.pc)
    assert u.cycle.is_equivalent(u.mas)
    assert not u.cycle.is_equivalent(u.dimensionless_unscaled)
    assert u.cycle.is_equivalent(u.dimensionless_unscaled,
                                 u.dimensionless_angles())
    assert not (u.Hz.is_equivalent(u.J))
    assert u.Hz.is_equivalent(u.J, u.spectral())
    assert u.J.is_equivalent(u.Hz, u.spectral())
    assert u.pc.is_equivalent(u.arcsecond, u.parallax())
    assert u.arcminute.is_equivalent(u.au, u.parallax())

    # Pass a tuple for multiple possibilities
    assert u.cm.is_equivalent((u.m, u.s, u.kg))
    assert u.ms.is_equivalent((u.m, u.s, u.kg))
    assert u.g.is_equivalent((u.m, u.s, u.kg))
    assert not u.L.is_equivalent((u.m, u.s, u.kg))
    assert not (u.km / u.s).is_equivalent((u.m, u.s, u.kg)) 
Example #8
Source File: test_quantities_fitting.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_compound_fitting_with_units():
    x = np.linspace(-5, 5, 15) * u.Angstrom
    y = np.linspace(-5, 5, 15) * u.Angstrom

    fitter = fitting.LevMarLSQFitter()
    m = models.Gaussian2D(10*u.Hz,
                          3*u.Angstrom, 4*u.Angstrom,
                          1*u.Angstrom, 2*u.Angstrom)
    p = models.Planar2D(3*u.Hz/u.Angstrom, 4*u.Hz/u.Angstrom, 1*u.Hz)
    model = m + p

    z = model(x, y)
    res = fitter(model, x, y, z)
    assert isinstance(res(x, y), np.ndarray)
    assert all([res[i]._has_units for i in range(2)])

    model = models.Gaussian2D() + models.Planar2D()
    res = fitter(model, x, y, z)
    assert isinstance(res(x, y), np.ndarray)
    assert all([res[i]._has_units for i in range(2)]) 
Example #9
Source File: test_quantities_fitting.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_compound_without_units(model):
    x = np.linspace(-5, 5, 10) * u.Angstrom
    with NumpyRNGContext(12345):
        y = np.random.sample(10)

    fitter = fitting.LevMarLSQFitter()
    res_fit = fitter(model, x, y * u.Hz)
    for param_name in res_fit.param_names:
        print(getattr(res_fit, param_name))
    assert all([res_fit[i]._has_units for i in range(3)])
    z = res_fit(x)
    assert isinstance(z, u.Quantity)

    res_fit = fitter(model, np.arange(10) * u.Unit('Angstrom'), y)
    assert all([res_fit[i]._has_units for i in range(3)])
    z = res_fit(x)
    assert isinstance(z, np.ndarray) 
Example #10
Source File: test_equivalencies.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_spectraldensity2():
    # flux density
    flambda = u.erg / u.angstrom / u.cm ** 2 / u.s
    fnu = u.erg / u.Hz / u.cm ** 2 / u.s

    a = flambda.to(fnu, 1, u.spectral_density(u.Quantity(3500, u.AA)))
    assert_allclose(a, 4.086160166177361e-12)

    # luminosity density
    llambda = u.erg / u.angstrom / u.s
    lnu = u.erg / u.Hz / u.s

    a = llambda.to(lnu, 1, u.spectral_density(u.Quantity(3500, u.AA)))
    assert_allclose(a, 4.086160166177361e-12)

    a = lnu.to(llambda, 1, u.spectral_density(u.Quantity(3500, u.AA)))
    assert_allclose(a, 2.44728537142857e11) 
Example #11
Source File: base.py    From baseband with GNU General Public License v3.0 6 votes vote down vote up
def get_frame_rate(self):
        """Determine the number of frames per second.

        This method first tries to determine the frame rate by looking for
        the highest frame number in the first second of data.  If that fails,
        it attempts to extract the sample rate from the header.

        Returns
        -------
        frame_rate : `~astropy.units.Quantity`
            Frames per second.
        """
        try:
            return super().get_frame_rate()
        except Exception as exc:
            with self.temporary_offset(0):
                try:
                    header = self.read_header()
                    return (header.sample_rate
                            / header.samples_per_frame).to(u.Hz).round()
                except Exception:
                    pass
            raise exc 
Example #12
Source File: test_equivalencies.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_equivalent_units2():
    units = set(u.Hz.find_equivalent_units(u.spectral()))
    match = set(
        [u.AU, u.Angstrom, u.Hz, u.J, u.Ry, u.cm, u.eV, u.erg, u.lyr,
         u.m, u.micron, u.pc, u.solRad, u.Bq, u.Ci, u.k, u.earthRad,
         u.jupiterRad])
    assert units == match

    from astropy.units import imperial
    with u.add_enabled_units(imperial):
        units = set(u.Hz.find_equivalent_units(u.spectral()))
        match = set(
            [u.AU, u.Angstrom, imperial.BTU, u.Hz, u.J, u.Ry,
             imperial.cal, u.cm, u.eV, u.erg, imperial.ft, imperial.fur,
             imperial.inch, imperial.kcal, u.lyr, u.m, imperial.mi,
             imperial.mil, u.micron, u.pc, u.solRad, imperial.yd, u.Bq, u.Ci,
             imperial.nmi, u.k, u.earthRad, u.jupiterRad])
        assert units == match

    units = set(u.Hz.find_equivalent_units(u.spectral()))
    match = set(
        [u.AU, u.Angstrom, u.Hz, u.J, u.Ry, u.cm, u.eV, u.erg, u.lyr,
         u.m, u.micron, u.pc, u.solRad, u.Bq, u.Ci, u.k, u.earthRad,
         u.jupiterRad])
    assert units == match 
Example #13
Source File: test_opener.py    From baseband with GNU General Public License v3.0 6 votes vote down vote up
def test_stream_template(self, tmpdir):
        template = str(tmpdir.join('{x2_0_64:03d}_{file_nr:02d}.bare'))
        header0 = BareHeader.fromvalues()
        with self.open(template, 'ws', header0=header0,
                       sample_rate=10*u.Hz) as fw:
            assert isinstance(fw, BareStreamWriter)
            assert isinstance(fw.fh_raw, sf.SequentialFileWriter)
            assert isinstance(fw.fh_raw.files, sf.FileNameSequencer)
            assert fw.fh_raw.files[0].endswith('001_00.bare')

        with self.open(template, 'w', x2_0_64=4,
                       sample_rate=10*u.Hz, parrot='life') as fw:
            assert fw.fh_raw.files[0].endswith('004_00.bare')

        with pytest.raises(TypeError):
            self.open(template, 'ws', coocoo=10,
                      sample_rate=10*u.Hz) 
Example #14
Source File: test_equivalency.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_equivalencies():
    """
    Return a list of example equivalencies for testing serialization.
    """
    return [eq.plate_scale(.3 * u.deg/u.mm), eq.pixel_scale(.5 * u.deg/u.pix),
            eq.spectral_density(350 * u.nm, factor=2),
            eq.spectral_density(350 * u.nm), eq.spectral(),
            eq.brightness_temperature(500 * u.GHz),
            eq.brightness_temperature(500 * u.GHz, beam_area=23 * u.sr),
            eq.with_H0(), eq.temperature_energy(), eq.temperature(),
            eq.thermodynamic_temperature(300 * u.Hz),
            eq.thermodynamic_temperature(140 * u.GHz, Planck15.Tcmb0),
            eq.beam_angular_area(3 * u.sr), eq.mass_energy(),
            eq.molar_mass_amu(), eq.doppler_relativistic(2 * u.m),
            eq.doppler_optical(2 * u.nm), eq.doppler_radio(2 * u.Hz),
            eq.parallax(), eq.logarithmic(), eq.dimensionless_angles(),
            eq.spectral() + eq.temperature(),
            (eq.spectral_density(35 * u.nm) +
             eq.brightness_temperature(5 * u.Hz, beam_area=2 * u.sr)),
            (eq.spectral() + eq.spectral_density(35 * u.nm) +
             eq.brightness_temperature(5 * u.Hz, beam_area=2 * u.sr))
            ] 
Example #15
Source File: test_quantities_fitting.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_fitting_missing_data_units():
    """
    Raise an error if the model has units but the data doesn't
    """
    class UnorderedGaussian1D(models.Gaussian1D):
        # Parameters are ordered differently here from Gaussian1D
        # to ensure the order does not break functionality.
        def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
            return {'amplitude': outputs_unit['y'],
                    'mean': inputs_unit['x'],
                    'stddev': inputs_unit['x']}

    g_init = UnorderedGaussian1D(amplitude=1. * u.mJy,
                                 mean=3 * u.cm,
                                 stddev=2 * u.mm)
    fit_g = fitting.LevMarLSQFitter()

    # We define flux unit so that conversion fails at wavelength unit.
    # This is because the order of parameter unit conversion seems to
    # follow the order defined in _parameter_units_for_data_units method.
    with pytest.raises(UnitsError) as exc:
        fit_g(g_init, [1, 2, 3],
              [4, 5, 6] * (u.erg / (u.s * u.cm * u.cm * u.Hz)))
    assert exc.value.args[0] == ("'cm' (length) and '' (dimensionless) are "
                                 "not convertible")

    with pytest.raises(UnitsError) as exc:
        fit_g(g_init, [1, 2, 3] * u.m, [4, 5, 6])
    assert exc.value.args[0] == ("'mJy' (spectral flux density) and '' "
                                 "(dimensionless) are not convertible") 
Example #16
Source File: test_quantities_fitting.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_fitting_incompatible_units():
    """
    Raise an error if the data and model have incompatible units
    """

    g_init = models.Gaussian1D(amplitude=1. * u.Jy,
                               mean=3 * u.m,
                               stddev=2 * u.cm)
    fit_g = fitting.LevMarLSQFitter()

    with pytest.raises(UnitsError) as exc:
        fit_g(g_init, [1, 2, 3] * u.Hz, [4, 5, 6] * u.Jy)
    assert exc.value.args[0] == ("'Hz' (frequency) and 'm' (length) are not convertible") 
Example #17
Source File: test_models.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_tabular_interp_1d():
    """
    Test Tabular1D model.
    """
    points = np.arange(0, 5)
    values = [1., 10, 2, 45, -3]
    LookupTable = models.tabular_model(1)
    model = LookupTable(points=points, lookup_table=values)
    xnew = [0., .7, 1.4, 2.1, 3.9]
    ans1 = [1., 7.3, 6.8, 6.3, 1.8]
    assert_allclose(model(xnew), ans1)
    # Test evaluate without passing `points`.
    model = LookupTable(lookup_table=values)
    assert_allclose(model(xnew), ans1)
    # Test bounds error.
    xextrap = [0., .7, 1.4, 2.1, 3.9, 4.1]
    with pytest.raises(ValueError):
        model(xextrap)
    # test extrapolation and fill value
    model = LookupTable(lookup_table=values, bounds_error=False,
                        fill_value=None)
    assert_allclose(model(xextrap),
                    [1., 7.3, 6.8, 6.3, 1.8, -7.8])

    # Test unit support
    xnew = xnew * u.nm
    ans1 = ans1 * u.nJy
    model = LookupTable(points=points*u.nm, lookup_table=values*u.nJy)
    assert_quantity_allclose(model(xnew), ans1)
    assert_quantity_allclose(model(xnew.to(u.nm)), ans1)
    assert model.bounding_box == (0 * u.nm, 4 * u.nm)

    # Test fill value unit conversion and unitless input on table with unit
    model = LookupTable([1, 2, 3], [10, 20, 30] * u.nJy, bounds_error=False,
                        fill_value=1e-33*(u.W / (u.m * u.m * u.Hz)))
    assert_quantity_allclose(model(np.arange(5)),
                             [100, 10, 20, 30, 100] * u.nJy) 
Example #18
Source File: physical_models.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def input_units(self):
        # The input units are those of the 'x' value, which should always be
        # Hz. Because we do this, and because input_units_allow_dimensionless
        # is set to True, dimensionless values are assumed to be in Hz.
        return {"x": u.Hz} 
Example #19
Source File: blackbody.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def input_units(self):
        # The input units are those of the 'x' value, which should always be
        # Hz. Because we do this, and because input_units_allow_dimensionless
        # is set to True, dimensionless values are assumed to be in Hz.
        return {'x': u.Hz} 
Example #20
Source File: test_units.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_composite():
    assert (u.cm / u.s * u.h)._get_converter(u.m)(1) == 36
    assert u.cm * u.cm == u.cm ** 2

    assert u.cm * u.cm * u.cm == u.cm ** 3

    assert u.Hz.to(1000 * u.Hz, 1) == 0.001 
Example #21
Source File: test_units.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_compose_best_unit_first():
    results = u.l.compose()
    assert len(results[0].bases) == 1
    assert results[0].bases[0] is u.l

    results = (u.s ** -1).compose()
    assert results[0].bases[0] in (u.Hz, u.Bq)

    results = (u.Ry.decompose()).compose()
    assert results[0].bases[0] is u.Ry 
Example #22
Source File: test_units.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_composite_unit_get_format_name():
    """See #1576"""
    unit1 = u.Unit('nrad/s')
    unit2 = u.Unit('Hz(1/2)')
    assert (str(u.CompositeUnit(1, [unit1, unit2], [1, -1])) ==
            'nrad / (Hz(1/2) s)') 
Example #23
Source File: test_format.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_latex_scale():
    fluxunit = u.Unit(1.e-24 * u.erg / (u.cm ** 2 * u.s * u.Hz))
    latex = r'$\mathrm{1 \times 10^{-24}\,\frac{erg}{Hz\,s\,cm^{2}}}$'
    assert fluxunit.to_string('latex') == latex 
Example #24
Source File: test_format.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_latex_inline_scale():
    fluxunit = u.Unit(1.e-24 * u.erg / (u.cm ** 2 * u.s * u.Hz))
    latex_inline = (r'$\mathrm{1 \times 10^{-24}\,erg'
                    r'\,Hz^{-1}\,s^{-1}\,cm^{-2}}$')
    assert fluxunit.to_string('latex_inline') == latex_inline 
Example #25
Source File: test_format.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_flatten_to_known():
    myunit = u.def_unit("FOOBAR_One", u.erg / u.Hz)
    assert myunit.to_string('fits') == 'erg Hz-1'
    myunit2 = myunit * u.bit ** 3
    assert myunit2.to_string('fits') == 'bit3 erg Hz-1' 
Example #26
Source File: test_logarithmic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_predefined_magnitudes():
    assert_quantity_allclose((-21.1*u.STmag).physical,
                             1.*u.erg/u.cm**2/u.s/u.AA)
    assert_quantity_allclose((-48.6*u.ABmag).physical,
                             1.*u.erg/u.cm**2/u.s/u.Hz)

    assert_quantity_allclose((0*u.M_bol).physical, c.L_bol0)
    assert_quantity_allclose((0*u.m_bol).physical,
                             c.L_bol0/(4.*np.pi*(10.*c.pc)**2)) 
Example #27
Source File: test_physical.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_photnu():
    photnu = u.photon / (u.cm ** 2 * u.s * u.Hz)
    assert photnu.physical_type == 'photon flux density' 
Example #28
Source File: test_equivalencies.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_spectral():
    a = u.AA.to(u.Hz, 1, u.spectral())
    assert_allclose(a, 2.9979245799999995e+18)
    b = u.Hz.to(u.AA, a, u.spectral())
    assert_allclose(b, 1)

    a = u.AA.to(u.MHz, 1, u.spectral())
    assert_allclose(a, 2.9979245799999995e+12)
    b = u.MHz.to(u.AA, a, u.spectral())
    assert_allclose(b, 1)

    a = u.m.to(u.Hz, 1, u.spectral())
    assert_allclose(a, 2.9979245799999995e+8)
    b = u.Hz.to(u.m, a, u.spectral())
    assert_allclose(b, 1) 
Example #29
Source File: test_equivalencies.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_spectral2():
    a = u.nm.to(u.J, 500, u.spectral())
    assert_allclose(a, 3.972891366538605e-19)
    b = u.J.to(u.nm, a, u.spectral())
    assert_allclose(b, 500)

    a = u.AA.to(u.Hz, 1, u.spectral())
    b = u.Hz.to(u.J, a, u.spectral())
    c = u.AA.to(u.J, 1, u.spectral())
    assert_allclose(b, c)

    c = u.J.to(u.Hz, b, u.spectral())
    assert_allclose(a, c) 
Example #30
Source File: test_equivalencies.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_spectraldensity3():
    # Define F_nu in Jy
    f_nu = u.Jy

    # Define F_lambda in ergs / cm^2 / s / micron
    f_lambda = u.erg / u.cm ** 2 / u.s / u.micron

    # 1 GHz
    one_ghz = u.Quantity(1, u.GHz)

    # Convert to ergs / cm^2 / s / Hz
    assert_allclose(f_nu.to(u.erg / u.cm ** 2 / u.s / u.Hz, 1.), 1.e-23, 10)

    # Convert to ergs / cm^2 / s at 10 Ghz
    assert_allclose(f_nu.to(u.erg / u.cm ** 2 / u.s, 1.,
                    equivalencies=u.spectral_density(one_ghz * 10)),
                    1.e-13, 10)

    # Convert to F_lambda at 1 Ghz
    assert_allclose(f_nu.to(f_lambda, 1.,
                    equivalencies=u.spectral_density(one_ghz)),
                    3.335640951981521e-20, 10)

    # Convert to Jy at 1 Ghz
    assert_allclose(f_lambda.to(u.Jy, 1.,
                    equivalencies=u.spectral_density(one_ghz)),
                    1. / 3.335640951981521e-20, 10)

    # Convert to ergs / cm^2 / s at 10 microns
    assert_allclose(f_lambda.to(u.erg / u.cm ** 2 / u.s, 1.,
                    equivalencies=u.spectral_density(u.Quantity(10, u.micron))),
                    10., 10)