本文整理汇总了Python中astropy.units.hour方法的典型用法代码示例。如果您正苦于以下问题:Python units.hour方法的具体用法?Python units.hour怎么用?Python units.hour使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类astropy.units
的用法示例。
在下文中一共展示了units.hour方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: circle2circle
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import hour [as 别名]
def circle2circle(line):
"""
Parse a string that describes a circle in ds9 format.
Parameters
----------
line : str
A string containing a DS9 region command for a circle.
Returns
-------
circle : [ra, dec, radius]
The center and radius of the circle.
"""
words = re.split('[(,\s)]', line)
ra = words[1]
dec = words[2]
radius = words[3][:-1] # strip the "
if ":" in ra:
ra = Angle(ra, unit=u.hour)
else:
ra = Angle(ra, unit=u.degree)
dec = Angle(dec, unit=u.degree)
radius = Angle(radius, unit=u.arcsecond)
return [ra.degree, dec.degree, radius.degree]
示例2: test_init_lonlat
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import hour [as 别名]
def test_init_lonlat(self):
s2 = SphericalRepresentation(Longitude(8, u.hour),
Latitude(5, u.deg),
Distance(10, u.kpc))
assert s2.lon == 8. * u.hourangle
assert s2.lat == 5. * u.deg
assert s2.distance == 10. * u.kpc
assert isinstance(s2.lon, Longitude)
assert isinstance(s2.lat, Latitude)
assert isinstance(s2.distance, Distance)
# also test that wrap_angle is preserved
s3 = SphericalRepresentation(Longitude(-90, u.degree,
wrap_angle=180*u.degree),
Latitude(-45, u.degree),
Distance(1., u.Rsun))
assert s3.lon == -90. * u.degree
assert s3.lon.wrap_angle == 180 * u.degree
示例3: test_to_string_precision
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import hour [as 别名]
def test_to_string_precision():
# There are already some tests in test_api.py, but this is a regression
# test for the bug in issue #1319 which caused incorrect formatting of the
# seconds for precision=0
angle = Angle(-1.23456789, unit=u.degree)
assert angle.to_string(precision=3) == '-1d14m04.444s'
assert angle.to_string(precision=1) == '-1d14m04.4s'
assert angle.to_string(precision=0) == '-1d14m04s'
angle2 = Angle(-1.23456789, unit=u.hourangle)
assert angle2.to_string(precision=3, unit=u.hour) == '-1h14m04.444s'
assert angle2.to_string(precision=1, unit=u.hour) == '-1h14m04.4s'
assert angle2.to_string(precision=0, unit=u.hour) == '-1h14m04s'
# Regression test for #7141
angle3 = Angle(-0.5, unit=u.degree)
assert angle3.to_string(precision=0, fields=3) == '-0d30m00s'
assert angle3.to_string(precision=0, fields=2) == '-0d30m'
assert angle3.to_string(precision=0, fields=1) == '-1d'
示例4: test_distance_change
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import hour [as 别名]
def test_distance_change():
ra = Longitude("4:08:15.162342", unit=u.hour)
dec = Latitude("-41:08:15.162342", unit=u.degree)
c1 = ICRS(ra, dec, Distance(1, unit=u.kpc))
oldx = c1.cartesian.x.value
assert (oldx - 0.35284083171901953) < 1e-10
# first make sure distances are immutible
with pytest.raises(AttributeError):
c1.distance = Distance(2, unit=u.kpc)
# now x should increase with a bigger distance increases
c2 = ICRS(ra, dec, Distance(2, unit=u.kpc))
assert c2.cartesian.x.value == oldx * 2
示例5: generate_IRAF_input
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import hour [as 别名]
def generate_IRAF_input(writefn=None):
dt = test_input_time.utc.datetime
coos = _get_test_input_radecs()
lines = []
for ra, dec in zip(coos.ra, coos.dec):
rastr = Angle(ra).to_string(u.hour, sep=':')
decstr = Angle(dec).to_string(u.deg, sep=':')
msg = '{yr} {mo} {day} {uth}:{utmin} {ra} {dec}'
lines.append(msg.format(yr=dt.year, mo=dt.month, day=dt.day,
uth=dt.hour, utmin=dt.minute,
ra=rastr, dec=decstr))
if writefn:
with open(writefn, 'w') as f:
for l in lines:
f.write(l)
else:
for l in lines:
print(l)
print('Run IRAF as:\nastutil\nrvcorrect f=<filename> observatory=Paranal')
示例6: set_jds
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import hour [as 别名]
def set_jds(self, val1, val2):
"""Convert datetime object contained in val1 to jd1, jd2"""
# Iterate through the datetime objects, getting year, month, etc.
iterator = np.nditer([val1, None, None, None, None, None, None],
flags=['refs_ok', 'zerosize_ok'],
op_dtypes=[None] + 5*[np.intc] + [np.double])
for val, iy, im, id, ihr, imin, dsec in iterator:
dt = val.item()
if dt.tzinfo is not None:
dt = (dt - dt.utcoffset()).replace(tzinfo=None)
iy[...] = dt.year
im[...] = dt.month
id[...] = dt.day
ihr[...] = dt.hour
imin[...] = dt.minute
dsec[...] = dt.second + dt.microsecond / 1e6
jd1, jd2 = erfa.dtf2d(self.scale.upper().encode('ascii'),
*iterator.operands[1:])
self.jd1, self.jd2 = day_frac(jd1, jd2)
示例7: value
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import hour [as 别名]
def value(self):
scale = self.scale.upper().encode('ascii')
iys, ims, ids, ihmsfs = erfa.d2dtf(scale, 9,
self.jd1, self.jd2_filled)
out = np.empty(self.jd1.shape, dtype=[('year', 'i4'),
('month', 'i4'),
('day', 'i4'),
('hour', 'i4'),
('minute', 'i4'),
('second', 'f8')])
out['year'] = iys
out['month'] = ims
out['day'] = ids
out['hour'] = ihmsfs['h']
out['minute'] = ihmsfs['m']
out['second'] = ihmsfs['s'] + ihmsfs['f'] * 10**(-9)
out = out.view(np.recarray)
return self.mask_if_needed(out)
示例8: test_to_datetime
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import hour [as 别名]
def test_to_datetime():
tz = TimezoneInfo(utc_offset=-10*u.hour, tzname='US/Hawaii')
# The above lines produces a `datetime.tzinfo` object similar to:
# tzinfo = pytz.timezone('US/Hawaii')
time = Time('2010-09-03 00:00:00')
tz_aware_datetime = time.to_datetime(tz)
assert tz_aware_datetime.time() == datetime.time(14, 0)
forced_to_astropy_time = Time(tz_aware_datetime)
assert tz.tzname(time.datetime) == tz_aware_datetime.tzname()
assert time == forced_to_astropy_time
# Test non-scalar time inputs:
time = Time(['2010-09-03 00:00:00', '2005-09-03 06:00:00',
'1990-09-03 06:00:00'])
tz_aware_datetime = time.to_datetime(tz)
forced_to_astropy_time = Time(tz_aware_datetime)
for dt, tz_dt in zip(time.datetime, tz_aware_datetime):
assert tz.tzname(dt) == tz_dt.tzname()
assert np.all(time == forced_to_astropy_time)
with pytest.raises(ValueError, match=r'does not support leap seconds'):
Time('2015-06-30 23:59:60.000').to_datetime()
示例9: test_ymdhms_output
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import hour [as 别名]
def test_ymdhms_output():
t = Time({'year': 2015, 'month': 2, 'day': 3,
'hour': 12, 'minute': 13, 'second': 14.567},
scale='utc')
# NOTE: actually comes back as np.void for some reason
# NOTE: not necessarily a python int; might be an int32
assert t.ymdhms.year == 2015
# There are two stages of validation now - one on input into a format, so that
# the format conversion code has tidy matched arrays to work with, and the
# other when object construction does not go through a format object. Or at
# least, the format object is constructed with "from_jd=True". In this case the
# normal input validation does not happen but the new input validation does,
# and can ensure that strange broadcasting anomalies can't happen.
# This form of construction uses from_jd=True.
示例10: test_valid_quantity_operations1
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import hour [as 别名]
def test_valid_quantity_operations1(self):
"""Check adding/substracting/comparing a time-valued quantity works
with a TimeDelta. Addition/subtraction should give TimeDelta"""
t0 = TimeDelta(106400., format='sec')
q1 = 10.*u.second
t1 = t0 + q1
assert isinstance(t1, TimeDelta)
assert t1.value == t0.value+q1.to_value(u.second)
q2 = 1.*u.day
t2 = t0 - q2
assert isinstance(t2, TimeDelta)
assert allclose_sec(t2.value, t0.value-q2.to_value(u.second))
# now comparisons
assert t0 > q1
assert t0 < 1.*u.yr
# and broadcasting
q3 = np.arange(12.).reshape(4, 3) * u.hour
t3 = t0 + q3
assert isinstance(t3, TimeDelta)
assert t3.shape == q3.shape
assert allclose_sec(t3.value, t0.value + q3.to_value(u.second))
示例11: __init__
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import hour [as 别名]
def __init__(self, values=None, number=None, spacing=None, format=None,
unit=None, decimal=None, format_unit=None, show_decimal_unit=True):
if unit is None:
unit = u.degree
if format_unit is None:
format_unit = unit
if format_unit not in (u.degree, u.hourangle, u.hour):
if decimal is False:
raise UnitsError("Units should be degrees or hours when using non-decimal (sexagesimal) mode")
self._decimal = decimal
self._sep = None
self.show_decimal_unit = show_decimal_unit
super().__init__(values=values, number=number, spacing=spacing,
format=format, unit=unit, format_unit=format_unit)
示例12: test_complicated_operation
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import hour [as 别名]
def test_complicated_operation(self):
""" Perform a more complicated test """
from astropy.units import imperial
# Multiple units
distance = u.Quantity(15., u.meter)
time = u.Quantity(11., u.second)
velocity = (distance / time).to(imperial.mile / u.hour)
assert_array_almost_equal(
velocity.value, 3.05037, decimal=5)
G = u.Quantity(6.673E-11, u.m ** 3 / u.kg / u.s ** 2)
new_q = ((1. / (4. * np.pi * G)).to(u.pc ** -3 / u.s ** -2 * u.kg))
# Area
side1 = u.Quantity(11., u.centimeter)
side2 = u.Quantity(7., u.centimeter)
area = side1 * side2
assert_array_almost_equal(area.value, 77., decimal=15)
assert area.unit == u.cm * u.cm
示例13: _process_photometry_from_plaintext
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import hour [as 别名]
def _process_photometry_from_plaintext(self, data_product):
"""
Processes the photometric data from a plaintext file into a list of dicts. File is read using astropy as
specified in the below documentation. The file is expected to be a multi-column delimited file, with headers for
time, magnitude, filter, and error.
# http://docs.astropy.org/en/stable/io/ascii/read.html
:param data_product: Photometric DataProduct which will be processed into a list of dicts
:type data_product: DataProduct
:returns: python list containing the photometric data from the DataProduct
:rtype: list
"""
photometry = []
data = ascii.read(data_product.data.path)
if len(data) < 1:
raise InvalidFileFormatException('Empty table or invalid file type')
for datum in data:
time = Time(float(datum['time']), format='mjd')
utc = TimezoneInfo(utc_offset=0*units.hour)
time.format = 'datetime'
value = {
'timestamp': time.to_datetime(timezone=utc),
'magnitude': datum['magnitude'],
'filter': datum['filter'],
'error': datum['error']
}
photometry.append(value)
return photometry
示例14: box2poly
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import hour [as 别名]
def box2poly(line):
"""
Convert a string that describes a box in ds9 format, into a polygon that is given by the corners of the box
Parameters
----------
line : str
A string containing a DS9 region command for a box.
Returns
-------
poly : [ra, dec, ...]
The corners of the box in clockwise order from top left.
"""
words = re.split('[(\s,)]', line)
ra = words[1]
dec = words[2]
width = words[3]
height = words[4]
if ":" in ra:
ra = Angle(ra, unit=u.hour)
else:
ra = Angle(ra, unit=u.degree)
dec = Angle(dec, unit=u.degree)
width = Angle(float(width[:-1])/2, unit=u.arcsecond) # strip the "
height = Angle(float(height[:-1])/2, unit=u.arcsecond) # strip the "
center = SkyCoord(ra, dec)
tl = center.ra.degree+width.degree, center.dec.degree+height.degree
tr = center.ra.degree-width.degree, center.dec.degree+height.degree
bl = center.ra.degree+width.degree, center.dec.degree-height.degree
br = center.ra.degree-width.degree, center.dec.degree-height.degree
return np.ravel([tl, tr, br, bl]).tolist()
示例15: poly2poly
# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import hour [as 别名]
def poly2poly(line):
"""
Parse a string of text containing a DS9 description of a polygon.
This function works but is not very robust due to the constraints of healpy.
Parameters
----------
line : str
A string containing a DS9 region command for a polygon.
Returns
-------
poly : [ra, dec, ...]
The coordinates of the polygon.
"""
words = re.split('[(\s,)]', line)
ras = np.array(words[1::2])
decs = np.array(words[2::2])
coords = []
for ra, dec in zip(ras, decs):
if ra.strip() == '' or dec.strip() == '':
continue
if ":" in ra:
pos = SkyCoord(Angle(ra, unit=u.hour), Angle(dec, unit=u.degree))
else:
pos = SkyCoord(Angle(ra, unit=u.degree), Angle(dec, unit=u.degree))
# only add this point if it is some distance from the previous one
coords.extend([pos.ra.degree, pos.dec.degree])
return coords