Python astropy.units.Unit() Examples

The following are 30 code examples of astropy.units.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: conf.py    From prysm with MIT License 7 votes vote down vote up
def sanitize_unit(unit, wavelength):
    """Sanitize a unit token, either an astropy unit or a string.

    Parameters
    ----------
    unit : `astropy.Unit` or `str`
        unit or string version of unit
    wavelength : `astropy.Unit`
        a wavelength unit generated by mkwvl or equivalent code

    Returns
    -------
    `astropy.Unit`
        an astropy unit

    """
    if not isinstance(unit, all_ap_unit_types):
        if unit.lower() in ('waves', 'wave', 'λ'):
            unit = wavelength
        else:
            unit = getattr(u, unit)
    else:
        unit = unit

    return unit 
Example #2
Source File: units.py    From astromodels with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _check_unit(new_unit, old_unit):
    """
    Check that the new unit is compatible with the old unit for the quantity described by variable_name

    :param new_unit: instance of astropy.units.Unit
    :param old_unit: instance of astropy.units.Unit
    :return: nothin
    """

    try:

        new_unit.physical_type

    except AttributeError:

        raise UnitMismatch("The provided unit (%s) has no physical type. Was expecting a unit for %s"
                           % (new_unit, old_unit.physical_type))

    if new_unit.physical_type != old_unit.physical_type:

        raise UnitMismatch("Physical type mismatch: you provided a unit for %s instead of a unit for %s"
                           % (new_unit.physical_type, old_unit.physical_type)) 
Example #3
Source File: conf.py    From prysm with MIT License 6 votes vote down vote up
def format_unit(unit_or_quantity, fmt):
    """(string) format a unit or quantity

    Parameters
    ----------
    unit_or_quantity : `astropy.units.Unit` or `astropy.units.Quantity`
        a unit or quantity
    fmt : `str`, {'latex', 'unicode'}
        a string format

    Returns
    -------
    `str`
        string

    """
    if isinstance(unit_or_quantity, all_ap_unit_types):
        return unit_or_quantity.to_string(fmt)
    elif isinstance(unit_or_quantity, u.quantity.Quantity):
        return unit_or_quantity.unit.to_string(fmt)
    else:
        raise ValueError('must be a Unit or Quantity instance.') 
Example #4
Source File: container.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(
        self,
        default=None,
        description="",
        unit=None,
        ucd=None,
        dtype=None,
        ndim=None,
        allow_none=True,
    ):

        self.default = default
        self.description = description
        self.unit = Unit(unit) if unit is not None else None
        self.ucd = ucd
        self.dtype = np.dtype(dtype) if dtype is not None else None
        self.ndim = ndim
        self.allow_none = allow_none 
Example #5
Source File: test_lightcurve.py    From lightkurve with MIT License 6 votes vote down vote up
def test_flux_unit():
    """Checks the use of lc.flux_unit and lc.flux_quantity."""
    with warnings.catch_warnings():  # We deprecated `flux_unit` in v2.0
        warnings.simplefilter("ignore", LightkurveDeprecationWarning)
        unit_obj = u.Unit("electron/second")
        # Can we set flux units using a Unit object?
        time, flux = range(3), np.ones(3)
        lc = LightCurve(time=time, flux=flux, flux_unit=unit_obj)
        assert lc.flux.unit == unit_obj
        # Can we set flux units using a string?
        lc = LightCurve(time=time, flux=flux, flux_unit="electron/second")
        assert lc.flux.unit == unit_obj
        # Can we pass a quantity to flux?
        lc = LightCurve(time=time, flux=flux*unit_obj)
        assert lc.flux.unit == unit_obj
        # Can we retrieve correct flux quantities?
        with warnings.catch_warnings():  # flux_quantity is deprecated
            warnings.simplefilter("ignore", LightkurveDeprecationWarning)
            assert lc.flux_quantity.unit ==unit_obj
            assert_array_equal(lc.flux_quantity.value, flux)
        # Is invalid user input validated?
        with pytest.raises(ValueError) as err:
            lc = LightCurve(time=time, flux=flux, flux_unit="blablabla")
        assert "not a valid unit" in err.value.args[0] 
Example #6
Source File: compat.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def unit(self, value):
        from . import conf

        try:
            if self._unit is not None and conf.warn_setting_unit_directly:
                log.info('Setting the unit directly changes the unit without '
                         'updating the data or uncertainty. Use the '
                         '.convert_unit_to() method to change the unit and '
                         'scale values appropriately.')
        except AttributeError:
            # raised if self._unit has not been set yet, in which case the
            # warning is irrelevant
            pass

        if value is None:
            self._unit = None
        else:
            self._unit = Unit(value)

    # Implement mask in a way that converts nicely to a numpy masked array 
Example #7
Source File: units.py    From astromodels with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _set_unit(self, what, new_unit):

        try:

            old_unit = self._units[what]

        except KeyError:

            raise UnknownUnit("You can only assign units for energy, time, angle and area. Don't know "
                              "anything about %s" % what)

        # This allows to use strings in place of Unit instances as new_unit

        new_unit = u.Unit(new_unit)

        # Check that old and new unit are for the appropriate quantity

        _check_unit(new_unit, old_unit)

        # set the new unit
        self._units[what] = new_unit 
Example #8
Source File: parameter.py    From astromodels with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _safe_assign_unit(input_unit):

        # We first try to use our own, thread-safe format, if we fail then we try the astropy one

        try:

            new_unit = u.Unit(input_unit, format='threadsafe')

        except ValueError:

            # Try with the default format of astropy
            new_unit = u.Unit(input_unit)

        return new_unit

    # Define the property 'unit' 
Example #9
Source File: parameter.py    From astromodels with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def in_unit_of(self, unit, as_quantity=False):
        """
        Return the current value transformed to the new units

        :param unit: either an astropy.Unit instance, or a string which can be converted to an astropy.Unit
            instance, like "1 / (erg cm**2 s)"
        :param as_quantity: if True, the method return an astropy.Quantity, if False just a floating point number.
            Default is False
        :return: either a floating point or a astropy.Quantity depending on the value of "as_quantity"
        """

        new_unit = u.Unit(unit)

        new_quantity = self.as_quantity.to(new_unit)

        if as_quantity:

            return new_quantity

        else:

            return new_quantity.value 
Example #10
Source File: unit_conversion.py    From fits2hdf with MIT License 6 votes vote down vote up
def units_to_fits(unit):
    """ Convert an astropy unit to a FITS format string.

    uses the to_string() method built-in to astropy Unit()

    Notes
    -----
    The output will be the format defined in the FITS standard:
    http://fits.gsfc.nasa.gov/fits_standard.html

    A roundtrip from fits_to_units -> units_to_fits may not return
    the original string, as people often don't follow the standard.
    """
    if unit is None:
        unit = Unit('')
    return unit.to_string("fits").upper() 
Example #11
Source File: test_sky_coord.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_galactic_three_components(repr_name, unit1, unit2, unit3, cls2, attr1, attr2, attr3,
                                   representation, c1, c2, c3):
    """
    Tests positional inputs using components (COMP1, COMP2, COMP3)
    and various representations.  Use weird units and Galactic frame.
    """
    sc = Galactic(1000*c1*u.Unit(unit1/1000), cls2(c2, unit=unit2),
                  1000*c3*u.Unit(unit3/1000), representation_type=representation)
    assert_quantities_allclose(sc, (c1*unit1, c2*unit2, c3*unit3),
                               (attr1, attr2, attr3))

    kwargs = {attr3: c3*unit3}
    sc = Galactic(c1*unit1, c2*unit2,
                  representation_type=representation, **kwargs)
    assert_quantities_allclose(sc, (c1*unit1, c2*unit2, c3*unit3),
                               (attr1, attr2, attr3))

    kwargs = {attr1: c1*unit1, attr2: c2*unit2, attr3: c3*unit3}
    sc = Galactic(representation_type=representation, **kwargs)
    assert_quantities_allclose(sc, (c1*unit1, c2*unit2, c3*unit3),
                               (attr1, attr2, attr3)) 
Example #12
Source File: test_units.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_initialisation():
    assert u.Unit(u.m) is u.m

    ten_meter = u.Unit(10.*u.m)
    assert ten_meter == u.CompositeUnit(10., [u.m], [1])
    assert u.Unit(ten_meter) is ten_meter

    assert u.Unit(10.*ten_meter) == u.CompositeUnit(100., [u.m], [1])

    foo = u.Unit('foo', (10. * ten_meter)**2, namespace=locals())
    assert foo == u.CompositeUnit(10000., [u.m], [2])

    assert u.Unit('m') == u.m
    assert u.Unit('') == u.dimensionless_unscaled
    assert u.one == u.dimensionless_unscaled
    assert u.Unit('10 m') == ten_meter
    assert u.Unit(10.) == u.CompositeUnit(10., [], []) 
Example #13
Source File: test_quantity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_1(self):
        # create objects through operations with Unit objects:

        quantity = 11.42 * u.meter  # returns a Quantity object
        assert isinstance(quantity, u.Quantity)
        quantity = u.meter * 11.42  # returns a Quantity object
        assert isinstance(quantity, u.Quantity)

        quantity = 11.42 / u.meter
        assert isinstance(quantity, u.Quantity)
        quantity = u.meter / 11.42
        assert isinstance(quantity, u.Quantity)

        quantity = 11.42 * u.meter / u.second
        assert isinstance(quantity, u.Quantity)

        with pytest.raises(TypeError):
            quantity = 182.234 + u.meter

        with pytest.raises(TypeError):
            quantity = 182.234 - u.meter

        with pytest.raises(TypeError):
            quantity = 182.234 % u.meter 
Example #14
Source File: ogip.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def parse(cls, s, debug=False):
        s = s.strip()
        try:
            # This is a short circuit for the case where the string is
            # just a single unit name
            return cls._parse_unit(s, detailed_exception=False)
        except ValueError:
            try:
                return core.Unit(
                    cls._parser.parse(s, lexer=cls._lexer, debug=debug))
            except ValueError as e:
                if str(e):
                    raise
                else:
                    raise ValueError(
                        f"Syntax error parsing unit '{s}'") 
Example #15
Source File: ogip.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _validate_unit(cls, unit, detailed_exception=True):
        if unit not in cls._units:
            if detailed_exception:
                raise ValueError(
                    "Unit '{}' not supported by the OGIP "
                    "standard. {}".format(
                        unit, utils.did_you_mean_units(
                            unit, cls._units, cls._deprecated_units,
                            cls._to_decomposed_alternative)))
            else:
                raise ValueError()

        if unit in cls._deprecated_units:
            utils.unit_deprecation_warning(
                unit, cls._units[unit], 'OGIP',
                cls._to_decomposed_alternative) 
Example #16
Source File: column.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def to(self, unit, equivalencies=[], **kwargs):
        """
        Converts this table column to a `~astropy.units.Quantity` object with
        the requested units.

        Parameters
        ----------
        unit : `~astropy.units.Unit` or str
            The unit to convert to (i.e., a valid argument to the
            :meth:`astropy.units.Quantity.to` method).
        equivalencies : list of equivalence pairs, optional
            Equivalencies to use for this conversion.  See
            :meth:`astropy.units.Quantity.to` for more details.

        Returns
        -------
        quantity : `~astropy.units.Quantity`
            A quantity object with the contents of this column in the units
            ``unit``.
        """
        return self.quantity.to(unit, equivalencies) 
Example #17
Source File: test_wcsapi.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_sliced_ND_input(sub_wcs, wcs_slice):
    slices_wcsaxes = [0, 'x', 'y']

    with warnings.catch_warnings():
        warnings.filterwarnings('ignore', category=FutureWarning)
        _, coord_meta = transform_coord_meta_from_wcs(sub_wcs, RectangularFrame, slices=slices_wcsaxes)

    assert all(len(x) == 3 for x in coord_meta.values())

    coord_meta['name'] = ['time', 'custom:pos.helioprojective.lat', 'custom:pos.helioprojective.lon']
    coord_meta['type'] = ['scalar', 'latitude', 'longitude']
    coord_meta['wrap'] = [None, None, 180.0]
    coord_meta['unit'] = [u.Unit("min"), u.Unit("deg"), u.Unit("deg")]
    coord_meta['visible'] = [False, True, True]
    coord_meta['format_unit'] = [u.Unit("min"), u.Unit("arcsec"), u.Unit("arcsec")]
    coord_meta['default_axislabel_position'] = ['', 'b', 't']
    coord_meta['default_ticklabel_position'] = ['', 'b', 't']
    coord_meta['default_ticks_position'] = ['', 'btlr', 'btlr']

    # Validate the axes initialize correctly
    plt.subplot(projection=sub_wcs, slices=slices_wcsaxes)
    plt.close('all') 
Example #18
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 #19
Source File: test_sky_coord.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_skycoord_spherical_two_components(repr_name, unit1, unit2, unit3, cls2,
                                           attr1, attr2, attr3, representation, c1, c2, c3):
    """
    Tests positional inputs using components (COMP1, COMP2) for spherical
    representations.  Use weird units and Galactic frame.
    """
    sc = SkyCoord(c1, c2, unit=(unit1, unit2), frame=Galactic,
                  representation_type=representation)
    assert_quantities_allclose(sc, (c1*unit1, c2*unit2),
                               (attr1, attr2))

    sc = SkyCoord(1000*c1*u.Unit(unit1/1000), cls2(c2, unit=unit2),
                  frame=Galactic,
                  unit=(unit1, unit2, unit3), representation_type=representation)
    assert_quantities_allclose(sc, (c1*unit1, c2*unit2),
                               (attr1, attr2))

    kwargs = {attr1: c1, attr2: c2}
    sc = SkyCoord(frame=Galactic, unit=(unit1, unit2),
                  representation_type=representation, **kwargs)
    assert_quantities_allclose(sc, (c1*unit1, c2*unit2),
                               (attr1, attr2)) 
Example #20
Source File: test_quantities_rotations.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_attributes():
    n2c = models.RotateNative2Celestial(20016 * u.arcsec, -72.3 * u.deg, np.pi * u.rad)
    assert_allclose(n2c.lat.value, -72.3)
    assert_allclose(n2c.lat._raw_value, -1.2618730491919001)
    assert_allclose(n2c.lon.value, 20016)
    assert_allclose(n2c.lon._raw_value, 0.09704030641088472)
    assert_allclose(n2c.lon_pole.value, np.pi)
    assert_allclose(n2c.lon_pole._raw_value, np.pi)
    assert(n2c.lon.unit is u.Unit("arcsec"))
    assert(n2c.lon.internal_unit is u.Unit("rad"))
    assert(n2c.lat.unit is u.Unit("deg"))
    assert(n2c.lat.internal_unit is u.Unit("rad"))
    assert(n2c.lon_pole.unit is u.Unit("rad"))
    assert(n2c.lon_pole.internal_unit is u.Unit("rad")) 
Example #21
Source File: test_quantity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_2(self):

        # create objects using the Quantity constructor:
        q1 = u.Quantity(11.412, unit=u.meter)
        q2 = u.Quantity(21.52, "cm")
        q3 = u.Quantity(11.412)

        # By default quantities that don't specify a unit are unscaled
        # dimensionless
        assert q3.unit == u.Unit(1)

        with pytest.raises(TypeError):
            q4 = u.Quantity(object(), unit=u.m) 
Example #22
Source File: gauss_method.py    From orbitdeterminator with MIT License 5 votes vote down vote up
def observerpos_mpc(long, parallax_s, parallax_c, t_utc):
    """Compute geocentric observer position at UTC instant t_utc, for Sun-centered orbits,
    at a given observation site defined by its longitude, and parallax constants S and C.
    Formula taken from top of page 266, chapter 5, Orbital Mechanics book (Curtis).
    The parallax constants S and C are defined by:
    S=rho cos phi' C=rho sin phi', where
    rho: slant range
    phi': geocentric latitude

       Args:
           long (float): longitude of observing site
           parallax_s (float): parallax constant S of observing site
           parallax_c (float): parallax constant C of observing site
           t_utc (astropy.time.Time): UTC time of observation

       Returns:
           1x3 numpy array: cartesian components of observer's geocentric position
    """
    # Earth's equatorial radius in kilometers
    # Re = cts.R_earth.to(uts.Unit('km')).value

    # define Longitude object for the observation site longitude
    long_site = Longitude(long, uts.degree, wrap_angle=360.0*uts.degree)
    # compute sidereal time of observation at site
    t_site_lmst = t_utc.sidereal_time('mean', longitude=long_site)
    lmst_rad = t_site_lmst.rad # np.deg2rad(lmst_hrs*15.0) # radians

    # compute cartesian components of geocentric (non rotating) observer position
    x_gc = Re*parallax_c*np.cos(lmst_rad)
    y_gc = Re*parallax_c*np.sin(lmst_rad)
    z_gc = Re*parallax_s

    return np.array((x_gc,y_gc,z_gc)) 
Example #23
Source File: fits.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _validate_unit(cls, unit, detailed_exception=True):
        if unit not in cls._units:
            if detailed_exception:
                raise ValueError(
                    "Unit '{}' not supported by the FITS standard. {}".format(
                        unit, utils.did_you_mean_units(
                            unit, cls._units, cls._deprecated_units,
                            cls._to_decomposed_alternative)))
            else:
                raise ValueError()

        if unit in cls._deprecated_units:
            utils.unit_deprecation_warning(
                unit, cls._units[unit], 'FITS',
                cls._to_decomposed_alternative) 
Example #24
Source File: gauss_method.py    From orbitdeterminator with MIT License 5 votes vote down vote up
def gauss_iterator_mpc(mpc_object_data, mpc_observatories_data, inds, refiters=0, r2_root_ind=0):
    """Gauss method iterator for minor planets ra/dec tracking data.
    Computes a first estimate of the orbit using gauss_estimate_sat function, and
    then refines this estimate using gauss_refinement. Assumes observation data
    file follows MPC format.

       Args:
           mpc_object_data (string): path to MPC-formatted observation data file
           mpc_observatories_data (string): path to MPC observation sites data file
           inds (1x3 int array): line numbers in data file to be processed
           refiters (int): number of refinement iterations to be performed
           r2_root_ind (int): index of selected Gauss polynomial root

       Returns:
           r1 (1x3 array): updated position at first observation
           r2 (1x3 array): updated position at second observation
           r3 (1x3 array): updated position at third observation
           v2 (1x3 array): updated velocity at second observation
           R (1x3 array): three observer position vectors
           rho1 (1x3 array): LOS vector at first observation
           rho2 (1x3 array): LOS vector at second observation
           rho3 (1x3 array): LOS vector at third observation
           rho_1_sr (float): slant range at first observation
           rho_2_sr (float): slant range at second observation
           rho_3_sr (float): slant range at third observation
           Ea_hc_pos (1x3 array): cartesian position vectors (Earth wrt Sun)
           obs_t (1x3 array): times of observations
    """
    # mu_Sun = 0.295912208285591100E-03 # Sun's G*m, au^3/day^2
    mu = mu_Sun # cts.GM_sun.to(uts.Unit("au3 / day2")).value
    r1, r2, r3, v2, D, R, rho1, rho2, rho3, tau1, tau3, f1, g1, f3, g3, Ea_hc_pos, rho_1_sr, rho_2_sr, rho_3_sr, obs_t =\
        gauss_estimate_mpc(mpc_object_data, mpc_observatories_data, inds, r2_root_ind=r2_root_ind)

    # Apply refinement to Gauss' method, `refiters` iterations
    for i in range(0,refiters):
        r1, r2, r3, v2, rho_1_sr, rho_2_sr, rho_3_sr, f1, g1, f3, g3 = \
            gauss_refinement(mu, tau1, tau3, r2, v2, 3e-14, D, R, rho1, rho2, rho3, f1, g1, f3, g3)

    return r1, r2, r3, v2, R, rho1, rho2, rho3, rho_1_sr, rho_2_sr, rho_3_sr, Ea_hc_pos, obs_t 
Example #25
Source File: column.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def unit(self, unit):
        if unit is None:
            self._unit = None
        else:
            self._unit = Unit(unit, parse_strict='silent') 
Example #26
Source File: sky_coordinate_parsers.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_representation_component_units(args, kwargs):
    """
    Get the unit from kwargs for the *representation* components (not the
    differentials).
    """
    if 'unit' not in kwargs:
        units = [None, None, None]

    else:
        units = kwargs.pop('unit')

        if isinstance(units, str):
            units = [x.strip() for x in units.split(',')]
            # Allow for input like unit='deg' or unit='m'
            if len(units) == 1:
                units = [units[0], units[0], units[0]]
        elif isinstance(units, (Unit, IrreducibleUnit)):
            units = [units, units, units]

        try:
            units = [(Unit(x) if x else None) for x in units]
            units.extend(None for x in range(3 - len(units)))
            if len(units) > 3:
                raise ValueError()
        except Exception:
            raise ValueError('Unit keyword must have one to three unit values as '
                             'tuple or comma-separated string')

    return units 
Example #27
Source File: test_sky_coord.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_coord_init_unit():
    """
    Test variations of the unit keyword.
    """
    for unit in ('deg', 'deg,deg', ' deg , deg ', u.deg, (u.deg, u.deg),
                 np.array(['deg', 'deg'])):
        sc = SkyCoord(1, 2, unit=unit)
        assert allclose(sc.ra, Angle(1 * u.deg))
        assert allclose(sc.dec, Angle(2 * u.deg))

    for unit in ('hourangle', 'hourangle,hourangle', ' hourangle , hourangle ',
                 u.hourangle, [u.hourangle, u.hourangle]):
        sc = SkyCoord(1, 2, unit=unit)
        assert allclose(sc.ra, Angle(15 * u.deg))
        assert allclose(sc.dec, Angle(30 * u.deg))

    for unit in ('hourangle,deg', (u.hourangle, u.deg)):
        sc = SkyCoord(1, 2, unit=unit)
        assert allclose(sc.ra, Angle(15 * u.deg))
        assert allclose(sc.dec, Angle(2 * u.deg))

    for unit in ('deg,deg,deg,deg', [u.deg, u.deg, u.deg, u.deg], None):
        with pytest.raises(ValueError) as err:
            SkyCoord(1, 2, unit=unit)
        assert 'Unit keyword must have one to three unit values' in str(err.value)

    for unit in ('m', (u.m, u.deg), ''):
        with pytest.raises(u.UnitsError) as err:
            SkyCoord(1, 2, unit=unit) 
Example #28
Source File: test_sky_coord.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_skycoord_three_components(repr_name, unit1, unit2, unit3, cls2, attr1, attr2, attr3,
                                   representation, c1, c2, c3):
    """
    Tests positional inputs using components (COMP1, COMP2, COMP3)
    and various representations.  Use weird units and Galactic frame.
    """
    sc = SkyCoord(c1, c2, c3, unit=(unit1, unit2, unit3),
                  representation_type=representation,
                  frame=Galactic)
    assert_quantities_allclose(sc, (c1*unit1, c2*unit2, c3*unit3),
                               (attr1, attr2, attr3))

    sc = SkyCoord(1000*c1*u.Unit(unit1/1000), cls2(c2, unit=unit2),
                  1000*c3*u.Unit(unit3/1000), frame=Galactic,
                  unit=(unit1, unit2, unit3), representation_type=representation)
    assert_quantities_allclose(sc, (c1*unit1, c2*unit2, c3*unit3),
                               (attr1, attr2, attr3))

    kwargs = {attr3: c3}
    sc = SkyCoord(c1, c2, unit=(unit1, unit2, unit3),
                  frame=Galactic,
                  representation_type=representation, **kwargs)
    assert_quantities_allclose(sc, (c1*unit1, c2*unit2, c3*unit3),
                               (attr1, attr2, attr3))

    kwargs = {attr1: c1, attr2: c2, attr3: c3}
    sc = SkyCoord(frame=Galactic, unit=(unit1, unit2, unit3),
                  representation_type=representation, **kwargs)
    assert_quantities_allclose(sc, (c1*unit1, c2*unit2, c3*unit3),
                               (attr1, attr2, attr3)) 
Example #29
Source File: formatter_locator.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def format_unit(self, unit):
        self._format_unit = u.Unit(unit) 
Example #30
Source File: angles.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __new__(cls, angle, unit=None, dtype=None, copy=True):

        if not isinstance(angle, u.Quantity):
            if unit is not None:
                unit = cls._convert_unit_to_angle_unit(u.Unit(unit))

            if isinstance(angle, tuple):
                angle = cls._tuple_to_float(angle, unit)

            elif isinstance(angle, str):
                angle, angle_unit = util.parse_angle(angle, unit)
                if angle_unit is None:
                    angle_unit = unit

                if isinstance(angle, tuple):
                    angle = cls._tuple_to_float(angle, angle_unit)

                if angle_unit is not unit:
                    # Possible conversion to `unit` will be done below.
                    angle = u.Quantity(angle, angle_unit, copy=False)

            elif (isiterable(angle) and
                  not (isinstance(angle, np.ndarray) and
                       angle.dtype.kind not in 'SUVO')):
                angle = [Angle(x, unit, copy=False) for x in angle]

        return super().__new__(cls, angle, unit, dtype=dtype, copy=copy)