Python astropy.units.hour() Examples

The following are 30 code examples of astropy.units.hour(). 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: test_formatting.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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' 
Example #2
Source File: test_basic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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() 
Example #3
Source File: test_basic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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. 
Example #4
Source File: test_velocity_corrs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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') 
Example #5
Source File: test_quantity_interaction.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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)) 
Example #6
Source File: test_distance.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #7
Source File: formatter_locator.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #8
Source File: test_quantity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #9
Source File: test_representation.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #10
Source File: formats.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #11
Source File: formats.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_jds(self, val1, val2):
        if val1 is None:
            # Input was empty list []
            jd1 = np.array([], dtype=np.float64)
            jd2 = np.array([], dtype=np.float64)

        else:
            jd1, jd2 = erfa.dtf2d(self.scale.upper().encode('ascii'),
                                  val1['year'],
                                  val1.get('month', 1),
                                  val1.get('day', 1),
                                  val1.get('hour', 0),
                                  val1.get('minute', 0),
                                  val1.get('second', 0))

        self.jd1, self.jd2 = day_frac(jd1, jd2) 
Example #12
Source File: MIMAS.py    From Aegean with Academic Free License v3.0 6 votes vote down vote up
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] 
Example #13
Source File: formats.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #14
Source File: formats.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, utc_offset=0*u.day, dst=0*u.day, tzname=None):
        """
        Parameters
        ----------
        utc_offset : `~astropy.units.Quantity`, optional
            Offset from UTC in days. Defaults to zero.
        dst : `~astropy.units.Quantity`, optional
            Daylight Savings Time offset in days. Defaults to zero
            (no daylight savings).
        tzname : str or `None`, optional
            Name of timezone

        Examples
        --------
        >>> from datetime import datetime
        >>> from astropy.time import TimezoneInfo  # Specifies a timezone
        >>> import astropy.units as u
        >>> utc = TimezoneInfo()    # Defaults to UTC
        >>> utc_plus_one_hour = TimezoneInfo(utc_offset=1*u.hour)  # UTC+1
        >>> dt_aware = datetime(2000, 1, 1, 0, 0, 0, tzinfo=utc_plus_one_hour)
        >>> print(dt_aware)
        2000-01-01 00:00:00+01:00
        >>> print(dt_aware.astimezone(utc))
        1999-12-31 23:00:00+00:00
        """
        if utc_offset == 0 and dst == 0 and tzname is None:
            tzname = 'UTC'
        self._utcoffset = datetime.timedelta(utc_offset.to_value(u.day))
        self._tzname = tzname
        self._dst = datetime.timedelta(dst.to_value(u.day)) 
Example #15
Source File: formats.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _regexify_subfmts(subfmts):
    """
    Iterate through each of the sub-formats and try substituting simple
    regular expressions for the strptime codes for year, month, day-of-month,
    hour, minute, second.  If no % characters remain then turn the final string
    into a compiled regex.  This assumes time formats do not have a % in them.

    This is done both to speed up parsing of strings and to allow mixed formats
    where strptime does not quite work well enough.
    """
    new_subfmts = []
    for subfmt_tuple in subfmts:
        subfmt_in = subfmt_tuple[1]
        if isinstance(subfmt_in, str):
            for strptime_code, regex in (('%Y', r'(?P<year>\d\d\d\d)'),
                                         ('%m', r'(?P<mon>\d{1,2})'),
                                         ('%d', r'(?P<mday>\d{1,2})'),
                                         ('%H', r'(?P<hour>\d{1,2})'),
                                         ('%M', r'(?P<min>\d{1,2})'),
                                         ('%S', r'(?P<sec>\d{1,2})')):
                subfmt_in = subfmt_in.replace(strptime_code, regex)

            if '%' not in subfmt_in:
                subfmt_tuple = (subfmt_tuple[0],
                                re.compile(subfmt_in + '$'),
                                subfmt_tuple[2])
        new_subfmts.append(subfmt_tuple)

    return tuple(new_subfmts) 
Example #16
Source File: formats.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def str_kwargs(self):
        """
        Generator that yields a dict of values corresponding to the
        calendar date and time for the internal JD values.
        """
        scale = self.scale.upper().encode('ascii'),
        iys, ims, ids, ihmsfs = erfa.d2dtf(scale, self.precision,
                                           self.jd1, self.jd2_filled)

        # Get the str_fmt element of the first allowed output subformat
        _, _, str_fmt = self._select_subfmts(self.out_subfmt)[0]

        if '{yday:' in str_fmt:
            has_yday = True
        else:
            has_yday = False
            yday = None

        ihrs = ihmsfs['h']
        imins = ihmsfs['m']
        isecs = ihmsfs['s']
        ifracs = ihmsfs['f']
        for iy, im, id, ihr, imin, isec, ifracsec in np.nditer(
                [iys, ims, ids, ihrs, imins, isecs, ifracs],
                flags=['zerosize_ok']):
            if has_yday:
                yday = datetime.datetime(iy, im, id).timetuple().tm_yday

            yield {'year': int(iy), 'mon': int(im), 'day': int(id),
                   'hour': int(ihr), 'min': int(imin), 'sec': int(isec),
                   'fracsec': int(ifracsec), 'yday': yday} 
Example #17
Source File: formats.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def parse_string(self, timestr, subfmts):
        """Read time and deprecated scale if present"""
        # Try parsing with any of the allowed sub-formats.
        for _, regex, _ in subfmts:
            tm = re.match(regex, timestr)
            if tm:
                break
        else:
            raise ValueError('Time {} does not match {} format'
                             .format(timestr, self.name))
        tm = tm.groupdict()
        # Scale and realization are deprecated and strings in this form
        # are no longer created.  We issue a warning but still use the value.
        if tm['scale'] is not None:
            warnings.warn("FITS time strings should no longer have embedded time scale.",
                          AstropyDeprecationWarning)
            # If a scale was given, translate from a possible deprecated
            # timescale identifier to the scale used by Time.
            fits_scale = tm['scale'].upper()
            scale = FITS_DEPRECATED_SCALES.get(fits_scale, fits_scale.lower())
            if scale not in TIME_SCALES:
                raise ValueError("Scale {!r} is not in the allowed scales {}"
                                 .format(scale, sorted(TIME_SCALES)))
            # If no scale was given in the initialiser, set the scale to
            # that given in the string.  Realization is ignored
            # and is only supported to allow old-style strings to be
            # parsed.
            if self._scale is None:
                self._scale = scale
            if scale != self.scale:
                raise ValueError("Input strings for {} class must all "
                                 "have consistent time scales."
                                 .format(self.name))
        return [int(tm['year']), int(tm['mon']), int(tm['mday']),
                int(tm.get('hour', 0)), int(tm.get('min', 0)),
                float(tm.get('sec', 0.))] 
Example #18
Source File: test_regression.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_regression_5889_5890():
    # ensure we can represent all Representations and transform to ND frames
    greenwich = EarthLocation(
        *u.Quantity([3980608.90246817, -102.47522911, 4966861.27310067],
        unit=u.m))
    times = Time("2017-03-20T12:00:00") + np.linspace(-2, 2, 3)*u.hour
    moon = get_moon(times, location=greenwich)
    targets = SkyCoord([350.7*u.deg, 260.7*u.deg], [18.4*u.deg, 22.4*u.deg])
    targs2d = targets[:, np.newaxis]
    targs2d.transform_to(moon) 
Example #19
Source File: test_basic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ymdhms_init_from_dict_scalar(kwargs):
    """
    Test YMDHMS functionality for a dict input. This includes ensuring that
    key and attribute access work.  For extra fun use a time within a leap
    second.
    """
    time_dict = {
        'year': 2016,
        'month': 12,
        'day': 31,
        'hour': 23,
        'minute': 59,
        'second': 60.123456789}

    tm = Time(time_dict, **kwargs)

    assert tm == Time('2016-12-31T23:59:60.123456789')
    for attr in time_dict:
        for value in (tm.value[attr], getattr(tm.value, attr)):
            if attr == 'second':
                assert allclose_sec(time_dict[attr], value)
            else:
                assert time_dict[attr] == value

    # Now test initializing from a YMDHMS format time using the object
    tm_rt = Time(tm)
    assert tm_rt == tm
    assert tm_rt.format == 'ymdhms'

    # Test initializing from a YMDHMS value (np.void, i.e. recarray row)
    # without specified format.
    tm_rt = Time(tm.ymdhms)
    assert tm_rt == tm
    assert tm_rt.format == 'ymdhms' 
Example #20
Source File: test_quantity_interaction.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_valid_quantity_operations(self):
        """Check that adding a time-valued quantity to a Time gives a Time"""
        t0 = Time(100000., format='cxcsec')
        q1 = 10.*u.second
        t1 = t0 + q1
        assert isinstance(t1, Time)
        assert t1.value == t0.value+q1.to_value(u.second)
        q2 = 1.*u.day
        t2 = t0 - q2
        assert allclose_sec(t2.value, t0.value-q2.to_value(u.second))
        # check broadcasting
        q3 = np.arange(15.).reshape(3, 5) * u.hour
        t3 = t0 - q3
        assert t3.shape == q3.shape
        assert allclose_sec(t3.value, t0.value-q3.to_value(u.second)) 
Example #21
Source File: formatter_locator.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def decimal(self):
        decimal = self._decimal
        if self.format_unit not in (u.degree, u.hourangle, u.hour):
            if self._decimal is None:
                decimal = True
            elif self._decimal is False:
                raise UnitsError("Units should be degrees or hours when using non-decimal (sexagesimal) mode")
        elif self._decimal is None:
            decimal = False
        return decimal 
Example #22
Source File: test_bls.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_period_units(data):
    t, y, dy, params = data
    t_unit = u.day
    y_unit = u.mag
    model = BoxLeastSquares(t * t_unit, y * y_unit, dy)

    p = model.autoperiod(params["duration"])
    assert p.unit == t_unit
    p = model.autoperiod(params["duration"] * 24 * u.hour)
    assert p.unit == t_unit
    with pytest.raises(u.UnitConversionError):
        model.autoperiod(params["duration"] * u.mag)

    p = model.autoperiod(params["duration"], minimum_period=0.5)
    assert p.unit == t_unit
    with pytest.raises(u.UnitConversionError):
        p = model.autoperiod(params["duration"], minimum_period=0.5*u.mag)

    p = model.autoperiod(params["duration"], maximum_period=0.5)
    assert p.unit == t_unit
    with pytest.raises(u.UnitConversionError):
        p = model.autoperiod(params["duration"], maximum_period=0.5*u.mag)

    p = model.autoperiod(params["duration"], minimum_period=0.5,
                         maximum_period=1.5)
    p2 = model.autoperiod(params["duration"], maximum_period=0.5,
                          minimum_period=1.5)
    assert_quantity_allclose(p, p2) 
Example #23
Source File: test_quantity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_unit_identity():
    q = 1.0 * u.hour
    assert q.unit is u.hour 
Example #24
Source File: test_quantity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_creation(self):
        l = self.Length(np.arange(10.)*u.km)
        assert type(l) is self.Length
        with pytest.raises(u.UnitTypeError):
            self.Length(np.arange(10.) * u.hour)

        with pytest.raises(u.UnitTypeError):
            self.Length(np.arange(10.))

        l2 = self.Length2(np.arange(5.))
        assert type(l2) is self.Length2
        assert l2._default_unit is self.Length2._default_unit

        with pytest.raises(u.UnitTypeError):
            self.Length3(np.arange(10.)) 
Example #25
Source File: test_quantity_non_ufuncs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_piecewise(self):
        x = np.linspace(-2.5, 2.5, 6) * u.m
        out = np.piecewise(x, [x < 0, x >= 0], [-1*u.s, 1*u.day])
        expected = np.piecewise(x.value, [x.value < 0, x.value >= 0],
                                [-1, 24*3600]) * u.s
        assert out.unit == expected.unit
        assert np.all(out == expected)

        out2 = np.piecewise(x, [x < 1 * u.m, x >= 0],
                            [-1*u.s, 1*u.day, lambda x: 1*u.hour])
        expected2 = np.piecewise(x.value, [x.value < 1, x.value >= 0],
                                 [-1, 24*3600, 3600]) * u.s
        assert out2.unit == expected2.unit
        assert np.all(out2 == expected2)

        out3 = np.piecewise(x, [x < 1 * u.m, x >= 0],
                            [0, 1*u.percent, lambda x: 1*u.one])
        expected3 = np.piecewise(x.value, [x.value < 1, x.value >= 0],
                                 [0, 0.01, 1]) * u.one
        assert out3.unit == expected3.unit
        assert np.all(out3 == expected3)

        with pytest.raises(TypeError):  # no Quantity in condlist.
            np.piecewise(x, [x], [0.])

        with pytest.raises(TypeError):  # no Quantity in condlist.
            np.piecewise(x.value, [x], [0.]) 
Example #26
Source File: test_units.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_getting_started():
    """
    Corresponds to "Getting Started" section in the docs.
    """
    from astropy.units import imperial
    with imperial.enable():
        speed_unit = u.cm / u.s
        x = speed_unit.to(imperial.mile / u.hour, 1)
        assert_allclose(x, 0.02236936292054402)
        speed_converter = speed_unit._get_converter("mile hour^-1")
        x = speed_converter([1., 1000., 5000.])
        assert_allclose(x, [2.23693629e-02, 2.23693629e+01, 1.11846815e+02]) 
Example #27
Source File: test_angles.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_negative_zero_hms():
    # Test for HMS parser
    a = Angle('-00:00:10', u.hour)
    assert_allclose(a.hour, -10. / 3600.) 
Example #28
Source File: MIMAS.py    From Aegean with Academic Free License v3.0 5 votes vote down vote up
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() 
Example #29
Source File: MIMAS.py    From Aegean with Academic Free License v3.0 5 votes vote down vote up
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 
Example #30
Source File: pointing.py    From banzai with GNU General Public License v3.0 5 votes vote down vote up
def do_stage(self, image):
        try:
            # OFST-RA/DEC is the same as CAT-RA/DEC but includes user requested offset
            requested_coords = SkyCoord(image.meta['OFST-RA'], image.meta['OFST-DEC'],
                                        unit=(u.hour, u.deg), frame='icrs')
        except ValueError as e:
            try:
                # Fallback to CAT-RA and CAT-DEC
                requested_coords = SkyCoord(image.meta['CAT-RA'], image.meta['CAT-DEC'],
                                            unit=(u.hour, u.deg), frame='icrs')
            except:
                logger.error(e, image=image)
                return image
        # This only works assuming CRPIX is at the center of the image
        solved_coords = SkyCoord(image.meta['CRVAL1'], image.meta['CRVAL2'],
                                 unit=(u.deg, u.deg), frame='icrs')

        angular_separation = solved_coords.separation(requested_coords).arcsec

        logging_tags = {'PNTOFST': angular_separation}

        pointing_severe = abs(angular_separation) > self.SEVERE_THRESHOLD
        pointing_warning = abs(angular_separation) > self.WARNING_THRESHOLD
        if pointing_severe:
            logger.error('Pointing offset exceeds threshold', image=image, extra_tags=logging_tags)
        elif pointing_warning:
            logger.warning('Pointing offset exceeds threshhold', image=image, extra_tags=logging_tags)
        qc_results = {'pointing.failed': pointing_severe,
                      'pointing.failed_threshold': self.SEVERE_THRESHOLD,
                      'pointing.warning': pointing_warning,
                      'pointing.warning_threshold': self.WARNING_THRESHOLD,
                      'pointing.offset': angular_separation}
        qc.save_qc_results(self.runtime_context, qc_results, image)

        image.meta['PNTOFST'] = (angular_separation, '[arcsec] offset of requested and solved center')

        return image