forked from mommermi/photometrypipeline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
diagnostics.py
1688 lines (1462 loc) · 74.7 KB
/
diagnostics.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
""" DIAGNOSTICS - diagnostic routines for photometry pipeline
v1.0: 2016-02-25, [email protected]
"""
# Photometry Pipeline
# Copyright (C) 2016-2018 Michael Mommert, [email protected]
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see
# <http://www.gnu.org/licenses/>.
import os
import sys
import numpy as np
import logging
import subprocess
from astropy.io import fits
from astropy import wcs
from astropy.visualization import (ZScaleInterval, ImageNormalize,
LogStretch, LinearStretch)
from astropy.time import Time
try:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pylab as plt
matplotlib.rcdefaults() # restore default parameters
except ImportError:
print('Module matplotlib not found. Please install with: pip install '
'matplotlib')
sys.exit()
try:
from skimage.transform import resize
except ImportError:
print('Module skimage not found. Please install with: pip install '
'scikit-kimage')
sys.exit()
# pipeline-specific modules
import _pp_conf
import toolbox
from catalog import *
# setup logging
logging.basicConfig(filename=_pp_conf.log_filename,
level=_pp_conf.log_level,
format=_pp_conf.log_formatline,
datefmt=_pp_conf.log_datefmt)
class Diagnostics_Html():
"""basis class for building pp html diagnostic output"""
from pp_setup import confdiagnostics as conf
def create_website(self, filename, content=''):
"""
create empty website for diagnostics output
"""
html = ("<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN'>\n"
"<HTML>\n"
"<HEAD>\n"
"<TITLE>Photometry Pipeline - Diagnostics</TITLE>\n"
"<LINK rel=\"stylesheet\" href=\"{:s}"
"diagnostics_stylesheet.css\">\n"
"</HEAD>\n"
"<BODY>\n"
"<script>\n"
"function toggledisplay(elementID)\n"
"{{\n"
"(function(style) {{\n"
"style.display = style.display === 'none' ? '' :"
"'none';\n"
"}})(document.getElementById(elementID).style);\n"
"}}\n"
"</script>\n\n"
"{:s}\n"
"</BODY>\n"
"</HTML>\n").format(os.getenv('PHOTPIPEDIR'), content)
outf = open(filename, 'w')
outf.writelines(html)
outf.close()
def append_website(self, filename, content,
replace_from='X?!do not replace anything!?X',
keep_at='</BODY>',):
"""append content to an existing website: replace content starting
at line containing `replace_from` until line containin `keep_at`;
by default, all content following `replace_from` is
replaced
"""
# read existing code
existing_html = open(filename, 'r').readlines()
# insert content into existing html
outf = open(filename, 'w')
delete = False
for line in existing_html:
if replace_from in line:
delete = True
continue
if keep_at in line:
outf.writelines(content)
delete = False
if delete:
continue
outf.writelines(line)
outf.close()
def abort(self, where):
"""
use this function to add information to index.html that the
pipeline crashed and where
"""
logging.info('adding pipeline crash to diagnostics')
html = ("<P><FONT COLOR=\"RED\">Pipeline crashed "
"unexpectedly in module {:s}; refer to <A "
"HREF=\"{:s}\">log</A> "
"for additional information</FONT>\n").format(
_pp_conf.log_filename, where)
self.append_website(os.path.join(self.conf.diagnostics_path,
self.conf.main_html), html)
logging.info('pipeline crash added')
class Prepare_Diagnostics(Diagnostics_Html):
"""diagnostics run as part of pp_prepare"""
function_tag = "<!-- pp_prepare -->"
def frame_table(self, filenames, obsparam):
logging.info('create data summary table')
if self.conf.individual_frame_pages:
self.frame_pages(filenames, obsparam)
# create frame information table
html = "<P><TABLE CLASS=\"gridtable\">\n"
html += ("<TR><TH>Idx</TH>"
"<TH>Filename</TH>"
"<TH>Observation Midtime (UT)</TH>"
"<TH>Object Name</TH>"
"<TH>Airmass</TH>"
"<TH>Exptime (s)</TH>"
"<TH>Pixel Size (\")"
"<TH>Binning</TH>"
"<TH>FoV (')</TH></TR>\n")
for idx, filename in enumerate(filenames):
hdulist = fits.open(filename, ignore_missing_end=True)
header = hdulist[0].header
binning = toolbox.get_binning(header, obsparam)
try:
objectname = header[obsparam['object']]
except KeyError:
objectname = 'Unknown Target'
if self.conf.individual_frame_pages:
framename = "<A HREF=\"{:s}\">{:s}</A>".format(
os.path.join(self.conf.diagnostics_path,
'.diagnostics', filename+'.html'),
filename)
if self.conf.show_quickview_image:
self.quickview_image(filename)
# update frame page
framehtml = ("<!-- Quickview -->\n"
"<A HREF=\"#quickview\" "
"ONCLICK=\"toggledisplay"
"('quickview');\"><H2>Quickview Image</H2>"
"</A>\n"
"<IMG ID=\"quickview\" SRC=\"{:s}\" "
"STYLE=\"display: none\"\>\n\n").format(
filename+'.' +
self.conf.image_file_format)
self.append_website(
os.path.join(self.conf.diagnostics_path,
'.diagnostics',
'{:s}.html'.format(filename)),
framehtml, replace_from='<!-- Quickview -->')
else:
framename = filename
html += ("<TR><TD>{:d}</TD>"
"<TD>{:s}</TD>"
"<TD>{:s}</TD>"
"<TD>{:s}</TD>"
"<TD>{:4.2f}</TD>"
"<TD>{:.1f}</TD>"
"<TD>{:.2f} x {:.2f}</TD>"
"<TD>{:d} x {:d}</TD>"
"<TD>{:.1f} x {:.1f}</TD>\n"
"</TR>\n").format(
idx+1, framename,
Time(header["MIDTIMJD"], format='jd').iso,
str(objectname),
float(header[obsparam['airmass']]),
float(header[obsparam['exptime']]),
obsparam['secpix'][0],
obsparam['secpix'][1],
int(binning[0]), int(binning[1]),
float(header[obsparam['extent'][0]]) *
obsparam['secpix'][0]*binning[0]/60.,
float(header[obsparam['extent'][1]]) *
obsparam['secpix'][1]*binning[1]/60.)
html += '</TABLE>\n'
logging.info('data summary table created')
return html
def quickview_image(self, filename):
"""create quickview image for one frame"""
logging.info('create image preview for file {:s}'.format(
filename))
hdulist = fits.open(filename, ignore_missing_end=True)
# create frame image
imgdat = hdulist[0].data.astype(np.float64)
# normalize imgdat to pixel values 0 < px < 1
imgdat[np.where(np.isnan(imgdat))[0]] = np.nanmedian(imgdat)
imgdat = np.clip(imgdat, np.percentile(imgdat, 1),
np.percentile(imgdat, 99))
imgdat = (imgdat-np.min(imgdat)) / np.max(imgdat-np.min(imgdat)+0.1)
# resize image larger than lg_image_size_px on one side
imgdat = resize(imgdat,
(min(imgdat.shape[0], self.conf.image_size_lg_px),
min(imgdat.shape[1], self.conf.image_size_lg_px)))
plt.figure(figsize=(self.conf.image_size_lg_in,
self.conf.image_size_lg_in))
norm = ImageNormalize(
imgdat, interval=ZScaleInterval(),
stretch={'linear': LinearStretch(),
'log': LogStretch()}[self.conf.image_stretch])
img = plt.imshow(imgdat, cmap='gray', norm=norm,
origin='lower')
# remove axes
plt.axis('off')
img.axes.get_xaxis().set_visible(False)
img.axes.get_yaxis().set_visible(False)
framefilename = os.path.join(self.conf.diagnostics_path,
'.diagnostics', filename + '.' +
self.conf.image_file_format)
plt.savefig(framefilename, format=self.conf.image_file_format,
bbox_inches='tight',
pad_inches=0, dpi=self.conf.image_dpi)
logging.info('image preview for file {:s} written to {:s}'.format(
filename, os.path.join(self.conf.diagnostics_path,
'.diagnostics', filename + '.' +
self.conf.image_file_format)))
plt.close()
hdulist.close()
def frame_pages(self, filenames, obsparam):
"""build information page for each individual frame"""
logging.info('setting up individual frame diagnostics report pages')
for idx, filename in enumerate(filenames):
header = fits.open(filename)[0].header
html = ("<H1>{:s} Diagnostics</H1>"
"<P><TABLE CLASS=\"gridtable\">\n"
"<TR><TH>Telescope/Instrument</TH><TD>{:s} ({:s})</TD>"
"</TR>\n"
"<TR><TH>Target/Field Identifier</TH><TD>{:s}</TD>"
"</TR>\n"
"<TR><TH>RA</TH><TD>{:s}</TD></TR>\n"
"<TR><TH>Dec</TH><TD>{:s}</TD></TR>\n"
"<TR><TH>Exposure Time (s)</TH><TD>{:s}</TD></TR>\n"
"<TR><TH>Observation Midtime</TH><TD>{:s}</TD></TR>\n"
"</TABLE><P>\n"
"<A HREF=\"{:s}\">"
"« previous frame «</A> | "
"<A HREF=\"../diagnostics.html\">run overview</A> | "
"<A HREF=\"{:s}\">"
"» next frame »</A></P>\n\n").format(
filename,
obsparam['telescope_instrument'],
obsparam['telescope_keyword'],
header[obsparam['object']],
str(header[obsparam['ra']]),
str(header[obsparam['dec']]),
str(header[obsparam['exptime']]),
str(Time(header['MIDTIMJD'], format='jd').iso),
filenames[(idx-1) % len(filenames)]+'.html',
filenames[(idx+1) % len(filenames)]+'.html')
self.create_website(
os.path.join(self.conf.diagnostics_path,
'.diagnostics', '{:s}.html'.format(filename)),
html)
logging.info(('diagnostics report page for file {:s} '
'written to {:s}').format(
filename,
os.path.join(self.conf.diagnostics_path,
'.diagnostics',
'{:s}.html'.format(filename))))
def add_index(self, filenames, datadirectory, obsparam):
"""
create index.html
diagnostic root website
"""
logging.info('create frame table')
os.mkdir(self.conf.diagnostics_path) if not os.path.exists(
self.conf.diagnostics_path) else None
os.mkdir(os.path.join(self.conf.diagnostics_path,
'.diagnostics')) if not os.path.exists(
os.path.join(self.conf.diagnostics_path,
'.diagnostics')) else None
# create header information
refheader = fits.open(filenames[0],
ignore_missing_end=True)[0].header
raw_filtername = refheader[obsparam['filter']]
translated_filtername = obsparam['filter_translations'][
refheader[obsparam['filter']]]
html = ("{:s}\n<H1>Photometry Pipeline Diagnostic Output</H1>\n"
"<TABLE CLASS=\"gridtable\">\n"
" <TR><TH>Data Directory</TH><TD>{:s}</TD></TR>\n"
" <TR><TH>Telescope/Instrument</TH><TD>{:s}</TD></TR>\n"
" <TR><TH>Number of Frames</TH><TD>{:d}</TD></TR>\n"
" <TR><TH>Raw Filter Identifier</TH><TD>{:s}</TD></TR>\n"
" <TR><TH>Translated Filter Identifier</TH>"
"<TD>{:s}</TD></TR>\n"
" <TR><TH>Log File</TH>"
" <TD><A HREF=\"{:s}\">available here</A></TD></TR>"
"</TABLE>\n").format(
self.function_tag,
datadirectory,
obsparam['telescope_instrument'],
len(filenames),
str(raw_filtername),
str(translated_filtername),
os.path.join(datadirectory, 'LOG'))
html += "<H3>Data Summary</H3>\n"
html += self.frame_table(filenames, obsparam)
self.create_website(os.path.join(self.conf.diagnostics_path,
self.conf.main_html), html)
logging.info('frame table created')
# registration results website
class Registration_Diagnostics(Diagnostics_Html):
function_tag = "<!-- pp_register -->"
def registration_table(self, data, extraction_data, obsparam):
"""build overview table with astrometric registration results"""
logging.info('creating image registration overview table')
html = ("<TABLE CLASS=\"gridtable\">\n<TR>\n"
"<TH>Filename</TH><TH>C<SUB>AS</SUB></TH>"
"<TH>C<SUB>XY</SUB></TH>"
"<TH>σ<SUB>RA</SUB> (arcsec)</TH>"
"<TH>σ<SUB>DEC</SUB> (arcsec)</TH>"
"<TH>χ<SUP>2</SUP><SUB>Reference</SUB></TH>"
"<TH>χ<SUP>2</SUP><SUB>Internal</SUB></TH>\n</TR>\n")
for dat in data['fitresults']:
framefilename = os.path.join(self.conf.diagnostics_path,
'.diagnostics',
'{:s}.html'.format(dat[0]))
if self.conf.individual_frame_pages:
filename = '<A HREF=\"{:s}\">{:s}</A>'.format(
framefilename, dat[0])
else:
filename = dat[0]
html += ("<TR><TD>{:s}</TD>"
+ "<TD>{:4.1f}</TD><TD>{:4.1f}</TD>"
+ "<TD>{:5.3f}</TD><TD>{:5.3f}</TD>"
+ "<TD>{:e}</TD><TD>{:e}</TD>\n</TR>\n").format(
filename, dat[1], dat[2], dat[3],
dat[4], dat[5], dat[6])
html += "</TABLE>\n"
html += ("<P CLASS=\"caption\"><STRONG>Legend</STRONG>: "
"C<SUB>AS</SUB>: position "
"angle/scale contrast (values >{:.1f} are ok); ").format(
_pp_conf.scamp_as_contrast_limit)
html += ("C<SUB>XY</SUB>: xy-shift contrast "
"(values >{:.1f} are ok); ").format(
_pp_conf.scamp_xy_contrast_limit)
html += ("σ<SUB>RA</SUB> and σ<SUB>DEC</SUB> "
"refer to the internal astrometric uncertainties as "
"provided by SCAMP; χ<SUP>2</SUP><SUB>Reference</SUB> "
"and χ<SUP>2</SUP><SUB>Internal</SUB> refer to the "
"χ<SUP>2</SUP> statistics based on the reference "
"catalog and the respective frame as provided by SCAMP."
"</P>\n")
logging.info('image registration overview table created')
return html
def registration_maps(self, data, extraction_data, obsparam):
"""build overlays for image maps indicating astrometric reference
stars"""
logging.info('create registration overlays with reference stars')
# load reference catalog
refcat = catalog(data['catalog'])
for filename in os.listdir('.'):
if data['catalog'] in filename and '.cat' in filename:
refcat.read_ldac(filename)
break
# create overlays
for dat in extraction_data:
framefilename = os.path.join(self.conf.diagnostics_path,
'.diagnostics',
'{:s}_astrometry.{:s}'.format(
dat['fits_filename'],
self.conf.image_file_format))
imgdat = fits.open(dat['fits_filename'],
ignore_missing_end=True)[0].data
resize_factor = min(
1.,
self.conf.image_size_lg_px/np.max(imgdat.shape))
header = fits.open(dat['fits_filename'],
ignore_missing_end=True)[0].header
# turn relevant header keys into floats
# astropy.io.fits bug
for key, val in list(header.items()):
if 'CD1_' in key or 'CD2_' in key or \
'CRVAL' in key or 'CRPIX' in key or \
'EQUINOX' in key:
header[key] = float(val)
plt.figure(figsize=(self.conf.image_size_lg_in,
self.conf.image_size_lg_in))
# create fake image to ensure image dimensions and margins
img = plt.imshow(np.ones((self.conf.image_size_lg_px,
self.conf.image_size_lg_px))*np.nan,
origin='lower')
# remove axes
plt.axis('off')
img.axes.get_xaxis().set_visible(False)
img.axes.get_yaxis().set_visible(False)
# plot reference sources
if refcat.shape[0] > 0:
try:
w = wcs.WCS(header)
world_coo = np.array(list(zip(refcat['ra_deg'],
refcat['dec_deg'])))
img_coo = w.wcs_world2pix(world_coo, True)
img_coo = [c for c in img_coo
if (c[0] > 0 and c[1] > 0 and
c[0] < header[obsparam['extent'][0]] and
c[1] < header[obsparam['extent'][1]])]
plt.scatter([c[0]*resize_factor for c in img_coo],
[c[1]*resize_factor for c in img_coo],
s=5, marker='o', edgecolors='red',
linewidth=self.conf.overlay_lg_linewidth,
facecolor='none')
except astropy.wcs._wcs.InvalidTransformError:
logging.error('could not plot reference sources due to '
'astropy.wcs._wcs.InvalidTransformError; '
'most likely unknown distortion '
'parameters.')
plt.savefig(framefilename, bbox_inches='tight',
pad_inches=0, dpi=self.conf.image_dpi,
transparent=True)
logging.info(('registration map image file for image {:s} '
'written to {:s}').format(
filename, os.path.abspath(framefilename)))
plt.close()
logging.info('create registration overlays with reference stars')
def add_registration(self, data, extraction_data):
"""
add registration results to website
"""
logging.info('adding registration information')
obsparam = extraction_data[0]['parameters']['obsparam']
html = self.function_tag+'\n'
html += ('<H2>Registration</H2>\n'
'<P>Registration based on {:s} catalog: \n').format(
data['catalog'])
if len(data['badfits']) == 0:
html += ('<STRONG><FONT COLOR="GREEN">All frames registered '
'successfully</FONT></STRONG></P>\n')
else:
html += ('<STRONG><FONT COLOR="RED">{:d} files could not be '
'registered</FONT></STRONG></P>\n').format(
len(data['badfits']))
if self.conf.show_registration_table:
html += self.registration_table(data, extraction_data, obsparam)
if (self.conf.individual_frame_pages and
self.conf.show_quickview_image and
self.conf.show_registration_star_map):
self.registration_maps(data, extraction_data, obsparam)
for framedata in data['fitresults']:
# update frame page
filename = framedata[0]
if filename in data['goodfits']:
resultstring = ('<P><FONT COLOR="GREEN">Registration '
'successful</FONT></P>')
else:
resultstring = ('<P><FONT COLOR="RED">Registration '
'failed</FONT></P>')
framehtml = (
"<!-- Registration -->\n"
"<A HREF=\"#registration\" "
"ONCLICK=\"toggledisplay('registration');\">"
"<H2>Astrometric Registration</H2></A>\n"
"<DIV ID=\"registration\" STYLE=\"display: none\">\n"
"<TABLE CLASS=\"gridtable\">\n<TR>\n"
"<TH>Filename</TH><TH>C<SUB>AS</SUB></TH>"
"<TH>C<SUB>XY</SUB></TH>"
"<TH>σ<SUB>RA</SUB> (arcsec)</TH>"
"<TH>σ<SUB>DEC</SUB> (arcsec)</TH>"
"<TH>χ<SUP>2</SUP><SUB>Reference</SUB></TH>"
"<TH>χ<SUP>2</SUP><SUB>Internal</SUB></TH>\n</TR>\n"
"<TR><TD>{:s}</TD>"
"<TD>{:4.1f}</TD><TD>{:4.1f}</TD>"
"<TD>{:5.3f}</TD><TD>{:5.3f}</TD>"
"<TD>{:e}</TD><TD>{:e}</TD>\n</TR>\n"
"</TABLE>\n"
"<STRONG>{:s}</STRONG>"
"<DIV CLASS=\"parent_image\">\n"
" <IMG CLASS=\"back_image\" SRC=\"{:s}\" />\n"
" <IMG CLASS=\"front_image\" SRC=\"{:s}\" />\n"
"</DIV>\n</DIV>\n\n").format(
filename, framedata[1], framedata[2], framedata[3],
framedata[4], framedata[5], framedata[6],
resultstring,
filename+'.'+self.conf.image_file_format,
filename+"_astrometry."+self.conf.image_file_format)
self.append_website(
os.path.join(self.conf.diagnostics_path,
'.diagnostics',
'{:s}.html'.format(filename)),
framehtml, replace_from='<!-- Registration -->')
self.append_website(os.path.join(self.conf.diagnostics_path,
self.conf.main_html), html,
replace_from=self.function_tag)
logging.info('registration information added')
class Photometry_Diagnostics(Diagnostics_Html):
function_tag = "<!-- pp_photometry -->"
def curve_of_growth_plot(self, data):
""" create curve of growth plot"""
logging.info('create curve-of-growth plot')
parameters = data['parameters']
growth_filename = os.path.join(self.conf.diagnostics_path,
'.diagnostics', 'curve_of_growth.' +
self.conf.image_file_format)
f, (ax1, ax2) = plt.subplots(2, sharex=True)
ax1.set_xlim([min(parameters['aprad']), max(parameters['aprad'])])
ax1.set_ylabel('Fractional Combined Flux')
if not parameters['target_only']:
ax1.plot(parameters['aprad'], data['background_flux'][0],
color='black', linewidth=1,
label='background sources')
ax1.fill_between(parameters['aprad'],
(data['background_flux'][0] -
data['background_flux'][1]),
(data['background_flux'][0] +
data['background_flux'][1]),
color='black', alpha=0.2)
if not parameters['background_only']:
ax1.plot(parameters['aprad'], data['target_flux'][0],
color='red', linewidth=1,
label='target')
ax1.fill_between(parameters['aprad'],
(data['target_flux'][0] -
data['target_flux'][1]),
(data['target_flux'][0] +
data['target_flux'][1]),
color='red', alpha=0.2)
ax1.set_ylim([0, ax1.get_ylim()[1]])
ax1.plot([data['optimum_aprad'], data['optimum_aprad']],
[ax1.get_ylim()[0], ax1.get_ylim()[1]],
linewidth=2, color='blue')
ax1.plot([plt.xlim()[0], plt.xlim()[1]],
[data['fluxlimit_aprad'], data['fluxlimit_aprad']],
color='black', linestyle='--')
ax1.grid()
ax1.legend(loc=4)
ax2.set_ylim([-0.1, 1.1])
ax2.set_ylabel('SNR')
if not parameters['target_only']:
ax2.errorbar(parameters['aprad'], data['background_snr'],
color='black', linewidth=1)
if not parameters['background_only']:
ax2.errorbar(parameters['aprad'], data['target_snr'],
color='red', linewidth=1)
ax2.plot([data['optimum_aprad'], data['optimum_aprad']],
[plt.ylim()[0], plt.ylim()[1]],
linewidth=2, color='blue')
ax2.grid()
ax2.set_xlabel('Aperture Radius (px)')
plt.savefig(growth_filename, format=self.conf.image_file_format,
dpi=self.conf.plot_dpi)
plt.close()
data['growth_filename'] = growth_filename
logging.info('curve-of-growth plot created')
def fwhm_vs_time_plot(self, extraction, data):
"""create fwhm plot"""
logging.info('create FWHM plot')
fwhm_filename = os.path.join(self.conf.diagnostics_path,
'.diagnostics',
'fwhm.'+self.conf.image_file_format)
frame_midtimes = np.array([frame['time'] for frame in extraction])
fwhm = [np.median(frame['catalog_data']['FWHM_IMAGE'])
for frame in extraction]
fwhm_sig = [np.std(frame['catalog_data']['FWHM_IMAGE'])
for frame in extraction]
fig, ax = plt.subplots()
ax.set_title('Median PSF FWHM per Frame')
ax.set_xlabel('Minutes after {:s} UT'.format(
Time(frame_midtimes.min(), format='jd',
out_subfmt='date_hm').iso))
ax.set_ylabel('Point Source FWHM (px)')
ax.scatter((frame_midtimes-frame_midtimes.min())*1440,
fwhm, marker='o',
color='black')
xrange = [plt.xlim()[0], plt.xlim()[1]]
ax.plot(xrange, [data['optimum_aprad']*2, data['optimum_aprad']*2],
color='blue')
ax.set_xlim(xrange)
ax.set_ylim([0, max([data['optimum_aprad']*2+1, max(fwhm)])])
ax.grid()
fig.savefig(fwhm_filename, dpi=self.conf.plot_dpi,
format=self.conf.image_file_format)
data['fwhm_filename'] = fwhm_filename
# create html map
if self.conf.individual_frame_pages:
data['fwhm_map'] = ""
for i in range(len(extraction)):
x, y = ax.transData.transform_point(
[((frame_midtimes-frame_midtimes.min())*1440)[i],
fwhm[i]])
filename = extraction[i]['fits_filename']
data['fwhm_map'] += (
'<area shape="circle" coords="{:.1f},{:.1f},{:.1f}" '
'href="{:s}#{:s}" alt="{:s}" title="{:s}">\n').format(
x, fig.bbox.height - y, 5,
os.path.join(self.conf.diagnostics_path,
'.diagnostics', filename+'.html'),
'',
filename, filename)
logging.info('FWHM plot created')
def add_photometry(self, data, extraction):
"""
add photometry results to website
"""
logging.info('adding photometry information')
# create curve-of-growth plot
self.curve_of_growth_plot(data)
# create fwhm vs time plot
self.fwhm_vs_time_plot(extraction, data)
# update index.html
html = self.function_tag+'\n'
html += ("<H2>Instrumental Photometry</H2>\n"
"<TABLE CLASS=\"gridtable\">\n"
"<TR><TH>Photometry Method</TH><TD>{:s}</TD></TR>\n"
"<TR><TH>Source Extractor MINAREA (px)</TH>"
"<TD>{:.1f}</TD></TR>\n"
"<TR><TH>Source Extractor Detection Threshold (σ)"
"</TH><TD>{:.1f}</TD></TR>\n").format(
{'APER': 'Aperture Photometry'}[_pp_conf.photmode],
extraction[0]['parameters']['source_minarea'],
extraction[0]['parameters']['sex_snr'])
if _pp_conf.photmode == 'APER':
if data['n_target'] > 0 and data['n_bkg'] > 0:
apsrc = ("{:d} target detections and {:d} "
"background detections").format(
data['n_target'], data['n_bkg'])
elif data['n_target'] == 0 and data['n_bkg'] > 0:
apsrc = "{:d} frames with background detections".format(
data['n_bkg'])
elif data['n_bkg'] == 0 and data['n_target'] > 0:
apsrc = "{:d} frames with target detections".format(
data['n_target'])
else:
apsrc = "manually defined"
html += ("<TR><TH>Aperture Radius (px)</TH>"
"<TD>{:.2f}</TD></TR>\n"
"<TR><TH>Aperture Radius Basis</TH>"
"<TD>{:s}</TD></TR>\n"
"<TR><TH>Aperture Radius Strategy</TH>"
"<TD>{:s}</TD></TR>\n").format(
data['optimum_aprad'],
apsrc,
data['aprad_strategy']
)
html += "</TABLE>\n"
html += "<P><IMG SRC=\"{:s}\">\n".format(data['growth_filename'])
if self.conf.individual_frame_pages:
html += "<IMG SRC=\"{:s}\" USEMAP=\"#FWHM\">\n".format(
data['fwhm_filename'])
html += "<MAP NAME=\"#FWHM\">\n{:s}</MAP>\n".format(
data['fwhm_map'])
else:
html += "<IMG SRC=\"{:s}\">\n".format(
data['fwhm_filename'])
self.append_website(os.path.join(self.conf.diagnostics_path,
self.conf.main_html), html,
replace_from=self.function_tag)
logging.info('photometry information added')
class Calibration_Diagnostics(Diagnostics_Html):
function_tag = "<!-- pp_calibrate -->"
def zeropoint_overview_plot(self, data):
"""produce a plot of magnitude zeropoint as a function of time"""
logging.info('create zeropoint overview plot')
times = np.array([dat['obstime'][0] for dat in data['zeropoints']])
zp = [dat['zp'] for dat in data['zeropoints']]
zperr = [dat['zp_sig'] for dat in data['zeropoints']]
fig, ax = plt.subplots()
ax.errorbar((times-times.min())*1440, zp, yerr=zperr, linestyle='',
color='blue', marker='s', capsize=3)
ax.set_xlabel('Minutes after {:s} UT'.format(
Time(times.min(), format='jd',
out_subfmt='date_hm').iso))
ax.set_ylabel(
'{:s}-Band Magnitude Zeropoints (mag)'.format(
data['filtername']))
ax.set_ylim([ax.get_ylim()[1], ax.get_ylim()[0]])
ax.grid()
fig.savefig(os.path.join(self.conf.diagnostics_path, '.diagnostics',
'zeropoints.'+self.conf.image_file_format),
format=self.conf.image_file_format,
dpi=self.conf.plot_dpi)
logging.info('zeropoint overview plot written to {:s}'.format(
os.path.abspath(os.path.join(self.conf.diagnostics_path,
'.diagnostics', 'zeropoints.' +
self.conf.image_file_format))))
data['zpplot'] = 'zeropoints.' + self.conf.image_file_format
# create html map
if self.conf.individual_frame_pages:
data['zpplotmap'] = ""
for i in range(len(times)):
x, y = ax.transData.transform_point(
[((times-times.min())*1440)[i],
[dat['zp'] for dat in data['zeropoints']][i]])
filename = data['zeropoints'][i]['filename'][:-4]+'fits'
data['zpplotmap'] += (
'<area shape="circle" coords="{:.1f},{:.1f},{:.1f}" '
'href="{:s}#{:s}" alt="{:s}" title="{:s}">\n').format(
x, fig.bbox.height - y, 5,
os.path.join(self.conf.diagnostics_path,
'.diagnostics', filename+'.html'),
'calibration_overview',
filename, filename)
logging.info('zeropoint overview plot created')
def phot_calibration_plot(self, data, idx):
"""produce diagnostic plot for each frame"""
logging.info('create photometric calibration overview plot')
f, (ax1, ax3) = plt.subplots(2)
plt.subplots_adjust(hspace=0.3)
ax1.set_title('{:s}: {:s}-band from {:s}'.format(
data['catalogs'][idx].catalogname,
data['filtername'],
data['ref_cat'].catalogname))
ax1.set_xlabel('Number of Reference Stars')
ax1.set_ylabel('Magnitude Zeropoint', fontdict={'color': 'red'})
zp_idx = data['zeropoints'][idx]['zp_idx']
clipping_steps = data['zeropoints'][idx]['clipping_steps']
x = [len(clipping_steps[i][3]) for i
in range(len(clipping_steps))]
ax1.errorbar(x, [clipping_steps[i][0] for i
in range(len(clipping_steps))],
yerr=[clipping_steps[i][1] for i
in range(len(clipping_steps))], color='red')
ax1.set_ylim(ax1.get_ylim()[::-1]) # reverse y axis
ax1.plot([len(clipping_steps[zp_idx][3]),
len(clipping_steps[zp_idx][3])],
ax1.get_ylim(), color='black')
ax1.grid(linestyle='--')
ax2 = ax1.twinx()
ax2.plot(x, [clipping_steps[i][2] for i
in range(len(clipping_steps))],
color='blue')
ax2.set_ylabel(r'reduced $\chi^2$', fontdict={'color': 'blue'})
ax2.set_yscale('log')
ax2.plot([min(x), max(x)], [1, 1], linestyle='dotted', color='blue')
# residual plot
ax3.set_xlabel('Reference Star Magnitude')
ax3.set_ylabel('Calibration-Reference (mag)')
match = data['zeropoints'][idx]['match']
x = match[0][0][clipping_steps[zp_idx][3]]
residuals = (match[1][0][clipping_steps[zp_idx][3]]
+ clipping_steps[zp_idx][0]
- match[0][0][clipping_steps[zp_idx][3]])
residuals_sig = np.sqrt(match[1][1][clipping_steps[zp_idx][3]]**2
+ clipping_steps[zp_idx][1]**2)
ax3.errorbar(x, residuals, yerr=residuals_sig, color='black',
marker='o', linestyle='')
x_range = ax3.get_xlim()
ax3.plot(x_range, [0, 0], color='black', linestyle='--')
ax3.set_xlim(x_range)
ax3.set_ylim(ax3.get_ylim()[::-1]) # reverse y axis
ax3.grid(linestyle='--')
plotfilename = os.path.join(self.conf.diagnostics_path,
'.diagnostics',
'{:s}_photcal.{:s}'.format(
data['catalogs'][idx].catalogname,
self.conf.image_file_format))
plt.savefig(plotfilename, dpi=self.conf.plot_dpi,
format=self.conf.image_file_format)
data['zeropoints'][idx]['plotfilename'] = plotfilename
logging.info('create photometric calibration overview plot')
def calibration_raw_data_tables(self, dat):
"""build table with photometric calibration raw data"""
logging.info('create calibration data table')
html = "<TD><TABLE CLASS=\"gridtable\">\n<TR>\n"
html += ("<TH>Idx</TH><TH>Source Name</TH><TH>RA</TH><TH>Dec</TH>"
"<TH>Catalog (mag)</TH>"
"<TH>Instrumental (mag)</TH><TH>Calibrated (mag)</TH>"
"<TH>Residual (mag</TH>\n</TR>\n")
for i, idx in enumerate(dat['zp_usedstars']):
name = str(dat['match'][0][2][idx])
if isinstance(name, bytes):
name = name.decode('utf8')
html += ("<TR><TD>{:d}</TD><TD>{:s}</TD><TD>{:12.8f}</TD>"
"<TD>{:12.8f}</TD><TD>{:.3f}+-{:.3f}</TD>"
"<TD>{:.3f}+-{:.3f}</TD>"
"<TD>{:.3f}+-{:.3f}</TD><TD>{:.3f}</TD>"
"</TR>").format(
i+1, name,
dat['match'][0][3][idx],
dat['match'][0][4][idx],
dat['match'][0][0][idx],
dat['match'][0][1][idx],
dat['match'][1][0][idx],
dat['match'][1][1][idx],
dat['zp']+dat['match'][1][0][idx],
np.sqrt(dat['zp_sig']**2 +
dat['match'][1][1][idx]**2),
(dat['zp']+dat['match'][1][0][idx]) -
dat['match'][0][0][idx])
html += "</TABLE>\n"
logging.info('calibration data table created')
return html
def calibration_star_maps(self, dat):
"""create thumbnail images with calibration stars marked"""
logging.info('create calibration reference star overlay')
fits_filename = (dat['filename'][:dat['filename'].find('.ldac')]
+ '.fits')
imgdat = fits.open(fits_filename,
ignore_missing_end=True)[0].data
resize_factor = min(
1.,
self.conf.image_size_lg_px/np.max(imgdat.shape))
header = fits.open(fits_filename,
ignore_missing_end=True)[0].header
# turn relevant header keys into floats
# astropy.io.fits bug
for key, val in list(header.items()):
if 'CD1_' in key or 'CD2_' in key or \
'CRVAL' in key or 'CRPIX' in key or \
'EQUINOX' in key:
header[key] = float(val)
plt.figure(figsize=(self.conf.image_size_lg_in,
self.conf.image_size_lg_in))
# create fake image to ensure image dimensions and margins
img = plt.imshow(np.ones((self.conf.image_size_lg_px,
self.conf.image_size_lg_px))*np.nan,
origin='lower')
# remove axes
plt.axis('off')
img.axes.get_xaxis().set_visible(False)
img.axes.get_yaxis().set_visible(False)
# plot reference sources
if len(dat['match'][0][3]) > 0 and len(dat['match'][0][4]) > 0:
try:
w = wcs.WCS(header)
world_coo = [[dat['match'][0][3][idx],
dat['match'][0][4][idx]]
for idx in dat['zp_usedstars']]
img_coo = w.wcs_world2pix(world_coo, True)
plt.scatter([c[0]*resize_factor for c in img_coo],
[c[1]*resize_factor for c in img_coo],
s=10, marker='o', edgecolors='red',
linewidth=0.3,
facecolor='none')
for i in range(len(dat['zp_usedstars'])):
plt.annotate(str(i+1),
xy=((img_coo[i][0]*resize_factor)+15,
img_coo[i][1]*resize_factor),
color='red',
horizontalalignment='left',
verticalalignment='center')
except astropy.wcs._wcs.InvalidTransformError:
logging.error('could not plot reference sources due to '
'astropy.wcs._wcs.InvalidTransformError; '
'most likely unknown distortion '
'parameters.')