本文整理汇总了Python中astropy.units.Unit方法的典型用法代码示例。如果您正苦于以下问题:Python units.Unit方法的具体用法?Python units.Unit怎么用?Python units.Unit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类astropy.units
的用法示例。
在下文中一共展示了units.Unit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: sanitize_unit
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import Unit [as 别名]
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
示例2: format_unit
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import Unit [as 别名]
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.')
示例3: __init__
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import Unit [as 别名]
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
示例4: test_flux_unit
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import Unit [as 别名]
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]
示例5: _check_unit
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import Unit [as 别名]
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))
示例6: _set_unit
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import Unit [as 别名]
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
示例7: _safe_assign_unit
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import Unit [as 别名]
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'
示例8: in_unit_of
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import Unit [as 别名]
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
示例9: units_to_fits
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import Unit [as 别名]
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()
示例10: unit
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import Unit [as 别名]
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
示例11: test_skycoord_spherical_two_components
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import Unit [as 别名]
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))
示例12: test_galactic_three_components
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import Unit [as 别名]
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))
示例13: test_compound_without_units
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import Unit [as 别名]
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)
示例14: test_sliced_ND_input
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import Unit [as 别名]
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')
示例15: to
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import Unit [as 别名]
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)