Python astropy.units.def_unit() Examples

The following are 12 code examples of astropy.units.def_unit(). 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_connect.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_write_drop_nonstandard_units(self, table_type, tmpdir):
        # While we are generous on input (see above), we are strict on
        # output, dropping units not recognized by the fits standard.
        filename = str(tmpdir.join('test_nonstandard_units.fits'))
        spam = u.def_unit('spam')
        t = table_type()
        t['a'] = [1., 2., 3.] * spam
        with catch_warnings() as w:
            t.write(filename)
        assert len(w) == 1
        assert 'spam' in str(w[0].message)
        if table_type is Table or not HAS_YAML:
            assert ('cannot be recovered in reading. '
                    'If pyyaml is installed') in str(w[0].message)
        else:
            assert 'lost to non-astropy fits readers' in str(w[0].message)

        with fits.open(filename) as ff:
            hdu = ff[1]
            assert 'TUNIT1' not in hdu.header 
Example #2
Source File: cassini.py    From heliopy with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, coords):
        valid_coords = ['KRTP', 'KSM', 'KSO', 'RTN']
        if coords not in valid_coords:
            raise ValueError('coords must be one of {}'.format(valid_coords))
        self.coords = coords

        Rs = u.def_unit('saturnRad', 60268 * u.km)
        if (coords == 'KRTP'):
            self.units = OrderedDict([('Bx', u.nT), ('By', u.nT), ('Bz', u.nT),
                                      ('X', Rs), ('|B|', u.nT),
                                      ('Y', u.deg),
                                      ('Z', u.deg),
                                      ('Local hour', u.dimensionless_unscaled),
                                      ('n points', u.dimensionless_unscaled)])
        if (coords == 'RTN'):
            self.units = OrderedDict([('Bx', u.nT), ('By', u.nT), ('Bz', u.nT),
                                      ('X', u.AU), ('Y', u.AU), ('Z', u.AU),
                                      ('|B|', u.nT),
                                      ('Local hour', u.dimensionless_unscaled),
                                      ('n points', u.dimensionless_unscaled)])
        if (coords == 'KSM' or coords == 'KSO'):
            self.units = OrderedDict([('Bx', u.nT), ('By', u.nT), ('Bz', u.nT),
                                      ('X', Rs), ('Y', Rs), ('Z', Rs),
                                      ('|B|', u.nT),
                                      ('Local hour', u.dimensionless_unscaled),
                                      ('n points', u.dimensionless_unscaled)]) 
Example #3
Source File: wavelengths.py    From prysm with MIT License 5 votes vote down vote up
def mkwvl(quantity, base=u.um):
    """Generate a new Wavelength unit.

    Parameters
    ----------
    quantity : `float` or `astropy.units.unit`
        number of (base) for the wavelength, e.g. quantity=632.8 with base=u.nm for HeNe.
        if an astropy unit, simply returned by this function
    base : `astropy.units.Unit`
        base unit, e.g. um or nm

    Returns
    -------
    `astropy.units.Unit`
        new Unit for appropriate wavelength

    """
    if quantity is None:
        return quantity
    elif not isinstance(quantity, u.Unit):
        return u.def_unit(['wave', 'wavelength'], quantity * base,
                          format={'latex': r'\lambda', 'unicode': 'λ'})
    else:
        return quantity


# IR 
Example #4
Source File: test_init.py    From pvl with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_load_w_quantity(self):
        try:
            from astropy import units as u
            from pvl.decoder import OmniDecoder
            pvl_file = 'tests/data/pds3/units1.lbl'
            km_upper = u.def_unit('KM', u.km)
            m_upper = u.def_unit('M', u.m)
            u.add_enabled_units([km_upper, m_upper])
            label = pvl.load(pvl_file,
                             decoder=OmniDecoder(quantity_cls=u.Quantity))
            self.assertEqual(label['FLOAT_UNIT'], u.Quantity(0.414, 'KM'))
        except ImportError:
            pass 
Example #5
Source File: test_representation.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_unit_non_length(self):

        s1 = CartesianRepresentation(x=1 * u.kg, y=2 * u.kg, z=3 * u.kg)

        s2 = CartesianRepresentation(x=1 * u.km / u.s, y=2 * u.km / u.s, z=3 * u.km / u.s)

        banana = u.def_unit('banana')
        s3 = CartesianRepresentation(x=1 * banana, y=2 * banana, z=3 * banana) 
Example #6
Source File: test_units.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_represents():
    assert u.m.represents is u.m
    assert u.km.represents.scale == 1000.
    assert u.km.represents.bases == [u.m]
    assert u.Ry.scale == 1.0 and u.Ry.bases == [u.Ry]
    assert_allclose(u.Ry.represents.scale, 13.605692518464949)
    assert u.Ry.represents.bases == [u.eV]
    bla = u.def_unit('bla', namespace=locals())
    assert bla.represents is bla
    blabla = u.def_unit('blabla', 10 * u.hr, namespace=locals())
    assert blabla.represents.scale == 10.
    assert blabla.represents.bases == [u.hr]
    assert blabla.decompose().scale == 10 * 3600
    assert blabla.decompose().bases == [u.s] 
Example #7
Source File: test_units.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_register():
    foo = u.def_unit("foo", u.m ** 3, namespace=locals())
    assert 'foo' in locals()
    with u.add_enabled_units(foo):
        assert 'foo' in u.get_current_unit_registry().registry
    assert 'foo' not in u.get_current_unit_registry().registry 
Example #8
Source File: test_units.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_duplicate_define():
    u.def_unit('m', namespace=u.__dict__) 
Example #9
Source File: test_format.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_flatten_impossible():
    myunit = u.def_unit("FOOBAR_Two")
    with u.add_enabled_units(myunit), pytest.raises(ValueError):
        myunit.to_string('fits') 
Example #10
Source File: test_connect.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_with_custom_units_qtable(self, tmpdir):
        # Test only for QTable - for Table's Column, new units are dropped
        # (as is checked in test_write_drop_nonstandard_units).
        filename = str(tmpdir.join('test_with_units.fits'))
        unit = u.def_unit('bandpass_sol_lum')
        t = QTable()
        t['l'] = np.ones(5) * unit
        with catch_warnings(AstropyUserWarning) as w:
            t.write(filename, overwrite=True)
        assert len(w) == 1
        assert 'bandpass_sol_lum' in str(w[0].message)
        # Just reading back, the data is fine but the unit is not recognized.
        with catch_warnings() as w:
            t2 = QTable.read(filename)
        assert isinstance(t2['l'].unit, u.UnrecognizedUnit)
        assert str(t2['l'].unit) == 'bandpass_sol_lum'
        assert len(w) == 1
        assert "'bandpass_sol_lum' did not parse" in str(w[0].message)
        assert np.all(t2['l'].value == t['l'].value)

        # But if we enable the unit, it should be recognized.
        with u.add_enabled_units(unit):
            t3 = QTable.read(filename)
            assert t3['l'].unit is unit
            assert equal_data(t3, t)

            # Regression check for #8897; write used to fail when a custom
            # unit was enabled.
            with catch_warnings(u.UnitsWarning) as w:
                t3.write(filename, overwrite=True)
            assert len(w) == 0 
Example #11
Source File: test_ecsv.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_round_trip_user_defined_unit(table_cls, tmpdir):
    """Ensure that we can read-back enabled user-defined units."""
    # Test adapted from #8897, where it was noted that this works
    # but was not tested.
    filename = str(tmpdir.join('test.ecsv'))
    unit = u.def_unit('bandpass_sol_lum')
    t = table_cls()
    t['l'] = np.arange(5) * unit
    t.write(filename)
    # without the unit enabled, get UnrecognizedUnit
    with catch_warnings(u.UnitsWarning) as w:
        t2 = table_cls.read(filename)
    assert isinstance(t2['l'].unit, u.UnrecognizedUnit)
    assert str(t2['l'].unit) == 'bandpass_sol_lum'
    if table_cls is QTable:
        assert len(w) == 1
        assert f"'{unit!s}' did not parse" in str(w[0].message)
        assert np.all(t2['l'].value == t['l'].value)
    else:
        assert len(w) == 0
        assert np.all(t2['l'] == t['l'])

    # But with it enabled, it works.
    with u.add_enabled_units(unit):
        with catch_warnings(u.UnitsWarning) as w:
            t3 = table_cls.read(filename)
        assert len(w) == 0
        assert t3['l'].unit is unit
        assert np.all(t3['l'] == t['l'])

        # Just to be sure, aloso try writing with unit enabled.
        filename2 = str(tmpdir.join('test2.ecsv'))
        t3.write(filename2)
        with catch_warnings(u.UnitsWarning) as w:
            t4 = table_cls.read(filename)
        assert len(w) == 0
        assert t4['l'].unit is unit
        assert np.all(t4['l'] == t['l']) 
Example #12
Source File: ogip.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _generate_unit_names():

        from astropy import units as u
        names = {}
        deprecated_names = set()

        bases = [
            'A', 'C', 'cd', 'eV', 'F', 'g', 'H', 'Hz', 'J',
            'Jy', 'K', 'lm', 'lx', 'm', 'mol', 'N', 'ohm', 'Pa',
            'pc', 'rad', 's', 'S', 'sr', 'T', 'V', 'W', 'Wb'
        ]
        deprecated_bases = []
        prefixes = [
            'y', 'z', 'a', 'f', 'p', 'n', 'u', 'm', 'c', 'd',
            '', 'da', 'h', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'
        ]

        for base in bases + deprecated_bases:
            for prefix in prefixes:
                key = prefix + base
                if keyword.iskeyword(key):
                    continue
                names[key] = getattr(u, key)
        for base in deprecated_bases:
            for prefix in prefixes:
                deprecated_names.add(prefix + base)

        simple_units = [
            'angstrom', 'arcmin', 'arcsec', 'AU', 'barn', 'bin',
            'byte', 'chan', 'count', 'day', 'deg', 'erg', 'G',
            'h', 'lyr', 'mag', 'min', 'photon', 'pixel',
            'voxel', 'yr'
        ]
        for unit in simple_units:
            names[unit] = getattr(u, unit)

        # Create a separate, disconnected unit for the special case of
        # Crab and mCrab, since OGIP doesn't define their quantities.
        Crab = u.def_unit(['Crab'], prefixes=False, doc='Crab (X-ray flux)')
        mCrab = u.Unit(10 ** -3 * Crab)
        names['Crab'] = Crab
        names['mCrab'] = mCrab

        deprecated_units = ['Crab', 'mCrab']
        for unit in deprecated_units:
            deprecated_names.add(unit)

        # Define the function names, so we can parse them, even though
        # we can't use any of them (other than sqrt) meaningfully for
        # now.
        functions = [
            'log', 'ln', 'exp', 'sqrt', 'sin', 'cos', 'tan', 'asin',
            'acos', 'atan', 'sinh', 'cosh', 'tanh'
        ]
        for name in functions:
            names[name] = name

        return names, deprecated_names, functions