Python astropy.time.TimeDelta() Examples
The following are 30
code examples of astropy.time.TimeDelta().
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.time
, or try the search function
.
Example #1
Source File: test_quantity_interaction.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_quantity_conversion_rounding(q1, q2): """Check that no rounding errors are incurred by unit conversion. This occurred before as quantities in seconds were converted to days before trying to split them into two-part doubles. See gh-7622. """ t = Time('2001-01-01T00:00:00.', scale='tai') expected = Time('2016-11-05T00:53:20.', scale='tai') if q2 is None: t0 = t + q1 else: t0 = t + q1 + q2 assert abs(t0 - expected) < 20 * u.ps dt1 = TimeDelta(q1, q2) t1 = t + dt1 assert abs(t1 - expected) < 20 * u.ps dt2 = TimeDelta(q1, q2, format='sec') t2 = t + dt2 assert abs(t2 - expected) < 20 * u.ps
Example #2
Source File: test_quantity_interaction.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #3
Source File: test_lightcurve.py From lightkurve with MIT License | 6 votes |
def test_fold_v2(): """The API of LightCurve.fold() changed in Lightkurve v2.x when we adopted AstroPy's TimeSeries.fold() method. This test verifies the new API.""" lc = LightCurve(time=np.linspace(0, 10, 100), flux=np.zeros(100)+1) # Can period be passed as a float? fld = lc.fold(period=1) fld2 = lc.fold(period=1*u.day) assert_array_equal(fld.phase, fld2.phase) assert isinstance(fld.time, TimeDelta) fld.plot_river() plt.close() # Does phase normalization work? fld = lc.fold(period=1, normalize_phase=True) assert isinstance(fld.time, u.Quantity) fld.plot_river() plt.close()
Example #4
Source File: test_table.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_mixin_pandas_masked(self): tm = Time([1, 2, 3], format='cxcsec') dt = TimeDelta([1, 2, 3], format='sec') tm[1] = np.ma.masked dt[1] = np.ma.masked t = table.QTable([tm, dt], names=['tm', 'dt']) tp = t.to_pandas() assert np.all(tp['tm'].isnull() == [False, True, False]) assert np.all(tp['dt'].isnull() == [False, True, False]) t2 = table.Table.from_pandas(tp) assert np.all(t2['tm'].mask == tm.mask) assert np.ma.allclose(t2['tm'].jd, tm.jd, rtol=1e-14, atol=1e-14) assert np.all(t2['dt'].mask == dt.mask) assert np.ma.allclose(t2['dt'].jd, dt.jd, rtol=1e-14, atol=1e-14)
Example #5
Source File: test_quantity_interaction.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_quantity_output_errors(self): dt = TimeDelta(250., format='sec') with pytest.raises(u.UnitsError): dt.to(u.m) with pytest.raises(u.UnitsError): dt.to_value(u.m) with pytest.raises(u.UnitsError): dt.to_value(unit=u.m) with pytest.raises(ValueError, match=("not one of the known formats.*" "failed to parse as a unit")): dt.to_value('parrot') with pytest.raises(TypeError): dt.to_value('sec', unit=u.s) with pytest.raises(TypeError): # TODO: would be nice to make this work! dt.to_value(u.s, subfmt='str')
Example #6
Source File: core.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self, t, y, dy=None): # If t is a TimeDelta, convert it to a quantity. The units we convert # to don't really matter since the user gets a Quantity back at the end # so can convert to any units they like. if isinstance(t, TimeDelta): t = t.to('day') # We want to expose self.t as being the times the user passed in, but # if the times are absolute, we need to convert them to relative times # internally, so we use self._trel and self._tstart for this. self.t = t if isinstance(self.t, Time): self._tstart = self.t[0] trel = (self.t - self._tstart).to(u.day) else: self._tstart = None trel = self.t self._trel, self.y, self.dy = self._validate_inputs(trel, y, dy)
Example #7
Source File: core.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _as_relative_time(self, name, times): """ Convert the provided times (if absolute) to relative times using the current _tstart value. If the times provided are relative, they are returned without conversion (though we still do some checks). """ if isinstance(times, TimeDelta): times = times.to('day') if self._tstart is None: if isinstance(times, Time): raise TypeError('{} was provided as an absolute time but ' 'the LombScargle class was initialized ' 'with relative times.'.format(name)) else: if isinstance(times, Time): times = (times - self._tstart).to(u.day) else: raise TypeError('{} was provided as a relative time but ' 'the LombScargle class was initialized ' 'with absolute times.'.format(name)) return times
Example #8
Source File: test_binned.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_initialization_time_bin_size(): # Make sure things crash when time_bin_size has no units with pytest.raises(TypeError) as exc: BinnedTimeSeries(data={"time": ["2016-03-22T12:30:31"]}, time_bin_start="2016-03-22T12:30:31", time_bin_size=1) assert exc.value.args[0] == ("'time_bin_size' should be a Quantity or a TimeDelta") # TimeDelta for time_bin_size ts = BinnedTimeSeries(data={"time": ["2016-03-22T12:30:31"]}, time_bin_start="2016-03-22T12:30:31", time_bin_size=TimeDelta(1)) assert isinstance(ts.time_bin_size, u.quantity.Quantity)
Example #9
Source File: test_quantity_interaction.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_delta_ut1_utc(self): t = Time('2010-01-01 00:00:00', format='iso', scale='utc', precision=6) t.delta_ut1_utc = 0.3 * u.s assert t.ut1.iso == '2010-01-01 00:00:00.300000' t.delta_ut1_utc = 0.4 / 60. * u.minute assert t.ut1.iso == '2010-01-01 00:00:00.400000' with pytest.raises(u.UnitsError): t.delta_ut1_utc = 0.4 * u.m # Also check that a TimeDelta works. t.delta_ut1_utc = TimeDelta(0.3, format='sec') assert t.ut1.iso == '2010-01-01 00:00:00.300000' t.delta_ut1_utc = TimeDelta(0.5/24./3600., format='jd') assert t.ut1.iso == '2010-01-01 00:00:00.500000'
Example #10
Source File: test_iers.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def setup_class(self): """Set up useful data for the tests. """ self.N = 40 self.ame = 30.0 self.iers_a_file_1 = os.path.join(os.path.dirname(__file__), 'data', 'finals2000A-2016-02-30-test') self.iers_a_file_2 = os.path.join(os.path.dirname(__file__), 'data', 'finals2000A-2016-04-30-test') self.iers_a_url_1 = os.path.normpath('file://' + os.path.abspath(self.iers_a_file_1)) self.iers_a_url_2 = os.path.normpath('file://' + os.path.abspath(self.iers_a_file_2)) self.t = Time.now() + TimeDelta(10, format='jd') * np.arange(self.N)
Example #11
Source File: core.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _as_relative_time(self, name, times): """ Convert the provided times (if absolute) to relative times using the current _tstart value. If the times provided are relative, they are returned without conversion (though we still do some checks). """ if isinstance(times, TimeDelta): times = times.to('day') if self._tstart is None: if isinstance(times, Time): raise TypeError('{} was provided as an absolute time but ' 'the BoxLeastSquares class was initialized ' 'with relative times.'.format(name)) else: if isinstance(times, Time): times = (times - self._tstart).to(u.day) else: raise TypeError('{} was provided as a relative time but ' 'the BoxLeastSquares class was initialized ' 'with absolute times.'.format(name)) times = validate_unit_consistency(self._trel, times) return times
Example #12
Source File: core.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _validate_inputs(self, t, y, dy): """Private method used to check the consistency of the inputs Parameters ---------- t : array_like, `~astropy.units.Quantity`, `~astropy.time.Time`, or `~astropy.time.TimeDelta` Sequence of observation times. y : array_like or `~astropy.units.Quantity` Sequence of observations associated with times t. dy : float, array_like, or `~astropy.units.Quantity` Error or sequence of observational errors associated with times t. Returns ------- t, y, dy : array_like, `~astropy.units.Quantity`, or `~astropy.time.Time` The inputs with consistent shapes and units. Raises ------ ValueError If the dimensions are incompatible or if the units of dy cannot be converted to the units of y. """ # Validate shapes of inputs if dy is None: t, y = np.broadcast_arrays(t, y, subok=True) else: t, y, dy = np.broadcast_arrays(t, y, dy, subok=True) if t.ndim != 1: raise ValueError("Inputs (t, y, dy) must be 1-dimensional") # validate units of inputs if any is a Quantity if dy is not None: dy = validate_unit_consistency(y, dy) return t, y, dy
Example #13
Source File: test_quantity_interaction.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_invalid_quantity_operations2(self): """Check that operations with non-time/quantity fail.""" td = TimeDelta(100000., format='sec') with pytest.raises(TypeError): td * object() with pytest.raises(TypeError): td / object()
Example #14
Source File: test_sampled.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_initialization_with_time_delta(): ts = TimeSeries(time_start=datetime(2018, 7, 1, 10, 10, 10), time_delta=TimeDelta(3, format='sec'), data=[[10, 2, 3], [4, 5, 6]], names=['a', 'b']) assert_equal(ts.time.isot, ['2018-07-01T10:10:10.000', '2018-07-01T10:10:13.000', '2018-07-01T10:10:16.000'])
Example #15
Source File: test_sampled.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_initialization_invalid_time_delta(): with pytest.raises(TypeError) as exc: TimeSeries(time_start=datetime(2018, 7, 1, 10, 10, 10), time_delta=[1, 4, 3], data=[[10, 2, 3], [4, 5, 6]], names=['a', 'b']) assert exc.value.args[0] == "'time_delta' should be a Quantity or a TimeDelta"
Example #16
Source File: test_sampled.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_initialization_invalid_both_time_and_time_delta(): with pytest.raises(TypeError) as exc: TimeSeries(time=INPUT_TIME, time_delta=TimeDelta(3, format='sec')) assert exc.value.args[0] == ("'time_delta' should not be specified since " "'time' is an array")
Example #17
Source File: timedelta.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def from_tree(cls, node, ctx): return TimeDelta.info._construct_from_dict(node)
Example #18
Source File: test_table.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_timedelta_mixin(tmpdir): t = table.Table() t['a'] = [1, 2] t['b'] = ['x', 'y'] t['c'] = TimeDelta([1, 2] * u.day) def check(ff): assert isinstance(ff['table']['c'], TimeDelta) helpers.assert_roundtrip_tree({'table': t}, tmpdir, asdf_check_func=check)
Example #19
Source File: yaml.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _timedelta_representer(dumper, obj): out = obj.info._represent_as_dict() return dumper.represent_mapping('!astropy.time.TimeDelta', out)
Example #20
Source File: test_fitstime.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_io_time_read_fits(self, table_types): """ Test that FITS table with time columns (standard compliant) can be read by io.fits as a table with Time columns. This tests the following: 1. The special-case where a column has the name 'TIME' and a time unit 2. Time from Epoch (Reference time) is appropriately converted. 3. Coordinate columns (corresponding to coordinate keywords in the header) other than time, that is, spatial coordinates, are not mistaken to be time. """ filename = self.data('chandra_time.fits') with pytest.warns(AstropyUserWarning, match=r'Time column "time" reference ' r'position will be ignored'): tm = table_types.read(filename, astropy_native=True) # Test case 1 assert isinstance(tm['time'], Time) assert tm['time'].scale == 'tt' assert tm['time'].format == 'mjd' non_native = table_types.read(filename) # Test case 2 ref_time = Time(non_native.meta['MJDREF'], format='mjd', scale=non_native.meta['TIMESYS'].lower()) delta_time = TimeDelta(non_native['time']) assert (ref_time + delta_time == tm['time']).all() # Test case 3 for colname in ['chipx', 'chipy', 'detx', 'dety', 'x', 'y']: assert not isinstance(tm[colname], Time)
Example #21
Source File: header.py From baseband with GNU General Public License v3.0 | 5 votes |
def get_time(self, frame_rate=None): """Converts ref_epoch, seconds, and frame_nr to Time object. Uses 'ref_epoch', which stores the number of half-years from 2000, and 'seconds'. By default, it also calculates the offset using the current frame number. For non-zero 'frame_nr', this requires the frame rate, which is calculated from the sample rate in the header. Parameters ---------- frame_rate : `~astropy.units.Quantity`, optional For non-zero 'frame_nr', this is required to calculate the corresponding offset. Returns ------- time : `~astropy.time.Time` """ frame_nr = self['frame_nr'] if frame_nr == 0: offset = 0. else: if frame_rate is None: raise ValueError("this header does not provide a frame " "rate. Pass it in explicitly.") offset = (frame_nr / frame_rate).to_value(u.s) return (self.ref_time + TimeDelta(self['seconds'], offset, format='sec'))
Example #22
Source File: test_miriad.py From pyuvdata with BSD 2-Clause "Simplified" License | 5 votes |
def test_readmiriad_write_miriad_check_time_format(tmp_path): """ test time_array is converted properly from Miriad format """ from pyuvdata.uvdata import aipy_extracts # test read-in fname = os.path.join(DATA_PATH, "zen.2457698.40355.xx.HH.uvcA") uvd = UVData() uvd.read(fname) uvd_t = uvd.time_array.min() uvd_l = uvd.lst_array.min() uv = aipy_extracts.UV(fname) uv_t = uv["time"] + uv["inttime"] / (24 * 3600.0) / 2 lat, lon, alt = uvd.telescope_location_lat_lon_alt t1 = Time(uv["time"], format="jd", location=(lon, lat)) dt = TimeDelta(uv["inttime"] / 2, format="sec") t2 = t1 + dt lsts = uvutils.get_lst_for_time(np.array([t1.jd, t2.jd]), lat, lon, alt) delta_lst = lsts[1] - lsts[0] uv_l = uv["lst"] + delta_lst # assert starting time array and lst array are shifted by half integration assert np.isclose(uvd_t, uv_t) # avoid errors if IERS table is too old (if the iers url is down) tolerance = 1e-8 assert np.allclose(uvd_l, uv_l, atol=tolerance) # test write-out fout = str(tmp_path / "ex_miriad") uvd.write_miriad(fout, clobber=True) # assert equal to original miriad time uv2 = aipy_extracts.UV(fout) assert np.isclose(uv["time"], uv2["time"]) assert np.isclose(uv["lst"], uv2["lst"], atol=tolerance)
Example #23
Source File: elements.py From orbital with MIT License | 5 votes |
def epoch(self): """Current epoch calculated from time since ref_epoch.""" return self.ref_epoch + time.TimeDelta(self.t, format='sec')
Example #24
Source File: lightcurve.py From lightkurve with MIT License | 5 votes |
def _set_xlabel(self, kwargs): """Helper function for plot, scatter, and errorbar. Ensures the xlabel is correctly set for folded light curves. """ if 'xlabel' not in kwargs: kwargs['xlabel'] = "Phase" if isinstance(self.time, TimeDelta): kwargs['xlabel'] += f" [{self.time.format.upper()}]" return kwargs
Example #25
Source File: test_comparisons.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_timedelta(self): dt = self.t2 - self.t1 with pytest.raises(TypeError): self.t1 > dt dt_gt_td0 = dt > TimeDelta(0., format='sec') assert np.all(dt_gt_td0 == np.array([False, False, False, False, False, False, True, True, True, True]))
Example #26
Source File: test_corrs.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_heliocentric(self): hval = self.obstime.light_travel_time(self.star, 'heliocentric') assert isinstance(hval, TimeDelta) assert hval.scale == 'tdb' assert abs(hval - 461.43037870502235 * u.s) < 1. * u.us
Example #27
Source File: test_corrs.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_barycentric(self): bval = self.obstime.light_travel_time(self.star, 'barycentric') assert isinstance(bval, TimeDelta) assert bval.scale == 'tdb' assert abs(bval - 460.58538779827836 * u.s) < 1. * u.us
Example #28
Source File: test_precision.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_mult_div(): """Test precision with multiply and divide""" dt_small = 6 * dt_tiny # pick a number that will leave remainder if divided by 6. dt_big = TimeDelta(20000., format='jd') dt_big_small_by_6 = (dt_big + dt_small) / 6. dt_frac = dt_big_small_by_6 - TimeDelta(3333., format='jd') assert allclose_jd2(dt_frac.jd2, 0.33333333333333354)
Example #29
Source File: test_precision.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_datetime_difference_agrees_with_timedelta(): scale = "tai" dt1 = datetime(1235, 1, 1, 0, 0) dt2 = datetime(9950, 1, 1, 0, 0, 0, 890773) t1 = Time(dt1, scale=scale) t2 = Time(dt2, scale=scale) assert(abs((t2-t1) - TimeDelta(dt2-dt1, scale=scale)) < 1*u.us)
Example #30
Source File: test_quantity_interaction.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_valid_quantity_input(self): """Test that TimeDelta can take quantity input.""" q = 500.25*u.day dt1 = TimeDelta(q, format='jd') assert dt1.value == q.value dt2 = TimeDelta(q, format='sec') assert dt2.value == q.to_value(u.second) dt3 = TimeDelta(q) assert dt3.value == q.value