本文整理汇总了Python中astropy.units.def_unit方法的典型用法代码示例。如果您正苦于以下问题:Python units.def_unit方法的具体用法?Python units.def_unit怎么用?Python units.def_unit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类astropy.units
的用法示例。
在下文中一共展示了units.def_unit方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_write_drop_nonstandard_units
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import def_unit [as 别名]
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
示例2: __init__
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import def_unit [as 别名]
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)])
示例3: mkwvl
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import def_unit [as 别名]
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
示例4: test_load_w_quantity
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import def_unit [as 别名]
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
示例5: test_unit_non_length
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import def_unit [as 别名]
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)
示例6: test_represents
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import def_unit [as 别名]
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]
示例7: test_register
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import def_unit [as 别名]
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
示例8: test_duplicate_define
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import def_unit [as 别名]
def test_duplicate_define():
u.def_unit('m', namespace=u.__dict__)
示例9: test_flatten_impossible
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import def_unit [as 别名]
def test_flatten_impossible():
myunit = u.def_unit("FOOBAR_Two")
with u.add_enabled_units(myunit), pytest.raises(ValueError):
myunit.to_string('fits')
示例10: test_with_custom_units_qtable
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import def_unit [as 别名]
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
示例11: test_round_trip_user_defined_unit
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import def_unit [as 别名]
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'])
示例12: _generate_unit_names
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import def_unit [as 别名]
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