-
Notifications
You must be signed in to change notification settings - Fork 3
/
copilot.py
executable file
·2074 lines (1756 loc) · 69.2 KB
/
copilot.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
#! /usr/bin/env python3.6
'''
This script is meant to be run during DECaLS/MzLS observing. It waits
for new images to appear, measures their sky brightness, seeing, and
transparency, and makes plots of the conditions.
'''
from __future__ import print_function
try:
from collections import OrderedDict
except:
print('Failed to import OrderedDict. You are probably using python 2.6. Please re-run with python2.7')
sys.exit(-1)
import sys
import os
import re
import time
import json
import datetime
import numpy as np
import fitsio
import ephem
from astrometry.util.starutil_numpy import hmsstring2ra, dmsstring2dec, mjdtodate, datetomjd
from measure_raw import measure_raw, get_default_extension, camera_name
from obsbot import (exposure_factor, get_tile_from_name, NewFileWatcher,
mjdnow, datenow)
from tractor.sfd import SFDMap
def initialize_django():
import obsdb
from camera import database_filename
obsdb.django_setup(database_filename=database_filename)
def db_to_fits(mm):
'''Converts the obsdb database entries
(obsdb/{mosaic3,decam}.sqlite3) into FITS format.'''
from astrometry.util.fits import fits_table
T = fits_table()
for field in ['filename', 'extension', 'expnum', 'exptime', 'mjd_obs',
'airmass', 'racenter', 'deccenter', 'rabore', 'decbore',
'band', 'ebv', 'zeropoint', 'transparency', 'seeing',
'sky', 'expfactor', 'camera', 'dx', 'dy', 'nmatched',
'md5sum', 'bad_pixcnt', 'readtime',
'obstype',
'object', 'tileid', 'passnumber', 'tileebv',
'affine_x0', 'affine_y0',
'affine_dx', 'affine_dxx', 'affine_dxy',
'affine_dy', 'affine_dyx', 'affine_dyy',]:
g = getattr(mm[0], field)
if str(g) == g:
T.set(field, np.array([str(getattr(m, field)) for m in mm]))
else:
T.set(field, np.array([getattr(m, field) for m in mm]))
return T
def filter_plot_color(filt, default='0.5'):
# Returns a matplotlib color for plotting the given filter name.
ccmap = dict(g='g',
r='r',
z='m',
zd='m',
# https://academo.org/demos/wavelength-to-colour-relationship/
N419=(109/255, 0., 251/255),
N501=(0., 1., 135/255),
N540=(129/255, 1., 0.),
N673='r',
N708=(241/255,0.,0.),
M411=(124/255,0,222/255),
M464=(0, 142/255, 255/255),
)
return ccmap.get(filt, default)
def recent_gr_seeing(recent=30., exps=None):
'''
Computes estimates of seeing in g and r bands based on recent measurements.
*recent*: how far back from now to look, in minutes
Returns:
None if no recent exposures are found.
(gsee, rsee, G, R) -- seeing estimates for g,r bands; exposures used for g,r estimates. These may include exposures from the other band!
'''
if exps is None:
exps = get_recent_exposures(recent, bands='gr')
if exps is None:
return None
r_exps = exps[np.flatnonzero(exps.band == 'r')]
g_exps = exps[np.flatnonzero(exps.band == 'g')]
r_avg = g_avg = None
if len(r_exps) >= 5:
r_avg = np.median(r_exps.seeing)
if len(g_exps) >= 5:
g_avg = np.median(g_exps.seeing)
if r_avg is not None and g_avg is not None:
see_ratio = r_avg / g_avg
print('Computed recent r/g seeing ratio', see_ratio)
else:
see_ratio = 1.0
recent_see = exps.seeing[-5:]
recent_bands = exps.band [-5:]
G = exps[-5:]
g_see = recent_see.copy()
g_see[recent_bands == 'r'] /= see_ratio
g = np.median(g_see)
if g_avg is not None:
# g = max(g, g_avg)
if g_avg > g:
g = g_avg
G = g_exps
R = exps[-5:]
r_see = recent_see.copy()
r_see[recent_bands == 'g'] *= see_ratio
r = np.median(r_see)
if r_avg is not None:
if r_avg > r:
r = r_avg
R = r_exps
return g,r,G,R
def recent_gr_sky_color(recent=30., pairs=5.):
'''
Estimates g-r sky color based on recent measurements.
*recent*: how far back from now to look, in minutes
*pairs*: compare pairs of g,r exposures within this many minutes of each other.
'''
exps = get_recent_exposures(recent, bands='gr')
if exps is None:
return None,0,0,0
gexps = exps[np.flatnonzero(exps.band == 'g')]
rexps = exps[np.flatnonzero(exps.band == 'r')]
print(len(gexps), 'g-band exposures')
print(len(rexps), 'r-band exposures')
# Find pairs of g,r exposures within 5 minutes of each other?
# Or just difference in medians?
diffs = []
for gexp in gexps:
I = np.flatnonzero(np.abs(gexp.mjd_obs - rexps.mjd_obs) < pairs/(60*24))
#print('g', gexp.expnum, 'has', len(I), 'r-band exposures w/in',
# pairs, 'minutes')
if len(I):
diffs.append(gexp.sky - rexps.sky[I])
if len(diffs) == 0:
return (None, 0, len(gexps), len(rexps))
diffs = np.hstack(diffs)
#print('All differences:', diffs)
diff = np.median(diffs)
#print('Median g-r diff:', diff)
return (diff, len(diffs), len(gexps), len(rexps))
def get_recent_ccds(recent, bands=None):
import obsdb
ccds = obsdb.MeasuredCCD.objects.filter(
mjd_obs__gte=mjdnow() - recent/(60*24))
if bands is not None:
ccds = ccds.filter(band__in=[b for b in bands])
print('Found', len(ccds), 'exposures in copilot db, within', recent,
'minutes', ('' if bands is None else ('bands ' + str(bands))))
if len(ccds) == 0:
return None
ccds = db_to_fits(ccds)
return ccds
def get_recent_exposures(recent, bands=None):
ccds = get_recent_ccds(recent, bands=bands)
if ccds is None:
return None
# Find unique exposure numbers
expnums,I = np.unique(ccds.expnum, return_index=True)
print(len(expnums), 'unique expnums')
# Copy the CCD measurements into the exposure measurements
exps = ccds[I]
# drop columns??
# exps.delete_column('extension')
# Average some measurements based on all extensions per exposure
for i,expnum in enumerate(expnums):
I = np.flatnonzero(ccds.expnum == expnum)
exps.sky[i] = np.mean(ccds.sky[I])
exps.seeing[i] = np.mean(ccds.seeing[I])
# Sort by date
exps.cut(np.argsort(exps.mjd_obs))
return exps
class Duck(object):
pass
def get_twilight(obs, date):
'''
*obs*: an ephem.Observer object
*date*: an ephem.Date object (in UTC)
Returns an object with attributes:
* sunset
* "eve10": -10 degree evening
* "eve12": -12 degree evening
* "eve18": -18 degree evening
* "morn18": -18 degree morning
* "morn12": -12 degree morning
* "morn10": -10 degree morning
* sunrise
'''
t = Duck()
saved_vals = (obs.date, obs.horizon)
obs.date = date
sun = ephem.Sun()
t.sunset = obs.previous_setting(sun)
obs.date = t.sunset
t.sunrise = obs.next_rising(sun)
obs.date = t.sunset
obs.horizon = -ephem.degrees('18:00:00.0')
t.eve18 = obs.next_setting(sun)
t.morn18 = obs.next_rising(sun)
obs.horizon = -ephem.degrees('15:00:00.0')
t.eve15 = obs.next_setting(sun)
t.morn15 = obs.next_rising(sun)
obs.horizon = -ephem.degrees('12:00:00.0')
t.eve12 = obs.next_setting(sun)
t.morn12 = obs.next_rising(sun)
obs.horizon = -ephem.degrees('10:00:00.0')
t.eve10 = obs.next_setting(sun)
t.morn10 = obs.next_rising(sun)
obs.date, obs.horizon = saved_vals
return t
def average_by_mjd(Tb):
mjds,I = np.unique(Tb.mjd_obs, return_index=True)
if len(mjds) == len(Tb):
return Tb,None
Tavg = Tb[I]
Iindiv = []
for i,mjd in enumerate(Tavg.mjd_obs):
II = np.flatnonzero(Tb.mjd_obs == mjd)
if len(II) > 1:
Iindiv.extend(II)
Tavg.seeing[i] = np.mean(Tb.seeing[II])
Tavg.sky[i] = np.mean(Tb.sky[II])
Iindiv = np.array(Iindiv)
return Tavg,Tb[Iindiv]
def plot_measurements(mm, plotfn, nom, mjds=[], mjdrange=None, allobs=None,
markmjds=[], show_plot=True, nightly=False,
label_nmatched=True, max_seeing=2.5, target_exptime=True,
nominal_sky=False):
'''
Plots our measurements of the conditions, as in the recent.png and
night.png plots.
'''
import pylab as plt
from astrometry.util.fits import merge_tables
T = db_to_fits(mm)
print('plot_measurements, nightly', nightly, 'target_exptime', target_exptime)
print(len(T), 'exposures')
# Replace filter "zd" -> "z", "rd" -> "r".
T.band = np.array([dict(zd='z', rd='r').get(b, b) for b in T.band])
T.mjd_end = T.mjd_obs + T.exptime / 86400.
T.isobject = np.logical_or(T.obstype == 'object', T.obstype == 'science')
Tnonobject = T[np.logical_not(T.isobject)]
print(len(Tnonobject), 'exposures are not OBJECTs')
print('Obs types:', np.unique(T.obstype))
T = T[T.isobject]
print(len(T), 'OBJECT exposures')
if len(T) == 0:
return None
bands = np.unique(T.band)
print('Unique bands:', bands)
TT = []
for band in bands:
TT.append(T[T.band == band])
print('Band', band, ':', len(TT[-1]), 'images')
plt.clf()
plt.subplots_adjust(hspace=0.1, top=0.98, right=0.95, left=0.1,
bottom=0.07)
def limitstyle(band):
return dict(mec='k', mfc='none', ms=7, mew=1)
# Check for bad things that can happen
bads = []
# bad_pixcnt
I = np.flatnonzero(T.bad_pixcnt)
print(len(I), 'images have bad_pixcnt')
for i in I:
bads.append((i, 'pixcnt'))
# low nmatched
if label_nmatched:
I = np.flatnonzero((T.nmatched >= 0) * (T.nmatched < 10))
print(len(I), 'images have bad nmatched')
for i in I:
print('Exposure', T.expnum[i], ': nmatched', T.nmatched[i])
bads.append((i, 'nmatched'))
if allobs is not None:
# Duplicate md5sum
for i in range(len(T)):
if T.md5sum[i] == '':
continue
a = allobs.filter(md5sum=T.md5sum[i]).exclude(
filename=T.filename[i], extension=T.extension[i])
if a.count():
# Only report this one as bad if one of the repeats was earlier
for ai in a:
if ai.mjd_obs < T.mjd_obs[i]:
bads.append((i, 'md5sum'))
break
# Group together bad things for the same image.
bd = {}
for i,reason in bads:
if i in bd:
bd[i] = bd[i] + ', ' + reason
else:
bd[i] = reason
bads = bd.items()
ilatest = np.argmax(T.mjd_obs)
latest = T[ilatest]
bbox = dict(facecolor='white', alpha=0.8, edgecolor='none')
SP = 5
# which ones will we use to set the scale?
I = np.flatnonzero((T.seeing > 0) * (T.exptime > 30))
if len(I):
mn,mx = T.seeing[I].min(), T.seeing[I].max()
else:
mn,mx = 0.7, 2.5
mx = min(mx, max_seeing)
yl,yh = mn - 0.15*(mx-mn), mx + 0.05*(mx-mn)
#print('mn,mx', mn,mx, 'yl,yh', yl,yh)
## Seeing
plt.subplot(SP,1,1)
for band,Tb in zip(bands, TT):
# print('Band', band, 'with', len(Tb), 'images. Seeing:', Tb.seeing, 'exptime', Tb.exptime)
# print('Expnum', Tb.expnum)
I = np.flatnonzero((Tb.seeing > 0) * (Tb.exptime > 30))
if len(I):
Tavg,Tind = average_by_mjd(Tb[I])
if Tind is not None:
plt.plot(Tind.mjd_obs, Tind.seeing, 'o',
mec='k', mfc='none', alpha=0.5)
plt.plot(Tavg.mjd_obs, Tavg.seeing, 'o',
color=filter_plot_color(band), mec='k')
I = np.flatnonzero(Tb.seeing > mx)
if len(I):
plt.plot(Tb.mjd_obs[I], [mx]*len(I), '^', **limitstyle(band))
plt.axhline(2.0, color='k', alpha=0.5)
plt.axhline(1.3, color='k', alpha=0.5)
plt.axhline(1.2, color='k', alpha=0.1)
plt.axhline(1.0, color='k', alpha=0.1)
plt.axhline(0.8, color='k', alpha=0.1)
if nightly:
I = np.flatnonzero(T.seeing > 0)
if len(I):
plt.text(latest.mjd_obs, yl+0.03*(yh-yl),
'Median: %.2f' % np.median(T.seeing[I]), ha='right', bbox=bbox)
else:
plt.text(latest.mjd_obs, yl+0.03*(yh-yl),
'%.2f' % latest.seeing, ha='center', bbox=bbox)
y = yl + 0.01*(yh-yl)
plt.plot(np.vstack((T.mjd_obs, T.mjd_end)),
np.vstack((y, y)), '-', lw=3, alpha=0.5,
color=filter_plot_color(band),
solid_joinstyle='bevel')
plt.ylim(yl,yh)
plt.ylabel('Seeing (arcsec)')
ax = plt.axis()
for i,reason in bads:
plt.axvline(T.mjd_obs[i], color='r', lw=3, alpha=0.3)
plt.text(T.mjd_obs[i], ax[3], reason,
rotation=90, va='top')
plt.axis(ax)
## Sky background
plt.subplot(SP,1,2)
T.dsky = np.zeros(len(T), np.float32)
minsky = -0.15
nomskies = []
medskies = []
keepbands = []
keepTT = []
for band,Tb in zip(bands, TT):
if nominal_sky:
try:
sky0 = nom.sky(band)
except KeyError:
# unknown filter
print('Unknown filter for sky:', band)
continue
else:
sky0 = 0.
T.dsky[T.band == band] = Tb.sky - sky0
keepbands.append(band)
keepTT.append(Tb)
TT = keepTT
bands = keepbands
# set the range based on:
# -- do we need to add a "darker than 15-deg twi" cut?
I = np.flatnonzero((T.seeing > 0) * (T.exptime > 30))
if len(I):
mn,mx = T.dsky[I].min(), T.dsky[I].max()
else:
mn,mx = -2, 1
mn = max(mn, -2.0)
yl,yh = mn - 0.15*(mx-mn), mx + 0.05*(mx-mn)
for band,Tb in zip(bands, TT):
if nominal_sky:
sky0 = nom.sky(band)
else:
sky0 = 0.
I = np.flatnonzero(Tb.sky > 0)
if len(I):
Tavg,Tind = average_by_mjd(Tb[I])
if Tind is not None:
plt.plot(Tind.mjd_obs, Tind.sky - sky0, 'o',
mec='k', mfc='none', alpha=0.5)
plt.plot(Tavg.mjd_obs, Tavg.sky - sky0, 'o',
color=filter_plot_color(band), mec='k',
label=band)
minsky = min(minsky, min(Tb.sky[I] - sky0))
nomskies.append((band, sky0))
medskies.append((band, np.median(Tb.sky[I])))
I = np.flatnonzero((Tb.sky - sky0) > mx)
if len(I):
plt.plot(Tb.mjd_obs[I], [mx]*len(I), '^', **limitstyle(band))
I = np.flatnonzero((Tb.sky - sky0) < mn)
if len(I):
plt.plot(Tb.mjd_obs[I], [mn]*len(I), '^', **limitstyle(band))
txt = ', '.join(['%s=%.2f' % (band,sky0) for band,sky0 in nomskies])
xl,xh = plt.xlim()
plt.text((xl+xh)/2., min(0., (yl + 0.95*(yh-yl))), txt,
va='bottom', bbox=bbox)
plt.axhline(0, color='k', alpha=0.5)
if nightly:
txt = 'Median: ' + ', '.join(['%s=%.2f' % (band,sky)
for band,sky in medskies])
plt.text(latest.mjd_obs, 0, txt, ha='right', va='top', bbox=bbox)
else:
latest = T[ilatest]
plt.text(latest.mjd_obs, latest.dsky - 0.05*(yh-yl),
'%.2f' % latest.sky, ha='center', va='top',
bbox=bbox)
# Plot strings of pass 1,2,3
I = np.argsort(T.mjd_obs)
TJ = T[I]
TJ.cut(TJ.passnumber > 0)
i = 0
while i < len(TJ):
t = TJ[i]
p0 = t.passnumber
j = i
while j < len(TJ) and TJ.passnumber[j] == p0:
j += 1
# print('Exposures from [%i,%i) have pass %i' % (i, j, p0))
tend = TJ[j-1]
y = yl + 0.1 * (yh-yl)
if j > i+1:
plt.plot([t.mjd_obs, tend.mjd_obs], [y, y], 'b-', lw=2, alpha=0.5)
# add error bar caps on the endpoints
for mjd in [t.mjd_obs, tend.mjd_obs]:
plt.plot([mjd, mjd], [y - 0.03*(yh-yl), y + 0.03*(yh-yl)],
'b-', lw=2, alpha=0.5)
plt.text((t.mjd_obs + tend.mjd_obs)/2., y, '%i' % p0,
ha='center', va='top')
i = j
plt.axhline(-0.25, color='k', alpha=0.25)
plt.ylim(yl,yh)
if nominal_sky:
plt.ylabel('Sky - nominal (mag)')
else:
plt.ylabel('Sky (mag/sq.arcsec)')
plt.legend()
## Transparency
plt.subplot(SP,1,3)
mx = 1.2
mn = 0.3
for band,Tb in zip(bands, TT):
I = np.flatnonzero(Tb.transparency > 0)
if len(I):
print('Transparency:', Tb.transparency[I])
print('Zeropoint:', Tb.zeropoint[I])
Tavg,Tind = average_by_mjd(Tb[I])
if Tind is not None:
plt.plot(Tind.mjd_obs, Tind.transparency, 'o',
mec='k', mfc='none', alpha=0.5)
plt.plot(Tavg.mjd_obs, Tavg.transparency, 'o',
color=filter_plot_color(band), mec='k')
I = np.flatnonzero(Tb.transparency > mx)
if len(I):
plt.plot(Tb.mjd_obs[I], [mx]*len(I), '^', **limitstyle(band))
I = np.flatnonzero((Tb.transparency < mn) * (Tb.transparency > 0))
if len(I):
plt.plot(Tb.mjd_obs[I], [mn]*len(I), 'v', **limitstyle(band))
plt.axhline(1.0, color='k', alpha=0.5)
plt.axhline(0.9, color='k', ls='-', alpha=0.25)
plt.ylabel('Transparency')
yl,yh = plt.ylim()
plt.axhline(0.7, color='k', ls='-', alpha=0.25)
yl,yh = min(0.89, min(mn, yl)), min(mx, max(yh, 1.01))
if nightly:
I = np.flatnonzero(T.transparency > 0)
if len(I):
plt.text(latest.mjd_obs, yl+0.03*(yh-yl),
'Median: %.2f' % np.median(T.transparency[I]),
ha='right', bbox=bbox)
else:
plt.text(latest.mjd_obs, yl+0.03*(yh-yl),
'%.2f' % latest.transparency, ha='center', bbox=bbox)
plt.ylim(yl, yh)
## Exposure time plot
plt.subplot(SP,1,4)
for band,Tb in zip(bands, TT):
fid = nom.fiducial_exptime(band)
if fid is None:
# Band not 'g','r', or 'z'
print('Unknown band', band)
continue
basetime = fid.exptime
lo,hi = fid.exptime_min, fid.exptime_max
# Exposure time we should have taken
exptime = basetime * Tb.expfactor
print('Exposure time we should have taken:', exptime, '= base time', basetime,
'x exposure factor', Tb.expfactor)
clipped = np.clip(exptime, lo, hi)
if band == 'z':
t_sat = nom.saturation_time(band, Tb.sky)
bad = (Tb.sky == 0)
clipped = np.minimum(clipped, t_sat + bad*1000000)
Tb.clipped_exptime = clipped
#Tb.depth_factor = Tb.exptime / clipped
Tb.depth_factor = Tb.exptime / exptime
if target_exptime:
I = np.flatnonzero((exptime < clipped) * (exptime > 0))
if len(I):
plt.plot(Tb.mjd_obs[I], exptime[I], '^', **limitstyle(band))
plt.plot(Tb.mjd_obs, clipped, 'o', mec='k', mfc='none', ms=9)
# Actual exposure times taken, marked with filled colored circles.
#I = np.flatnonzero(Tb.exptime > 30)
I = np.flatnonzero(Tb.exptime > 0)
if len(I):
plt.plot(Tb.mjd_obs[I], Tb.exptime[I], 'o', mec='k',
color=filter_plot_color(band))
yl,yh = plt.ylim()
for band,Tb in zip(bands, TT):
fid = nom.fiducial_exptime(band)
if fid is None:
continue
basetime = fid.exptime
lo,hi = fid.exptime_min, fid.exptime_max
dt = dict(g=-0.5,r=+0.5).get(band, 0.)
if target_exptime:
exptime = basetime * Tb.expfactor
clipped = np.clip(exptime, lo, hi)
I = np.flatnonzero(exptime > clipped)
if len(I):
plt.plot(Tb.mjd_obs[I], exptime[I], 'v', **limitstyle(band))
if False:
I = np.flatnonzero(exptime > mx)
if len(I):
plt.plot(Tb.mjd_obs[I], [mx]*len(I), '^', **limitstyle(band))
if target_exptime:
plt.axhline(basetime+dt, color=filter_plot_color(band), alpha=0.2)
plt.axhline(lo+dt, color=filter_plot_color(band), ls='--', alpha=0.5)
plt.axhline(hi+dt, color=filter_plot_color(band), ls='--', alpha=0.5)
if band == 'z':
I = np.flatnonzero(Tb.sky > 0)
if len(I):
plt.plot(Tb.mjd_obs[I], t_sat[I], color=filter_plot_color(band),
ls='-', alpha=0.5)
if (not nightly) and target_exptime:
I = np.flatnonzero(Tb.exptime > 0)
if len(I):
for i in I:
plt.text(Tb.mjd_obs[i], Tb.exptime[i] + 0.04*(yh-yl),
'%.2f' % (Tb.depth_factor[i]),
rotation=90, ha='center', va='bottom')
yh = max(yh, max(Tb.exptime[I] + 0.3*(yh-yl)))
if not nightly:
plt.text(latest.mjd_obs, yl+0.03*(yh-yl),
'%i s' % int(latest.exptime), ha='center', bbox=bbox)
plt.ylim(yl,yh)
plt.ylabel('Exposure time (s)')
plt.subplot(SP,1,5)
I = np.argsort(T.mjd_obs)
Tx = T[I]
CDs = dict([(ext, nom.cdmatrix(ext)) for ext in np.unique(Tx.extension)])
CD = np.array([CDs[ext] for ext in Tx.extension])
dra = (CD[:,0] * Tx.dx + CD[:,1] * Tx.dy) * 3600.
ddec = (CD[:,2] * Tx.dx + CD[:,3] * Tx.dy) * 3600.
mx = np.percentile(np.abs(np.append(dra, ddec)), 95)
# make the range at least +- 10 arcsec.
mx = max(mx, 10)
mx *= 1.2
yl,yh = -mx,mx
refdra,refddec = None,None
#print('Camera', Tx.camera[0])
if Tx.camera[0].strip() == 'mosaic3':
# Convert into offsets that match Mosstat ie, offsets in im16,
# plus magical offset of mosstat-copilot on im16.
if not np.all(Tx.affine_x0 == 0):
from camera_mosaic import dradec_to_ref_chip
refdra,refddec = dradec_to_ref_chip(Tx)
if refdra is not None:
# imX plotted lightly
plt.plot(Tx.mjd_obs, dra, 'bo', alpha=0.2)
plt.plot(Tx.mjd_obs, ddec, 'go', alpha=0.2)
plt.plot(Tx.mjd_obs, dra, 'b-', alpha=0.1)
plt.plot(Tx.mjd_obs, ddec, 'g-', alpha=0.1)
# Predicted im16 plotted heavy
I = np.flatnonzero(Tx.affine_x0)
plt.plot(Tx.mjd_obs[I], refdra[I], 'bo')
plt.plot(Tx.mjd_obs[I], refddec[I], 'go')
pr = plt.plot(Tx.mjd_obs[I], refdra[I], 'b-', alpha=0.5)
pd = plt.plot(Tx.mjd_obs[I], refddec[I], 'g-', alpha=0.5)
if not nightly:
mjd = Tx.mjd_obs[I[-1]]
r,d = refdra[I[-1]], refddec[I[-1]]
plt.text(mjd, yl+0.03*(yh-yl), '(%.1f, %.1f)' % (r,d),
ha='center', bbox=bbox)
else:
plt.plot(Tx.mjd_obs, dra, 'bo')
plt.plot(Tx.mjd_obs, ddec, 'go')
pr = plt.plot(Tx.mjd_obs, dra, 'b-', alpha=0.5)
pd = plt.plot(Tx.mjd_obs, ddec, 'g-', alpha=0.5)
#plt.legend((pr[0], pd[0]), ('RA', 'Dec'))
plt.axhline(0.0, color='k', alpha=0.5)
plt.axhline(+10., color='k', alpha=0.2)
plt.axhline(-10., color='k', alpha=0.2)
# i = np.argmax(T.mjd_obs)
# plt.text(T.mjd_obs[i], dra[i], ' RA', ha='left', va='center')
# plt.text(T.mjd_obs[i], ddec[i], ' Dec', ha='left', va='center')
F = Tnonobject[Tnonobject.obstype == 'focus']
Z = Tnonobject[Tnonobject.obstype == 'zero']
print(len(F), 'focus frames,', len(Z), 'zero frames')
if len(F):
plt.plot(F.mjd_obs, np.zeros(len(F)), 'ro')
for f in F:
plt.text(f.mjd_obs, 0., 'F', ha='center', va='top')
if len(Z):
plt.plot(Z.mjd_obs, np.zeros(len(Z)), 'mo')
for f in Z:
plt.text(f.mjd_obs, 0., 'Z', ha='center', va='top')
if len(Tx) > 50:
ii = [np.argmin(Tx.expnum + (Tx.expnum == 0)*1000000),
np.argmax(Tx.expnum)]
else:
ii = range(len(Tx))
txty = mx * 0.8
for i in ii:
if Tx.expnum[i] == 0:
continue
plt.text(Tx.mjd_obs[i], txty, '%i ' % Tx.expnum[i],
rotation=90, va='center', ha='center', fontsize=10,
bbox=dict(facecolor='white', alpha=0.8, edgecolor='none'))
if len(Tx) <= 50:
# Mark focus frames too
for i in range(len(F)):
plt.text(F.mjd_obs[i], txty, '%i ' % F.expnum[i],
rotation=90, va='top', ha='center')
for i in range(len(Z)):
plt.text(Z.mjd_obs[i], txty, '%i ' % Z.expnum[i],
rotation=90, va='top', ha='center')
if refdra is None and not nightly:
# If refdra is available, only label that.
plt.text(Tx.mjd_obs[-1], yl+0.03*(yh-yl),
'(%.1f, %.1f)' % (dra[-1], ddec[-1]), ha='center', bbox=bbox)
plt.ylim(yl, yh)
plt.ylabel('dRA (blu), dDec (grn) (arcsec)')
plt.xlabel('MJD')
if mjdrange is not None:
for sp in range(SP):
plt.subplot(SP,1,sp+1)
plt.xlim(mjdrange)
plt.subplot(SP,1,SP)
xl,xh = plt.xlim()
if xh - xl < 2./24.:
# range of less than 2 hours: label every ten minutes
tx = []
tt = []
dl = mjdtodate(xl)
d = datetime.datetime(dl.year, dl.month, dl.day, dl.hour)
while True:
mjd = datetomjd(d)
if mjd > xh:
break
if mjd > xl:
tx.append(mjd)
tt.append(d.strftime('%H:%M'))
d += datetime.timedelta(0, 600)
plt.xticks(tx, tt)
plt.xlabel(dl.strftime('Time UTC starting %Y-%m-%d'))
elif xh - xl < 1:
# range of less than a day: label the hours
tx = []
tt = []
dl = mjdtodate(xl)
d = datetime.datetime(dl.year, dl.month, dl.day, dl.hour)
while True:
mjd = datetomjd(d)
if mjd > xh:
break
if mjd > xl:
tx.append(mjd)
tt.append(d.strftime('%H:%M'))
d += datetime.timedelta(0, 3600)
plt.xticks(tx, tt)
plt.xlabel(dl.strftime('Time UTC starting %Y-%m-%d'))
else:
tx,tt = plt.xticks()
# Set consistent tick marks but no labels on top plots
tt = ['']*len(tx)
for sp in range(1, SP):
plt.subplot(SP,1,sp)
plt.xticks(tx,tt)
plt.xlim(xl,xh)
plt.xlim(xl,xh)
if len(markmjds):
for sp in range(1, SP+1):
plt.subplot(SP,1,sp)
ax = plt.axis()
for mark in markmjds:
if len(mark) == 2:
mjd,c = mark
if len(mark) in [3,4]:
# For twilight markers: only label the first subplot.
if len(mark) == 4:
mjd,c,txt,subplots = mark
if not sp in subplots:
txt = None
else:
# So far, this is only used for MISSING IMAGE text.
mjd,c,txt = mark
if txt is not None:
plt.text(mjd, (ax[2]+ax[3])/2, txt, rotation=90,
va='center', ha='right')
plt.axvline(mjd, color=c, alpha=0.5, lw=2)
plt.axis(ax)
#Tcount = T[(T.passnumber > 0) * (T.bad_pixcnt == False) *
# (T.nmatched > 10)]
#number of images with depth factor < 0.3 + number of images with seeing > 2"
#for band in np.unique(Tcount.band):
depth_thresh = 0.3
seeing_thresh = 2.0
Tbad = []
for band,Tb in zip(bands, TT):
for passnum in [1,2,3]:
Tcount = Tb[(Tb.passnumber == passnum) * (Tb.bad_pixcnt == False) *
(Tb.nmatched > 10)]
N = len(Tcount)
print('\nBand %s, pass %i: total of %i tiles' % (band, passnum, N))
if N > 0:
shallow = (Tcount.depth_factor < depth_thresh)
blurry = (Tcount.seeing > seeing_thresh)
if np.sum(shallow):
print(' %i have low depth_factor < %g' % (np.sum(shallow), depth_thresh))
if np.sum(blurry):
print(' %i have large seeing > %g' % (np.sum(blurry), seeing_thresh))
Ngood = np.sum(np.logical_not(shallow) * np.logical_not(blurry))
print('Band %s, pass %i: total of %i good tiles' % (band, passnum, Ngood))
Tbad.append(Tcount[np.logical_or(shallow, blurry)])
Tall = merge_tables(TT, columns='fillzero')
Tall.cut(np.argsort(Tall.expnum))
Tall.writeto('night.fits')
if len(Tbad):
Tbad = merge_tables(Tbad)
print('Possible bad_expid.txt entries:')
for t in Tbad:
bad = []
if t.depth_factor < depth_thresh:
# Find other exposures of the same tile
I = np.flatnonzero(Tall.object == t.object)
depthsum = np.sum(Tall.depth_factor[I])
if depthsum > depth_thresh:
print('# split exposures have enough total depth: %i %s this depth=%.2f, total depth=%.2f' % (t.expnum, t.object, t.depth_factor, depthsum))
continue
bad.append('expfactor=%.2f' % t.depth_factor)
if t.seeing > seeing_thresh:
bad.append('seeing=%.2f' % t.seeing)
print('%i %s %s' % (t.expnum, ','.join(bad), t.object))
print()
if show_plot:
plt.draw()
plt.show(block=False)
plt.pause(0.001)
plt.savefig(plotfn)
print('Saved', plotfn)
if show_plot:
plt.draw()
plt.show(block=False)
plt.pause(0.001)
return Tall
def ephemdate_to_mjd(edate):
# pyephem.Date is days since noon UT on the last day of 1899.
# MJD is days since midnight UT on 1858/11/17
# This constant offset in days was computed via:
# mjdnow = datetomjd(datetime.datetime.utcnow())
# enow = ephem.now()
# mjdnow - enow ==> 15019.499915068824
mjd = float(edate) + 15019.5
return mjd
def set_tile_fields(ccd, hdr, tiles):
obj = hdr.get('OBJECT', '')
#print('Object name', obj)
ccd.object = obj
tile = get_tile_from_name(obj, tiles)
if tile is not None:
ccd.tileid = tile.tileid
ccd.passnumber = tile.get('pass')
ccd.tileebv = tile.ebv_med
#print('Tile id', ccd.tileid, 'pass', ccd.passnumber)
# SFD map isn't picklable, use global instead
gSFD = None
def get_expnum(phdr):
expnum = phdr.get('EXPNUM', 0)
instrument = phdr.get('INSTRUME')
if instrument is None:
return expnum
instrument = instrument.strip()
# Bok
if instrument == '90prime':
date = phdr.get('DATE-OBS').strip()
#2017-06-15T10:42:01.301'
yr = date[2:4]
month = date[5:7]
day = date[8:10]
hr = date[11:13]
minute = date[14:16]
sec = date[17:19]
expnum = int(yr + month + day + hr + minute + sec, 10)
print('Date', date, '-> faked expnum', expnum)
# DESI CI
if instrument == 'DESI':
expnum = phdr.get('EXPID', 0)
return expnum
def get_filter(phdr):
filt = phdr.get('FILTER', None)
if filt is None:
instrument = phdr.get('INSTRUME')
if instrument is None:
return None
instrument = instrument.strip()
# DESI CI
if instrument == 'DESI':
filt = 'r'
if filt is not None:
filt = filt.strip()
filt = filt.split()[0]
return filt
def process_image(fn, ext, nom, sfd, opt, obs, tiles):
if obs is None:
from camera import ephem_observer
obs = ephem_observer()
db = opt.db
print('Reading', fn)
print('SFD:', sfd)
if sfd is None:
print('gSFD:', gSFD)
sfd = gSFD
if sfd is None:
sfd = SFDMap()
# Read primary FITS header
phdr = fitsio.read_header(fn, ext=opt.primext)
obstype = phdr.get('OBSTYPE','').strip()
if len(obstype) == 0:
obstype = phdr.get('FLAVOR','').strip()
print('obstype:', obstype)
exptime = phdr.get('EXPTIME', 0)
# pointing cam
if exptime == 0:
exptime = phdr.get('EXPOSURE', 0) / 1000.
expnum = get_expnum(phdr)
filt = get_filter(phdr)
if filt is None:
filt = ''
print('filter:', filt)
airmass = phdr.get('AIRMASS', 0.)
ra = phdr.get('RA', '0')
dec = phdr.get('DEC', '0')
if not (isinstance(ra, float) and isinstance(dec, float)):
ra = hmsstring2ra (ra)
dec = dmsstring2dec(dec)
# DECam rawdata/DECam_00521494.fits.fz -- "NaN"
if isinstance(airmass, str):