-
Notifications
You must be signed in to change notification settings - Fork 0
/
report.py
2142 lines (1790 loc) · 86 KB
/
report.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
from functions import *
import os
import collections
from datetime import datetime
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt, mpld3
from matplotlib import cm, ticker, colors
from mpld3 import plugins
from matplotlib.patches import Ellipse
import matplotlib.image as image
#import seaborn
from astropy.io import fits
from astropy.io import votable
from astropy.table import Table
from astropy.coordinates import SkyCoord
from astropy.utils.exceptions import AstropyWarning
import warnings
from inspect import currentframe, getframeinfo
#ignore annoying astropy warnings and set my own obvious warning output
warnings.simplefilter('ignore', category=AstropyWarning)
cf = currentframe()
WARN = '\n\033[91mWARNING: \033[0m' + getframeinfo(cf).filename
class report(object):
def __init__(self,cat,main_dir,img=None,raw_img=None,resid_img=None,plot_to='html',css_style=None,fig_font={'fontname':'Serif', 'fontsize' : 18},fig_size={'figsize' : (8,8)},
label_size={'labelsize' : 12},markers={'s' : 20, 'linewidth' : 1, 'marker' : 'o', 'color' : 'b'},
colour_markers={'marker' : 'o', 's' : 30, 'linewidth' : 0},cmap='plasma',cbins=20,
arrows={'color' : 'r', 'width' : 0.01, 'scale' : 30},src_cnt_bins=50,rms_map=None,redo=False,do_source_counts=False,write=True,verbose=True):
"""Initialise a report object for writing a html report of the image and cross-matches, including plots.
Arguments:
----------
cat : catalogue
Catalogue object with the data for plotting.
main_dir : string
Main directory that contains all the necessary files.
Keyword arguments:
------------------
img : radio_image
Radio image object used to write report table. If None, report will not be written, but plots will be made.
plot_to : string
Where to show or write the plot. Options are:
'html' - save as a html file using mpld3.
'screen' - plot to screen [i.e. call plt.show()].
'extn' - write file with this extension (e.g. 'pdf', 'eps', 'png', etc).
css_style : string
A css format to be inserted in <head>.
fig_font : dict
Dictionary of kwargs for font name and size for title and axis labels of matplotlib figure.
fig_size : dict
Dictionary of kwargs to pass into pyplot.figure.
label_size : dict
Dictionary of kwargs for tick params.
markers : dict
Dictionary of kwargs to pass into pyplot.figure.scatter, etc (when single colour used).
colour_markers : dict
Dictionary of kwargs to pass into pyplot.figure.scatter, etc (when colourmap used).
arrows : dict
Dictionary of kwargs to pass into pyplot.figure.quiver.
rms_map : str
Path to RMS map if no image input.
redo: bool
Produce all plots and save them, even if the files already exist.
write : bool
Write the source counts and figures to file. Input False to only write report.
verbose : bool
Verbose output.
See Also:
---------
matplotlib.pyplot
mpld3"""
self.cat = cat
self.img = img
self.raw_img = raw_img
self.resid_img = resid_img
self.plot_to = plot_to
self.fig_font = fig_font
self.fig_size = fig_size
self.label_size = label_size
self.markers = markers
self.colour_markers = colour_markers
self.arrows = arrows
self.cmap = plt.get_cmap(cmap,cbins)
self.src_cnt_bins = src_cnt_bins
self.main_dir = main_dir
self.redo = redo
self.write = write
self.verbose = verbose
#set name of directory for figures and create if doesn't exist
self.figDir = 'figures'
if self.write and not os.path.exists(self.figDir):
os.mkdir(self.figDir)
#use css style passed in or default style for CASS web server below
if css_style is not None:
self.css_style = css_style
else:
self.css_style = """<?php include("base.inc"); ?>
<meta name="DCTERMS.Creator" lang="en" content="personalName=Collier,Jordan" />
<meta name="DC.Title" lang="en" content="Continuum Validation Report" />
<meta name="DC.Description" lang="en" content="Continuum validation report summarising science readiness of data via several metrics" />
<?php standard_head(); ?>
<style>
.reportTable {
border-collapse: collapse;
width: 100%;
}
.reportTable th, .reportTable td {
padding: 15px;
text-align: middle;
border-bottom: 1px solid #ddd;
vertical-align: top;
}
.reportTable tr {
text-align:center;
vertical-align:middle;
}
.reportTable tr:hover{background-color:#f5f5f5}
#good {
background-color:#00FA9A;
}
#uncertain {
background-color:#FFA500;
}
#bad {
background-color:#FF6347;
}
</style>\n"""
self.css_style += "<title>{0} Continuum Validation Report</title>\n""".format(self.cat.name)
#filename of html report
self.name = 'index.html'
#Open file html file and write css style, title and heading
self.write_html_head()
#write table summary of observations and image if radio_image object passed in
if img is not None:
self.write_html_img_table(img)
rms_map = img.rms_map
solid_ang = 0
elif rms_map is not None:
solid_ang = 0
#otherwise assume area based on catalogue RA/DEC limits
else:
solid_ang = self.cat.area*(np.pi/180)**2
self.write_html_cat_table(do_source_counts=do_source_counts)
#plot the in-band spectral index, and int/peak flux as a function of peak flux
if self.cat.finder is not None and self.cat.finder.lower() == 'selavy':
self.in_band_si()
else:
self.html.write("""</td><td></td>""")
self.int_peak_flux(usePeak=False)
#write source counts to report using rms map to measure solid angle or approximate solid angle
if self.cat.name in list(self.cat.flux.keys()) and do_source_counts:
self.source_counts(self.cat.flux[self.cat.name],self.cat.freq[self.cat.name],rms_map=rms_map,solid_ang=solid_ang,write=self.write)
else:
self.sc_red_chi_sq = -1
self.html.write("""</td>
</tr>
</table>""")
#write cross-match table header
self.write_html_cross_match_table()
#store dictionary of metrics, where they come from, how many matches they're derived from, and their level (0,1 or 2)
#spectral index defaults to -99, as there is a likelihood it will not be needed (if Taylor-term imaging is not done)
#RA and DEC offsets used temporarily and then dropped before final metrics computed
key_value_pairs = [ ('Flux Ratio' , 0),
('Flux Ratio Uncertainty' , -111),
('Positional Offset' , 0),
('Positional Offset Uncertainty' , -111),
('Resolved Fraction' , self.cat.resolved_frac),
('Spectral Index' , 0),
('RMS', self.cat.img_rms),
('Bad beams', self.num_bad_beams),
('Source Counts Reduced Chi-squared' , -111), #self.sc_red_chi_sq
('RA Offset' , 0),
('DEC Offset' , 0)]
self.metric_val = collections.OrderedDict(key_value_pairs)
self.metric_source = self.metric_val.copy()
#Convert data type to str
for key in list(self.metric_source.keys()):
self.metric_source[key] = ''
self.metric_count = self.metric_val.copy()
self.metric_level = self.metric_val.copy()
def write_html_head(self):
"""Open the report html file and write the head."""
self.html = open(self.name,'w')
self.html.write("""<!DOCTYPE HTML>
<html lang="en">
<head>
{0}
</head>
<?php title_bar("atnf"); ?>
<body>
<h1 align="middle">{1} Continuum Data Validation Report</h1>""".format(self.css_style,self.cat.name))
def write_html_img_table(self,img):
"""Write an observations and image and catalogue report tables derived from fits image and header.
Arguments:
----------
img : radio_image
A radio image object used to write values to the html table."""
#generate link to confluence page for each project code
project = img.project
if project in ['AS032','AS033','AS034','AS035','AS100']:
project = self.add_html_link("https://confluence.csiro.au/display/askapsst/{0}+Data".format(img.project),img.project,file=False)
if img.sbid != '':
header = """<th>SBID</th>
<th>Project</th>"""
data = """<td>{0}</td>
<td>{1}</td>""".format(img.sbid,project)
else:
header = ''
data = ''
#Write observations report table
self.html.write("""
<h2 align="middle">Observations</h2>
<table class="reportTable">
<tr>
{0}
<th>Date</th>
<th>Duration<br>(hours)</th>
<th>Field Centre</th>
<th>Central Frequency<br>(MHz)</th>
</tr>
<tr>
{1}
<td>{2}</td>
<td>{3}</td>
<td>{4}</td>
<td>{5:.2f}</td>
</tr>
</table>""".format( header,
data,
img.date,
img.duration,
img.centre,
img.freq))
header = ''
data = ''
if img.soft_version != '':
header += """<th>ASKAPsoft<br>version</th>
<th>Pipeline<br>version</th>"""
data += """<td>{0}</td>
<td>{1}</td>""".format(img.soft_version,img.pipeline_version)
if self.raw_img is not None:
header += '\n<th>Number of<br>bad beams</th>'
#Write image report table
self.html.write("""
<h2 align="middle">Image</h2>
<h4 align="middle"><i>File: '{0}'</i></h3>
<table class="reportTable">
<tr>
{1}
<th>Synthesised Beam<br>(arcsec)</th>
<th>Median r.m.s.<br>(uJy)</th>
<th>Image peak<br>(Jy)</th>
<th>Dynamic Range</th>
<th>Sky Area<br>(deg<sup>2</sup>)</th>
</tr>
<tr>
{2}""".format(img.name,header,data))
self.PSFs(self.raw_img)
self.resid_RMS(self.resid_img)
self.html.write("""
<td>{0:.1f} x {1:.1f}</td>
<td>{2}</td>
<td>{3:.2f}</td>
<td>{4:.0E}</td>
<td>{5:.2f}</td>
</tr>
</table>""".format( img.bmaj,
img.bmin,
self.cat.img_rms,
self.cat.img_peak,
self.cat.dynamic_range,
self.cat.area))
def write_html_cat_table(self,do_source_counts=False):
"""Write an observations and image and catalogue report tables derived from fits image, header and catalogue."""
flux_type = 'integrated'
if self.cat.use_peak:
flux_type = 'peak'
if self.cat.med_si == -99:
med_si = ''
else:
med_si = '{0:.2f}'.format(self.cat.med_si)
if do_source_counts:
colhead = '<th>Source Counts<br>χ<sub>red</sub><sup>2</sup></th>'
else:
colhead = ''
#Write catalogue report table
self.html.write("""
<h2 align="middle">Catalogue</h2>
<h4 align="middle"><i>File: '{0}'</i></h3>
<table class="reportTable">
<tr>
<th>Source Finder</th>
<th>Flux Type</th>
<th>Number of<br>sources (≥{1}σ)</th>
<th>Multi-component<br>islands</th>
<th>Sum of image flux vs.<br>sum of catalogue flux</th>
<th>Median in-band spectral index</th>
<th>Median int/peak flux</th>
{2}
</tr>
<tr>
<td>{3}</td>
<td>{4}</td>
<td>{5}</td>
<td>{6}</td>
<td>{7:.1f} Jy vs. {8:.1f} Jy""".format( self.cat.filename,
self.cat.SNR,
colhead,
self.cat.finder,
flux_type,
self.cat.initial_count,
self.cat.blends,
self.cat.img_flux,
self.cat.cat_flux))
def write_html_cross_match_table(self):
"""Write the header of the cross-matches table."""
self.html.write("""
<h2 align="middle">Cross-matches</h2>
<table class="reportTable">
<tr>
<th>Survey</th>
<th>Frequency<br>(MHz)</th>
<th>Cross-matches</th>
<th>Median offset<br>(arcsec)</th>
<th>Median flux ratio</th>
<th>Median spectral index</th>
</tr>""")
def get_metric_level(self,good_condition,uncertain_condition):
"""Return metric level 1 (good), 2 (uncertain) or 3 (bad), according to the two input conditions.
Arguments:
----------
good_condition : bool
Condition for metric being good.
uncertain_condition : bool
Condition for metric being uncertain."""
if good_condition:
return 1
if uncertain_condition:
return 2
return 3
def assign_metric_levels(self):
"""Assign level 1 (good), 2 (uncertain) or 3 (bad) to each metric, depending on specific tolerenace values.
See https://confluence.csiro.au/display/askapsst/Continuum+validation+metrics"""
for metric in list(self.metric_val.keys()):
# Remove keys that don't have a valid value (value=-99 or -1111)
if self.metric_val[metric] == -99 or self.metric_val[metric] == -111:
self.metric_val.pop(metric)
self.metric_source.pop(metric)
self.metric_level.pop(metric)
else:
#flux ratio within 10%?
if metric == 'Flux Ratio':
val = np.abs(self.metric_val[metric]-1)
good_condition = val < 0.1
uncertain_condition = False
self.metric_source[metric] = 'Median flux density ratio [ASKAP / {0}]'.format(self.metric_source[metric])
#uncertainty on flux ratio less than 10/20%?
elif metric == 'Flux Ratio Uncertainty':
good_condition = self.metric_val[metric] < 0.1
uncertain_condition = self.metric_val[metric] < 0.2
self.metric_source[metric] = 'R.M.S. of median flux density ratio [ASKAP / {0}]'.format(self.metric_source[metric])
self.metric_source[metric] += ' (estimated from median absolute deviation from median)'
#positional offset < 2 arcsec
elif metric == 'Positional Offset':
good_condition = self.metric_val[metric] < 2
uncertain_condition = False
self.metric_source[metric] = 'Median positional offset (arcsec) [ASKAP-{0}]'.format(self.metric_source[metric])
#uncertainty on positional offset < 1/5 arcsec
elif metric == 'Positional Offset Uncertainty':
good_condition = self.metric_val[metric] < 5
uncertain_condition = self.metric_val[metric] < 10
self.metric_source[metric] = 'R.M.S. of median positional offset (arcsec) [ASKAP-{0}]'.format(self.metric_source[metric])
self.metric_source[metric] += ' (estimated from median absolute deviation from median)'
#reduced chi-squared of source counts < 3/50?
elif metric == 'Source Counts Reduced Chi-squared':
good_condition = self.metric_val[metric] < 3
uncertain_condition = self.metric_val[metric] < 50
self.metric_source[metric] = 'Reduced chi-squared of source counts'
#resolved fraction of sources between 5-30%?
elif metric == 'Resolved Fraction':
good_condition = self.metric_val[metric] > 0.05 and self.metric_val[metric] < 0.3
uncertain_condition = False
self.metric_source[metric] = 'Fraction of sources resolved according to int/peak flux densities'
#spectral index less than 0.1 away from -0.8?
elif metric == 'Spectral Index':
val = np.abs(self.metric_val[metric]+0.8)
good_condition = val <= 0.1
uncertain_condition = False
self.metric_source[metric] = 'Median in-band spectral index'
elif metric == 'RMS':
good_condition = self.metric_val[metric] < 35
uncertain_condition = False
if self.resid_img is not None:
rms_description = 'Image R.M.S. (uJy), calculated from clipped Selavy component residual map'
else:
rms_description = 'Median image R.M.S. (uJy) from noise map'
self.metric_source[metric] = rms_description
elif metric == 'Bad beams':
good_condition = self.metric_val[metric] < 3
uncertain_condition = False
self.metric_source[metric] = 'Number of raw PSFs with major axis above convolved beam size'
#if unknown metric, set it to 3 (bad)
else:
good_condition = False
uncertain_condition = False
#assign level to metric
self.metric_level[metric] = self.get_metric_level(good_condition,uncertain_condition)
if self.img is not None:
self.write_CASDA_xml()
def write_pipeline_offset_params(self):
"""Write a txt file with offset params for ASKAPsoft pipeline for user to easily import into config file, and then drop them from metrics.
See http://www.atnf.csiro.au/computing/software/askapsoft/sdp/docs/current/pipelines/ScienceFieldContinuumImaging.html?highlight=offset"""
txt = open('offset_pipeline_params.txt','w')
txt.write("DO_POSITION_OFFSET=true\n")
txt.write("RA_POSITION_OFFSET={0:.2f}\n".format(-self.metric_val['RA Offset']))
txt.write("DEC_POSITION_OFFSET={0:.2f}\n".format(-self.metric_val['DEC Offset']))
txt.close()
for metric in ['RA Offset','DEC Offset']:
self.metric_val.pop(metric)
self.metric_source.pop(metric)
self.metric_level.pop(metric)
self.metric_count.pop(metric)
def write_CASDA_xml(self):
"""Write xml table with all metrics for CASDA."""
tmp_table = Table( [list(self.metric_val.keys()),list(self.metric_val.values()),list(self.metric_level.values()),list(self.metric_source.values())],
names=['metric_name','metric_value','metric_status','metric_description'],
dtype=[str,float,np.int32,str])
vot = votable.from_table(tmp_table)
vot.version = 1.3
table = vot.get_first_table()
table.params.extend([votable.tree.Param(vot, name="project", datatype="char", arraysize="*", value=self.img.project)])
valuefield=table.fields[1]
valuefield.precision='2'
prefix = ''
if self.img.project != '':
prefix = '{0}_'.format(self.img.project)
xml_filename = '{0}CASDA_continuum_validation.xml'.format(prefix)
votable.writeto(vot, xml_filename)
def write_html_end(self,do_source_counts=False,flux_uncertainty=False,pos_uncertainty=False,spec_index=True):
"""Write the end of the html report file (including table of metrics) and close it."""
#Close cross-matches table and write header of validation summary table
self.html.write("""
</td>
</tr>
</table>
<h2 align="middle">{0} continuum validation metrics</h2>
<table class="reportTable">
<tr>
<th>Flux Ratio<br>({0} / {1})</th>
<th>Positional Offset (arcsec)<br>({0} — {2})</th>
""".format(self.cat.name,self.metric_source['Flux Ratio'],self.metric_source['Positional Offset']))
if flux_uncertainty:
self.html.write('<th>Flux Ratio Uncertainty<br>({0} / {1})</th>\n'.format(self.cat.name,self.metric_source['Flux Ratio']))
if pos_uncertainty:
self.html.write('<th>Positional Offset Uncertainty (arcsec)<br>({0} — {1})</th>\n'.format(self.cat.name,self.metric_source['Positional Offset']))
self.html.write("""
<th>Resolved Fraction from int/peak Flux<br>({0})</th>
<th>r.m.s. (uJy)<br>({0})</th>
""".format(self.cat.name))
#assign levels to each metric
self.assign_metric_levels()
if spec_index and 'Spectral Index' in list(self.metric_val.keys()):
self.html.write('<th>Median in-band<br>spectral index</th>\n')
if do_source_counts:
self.html.write('<th>Source Counts χ<sub>red</sub><sup>2</sup><br>({0})</th>\n'.format(self.cat.name))
if self.raw_img is not None:
self.html.write('<th>Number of bad<br>beams ({0})</th>\n'.format(self.cat.name))
#Write table with values of metrics and colour them according to level
self.html.write("""</tr>
<tr>
<td {0}>{1:.2f}</td>
<td {2}>{3:.2f}</td>
""".format(self.html_colour(self.metric_level['Flux Ratio']),self.metric_val['Flux Ratio'],
self.html_colour(self.metric_level['Positional Offset']),self.metric_val['Positional Offset']))
if flux_uncertainty:
self.html.write('<td {0}>{1:.2f}</td>'.format(self.html_colour(self.metric_level['Flux Ratio Uncertainty']),
self.metric_val['Flux Ratio Uncertainty']))
if pos_uncertainty:
self.html.write('<td {0}>{1:.2f}</td>'.format(self.html_colour(self.metric_level['Positional Offset Uncertainty']),
self.metric_val['Positional Offset Uncertainty']))
self.html.write("""
<td {0}>{1:.2f}</td>
<td {2}>{3}</td>
""".format(self.html_colour(self.metric_level['Resolved Fraction']),self.metric_val['Resolved Fraction'],
self.html_colour(self.metric_level['RMS']),self.metric_val['RMS']))
if spec_index and 'Spectral Index' in list(self.metric_val.keys()):
self.html.write('<td {0}>{1:.2f}</td>'.format(self.html_colour(self.metric_level['Spectral Index']),
self.metric_val['Spectral Index']))
if do_source_counts:
self.html.write('<td {0}>{1:.2f}</td>'.format(self.html_colour(self.metric_level['Source Counts Reduced Chi-squared']),
self.metric_val['Source Counts Reduced Chi-squared']))
if self.raw_img is not None:
self.html.write('<td {0}>{1}</td>'.format(self.html_colour(self.metric_level['Bad beams']),
self.metric_val['Bad beams']))
by = ''
if self.cat.name != 'ASKAP':
by = """ by <a href="mailto:[email protected]">Jordan Collier</a>"""
#Close table, write time generated, and close html file
self.html.write("""</tr>
</table>
<p><i>Generated at {0}{1}</i></p>
<?php footer(); ?>
</body>
</html>""".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"),by))
self.html.close()
print("Continuum validation report written to '{0}'.".format(self.name))
def add_html_link(self,target,link,file=True,newline=False):
"""Return the html for a link to a URL or file.
Arguments:
----------
target : string
The name of the target (a file or URL).
link : string
The link to this file (thumbnail file name or string to list as link name).
Keyword Arguments:
------------------
file : bool
The input link is a file (e.g. a thumbnail).
newline : bool
Write a newline / html break after the link.
Returns:
--------
html : string
The html link."""
html = """<a href="{0}">""".format(target)
if file:
html += """<IMG SRC="{0}"></a>""".format(link)
else:
html += "{0}</a>".format(link)
if newline:
html += "<br>"
return html
def text_to_html(self,text):
"""Take a string of text that may include LaTeX, and return the html code that will generate it as LaTeX.
Arguments:
----------
text : string
A string of text that may include LaTeX.
Returns:
--------
html : string
The same text readable as html."""
#this will allow everything between $$ to be generated as LaTeX
html = """
<script type="text/x-mathjax-config">
MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
</script>
<script type="text/javascript"
src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<br>
"""
#write a newline / break for each '\n' in string
for line in text.split('\n'):
html += line + '<br>'
return html
def html_colour(self,level):
"""Return a string representing green, yellow or red in html if level is 1, 2 or 3.
Arguments:
----------
level : int
A validation level.
Returns:
--------
colour : string
The html for green, yellow or red."""
if level == 1:
colour = "id='good'"
elif level == 2:
colour = "id='uncertain'"
else:
colour = "id='bad'"
return colour
def int_peak_flux(self,usePeak=False,overlay=False):
"""Plot the int/peak fluxes as a function of peak flux.
Keyword Arguments:
------------------
usePeak : bool
Use peak flux as x axis, instead of SNR."""
ratioCol = '{0}_int_peak_ratio'.format(self.cat.name)
self.cat.df[ratioCol] = self.cat.df[self.cat.flux_col] / self.cat.df[self.cat.peak_col]
SNR = self.cat.df[self.cat.peak_col]/self.cat.df[self.cat.rms_val]
ratio = self.cat.df[ratioCol]
peak = self.cat.df[self.cat.peak_col]
xaxis = SNR
if usePeak:
xaxis = peak
#plot the int/peak flux ratio
fig = plt.figure(**self.fig_size)
title = "{0} int/peak flux ratio".format(self.cat.name)
if self.plot_to == 'html':
if usePeak:
xlabel = 'Peak flux ({0})'.format(self.cat.flux_unit.replace('j','J'))
else:
xlabel = 'S/N'
ylabel = 'Int / Peak Flux Ratio'
else:
xlabel = r'${\rm S_{peak}'
if usePeak:
xlabel += '}$ (%s)' % self.cat.flux_unit.replace('j','J')
else:
xlabel += r' / \sigma_{rms}}$'
ylabel = r'${\rm S_{int} / S_{peak}}$'
if self.plot_to != 'screen':
filename = '{0}/{1}_int_peak_ratio.{2}'.format(self.figDir,self.cat.name,self.plot_to)
else:
filename = 'screen'
#get non-nan data shared between each used axis as a numpy array
x,y,c,indices = self.shared_indices(xaxis,yaxis=ratio)#,caxis=self.cat.dec[self.cat.name])
plt.loglog()
plt.gca().grid(b=True, which='minor', color='w', linewidth=0.5)
#hack to overlay resolved sources in red
xres,yres= xaxis[self.cat.resolved],ratio[self.cat.resolved]
markers = self.markers.copy()
markers['color'] = 'r'
markers.pop('s')
data, = plt.plot(xres,yres,'o',zorder=50,**markers)
leg_labels = ['Resolved','Unresolved']
#derive the statistics of y and store in string
ymed,ymean,ystd,yerr,ymad = get_stats(ratio)
txt = '$\widetilde{Ratio}$: %.2f\n' % ymed
txt += '$\overline{Ratio}$: %.2f\n' % ymean
txt += '$\sigma_{Ratio}$: %.2f\n' % ystd
txt += '$\sigma_{\overline{Ratio}}$: %.2f\n' % yerr
txt += 'MAD Ratio: %.2f' % ymad
#store median int/peak flux ratio and write to report table
self.int_peak_ratio = ymed
self.html.write('<td>{0:.2f} ± {1:.2f}<br>'.format(ymed,ymad))
#plot the int/peak flux ratio
self.plot(x,
y=y,
c=c,
figure=fig,
line_funcs=[self.y1],
title=title,
xlabel=xlabel,
ylabel=ylabel,
text=txt,
loc='tl',
axis_perc=0,
filename=filename,
leg_labels=leg_labels,
handles=[data],
overlay=overlay,
redo=self.redo)
def in_band_si(self,overlay=False):
"""Plot the in-band spectral index (Selavy only)."""
xaxis = '{0}_spectral_index'.format(self.cat.name)
#plot the in-band spectral index
fig = plt.figure(**self.fig_size)
plt.xlim(-3,2)
title = "{0} in-band Spectral Index".format(self.cat.name)
filename = 'screen'
if self.plot_to != 'screen':
filename = '{0}/{1}_in_band_spectal_index.{2}'.format(self.figDir,self.cat.name,self.plot_to)
#get non-nan data shared between each used axis as a numpy array
x,y,c,indices = self.shared_indices(xaxis)
x = x[x != -99]
#format labels according to destination of figure
freq = int(round(self.cat.freq[self.cat.name]))
if self.plot_to == 'html':
xlabel = 'In-band \u03B1 [{0} MHz]'.format(freq)
else:
xlabel = r'In-band $\alpha$ [{0} MHz]'.format(freq)
#derive the statistics of x and store in string
alpha_med,alpha_mean,alpha_std,alpha_err,alpha_mad = get_stats(x)
txt = '$\widetilde{\\alpha}$: %.2f\n' % alpha_med
txt += '$\overline{\\alpha}$: %.2f\n' % alpha_mean
txt += '$\sigma_{\\alpha}$: %.2f\n' % alpha_std
txt += '$\sigma_{\overline{\\alpha}}$: %.2f\n' % alpha_err
txt += 'MAD $\\alpha$: %.2f' % alpha_mad
#write the spectral index to html report table
self.html.write("""</td>
<td>{0:.2f} ± {1:.2f}<br>""".format(alpha_med,alpha_mad))
#plot the spectral index
self.plot(x,
figure=fig,
title=title,
xlabel=xlabel,
ylabel='N',
axis_perc=0,
filename=filename,
text=txt,
loc='tl',
overlay=overlay,
redo=self.redo)
self.html.write("""</td>""")
def PSFs(self,raw_img,threshold=15,overlay=False):
"""Plot the PSFs per beam."""
self.num_bad_beams = 0
if raw_img is not None:
#plot the PSFs per beam
fig = plt.figure(**self.fig_size)
title = "{0} PSFs per beam".format(self.cat.name)
filename = 'screen'
if self.plot_to != 'screen':
filename = '{0}/{1}_PSFs.{2}'.format(self.figDir,self.cat.name,self.plot_to)
psf_table = fits.open(raw_img)[1].data
RAs = psf_table['RA']
if np.all(RAs < 0):
RAs += 360
#get non-nan data shared between each used axis as a numpy array
x,y,c,indices = self.shared_indices(RAs,yaxis=psf_table['Dec'])
xlabel = 'RA (deg)'
ylabel = 'Dec (deg)'
ellipses=[]
for i in range(psf_table['BMAJ'].size):
if psf_table['BMAJ'][i] > threshold:
color = 'red'
else:
color = 'black'
e = Ellipse((psf_table['RA'][i],psf_table['DEC'][i]),width=2*psf_table['BMAJ'][i]/60.0,height=2*psf_table['BMIN'][i]/60.0,angle=psf_table['BPA'][i],color=color,fill=False,zorder=10,linewidth=3)
ellipses.append(e)
ellipses.append(Ellipse((axis_lim(psf_table['RA'],min,0.5),axis_lim(psf_table['Dec'],min,0.5)),width=2*threshold/60.0,height=2*threshold/60.0,color='blue',fill=False,zorder=10,linewidth=3))
#number of beams with BMAJ over threshold (assuming BMIN always < BMAJ)
num_bad_beams = np.where(psf_table['BMAJ'] > threshold)[0].size
self.num_bad_beams = num_bad_beams
#derive the statistics of x and store in string
BMAJ_med,BMAJ_mean,BMAJ_std,BMAJ_err,BMAJ_mad = get_stats(psf_table['BMAJ'])
txt = 'Number of beams before convolution with PSF > {0} arcsec: {1}\n'.format(threshold,num_bad_beams)
txt += '$\widetilde{BMAJ}$: %.2f\n' % BMAJ_med
txt += '$\overline{BMAJ}$: %.2f\n' % BMAJ_mean
labels = ['{0:.1f} x {1:.1f}"'.format(BMAJ,BMIN) for BMAJ,BMIN in zip(psf_table['BMAJ'],psf_table['BMIN'])]
#leg_labels = ['Good beams','Bad beams','Convolved beam']
#write the number of bad beams to html report table
self.html.write("""<td>{0}<br>""".format(num_bad_beams))
#plot the PSFs per beam
self.plot(x,
y=y,
figure=fig,
title=title,
xlabel=xlabel,
ylabel=ylabel,
ellipses=ellipses,
axis_perc=1,
alpha=0.0,
filename=filename,
text=txt,
loc='tl',
labels=labels,
overlay=overlay,
projection=self.img.w,
redo=self.redo)
self.html.write("""</td>""")
def resid_RMS(self,resid_img,sigma=3.0):
"""Calculate the RMS using the Selavy component residual."""
if resid_img is not None:
img = fits.open(resid_img)
dat = img[0].data[~np.isnan(img[0].data)]
img.close()
med = np.median(dat)
mad = np.median(np.abs(dat - med))
std = 1.4826 * mad
mask = np.abs(dat) > med + sigma*std
dat = dat[~mask]
RMS = np.sqrt(np.mean(dat**2))
self.cat.img_rms = int(RMS*1e6)
def source_counts(self,fluxes,freq,rms_map=None,solid_ang=0,overlay=False,write=True):
"""Compute and plot the (differential euclidean) source counts based on the input flux densities.
Arguments:
----------
fluxes : list-like
A list of fluxes in Jy.
freq : float
The frequency of these fluxes in MHz.
Keyword arguments:
------------------
rms_map : str
A path to a fits image of the local rms in Jy.
solid_ang : float
A fixed solid angle over which the source counts are computed. Only used when rms_map is None.
write : bool
Write the source counts to file."""
mask = fluxes > 0 #self.cat.df[self.cat.flux_col] / self.cat.df[self.cat.rms_val] > 10
fluxes = fluxes[mask]
#derive file names based on user input
filename = 'screen'
counts_file = '{0}_source_counts.csv'.format(self.cat.basename)
if self.plot_to != 'screen':
filename = '{0}/{1}_source_counts.{2}'.format(self.figDir,self.cat.name,self.plot_to)
#read the log of the source counts from Norris+11 from same directory of this script
df_Norris = pd.read_table('{0}/all_counts.txt'.format(self.main_dir),sep=' ')
x = df_Norris['S']-3 #convert from log of flux in mJy to log of flux in Jy
y = df_Norris['Counts']
yerr = (df_Norris['ErrDown'],df_Norris['ErrUp'])
#fit 6th degree polynomial to Norris+11 data
deg = 6
poly_paras = np.polyfit(x,y,deg)
f = np.poly1d(poly_paras)
xlin = np.linspace(min(x)*1.2,max(x)*1.2)
ylin = f(xlin)
#perform source counts if not already written to file or user specifies to re-do
if not os.path.exists(counts_file) or self.redo:
#warn user if they haven't input an rms map or fixed solid angle
if rms_map is None and solid_ang == 0:
warnings.warn_explicit("You must input a fixed solid angle or an rms map to compute the source counts!\n",UserWarning,WARN,cf.f_lineno)
return
#get the number of bins from the user
nbins = self.src_cnt_bins
print("Deriving source counts for {0} using {1} bins.".format(self.cat.name,nbins))
#Normalise the fluxes to 1.4 GHz
fluxes = flux_at_freq(1400,freq,fluxes,-0.8)
#Correct for Eddington bias for every flux, assuming Hogg+98 model
r = self.cat.df[self.cat.flux_col][mask] / self.cat.df[self.cat.rms_val][mask]
slope = np.polyder(f)
q = 1.5 - slope(fluxes)
bias = 0.5 + 0.5*np.sqrt(1 - (4*q+4)/(r**2))
#q is derived in log space, so correct for the bias in log space (for non-nan values)
fluxes = 10**(np.log10(fluxes[~np.isnan(bias)])/bias[~np.isnan(bias)])
if rms_map is not None:
rms_map_data = fits.open(rms_map)[0]
w = WCS(rms_map_data.header)
if self.verbose:
print("Using rms map '{0}' to derive solid angle for each flux bin.".format(rms_map))
total_area = get_pixel_area(rms_map_data, flux=100, w=w)[0]
else:
total_area = 0
#add one more bin and then discard it, since this is dominated by the few brightest sources
#we also add one more to the bins since there's one more bin edge than number of bins
edges = np.percentile(fluxes,np.linspace(0,100,nbins+2))
dN,edges,patches=plt.hist(fluxes,bins=edges)
dN = dN[:-1]
edges = edges[:-1]
#derive the lower and upper edges and dS
lower = edges[:-1]
upper = edges[1:]
dS = upper-lower
S = np.zeros(len(dN))
solid_angs = np.zeros(len(dN))