本文整理汇总了Python中astropy.units.Quantity.to方法的典型用法代码示例。如果您正苦于以下问题:Python Quantity.to方法的具体用法?Python Quantity.to怎么用?Python Quantity.to使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类astropy.units.Quantity
的用法示例。
在下文中一共展示了Quantity.to方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_saturation_water_pressure
# 需要导入模块: from astropy.units import Quantity [as 别名]
# 或者: from astropy.units.Quantity import to [as 别名]
def test_saturation_water_pressure():
args_list = [
(1.e-30, None, apu.K),
(1.e-30, None, apu.hPa),
]
check_astro_quantities(atm.saturation_water_pressure, args_list)
temp = Quantity([100, 200, 300], apu.K)
press = Quantity([900, 1000, 1100], apu.hPa)
press_w = Quantity(
[2.57439748e-17, 3.23857740e-03, 3.55188758e+01], apu.hPa
)
assert_quantity_allclose(
atm.saturation_water_pressure(temp, press),
press_w
)
assert_quantity_allclose(
atm.saturation_water_pressure(
temp.to(apu.mK), press.to(apu.Pa)
),
press_w
)
示例2: MyQuantity
# 需要导入模块: from astropy.units import Quantity [as 别名]
# 或者: from astropy.units.Quantity import to [as 别名]
class MyQuantity(Quantity):
def __init__(self,coord,unit):
self.q = Quantity(coord,unit)
@property
def value(self):
return self.q.value
@property
def unit(self):
return self.q.unit
def set_value(self,value):
assert isinstance(value,(float,int))
_unit = self.q.unit
self.q = Quantity(value,_unit)
def change_unit(self,unit):
assert isinstance(unit,(str,Unit))
_newQ = self.q.to(unit)
self.q = _newQ
def asunit(self,unit):
_q = self.q.to(unit,equivalencies=spectral())
return _q
示例3: test_refractive_index
# 需要导入模块: from astropy.units import Quantity [as 别名]
# 或者: from astropy.units.Quantity import to [as 别名]
def test_refractive_index():
args_list = [
(1.e-30, None, apu.K),
(1.e-30, None, apu.hPa),
(1.e-30, None, apu.hPa),
]
check_astro_quantities(atm.refractive_index, args_list)
temp = Quantity([100, 200, 300], apu.K)
press = Quantity([900, 1000, 1100], apu.hPa)
press_w = Quantity([200, 500, 1000], apu.hPa)
refr_index = Quantity(
[1.0081872, 1.0050615, 1.00443253], cnv.dimless
)
assert_quantity_allclose(
atm.refractive_index(temp, press, press_w),
refr_index
)
assert_quantity_allclose(
atm.refractive_index(
temp.to(apu.mK), press.to(apu.Pa), press_w.to(apu.Pa)
),
refr_index
)
示例4: _get_range_from_textfields
# 需要导入模块: from astropy.units import Quantity [as 别名]
# 或者: from astropy.units.Quantity import to [as 别名]
def _get_range_from_textfields(self, min_text, max_text, linelist_units, plot_units):
amin = amax = None
if min_text.hasAcceptableInput() and max_text.hasAcceptableInput():
amin = float(min_text.text())
amax = float(max_text.text())
amin = Quantity(amin, plot_units)
amax = Quantity(amax, plot_units)
amin = amin.to(linelist_units, equivalencies=u.spectral())
amax = amax.to(linelist_units, equivalencies=u.spectral())
return (amin, amax)
示例5: logspace
# 需要导入模块: from astropy.units import Quantity [as 别名]
# 或者: from astropy.units.Quantity import to [as 别名]
def logspace(cls, vmin, vmax, nbins, unit=None):
"""Create axis with equally log-spaced nodes
if no unit is given, it will be taken from vmax
Parameters
----------
vmin : `~astropy.units.Quantity`, float
Lowest value
vmax : `~astropy.units.Quantity`, float
Highest value
bins : int
Number of bins
unit : `~astropy.units.UnitBase`, str
Unit
"""
if unit is not None:
vmin = Quantity(vmin, unit)
vmax = Quantity(vmax, unit)
else:
vmin = Quantity(vmin)
vmax = Quantity(vmax)
unit = vmax.unit
vmin = vmin.to(unit)
x_min, x_max = np.log10([vmin.value, vmax.value])
vals = np.logspace(x_min, x_max, nbins)
return cls(vals * unit, interpolation_mode='log')
示例6: Spectrum2D
# 需要导入模块: from astropy.units import Quantity [as 别名]
# 或者: from astropy.units.Quantity import to [as 别名]
class Spectrum2D(object):
"""
A 2D spectrum.
Parameters
----------
dispersion : `astropy.units.Quantity` or array, shape (N,)
Spectral dispersion axis.
data : array, shape (N, M)
The spectral data.
unit : `astropy.units.UnitBase` or str, optional
Unit for the dispersion axis.
"""
def __init__(self, dispersion, data, unit=None):
self.dispersion = Quantity(dispersion, unit=unit)
if unit is not None:
self.wavelength = self.dispersion.to(angstrom)
else:
self.wavelength = self.dispersion
self.data = data
示例7: evaluate
# 需要导入模块: from astropy.units import Quantity [as 别名]
# 或者: from astropy.units.Quantity import to [as 别名]
def evaluate(self, x):
"""Wrapper around the evaluate method on the Astropy model classes.
Parameters
----------
x : `~gammapy.utils.energy.Energy`
Evaluation point
"""
if self.spectral_model == 'PowerLaw':
flux = models.PowerLaw1D.evaluate(x, self.parameters.norm,
self.parameters.reference,
self.parameters.index)
elif self.spectral_model == 'LogParabola':
# LogParabola evaluation does not work with arrays because
# there is bug when using '**' with Quantities
# see https://github.com/astropy/astropy/issues/4764
flux = Quantity([models.LogParabola1D.evaluate(xx,
self.parameters.norm,
self.parameters.reference,
self.parameters.alpha,
self.parameters.beta)
for xx in x])
else:
raise NotImplementedError('Not implemented for model {}.'.format(self.spectral_model))
return flux.to(self.parameters.norm.unit)
示例8: clean_up
# 需要导入模块: from astropy.units import Quantity [as 别名]
# 或者: from astropy.units.Quantity import to [as 别名]
def clean_up(table_in):
"""Create a new table with exactly the columns / info we want.
"""
table = Table()
v = Quantity(table_in['v'].data, table_in['v'].unit)
energy = v.to('MeV', equivalencies=u.spectral())
table['energy'] = energy
#vFv = Quantity(table['vFv'].data, table['vFv'].unit)
#flux = (vFv / (energy ** 2)).to('cm^-2 s^-1 MeV^-1')
table['energy_flux'] = table_in['vFv']
table['energy_flux_err_lo'] = table_in['ed_vFv']
table['energy_flux_err_hi'] = table_in['eu_vFv']
# Compute symmetrical error because most chi^2 fitters
# can't handle asymmetrical Gaussian erros
table['energy_flux_err'] = 0.5 * (table_in['eu_vFv'] + table_in['ed_vFv'])
table['component'] = table_in['component']
table['paper'] = table_in['paper']
mask = table['energy_flux_err_hi'] == 0
return table
示例9: solid_angle
# 需要导入模块: from astropy.units import Quantity [as 别名]
# 或者: from astropy.units.Quantity import to [as 别名]
def solid_angle(image):
"""Compute the solid angle of each pixel.
This will only give correct results for CAR maps!
Parameters
----------
image : `~astropy.io.fits.ImageHDU`
Input image
Returns
-------
area_image : `~astropy.units.Quantity`
Solid angle image (matching the input image) in steradians.
"""
# Area of one pixel at the equator
cdelt0 = image.header['CDELT1']
cdelt1 = image.header['CDELT2']
equator_area = Quantity(abs(cdelt0 * cdelt1), 'deg2')
# Compute image with fraction of pixel area at equator
glat = coordinates(image)[1]
area_fraction = np.cos(np.radians(glat))
result = area_fraction * equator_area.to('sr')
return result
示例10: test_LogEnergyAxis
# 需要导入模块: from astropy.units import Quantity [as 别名]
# 或者: from astropy.units.Quantity import to [as 别名]
def test_LogEnergyAxis():
from scipy.stats import gmean
energy = Quantity([1, 10, 100], 'TeV')
energy_axis = LogEnergyAxis(energy)
energy = Quantity(gmean([1, 10]), 'TeV')
pix = energy_axis.wcs_world2pix(energy.to('MeV'))
assert_allclose(pix, 0.5)
world = energy_axis.wcs_pix2world(pix)
assert_quantity_allclose(world, energy)
示例11: evaluate
# 需要导入模块: from astropy.units import Quantity [as 别名]
# 或者: from astropy.units.Quantity import to [as 别名]
def evaluate(self, method=None, **kwargs):
"""Evaluate NDData Array
This function provides a uniform interface to several interpolators.
The evaluation nodes are given as ``kwargs``.
Currently available:
`~scipy.interpolate.RegularGridInterpolator`, methods: linear, nearest
Parameters
----------
method : str {'linear', 'nearest'}, optional
Interpolation method
kwargs : dict
Keys are the axis names, Values the evaluation points
Returns
-------
array : `~astropy.units.Quantity`
Interpolated values, axis order is the same as for the NDData array
"""
values = []
for axis in self.axes:
# Extract values for each axis, default: nodes
temp = Quantity(kwargs.pop(axis.name, axis.nodes))
# Transform to correct unit
temp = temp.to(axis.unit).value
# Transform to match interpolation behaviour of axis
values.append(np.atleast_1d(axis._interp_values(temp)))
# This is to catch e.g. typos in axis names
if kwargs != {}:
raise ValueError("Input given for unknown axis: {}".format(kwargs))
if method is None:
out = self._eval_regular_grid_interp(values)
elif method == 'linear':
out = self._eval_regular_grid_interp(values, method='linear')
elif method == 'nearest':
out = self._eval_regular_grid_interp(values, method='nearest')
else:
raise ValueError('Interpolator {} not available'.format(method))
# Clip interpolated values to be non-negative
np.clip(out, 0, None, out=out)
# Attach units to the output
out = out * self.data.unit
return out
示例12: parse_value
# 需要导入模块: from astropy.units import Quantity [as 别名]
# 或者: from astropy.units.Quantity import to [as 别名]
def parse_value(value, default_units, equivalence=None):
if isinstance(value, string_types):
v = value.split(",")
if len(v) == 2:
value = (float(v[0]), v[1])
else:
value = float(v[0])
if hasattr(value, "to_astropy"):
value = value.to_astropy()
if isinstance(value, Quantity):
q = Quantity(value.value, value.unit)
elif iterable(value):
q = Quantity(value[0], value[1])
else:
q = Quantity(value, default_units)
return q.to(default_units, equivalencies=equivalence).value
示例13: __str__
# 需要导入模块: from astropy.units import Quantity [as 别名]
# 或者: from astropy.units.Quantity import to [as 别名]
def __str__(self):
"""Summary report (`str`).
"""
ss = '*** Observation summary ***\n'
ss += 'Target position: {}\n'.format(self.target_pos)
ss += 'Number of observations: {}\n'.format(len(self.obs_table))
livetime = Quantity(sum(self.obs_table['LIVETIME']), 'second')
ss += 'Livetime: {:.2f}\n'.format(livetime.to('hour'))
zenith = self.obs_table['ZEN_PNT']
ss += 'Zenith angle: (mean={:.2f}, std={:.2f})\n'.format(
zenith.mean(), zenith.std())
offset = self.offset
ss += 'Offset: (mean={:.2f}, std={:.2f})\n'.format(
offset.mean(), offset.std())
return ss
示例14: solid_angle_image
# 需要导入模块: from astropy.units import Quantity [as 别名]
# 或者: from astropy.units.Quantity import to [as 别名]
def solid_angle_image(self):
"""Solid angle image.
TODO: currently uses CDELT1 x CDELT2, which only
works for cartesian images near the equator.
Returns
-------
solid_angle_image : `~astropy.units.Quantity`
Solid angle image (steradian)
"""
cdelt = self.wcs.wcs.cdelt
solid_angle = np.abs(cdelt[0]) * np.abs(cdelt[1])
shape = self.data.shape[:2]
solid_angle = solid_angle * np.ones(shape, dtype=float)
solid_angle = Quantity(solid_angle, 'deg^2')
return solid_angle.to('steradian')
示例15: find_node
# 需要导入模块: from astropy.units import Quantity [as 别名]
# 或者: from astropy.units.Quantity import to [as 别名]
def find_node(self, val):
"""Find next node
Parameters
----------
val : `~astropy.units.Quantity`
Lookup value
"""
val = Quantity(val)
if not val.unit.is_equivalent(self.unit):
raise ValueError("Units {} and {} do not match".format(val.unit, self.unit))
val = val.to(self.data.unit)
val = np.atleast_1d(val)
x1 = np.array([val] * self.nbins).transpose()
x2 = np.array([self.nodes] * len(val))
temp = np.abs(x1 - x2)
idx = np.argmin(temp, axis=1)
return idx