-
Notifications
You must be signed in to change notification settings - Fork 23
/
obstools.py
2583 lines (2114 loc) · 89.6 KB
/
obstools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Copyright 2008 Erik Tollerud
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
===============================================
obstools -- miscellaneous tools for observation
===============================================
The :mod:`obstools` module stores tools for oberving (pre- and post-) as well as
functioning as a module for various corrections and simple calculations that
don't have a better place to live.
Most implementations are for optical astronomy, as that is what the primary
author does.
Note that throughout this module it is assumed that UTC as used in
:mod:`datetime` is the same as UT1 (the UT used for calculations). This is only
an issue if leapseconds stop being updated or if something such as daylight
savings time calculations in :mod:`datetime` are important to be correct to less
than DUT1 - otherwise, the "UTC" in :mod:`datetime` can simply by replaced with
UT1 values when precision better than DUT1 is needed.
Also note that some of these functions require the `dateutil
<http://labix.org/python-dateutil>`_ package (it is installed by default with
matplotlib)
.. todo:: examples/tutorials
.. seealso::
:func:`astropysics.coords.earth_rotation_angle`
:func:`astropysics.coords.greenwich_sidereal_time`
Classes and Inheritance Structure
---------------------------------
.. inheritance-diagram:: astropysics.obstools
:parts: 1
Module API
----------
"""
#TODO: exposure time calculator (maybe in phot instead?)
#TODO: make Extinction classes spec.HasSpecUnits and follow models framework?
#TODO: return Pipeline support to Extinction
#TODO: Instruments and telescopes for sites
#TODO: get leap second from IERS web site
from __future__ import division,with_statement
from .constants import pi
from .utils import DataObjectRegistry
from .pipeline import PipelineElement
import numpy as np
from datetime import timedelta
try:
from dateutil import tz as tzmod
tzoffset = tzmod.tzoffset
except ImportError:
import datetime
tzmod = None
class tzoffset(datetime.tzinfo):
"""
Backup class to do basic fixed-offset time zones if :mod:`dateutil.tz`
is missing.
"""
def __init__(self,name,offset):
if not isinstance(name,basestring):
raise TypeError('name must be a string')
self._name = name
self._hoffset = offset
def dst(self):
return False
def tzname(self):
return self._name
def utcoffset(self):
from datetime import timedelta
return timedelta(hours=self._hoffset)
#<----------------------Time and calendar functions---------------------------->
jd2000 = 2451545.0
mjdoffset = 2400000.5
"""
Offset between Julian Date and Modified Julian Date - e.g. mjd = jd - mjdoffset
"""
def jd_to_calendar(jd,rounding=1000000,output='datetime',gregorian=None,mjd=False):
"""
Converts a julian date to a calendar date and time.
:param jd:
The Julian Date at which to compute the calendar date/time, a sequence
of JDs, or None for the current date/time at the moment the function is
called.
:type jd: scalar, array-like, or None
:param rounding:
If non-0, Performs a fix for floating-point errors. It specifies the
number of milliseconds by which to round the result to the nearest
second. If 1000000 (one second), no milliseconds are recorded. If
larger, a ValueError is raised.
:type rounding: scalar
:param output:
Determines the format of the returned object and can be:
* 'datetime'
A list of :class:`datetime.datetime` objects in UTC will be
returned. If the input is a scalar, a single object will be
returned.
* 'array'
A Nx7 array will be returned of the form
[(year,month,day,hr,min,sec,msec),...] unless the input was a
scalar, in which case it will be a length-7 array.
* 'fracarray'
An Nx3 array (year,month,day) where day includes the decimal
portion.
:param gregorian:
If True, the output will be in the Gregorian calendar. Otherwise, it
will be Julian. If None, it will be assumed to switch over on October
4/15 1582.
:type gregorian: bool or None
:param bool mjd:
If True, the input is interpreted as a modified julian date instead of a
standard julian date.
:returns:
The calendar date and time in a format determined by the `output`
parameter (see above).
:except ValueError:
If `rounding` is larger than one second, or `output` is invalid.
**Examples**
>>> jd_to_calendar(2451545)
datetime.datetime(2000, 1, 1, 12, 0, tzinfo=tzutc())
>>> jd_to_calendar(2305812.5)
datetime.datetime(1600, 12, 31, 0, 0, tzinfo=tzutc())
>>> jd_to_calendar([2415020.5,2305447.5],output='array')
array([[1900, 1, 1, 0, 0, 0, 0],
[1600, 1, 1, 0, 0, 0, 0]])
>>> jd_to_calendar(0.0,output='fracarray')
array([[ -4.71200000e+03, 1.00000000e+00, 1.50000000e+00]])
"""
import datetime
from dateutil import tz
if jd is None:
jd = calendar_to_jd(datetime.datetime.now(tz.tzlocal()))
jd = np.array(jd,copy=True,dtype=float)
scalar = jd.shape == ()
jd = jd.ravel()
if mjd:
jd += mjdoffset
if rounding > 1000000:
raise ValueError('rounding cannot exceed a second')
elif rounding <= 0:
jd += .5
else:
rounding = int(rounding)
roundingfrac = rounding/86400000000
jd += .5 + roundingfrac
z = np.floor(jd).astype(int)
dec = jd - z #fractional piece
#fix slight floating-point errors if they hapepn TOOD:check
dgtr1 = dec>=1.0
dec[dgtr1] -= 1.0
z[dgtr1] += 1
if gregorian is None:
gregorian = 2299161
if gregorian is True:
alpha = ((z-1867216.25)/36524.25).astype(int)
z += 1 + alpha - alpha//4
elif gregorian is False:
pass
else:
gmask = z >= gregorian
alpha = ((z[gmask]-1867216.25)/36524.25).astype(int)
z[gmask] += 1 + alpha - alpha//4
b = z + 1524
c = ((b-122.1)/365.25).astype(int)
d = (365.25*c).astype(int)
e = ((b-d)/30.6001).astype(int)
day = b - d - (30.6001*e).astype(int)
mmask = e<14
month = e
month[mmask] -= 1
month[~mmask] -= 13
year = c
year[month>2] -= 4716
year[month<=2] -= 4715
if output == 'fracarray':
dec = dec-roundingfrac
dec[dec<0]=0
return np.array((year,month,day+dec)).T
if rounding == 1000000:
secdec = dec*86400
sec = secdec.astype(int)
min = sec//60
sec -= 60*min
hr = min//60
min -= 60*hr
#sec[sec==secdec] -= 1
msec = None
else:
msec = (dec*86400000000.).astype('int64')
if rounding > 0:
div = (msec//1000000)*1000000
toround = (msec - div)<(2*rounding)
msec[toround] = div + rounding
msec -= rounding
sec = msec//1000000
msec -= 1000000*sec
min = sec//60
sec -= 60*min
hr = min//60
min -= 60*hr
if output == 'datetime':
tzi = tz.tzutc()
if msec is None:
ts = (year,month,day,hr%24,min%60,sec%60)
else:
ts = (year,month,day,hr%24,min%60,sec%60,msec%1000000)
res = [datetime.datetime(*t,**dict(tzinfo=tzi)) for t in zip(*ts)]
elif output == 'array':
msec = np.zeros_like(sec) if msec is None else msec
res = np.array([year,month,day,hr%24,min%60,sec%60,msec]).T
else:
raise ValueError('invlid output form '+str(output))
if scalar:
return res[0]
else:
return res
def calendar_to_jd(caltime,tz=None,gregorian=True,mjd=False):
"""
Convert a calendar date and time to julian date.
:param caltime:
The date and time to compute the JD. Can be in one of these forms:
* A sequence of floats in the order (yr,month,day,[hr,min,sec]).
* A sequence in the order (yr,month,day,[hr,min,sec]) where at least
one of the elements is a sequence (a sequence will be returned).
* A :class:`datetime.datetime` or :class:`datetime.date` object
* A sequence of :class:`datetime.datetime` or :class:`datetime.date`
objects (a sequence will be returned).
* None : returns the JD at the moment the function is called.
If the time is unspecified, it is taken to be noon (i.e. Julian Date =
Julian Day Number)
:param tz:
Sets the time zone to assume for the inputs for conversion to UTC. Can
be any of the following:
* None
No time zone conversion will occur unless `caltime` is given as
:class:`datetime.datetime` or :class:`datetime.date` objects
with `tzinfo`, in which case they will be converted to UTC using
their own `tzinfo`.
* a string
Specifies a timezone name (resolved into a timezone using the
:func:`dateutil.tz.gettz` function).
* a scalar
The hour offset of the timezone.
* a :class:`datetime.tzinfo` object,
This object will be used for timezone information.
:param gregorian:
If True, the input will be interpreted as in the Gregorian calendar.
Otherwise, it will be Julian. If None, it will be assumed to switch over
on October 4/15, 1582.
:type gregorian: bool or None
:param bool mjd:
If True, a modified julian date is returned instead of the standard
julian date.
:returns: JD as a float, or a sequence of JDs if sequences were input.
**Examples**
>>> import datetime,dateutil
>>> calendar_to_jd((2010,1,1))
2455198.0
>>> calendar_to_jd(datetime.datetime(2000,12,21,3,0,0))
2451899.625
>>> calendar_to_jd([2004,3,(5,6)])
array([ 2453070., 2453071.])
>>> dates = [datetime.datetime(2004,3,5),datetime.datetime(2004,3,9)]
>>> calendar_to_jd(dates)
array([ 2453069.5, 2453073.5])
>>> tz = dateutil.tz.tzoffset('2',3*3600)
>>> calendar_to_jd((2010,1,1),tz)
2455197.875
"""
#Adapted from xidl jdcnv.pro
from datetime import datetime,date,tzinfo
if caltime is None:
from dateutil.tz import tzlocal
datetimes = [datetime.now(tzlocal())]
scalarout = True
elif isinstance(caltime,datetime) or isinstance(caltime,date):
datetimes = [caltime]
scalarout = True
elif all([isinstance(ct,datetime) or isinstance(ct,date) for ct in caltime]):
datetimes = caltime
scalarout = False
else:
datetimes = None
caltime = list(caltime)
if not (3 <= len(caltime) < 8):
raise ValueError('caltime input sequence is invalid size')
while len(caltime) < 7:
if len(caltime) == 3:
#make hours 12
caltime.append(12*np.ones_like(caltime[-1]))
else:
caltime.append(np.zeros_like(caltime[-1]))
yr,month,day,hr,min,sec,msec = caltime
scalarout = all([np.shape(v) is tuple() for v in caltime])
#if input objects are datetime objects, generate arrays
if datetimes is not None:
yr,month,day,hr,min,sec,msec = [],[],[],[],[],[],[]
for dt in datetimes:
if not hasattr(dt,'hour'):
dt = datetime(dt.year,dt.month,dt.day,12)
if tz is None:
off = dt.utcoffset()
if off is not None:
dt = dt - off
yr.append(dt.year)
month.append(dt.month)
day.append(dt.day)
hr.append(dt.hour)
min.append(dt.minute)
sec.append(dt.second)
msec.append(dt.microsecond)
yr = np.array(yr,dtype='int64',copy=False).ravel()
month = np.array(month,dtype='int64',copy=False).ravel()
day = np.array(day,dtype='int64',copy=False).ravel()
hr = np.array(hr,dtype=float,copy=False).ravel()
min = np.array(min,dtype=float,copy=False).ravel()
sec = np.array(sec,dtype=float,copy=False).ravel()
msec = np.array(msec,dtype=float,copy=False).ravel()
#do tz conversion if tz is provided
if isinstance(tz,basestring) or isinstance(tz,tzinfo):
if isinstance(tz,basestring):
from dateutil import tz
tzi = tz.gettz(tz)
else:
tzi = tz
utcoffset = []
for t in zip(yr,month,day,hr,min,sec,msec):
#microsecond from float component of seconds
dt = datetime(*[int(ti) for ti in t],**dict(tzinfo=tzi))
utcdt = dt.utcoffset()
if utcdt is None:
utcoffset.append(0)
else:
utcoffset.append(utcdt.days*24 + (utcdt.seconds + utcdt.microseconds*1e-6)/3600)
else:
utcoffset = tz
# ly = ((month-14)/12).astype(int) #In leap years, -1 for Jan, Feb, else 0
# jdn = day - 32075l + 1461l*(yr+4800l+ly)//4
# jdn += 367l*(month - 2-ly*12)//12 - 3*((yr+4900l+ly)//100)//4
# res = jdn + (hr/24.0) + min/1440.0 + sec/86400.0 - 0.5
#this algorithm from meeus 2ed
m3 = month < 3
yr[m3] -= 1
month[m3] += 12
cen = yr//100
if gregorian is None:
gregorian = (1582,10,4)
if gregorian is True:
gregoffset = 2 - cen + cen//4
elif gregorian is False:
gregoffset = 0
else:
gregoffset = 2 - cen + cen//4
gmask = (yr>gregorian[0])&(month>gregorian[1])&(day>gregorian[2])
gregoffset[~gmask] = 0
jdn = (365.25*(yr+4716)).astype(int) + \
(30.6001*(month + 1)).astype(int) + \
day + gregoffset - 1524.5
res = jdn + hr/24.0 + min/1440.0 + sec/86400.0
if mjd:
res -= mjdoffset
if np.any(utcoffset):
res -= np.array(utcoffset)/24.0
if scalarout:
return res[0]
else:
return res
def jd_to_epoch(jd,julian=True,asstring=False,mjd=False):
"""
Converts a Julian Date to a Julian or Besselian Epoch expressed in decimal
years.
:param jd: Julian Date for computing the epoch, or None for current epoch.
:type jd: scalar, array-like, or None
:param bool julian:
If True, a Julian Epoch will be used (the year is exactly 365.25 days
long). Otherwise, the epoch will be Besselian (assuming a tropical year
of 365.242198781 days).
:param bool asstring:
If True, a string of the form 'J2000.0' will be returned. If it is an
integer, the number sets the number of significant figures in the output
string Otherwise, scalars are returned (an int if a whole year, float if
not).
:param bool mjd:
If True, a modified julian date is returned instead of the standard
julian date.
:returns:
The epoch as a string (or list of strings if `jd` was array-like) if
`asstring` is True. If not, an int if a whole year, or a float (or array
if `jd` was array-like).
:Reference: http://www.iau-sofa.rl.ac.uk/2003_0429/sofa/epj.html
"""
if jd is None:
jd = calendar_to_jd(None)
else:
jd = np.array(jd,copy=False)
if mjd:
jd += mjdoffset
if julian:
epoch = 2000.0 + (jd - 2451545.0)/365.25
else:
epoch = 1900 + (jd - 2415020.31352)/365.242198781
if asstring:
if asstring is not True:
fmt = ('J' if julian else 'B')+'{0:.'+str(int(asstring))+'}'
else:
fmt = 'J{0}' if julian else 'B{0}'
if len(epoch.shape) == 0:
return fmt.format(epoch)
else:
return [fmt.format(e) for e in epoch]
else:
if len(epoch.shape) == 0:
if round(epoch)==epoch:
return int(epoch)
else:
return float(epoch)
else:
return epoch
def epoch_to_jd(epoch,julian=True,mjd=False):
"""
Converts a Julian or Besselian Epoch to a Julian Day.
:param epoch: The epoch as a decimal year.
:type epoch: string, scalar, or array-like
:param bool julian:
If True, a Julian Epoch will be used (the year is exactly 365.25 days
long). Otherwise, the epoch will be Besselian (assuming a tropical year
of 365.242198781 days). If `epoch` is a string and starts with 'B' or
'J', this parameter will be ignored, and the 'B' or 'J' specifies the
epoch type.
:param bool mjd:
If True, a modified julian date is returned instead of the standard
julian date.
:returns: The Julian Day as a float or array (if `epoch` is array-like)
:Reference: http://www.iau-sofa.rl.ac.uk/2003_0429/sofa/epj.html
"""
if isinstance(epoch,basestring):
if epoch[0]=='J':
julian = True
epoch = epoch[1:]
elif epoch[0]=='B':
julian = False
epoch = epoch[1:]
epoch = float(epoch)
else:
epoch = np.array(epoch,copy=False)
if epoch.dtype.kind == 'S':
return np.array([epoch_to_jd(e,julian) for e in epoch])
if julian:
res = (epoch - 2000)*365.25 + 2451545.0
else:
res = (epoch - 1900)*365.242198781 + 2415020.31352
if mjd:
return res - mjdoffset
else:
return res
def delta_AT(jdutc,usett=False):
"""
Computes the difference between International Atomic Time (TAI) and
UTC, known as delta(AT).
Note that this is not valid before UTC (Jan 1,1960) beganand it is not
correct for future dates, as leap seconds are not predictable. Hence,
warnings are issued if before UTC or >5 years from the date of the
algorithm.
Implementation adapted from the matching `SOFA <http://www.iausofa.org/>`_
algorithm (dat.c).
:param utc:
UTC time as a Julian Date (use :func:`calendar_to_jd` for calendar form
inputs.)
:type utc: float
:param usett:
If True, the return value will be the difference between UTC and
Terrestrial Time (TT) instead of TAI (TT - TAI = 32.184 s).
:type usett: bool
:returns: TAI - UTC in seconds as a float (or TT - UTC if `usett` is True)
"""
from warnings import warn
dt = jd_to_calendar(jdutc)
#get data from arrays defined below
drift = __dat_drift
cyear,cmonth,cdelat = __dat_changes
if dt.year > __dat_valid_year+5:
warn('delta(AT) requested for more than 5 years after current leap seconds (%i)'%dt.year)
m = 12*dt.year + dt.month
i = np.sum(__dat_m<m)-1
if i < 0:
warn('delta(AT) requested before 1960 (%i)'%dt.year)
i = 0
delat = cdelat[i]
#if pre leap seconds, account for drift
if i < drift.shape[0]:
fd = dt.hour/24+dt.minute/24/60+dt.second/24/3.6e3+dt.microsecond/24/3.6e9 #fraction of day
delat += (jdutc - mjdoffset + fd - drift[i,0]) * drift[i,1]
if usett:
return delat - 32.184
else:
return delat
#fixed arrays/values for delta_AT:
__dat_valid_year = 2009
#Reference dates (MJD) and drift rates (s/day), pre leap seconds
__dat_drift = np.array([
[ 37300.0, 0.0012960 ],
[ 37300.0, 0.0012960 ],
[ 37300.0, 0.0012960 ],
[ 37665.0, 0.0011232 ],
[ 37665.0, 0.0011232 ],
[ 38761.0, 0.0012960 ],
[ 38761.0, 0.0012960 ],
[ 38761.0, 0.0012960 ],
[ 38761.0, 0.0012960 ],
[ 38761.0, 0.0012960 ],
[ 38761.0, 0.0012960 ],
[ 38761.0, 0.0012960 ],
[ 39126.0, 0.0025920 ],
[ 39126.0, 0.0025920 ]
])
#year,month,delat
__dat_changes = np.array([
[ 1960, 1, 1.4178180 ],
[ 1961, 1, 1.4228180 ],
[ 1961, 8, 1.3728180 ],
[ 1962, 1, 1.8458580 ],
[ 1963, 11, 1.9458580 ],
[ 1964, 1, 3.2401300 ],
[ 1964, 4, 3.3401300 ],
[ 1964, 9, 3.4401300 ],
[ 1965, 1, 3.5401300 ],
[ 1965, 3, 3.6401300 ],
[ 1965, 7, 3.7401300 ],
[ 1965, 9, 3.8401300 ],
[ 1966, 1, 4.3131700 ],
[ 1968, 2, 4.2131700 ],
[ 1972, 1, 10.0 ],
[ 1972, 7, 11.0 ],
[ 1973, 1, 12.0 ],
[ 1974, 1, 13.0 ],
[ 1975, 1, 14.0 ],
[ 1976, 1, 15.0 ],
[ 1977, 1, 16.0 ],
[ 1978, 1, 17.0 ],
[ 1979, 1, 18.0 ],
[ 1980, 1, 19.0 ],
[ 1981, 7, 20.0 ],
[ 1982, 7, 21.0 ],
[ 1983, 7, 22.0 ],
[ 1985, 7, 23.0 ],
[ 1988, 1, 24.0 ],
[ 1990, 1, 25.0 ],
[ 1991, 1, 26.0 ],
[ 1992, 7, 27.0 ],
[ 1993, 7, 28.0 ],
[ 1994, 7, 29.0 ],
[ 1996, 1, 30.0 ],
[ 1997, 7, 31.0 ],
[ 1999, 1, 32.0 ],
[ 2006, 1, 33.0 ],
[ 2009, 1, 34.0 ]
]).T
__dat_m = 12*__dat_changes[0] + __dat_changes[1]
#<-------------------Site and Observing/Instrumentation-related---------------->
class Site(object):
"""
This class represents a location on Earth from which skies are observable.
lat/long are coords.AngularCoordinate objects, altitude in meters.
`latitude` here is the geographic/geodetic latitude.
"""
# tznames = {'EST':-5,'CST':-6,'MST':-7,'PST':-8,
# 'EDT':-4,'CDT':-5,'MDT':-6,'PDT':-7}
def __init__(self,lat,long,alt=0,tz=None,name=None):
"""
generate a site by specifying latitude and longitude (as
coords.AngularCoordinate objects or initializers for one), optionally
providing altitude (in meters), time zone (either as a timezone name
provided by the system or as an offset from UTC), and/or a site name.
"""
self.latitude = lat
self.latitude.range = (-90,90)
self.longitude = long
self.longitude.range = (-180,180)
self.altitude = alt
if tz is None:
self.tz = self._tzFromLong(self._long)
elif isinstance(tz,basestring) and tzmod is not None:
self.tz = tzmod.gettz(tz)
if self.tz is None:
raise ValueError('unrecognized time zone string '+tz)
else:
self.tz = tzoffset(str(tz),int(tz*60*60))
if name is None:
name = 'Default Site'
self.name = name
self._currjd = None
@staticmethod
def _tzFromLong(long):
offset = int(np.round(long.degrees/15))
return tzoffset(str(offset),offset*60*60)
def _getLatitude(self):
return self._lat
def _setLatitude(self,val):
from .coords import AngularCoordinate
from operator import isSequenceType
if isinstance(val,AngularCoordinate):
self._lat = val
elif isSequenceType(val) and not isinstance(val,basestring):
self._lat = AngularCoordinate(*val)
else:
self._lat = AngularCoordinate(val)
latitude = property(_getLatitude,_setLatitude,doc='Geographic/Geodetic Latitude of the site as an :class:`AngularCoordinate` object')
def _getGeocentriclat(self):
from .coords import geographic_to_geocentric_latitude
return geographic_to_geocentric_latitude(self._lat)
def _setGeocentriclat(self,val):
from .coords import geocentric_to_geographic_latitude
self._lat = geocentric_to_geographic_latitude(val)
geocentriclat = property(_getGeocentriclat,_setGeocentriclat,doc=None)
def _getLongitude(self):
return self._long
def _setLongitude(self,val):
from .coords import AngularCoordinate
from operator import isSequenceType
if isinstance(val,AngularCoordinate):
self._long = val
elif isSequenceType(val) and not isinstance(val,basestring):
self._long = AngularCoordinate(*val)
else:
self._long = AngularCoordinate(val)
longitude = property(_getLongitude,_setLongitude,doc='Longitude of the site as an :class:`AngularCoordinate` object')
def _getAltitude(self):
return self._alt
def _setAltitude(self,val):
if val is None:
self._alt = None
else:
self._alt = float(val)
altitude = property(_getAltitude,_setAltitude,doc='Altitude of the site in meters')
def _getCurrentobsjd(self):
if self._currjd is None:
from datetime import datetime
return calendar_to_jd(datetime.utcnow(),tz=None)
else:
return self._currjd
def _setCurrentobsjd(self,val):
if val is None:
self._currjd = None
else:
if np.isscalar(val):
self._currjd = val
else:
self._currjd = calendar_to_jd(val)
currentobsjd = property(_getCurrentobsjd,_setCurrentobsjd,doc="""
Date and time to use for computing time-dependent values. If set to None,
the jd at the instant of calling will be used. It can also be set as
datetime objects or (yr,mon,day,hr,min,sec) tuples.
""")
def localSiderialTime(self,*args,**kwargs):
"""
Compute the local siderial time given an input civil time. The various
input forms are used to determine the interpretation of the civil time:
* localSiderialTime()
current local siderial time for this Site or uses the value of the
:attr:`currentobsjd` property.
* localSiderialTime(JD)
input argument is julian date UT1
* localSdierialTime(:class:`datetime.date`)
compute the local siderial time for midnight on the given date
* localSiderialTime(:class:`datetime.datetime`)
the datetime object specifies the local time. If it has tzinfo, the
object's time zone will be used, otherwise the :class:`Site's<Site>`
* localSiderialTime(time,year,month,day)
input arguments determine local time - time is in hours
* localSiderialTime(year,month,day,hr,min,sec)
local time - hours and minutes will be interpreted as integers
*keywords*
* `apparent`
if True (default) the returned time will be local apparent sidereal
time (i.e. nutation terms included), otherwise it will be local mean
sidereal time
* `returntype`
a string that determines the form of the returned LST as described
below
returns the local siderial time in a format that depends on the
`returntype` keyword. It can be:
* None/'hours' (default)
LST in decimal hours
* 'string'
LST as a hh:mm:ss.s
* 'datetime'
a :class:`datetime.time` object
"""
#guts of calculation adapted from xidl
import datetime
from .coords import greenwich_sidereal_time
rettype = kwargs.pop('returntype',None)
apparent = kwargs.pop('apparent',True)
if len(kwargs)>0:
raise TypeError('got unexpected argument '+kwargs.keys()[0])
if len(args)==0:
jd = self.currentobsjd
elif len(args)==1:
if hasattr(args[0],'year'):
if hasattr(args[0],'hour'):
if args[0].tzinfo is None:
dtobj = datetime.datetime(args[0].year,args[0].month,
args[0].day,args[0].hour,args[0].minute,
args[0].second,args[0].microsecond,self.tz)
else:
dtobj = args[0]
else: #only date provided
dtobj = datetime.datetime(args[0].year,args[0].month,
args[0].day,tzinfo=self.tz)
jd = calendar_to_jd(dtobj,tz=None)
else:
jd = args[0]
elif len(args) == 4:
time,year,month,day = args
hr = int(np.floor(time))
min = int(np.floor(60*(time - hr)))
sec = int(np.floor(60*(60*(time-hr) - min)))
msec = int(np.floor(1e6*(60*(60*(time-hr) - min) - sec)))
jd = calendar_to_jd(datetime.datetime(year,month,day,hr,min,sec,msec,self.tz),tz=None)
elif len(args) == 6:
year,month,day,hr,min,sec = args
msec = int(1e6*(sec - np.floor(sec)))
sec = int(np.floor(sec))
jd = calendar_to_jd(datetime.datetime(year,month,day,hr,min,sec,msec,self.tz),tz=None)
else:
raise TypeError('invalid number of input arguments')
lst = (greenwich_sidereal_time(jd,apparent) + self._long.d/15)%24.0
# #from idl astro ct2lst.pro
# jd2000 = 2451545.0
# t0 = jd - jd2000
# t = t0//36525 #TODO:check if true-div
# #Compute GMST in seconds. constants from Meeus 1ed, pg 84
# c1,c2,c3,c4 = 280.46061837,360.98564736629,0.000387933,38710000.0
# theta = c1 + (c2 * t0) + t**2*(c3 - t/ c4 )
# #TODO: Add in mean->apparent corrections
# #Compute LST in hours.
# lst = np.array((theta + self._long.d)/15.0) % 24.0
if lst.shape == tuple():
lst = lst.ravel()[0]
if rettype is None or rettype == 'hours':
return lst
elif rettype == 'string':
hr = int(lst)
min = 60*(lst - hr)
sec = 60*(min - int(min))
min = int(min)
return '%02i:%02i:%f'%(hr,min,sec)
elif rettype == 'datetime':
hr = int(lst)
min = 60*(lst - hr)
sec = 60*(min - int(min))
min = int(min)
msec = int(1e6*(sec-int(sec)))
sec = int(sec)
return datetime.time(hr,min,sec,msec)
else:
raise ValueError('invalid returntype argument')
def localTime(self,lsts,date=None,apparent=True,returntype=None,utc=False):
"""
Computes the local civil time given a particular local siderial time.
`lsts` are the input local times, and may be either a scalar or array,
and must be in decimal hours. Althernatively, it can be a
:class:`datetime.datetime` object, in which case the date will be
inferred from this object and the `date` argument will be ignored.
`date` should be a :class:`datetime.date` object or a (year,month,day)
tuple. If None, the current date will be assumed as inferred from
:attr:`Site.currentobsjd`
if `lsts` is a :class:`datetime.datetime` object, the object will be
interpreted as the local siderial time with the corresponding date (any
timezone info will be ignored), and the `date` argument will be ignored.
if `apparent` is True, the inputs are assumed to be in local apparent
siderial time (i.e. nutation terms included), otherwise local mean
siderial time.
returns the local time in a format that depends on the `returntype`
keyword. It can be:
* None/'hours' (default)
local time in decimal hours
* 'string'
local time as a hh:mm:ss.s
* 'datetime'
a :class:`datetime.time` object with the appropriate tzinfo
If `utc` is True, the time will be converted to UTC before being
returned.
"""
import datetime
from operator import isSequenceType
if isinstance(lsts,datetime.datetime):
utcoffset = lsts.replace(tzinfo=self.tz).utcoffset()
date = lsts.date()
lsts = datetime.time()
lsts = lsts.hour+lsts.minute/60+(lsts.second+lsts.microsecond*1e6)/3600
else:
jds,dt = self._processDate(date)
utcoffset = dt.replace(tzinfo=self.tz).utcoffset()
if isSequenceType(dt):
raise ValueError('must provide only one date for localTime')
date = dt.date()
lsts = np.array(lsts,copy=False)
scalarout = False
if lsts.shape == tuple():
scalarout = True
lsts = lsts.ravel()
lst0 = self.localSiderialTime(date)
lthrs = (lsts - lst0)%24
#NB floor rounds towards -ve infinity. This is undesirable because:
#Sometimes current lst - lst0 < 0 as the LST has looped since daybreak.
#So floor will round a negative fraction to a whole day offset.
dayoffs = [ int((lst - lst0) / 24.0) for lst in lsts ]
lthrs /= 1.0027378507871321 #correct for siderial day != civil day
if utc:
lthrs = (lthrs - utcoffset.days*24 - utcoffset.seconds/3600)%24
if returntype is None or returntype == 'hours':
res = lthrs
elif returntype == 'string':
res = []
for lthr in lthrs:
hr = int(lthr)
min = 60*(lthr - hr)
sec = 60*(min - int(min))
min = int(min)
res.append('%02i:%02i:%f'%(hr,min,sec))
elif returntype == 'datetime':
res = []
for lthr,dayoff in zip(lthrs,dayoffs):
hr = int(lthr)
min = 60*(lthr - hr)
sec = 60*(min - int(min))
min = int(min)
msec = int(1e6*(sec-int(sec)))