-
Notifications
You must be signed in to change notification settings - Fork 1
/
IQA_script.py
3089 lines (2708 loc) · 130 KB
/
IQA_script.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
#########################################################
## Image Quality Assessment (IQA) scripts for CASA
##
## Created: Feb. 2020
## Last modified: Dec. 2022
## Authors:
## 1.- Genearal IQA tests: Alvaro Hacar (alvaro.hacar@univie.ac.at)
## 2.- Power spectra: Nickolas Pingel (Nickolas.Pingel@anu.edu.au), Dirk Petry (dpetry@eso.org)
## 3.- Aperture methods: Brian Mason (bmason@nrao.edu), Alvaro Hacar (alvaro.hacar@univie.ac.at)
##
#########################################################
##############################################################################################
# 1.- General IQA tests
# Script to obtain general IQA tests (Aperture, Fidelity, Differences) for both continuum and cube images
#
# authors: Alvaro Hacar (alvaro.hacar@univie.ac.at)
## Functions
## keywords
##
## FITSfile = path to FITS file
## convo_file = path to CASA image to be convolved
## beam_final = final beamsize (in arcsec)
## target_image = target image (e.g., Interferometric image)
## ref_image = reference image (e.g., TP image)
##
##-------------------------------------------------------
## Imports
from scipy import fftpack
from astropy.io import fits
import numpy as np
import pylab as py
import matplotlib.pyplot as plt
import os
import copy
from numpy import inf
from matplotlib.colors import LogNorm
from scipy.stats import kurtosis, skew
#import casatools# as cto
#import casatasks# as cta
from casatasks import *
from casatools import image as iatool
ia = iatool()
## IQA colours
#IQA_colours = ["red", "blue", "orange", "green" , "cyan", "pink", "brown","yellow","magenta","black"]
## IQA colours (color blind friendly CMRmap scale)
start = 0.0
stop = 1.0
number_of_lines= 8
cm_subsection = np.linspace(start, stop, number_of_lines)
IQA_colours = [ plt.cm.CMRmap(x) for x in cm_subsection ]
IQA_colours = IQA_colours[1:7]
IQA_colours = [IQA_colours[0],IQA_colours[5],IQA_colours[2],IQA_colours[4],IQA_colours[1],IQA_colours[3]]
IQA_colours = ["#d73027", "#fc8d59", "#fee090", "#91bfdb", "#4575b4"]
IQA_colours = ["red", "blue", "orange", "green" , "cyan", "pink", "brown","yellow","magenta","black"]
##-------------------------------------------------------
## Image manipulation
## Convert FITS files into CASA images
def fits2CASA(FITSfile):
print(FITSfile)
os.system("rm -rf "+ FITSfile+".image")
importfits(fitsimage=FITSfile,imagename=FITSfile+'.image')
## Convert FITS files into CASA images
def CASA2fits(CASAfile):
print(CASAfile)
os.system("rm -rf "+ CASAfile+".fits")
exportfits(imagename=CASAfile,fitsimage=CASAfile+".fits")
def CASA2fits_drop(CASAfile):
print(CASAfile)
os.system("rm -rf "+ CASAfile+".fits")
exportfits(imagename=CASAfile,fitsimage=CASAfile+".fits",dropdeg=True)
## same as fits2CASA but for a list of FITS
def fitslist2CASA(FITSfile):
for i in FITSfile:
print(i)
os.system("rm -rf "+ i+".image")
importfits(fitsimage=i,imagename=i+'.image')
## Convolve CASA image with a final resolution (beam_final)
def get_convo(convo_file,beam_final):
imsmooth(imagename= convo_file,
outfile= convo_file + '_conv' + str(beam_final),
kernel='gauss',
major=str(beam_final)+'arcsec',
minor=str(beam_final)+'arcsec',
pa='0deg',
targetres=True)
## same as get_convo but for FITS files
def getFITS_convo(FITSfile,beam_final):
# FITS into CASA
convo_file = FITSfile+'.image'
os.system("rm -rf "+convo_file)
importfits(fitsimage=FITSfile,imagename=convo_file)
# convolution
imsmooth(imagename= convo_file,
outfile= convo_file + '_conv' + str(beam_final),
kernel='gauss',
major=str(beam_final)+'arcsec',
minor=str(beam_final)+'arcsec',
pa='0deg',
targetres=True)
## Convolve CASA image with a final resolution (beam_final)
#def get_convo2target(convo_file,ref_image):
# # Get beam info from refence image
# hdr = imhead(ref_image,mode='summary')
# beam_major = hdr['restoringbeam']['major']
# beam_minor = hdr['restoringbeam']['minor']
# beam_PA = hdr['restoringbeam']['positionangle']
# # Convolution into the same beam as the reference
# os.system("rm -rf " + convo_file + '_conv' + str(round(beam_major['value'])))
# imsmooth(imagename= convo_file,
# outfile= convo_file + '_conv' + str(round(beam_major['value'])),
# kernel='gauss',
# major=beam_major,
# minor=beam_minor,
# pa=beam_PA,
# targetres=True)
def get_beam(image):
# Get beam info from image: return [maj, min, pa, effbeamsize]
hdr = imhead(image,mode='summary')
beam_major = hdr['restoringbeam']['major']
beam_minor = hdr['restoringbeam']['minor']
beam_PA = hdr['restoringbeam']['positionangle']
effbeamsize = np.sqrt((beam_major.get("value")**2.)/2. + (beam_minor.get("value")**2.)/2.)
return [beam_major, beam_minor, beam_PA, effbeamsize]
## same as get_convo2target but for FITS
def getFITS_convo2target(convo_file,ref_image):
# FITS into CASA
convo_file = FITSfile+'.image'
os.system("rm -rf "+convo_file)
importfits(fitsimage=FITSfile,imagename=convo_file)
# Get beam info from refence image
hdr = imhead(ref_image,mode='summary')
beam_major = hdr['restoringbeam']['major']
beam_minor = hdr['restoringbeam']['minor']
beam_PA = hdr['restoringbeam']['positionangle']
# Convolution into the same beam as the reference
os.system("rm -rf tmp.tmp")
imsmooth(imagename= convo_file,
outfile= "tmp.tmp",
kernel='gauss',
major=beam_major,
minor=beam_minor,
pa=beam_PA,
targetres=True)
os.system("rm -rf convo2ref")
imregrid(imagename= "tmp.tmp",
template= ref_image,
output= 'convo2ref')
os.system("rm -rf tmp.tmp")
## Convolve CASA image with a final resolution (beam_final)
def get_convo2target(convo_file,ref_image):
# Get beam info from refence image
hdr = imhead(ref_image,mode='summary')
beam_major = hdr['restoringbeam']['major']
beam_minor = hdr['restoringbeam']['minor']
beam_PA = hdr['restoringbeam']['positionangle']
ref_unit = hdr['unit']
# Convolution into the same beam as the reference
os.system("rm -rf tmp.tmp")
imsmooth(imagename= convo_file,
outfile= "tmp.tmp",
kernel='gauss',
major=beam_major,
minor=beam_minor,
pa=beam_PA,
targetres=True)
#imhead(convo_file, mode='put', hdkey='Bunit', hdvalue=ref_unit)
os.system("rm -rf convo2ref")
imregrid(imagename= "tmp.tmp",
template= ref_image,
output= 'convo2ref')
imhead('convo2ref', mode='put', hdkey='Bunit', hdvalue=ref_unit) # Lydia's modification to avoid lost bunits
os.system("rm -rf tmp.tmp")
## Resample
def resample_velaxis(image,template):
os.system('rm -rf '+image+'_resvel')
imregrid(imagename= image,
template= template,
axes=[2],
output= image+'_resvel')
## Add gaussian noise to an image
def addnoise(image,noiselevel):
os.system("tm -rf " + image + "_gaussnoise")
os.system("cp -r " + image + " " + image + "_gaussnoise")
ia.open(image + "_gaussnoise")
ia.addnoise(type="normal",pars=[0,noiselevel])
ia.close()
print(image + "_gaussnoise file created")
# Mask data (typically reference image)
def mask_image(myimage,threshold=0.0,relative=False):
"""
mask_image (A. Hacar, Univ. of Vienna)
Mask an image (typicaly your reference) below an intensity threshold.
Thresholding is recommended to avoid noisy data in many of the IQA tests
Arguments:
myimage - image to be masked
threshold - value for thresholding
relative - (default False)
False = threshold is taken as absolute value (see image flux units)
True = threshold value is measured as rms fraction (aka sigma)
"""
print("=========================================")
print(" mask_image(): masking image ")
print("=========================================")
print(" Original image : " + str(myimage))
# Create a copy of your image
os.system('rm -rf masked.tmp')
os.system('cp -r ' + str(myimage) + ' masked.tmp')
# Create your mask
ia.open('masked.tmp')
if (relative == False):
ia.calcmask(mask= 'masked.tmp >= '+str(threshold), name='mymask')
if (relative == True):
ima_sigma = imstat(myimage)["rms"][0]
ia.calcmask(mask= 'masked.tmp >= '+str(threshold*ima_sigma), name='mymask')
ia.close()
os.system('mv masked.tmp ' + str(myimage) + '_masked')
#makemask(mode='copy',inpimage='masked.tmp',inpmask=['masked.tmp:mymask'],output=str(myimage) + '_masked',overwrite=True)
print(" New masked image : " + str(myimage) + '_masked')
print("-----------------------------------------")
print(" mask_image(): DONE ")
print("=========================================")
# Check if images have the same axis order as reference
def check_axis(ref_image,target_im=[]):
print("=========================================")
print(" check_axis(): checking axis consistency ")
print("=========================================")
# reference: check axis
axis_ref = imhead(ref_image).get("axisnames")
print(" Reference image: " + str(ref_image))
print(" Axis : ("),
for j in np.arange(np.shape(axis_ref)[0]):
print(axis_ref[j] + " "),
print(")")
print("-----------------------------------------")
# Targets: check axis
n = 0
for i in target_im:
n = n+1
axis_target = imhead(i).get("axisnames")
print(" Target image #" + str(n) + ": " + str(i))
print(" Axis : ("),
transpose = -1
for j in np.arange(np.shape(axis_target)[0]):
print(axis_target[j] + " "),
if (axis_ref[j] != axis_target[j]):
transpose = j
print(")")
if (transpose != -1):
print(" WARNING: Axis do not match reference -> transpose OR drop axis")
print(" (see also drop_axis function)")
print("-----------------------------------------")
print(" check_axis(): DONE ")
print("=========================================")
def drop_axis(myimage):
"""
drop_axis (A. Hacar, Univ. of Vienna)
Drop unnecesary axis (e.g. Stokes)
Arguments:
myimage : image wher drop_axis will be applied (CASA image)
Notes:
Check axis consistency with check_axis()
Usage:
drop_axis(myimage)
"""
print("=================================================")
print(" drop_axis(): drop additional axis (e.g. Stokes) ")
print("=================================================")
# reference: check axis
os.system("rm -rf " + myimage + "_subimage")
imsubimage(imagename=myimage,outfile=myimage + "_subimage",dropdeg=True,stretch=True)
print(" Reference image: " + str(myimage))
print(" New image: " + str(myimage) +"_subimage")
print("-----------------------------------------")
print(" drop_axis(): DONE ")
print("=========================================")
##-------------------------------------------------------
## Quality estimators
## see a detailed discussion in: https://library.nrao.edu/public/memos/ngvla/NGVLA_67.pdf
## Calculate Image Accuracy parameter (Apar)
def image_Apar(image,ref_image):
"""
image_Apar (A. Hacar, Univ. of Vienna)
Function to generate A-par maps
A-par is defined as the relative error between the target and reference images:
Apar = (image-reference)/abs(reference)
Arguments:
image - target image
ref_image - reference image
(Note that the target image should have the same resolution as the target one)
Outputs:
str(image)+'_Apar' - A-par image
Description:
A=0 - Perfect image
A>1 - target image overestimates the expected flux in the reference
A<1 - target image underestimates the expected flux in the reference
A value - relative difference (in %) between the target and the reference
"""
# Resampling
os.system('rm -rf tmp_resampled')
imregrid(imagename= image,
template= ref_image,
#axes=[0, 1],
output= 'tmp_resampled')
os.system('rm -rf ' + image + '_Apar')
# Q parameter
immath(imagename=['tmp_resampled',ref_image],
outfile= image + '_Apar',
expr='(IM0-IM1)/abs(IM1)')
# Clean-up
os.system('rm -rf tmp_resampled')
## Calculate image Fidelity
def image_Fidelity(image,ref_image):
"""
image_Fidelity (A. Hacar, Univ. of Vienna)
Function to generate Fidelity maps
Fidelity is defined as the ratio between the reference image and the difference between
target and the reference images all in absolute terms:
Fidelity = abs(reference)/abs(image-reference)
Arguments:
image - target image
ref_image - reference image
(Note that the target image should have the same resolution as the reference one)
Outputs:
str(image)+'_fidelity' - Fidelity image
Description:
The higher the fidelity, the better correspondance between the target and the reference images
"""
# Resampling
os.system('rm -rf tmp_resampled')
imregrid(imagename= image,
template= ref_image,
#axes=[0, 1],
output= 'tmp_resampled')
# Fidelity parameter
os.system('rm -rf ' + image + '_Fidelity')
immath(imagename=['tmp_resampled',ref_image],
outfile= image + '_Fidelity',
expr='abs(IM1)/abs(IM1-IM0)')
# Clean-up
os.system('rm -rf tmp_resampled')
## Calculate image Difference
def image_Diff(image,ref_image):
"""
Generate difference image: Difference = reference-image
Arguments:
image - target CASA image
ref_image - CASA image used as reference
Output:
str(image)+'_Diff' = Difference CASA image
"""
# Resampling
os.system('rm -rf tmp_resampled')
imregrid(imagename= image,
template= ref_image,
#axes=[0, 1],
output= 'tmp_resampled')
# Fidelity parameter
os.system('rm -rf ' + image + '_Diff')
immath(imagename=['tmp_resampled',ref_image],
outfile= image + '_Diff',
expr='IM1-IM0')
# Clean-up
os.system('rm -rf tmp_resampled')
def noise_image(fitsfile,noise=0.1,noisefile="noise"):
"""
Generate a nosie FITS with similar properties than fitsfile
Arguments:
fitsfile - FITS file used as template
noise - noise level (in whatever units if fitsfile)
noisefile - name of the file where the results will be stored (default = "noise"+".fits"
Output:
str(noisefile)+'.fits' - FITS noise file
"""
# Read Templeate
hdu = fits.open(fitsfile)
# Copy maks
mask = np.isnan(hdu[0].data)
# Create a noise dataset
hdu[0].data = np.random.normal(0.,noise,(hdu[0].data.shape[0],hdu[0].data.shape[1])) # Noise image
#
hdu[0].data[mask] = np.nan
# Write to file
fits.writeto(noisefile+".fits",data=hdu[0].data,header=hdu[0].header,overwrite=True)
##-------------------------------------------------------
## Wrappers
# IQA methods: Accuracy, Fidelity, etc...
def get_IQA(ref_image = '',target_image=[''], pb_image=None, masking_RMS=None,
target_beam_index=0): #, pbval=0.2):
"""
get_IQA (A. Hacar, Univ. of Vienna; Dirk Petry, ESO)
Obtain all Image Quality Assesment images
Arguments:
ref_image - image used as reference
target_image - list of images to be compared with reference
pb_image - primary beam image needed to evaluate assessment area
masking_RMS - masking RMS in units of Jy/beam of the targer_image (e.g. Interferometric image)
Assesssing Mask: AM = 3*masking_RMS*1/PB*(beam_ref/beam_target)
(see main paper for further details)
Note that ideally masking_RMS should correspond to 3*RMS_target, that is, the noise level of the Interferometric images
target_beam_index - defines which target_image is used to evaluate the targetbeam
#pbval - flux level for PB-cutoff-mask
Procedure:
1.- Each target image will be convolved and resapled into the ref_image resolution and grid.
Results are stored in: target_image[i]_convo2ref
2.- The new target_image[i]_convo2ref image is then used to obtain different IQA tests, namely:
a) Accuracy: target_image[i]_convo2ref_Apar
b) Fidelity: target_image[i]_convo2ref_Fidelity
3.- All results are exported into FITS
Notes:
- Depending on the image/cube size, this process may take a while
- Exectute this script to procude the Apar, Fidelity,... images. This script only needs to be executed once
Example:
get_IQA(ref_image = 'TP_image',target_image=['Feather.image','TP2vis.image'], pb_image='Feather.pb', masking_RMS=0.1, target_beam_index=0)
"""
# Reference image
print("=============================================")
print(" get_IQA(): Obtain IQA estimators")
print(" Reference : "+ str(ref_image))
print(" Depending on the image/cube size, this process may take a while...")
print("---------------------------------------------")
# Target images
do_mask=False
# Mask based on PBcor + Threshold
if(pb_image!=None and masking_RMS!=None):
do_mask=True
myrefbeaminfo = get_beam(ref_image)
effrefbeam = myrefbeaminfo[3]
#pbval = str(pbval)
# convolve PB image to reference resolution
get_convo2target(pb_image,ref_image)
os.system("rm -rf " + pb_image + "_convo2ref")
os.system("mv convo2ref " + pb_image + "_convo2ref")
mybeaminfo = get_beam(target_image[target_beam_index])
efftargetbeam = mybeaminfo[3]
# compute masking threshold image temp.mask
os.system("rm -rf " + target_image[target_beam_index]+'_thrsh')
immath(imagename=[pb_image+'_convo2ref'], outfile=target_image[target_beam_index]+'_thrsh', expr='3*'+str(masking_RMS)+'*'+str(effrefbeam)+'/'+str(efftargetbeam)+'/IM0')
print(" Targetbeam = " +str(efftargetbeam))
print(" Masking_RMS (at Target res.) = " +str(masking_RMS))
print(" Refbeam = " +str(effrefbeam))
print(" Masking threshold (at Reference res.) = " +str(3.*masking_RMS*effrefbeam/efftargetbeam)+" *1/PB")
ia.open(target_image[target_beam_index]+'_thrsh')
print(target_image[target_beam_index]+'_thrsh = ', ia.shape())
ia.close()
#os.system("rm -rf temp_1.mask")
os.system("rm -rf temp.mask temp.mask_subimage")
immath(imagename=[ref_image,target_image[target_beam_index]+'_thrsh'], outfile='temp.mask', expr='iif(IM0>IM1,1,0)')
ia.open("temp.mask")
print("temp.mask = ", ia.shape())
ia.close()
#immath(imagename=[ref_image,target_image[target_beam_index]+'_thrsh'], outfile='temp_1.mask', expr='iif(IM0>IM1,1,0)')
#immath(imagename=['temp_1.mask',pb_image], outfile='temp.mask', expr='IM0[IM1>'+pbval+']')
# Masking also the reference
os.system("rm -rf "+ ref_image + "_masked")
# drop axis leads to crash!
drop_axis("temp.mask") # Regridding mask to ref_image (remove/add extra dim)
ia.open("temp.mask_subimage")
print("temp.mask_subimage = ", ia.shape())
ia.close() #immath(imagename=[ref_image,pb_image],mode='evalexpr',expr='IM0[IM1>'+pbval+']',outfile=ref_image+'_masked',mask='temp.mask')#_subimage')
ia.open(ref_image)
print(ref_image, " = ", ia.shape())
ia.close()
immath(imagename=ref_image,mode='evalexpr',expr='IM0',outfile=ref_image+'_masked',mask='temp.mask')#_subimage')
exportfits(imagename=ref_image + "_masked",fitsimage=ref_image + "_masked.fits",dropdeg=True,overwrite=True)
# Mask based on Threshold (only) without PBcorr
if(pb_image==None and masking_RMS!=None):
do_mask=True
myrefbeaminfo = get_beam(ref_image)
effrefbeam = myrefbeaminfo[3]
#pbval = str(pbval)
# Create fake PB image and do the same as above
os.system("rm -rf fake_pb_image")
immath(imagename=target_image[0],expr='IM0*0+1.',outfile="fake_pb_image") # flat PB image = 1.
pb_image = "fake_pb_image"
#ia.open("fake_pb_image")
imhead(pb_image,mode='put',hdkey='bunit',hdvalue='') # remove Jy/beam units
#ia.close()
get_convo2target(pb_image,ref_image)
os.system("rm -rf " + pb_image + "_convo2ref")
os.system("mv convo2ref " + pb_image + "_convo2ref")
mybeaminfo = get_beam(target_image[target_beam_index])
efftargetbeam = mybeaminfo[3]
# compute masking threshold image temp.mask
os.system("rm -rf " + target_image[target_beam_index]+'_thrsh')
immath(imagename=[pb_image+'_convo2ref'], outfile=target_image[target_beam_index]+'_thrsh', expr='3*'+str(masking_RMS)+'*'+str(effrefbeam)+'/'+str(efftargetbeam)+'/IM0')
print(" Targetbeam = " +str(efftargetbeam))
print(" Masking_RMS (at Target res.) = " +str(masking_RMS))
print(" Refbeam = " +str(effrefbeam))
print(" Masking threshold (at Reference res.) = " +str(3.*masking_RMS*effrefbeam/efftargetbeam))
ia.open(target_image[target_beam_index]+'_thrsh')
print(target_image[target_beam_index]+'_thrsh = ', ia.shape())
ia.close()
#os.system("rm -rf temp_1.mask")
os.system("rm -rf temp.mask temp.mask_subimage")
immath(imagename=[ref_image,target_image[target_beam_index]+'_thrsh'], outfile='temp.mask', expr='iif(IM0>IM1,1,0)')
ia.open("temp.mask")
print("temp.mask = ", ia.shape())
ia.close()
#immath(imagename=[ref_image,target_image[target_beam_index]+'_thrsh'], outfile='temp_1.mask', expr='iif(IM0>IM1,1,0)')
#immath(imagename=['temp_1.mask',pb_image], outfile='temp.mask', expr='IM0[IM1>'+pbval+']')
# Masking also the reference
os.system("rm -rf "+ ref_image + "_masked")
# drop axis leads to crash!
drop_axis("temp.mask") # Regridding mask to ref_image (remove/add extra dim)
ia.open("temp.mask_subimage")
print("temp.mask_subimage = ", ia.shape())
ia.close() #immath(imagename=[ref_image,pb_image],mode='evalexpr',expr='IM0[IM1>'+pbval+']',outfile=ref_image+'_masked',mask='temp.mask')#_subimage')
ia.open(ref_image)
print(ref_image, " = ", ia.shape())
ia.close()
immath(imagename=ref_image,mode='evalexpr',expr='IM0',outfile=ref_image+'_masked',mask='temp.mask')#_subimage')
exportfits(imagename=ref_image + "_masked",fitsimage=ref_image + "_masked.fits",dropdeg=True,overwrite=True)
for j in np.arange(0,np.shape(target_image)[0],1):
# print file
print(" Target image " + str(j+1) + " : " + str(target_image[j]))
# Convolve data into reference resolution
get_convo2target(target_image[j],ref_image)
# Mask it
os.system("rm -rf " + target_image[j] + "_convo2ref_masked")
if do_mask:
drop_axis('convo2ref')
immath(imagename='convo2ref_subimage',mode='evalexpr',expr='IM0',outfile='convo2ref_masked',mask='temp.mask_subimage')
else:
immath(imagename='convo2ref',mode='evalexpr',expr='IM0',outfile='convo2ref_masked',mask='mask("'+str(ref_image)+'")')
os.system("rm -rf " + target_image[j] + "_convo2ref")
os.system("mv convo2ref_masked " + target_image[j] + "_convo2ref")
#
# Get Apar, Fidelity, etc... images
image_Apar(target_image[j] + "_convo2ref",ref_image)
image_Fidelity(target_image[j] + "_convo2ref",ref_image)
image_Diff(target_image[j] + "_convo2ref",ref_image)
# export into FITS
os.system('rm -rf '+target_image[j] + "_convo2ref*.fits")
exportfits(imagename=target_image[j] + "_convo2ref",fitsimage=target_image[j] + "_convo2ref.fits",dropdeg=True)
exportfits(imagename=target_image[j] + "_convo2ref_Apar",fitsimage=target_image[j] + "_convo2ref_Apar.fits",dropdeg=True)
exportfits(imagename=target_image[j] + "_convo2ref_Fidelity",fitsimage=target_image[j] + "_convo2ref_Fidelity.fits",dropdeg=True)
exportfits(imagename=target_image[j] + "_convo2ref_Diff",fitsimage=target_image[j] + "_convo2ref_Diff.fits",dropdeg=True)
print(" See results in " +target_image[j] + "_convo2ref* images")
print("---------------------------------------------")
print(" IQA estimators... DONE")
print("=============================================")
# Tools for continuum and/or mom0 maps
# Accuracy parameter comparisons
def Compare_Apar(ref_image = '',target_image=[''],adjustDR=True,
save=False, plotname='',
labelname=[''], titlename=''):
"""
Compare all Apar images (continuum or mom0 maps) (A. Hacar, Univ. of Vienna)
Arguments:
ref_image - image used as reference
target_image - list of images to be compared with reference
adjustDR - adjust DR in plot
save - save plot? (default = False)
Requires:
The script will look for target_image[i]_convo2ref_Apar.fits images produced by the get_IQA() script
Results:
1- Histogram including the Apar distributions for all input images
2- Numerical results: Total flux in the image, mean + std + kurtosis + skewness of each histogram
Example:
Compare_Apar(ref_image = 'TP_image',target_image=['Feather.image','TP2vis.image'])
"""
# Reference image
print("=============================================")
print(" A-par: comparisons")
print(" Reference : "+str(ref_image+"_masked.fits"))
flux0 = np.round(imstat(ref_image+"_masked.fits")["flux"][0])
print(" Total Flux = " + str(flux0) + " Jy")
print("---------------------------------------------")
# Number of plots
Nplots = np.shape(target_image)[0]
# Global comparisons
plt.figure(figsize=(8,11))
grid = plt.GridSpec(ncols=1,nrows=5, wspace=0.3, hspace=0.3)
ax1 = plt.subplot(grid[0:4, 0])
# get y-max value
hmax = -10.
# Loop over all images
for m in np.arange(Nplots):
# Get total flux in image
flux = np.round(imstat(target_image[m]+"_convo2ref.fits")["flux"][0])
# Extract values from file
nchans, b, mids, h = get_ALLvalues(FITSfile=target_image[m]+"_convo2ref_Apar.fits",xmin=-1.525,xmax=1.525,xstep=0.025)
if (np.max(h) > hmax):
hmax = np.max(h)
# Get mean and std
meanvalue = np.round(np.average(mids,weights=h),2)
########sigmavalue = np.round(np.sqrt(np.cov(mids, aweights=h)),2)
sigmavalue = np.round(np.average((mids - meanvalue)**2, weights=h),2)
# Get skewness and kurtosis of the Apar image
hdu = fits.open(target_image[m]+"_convo2ref_Apar.fits")
Adist = hdu[0].data.flatten()
Adist = Adist[(Adist <= 10.) & (Adist >= -10.)] # remove big outlayers
skewness = np.round(skew(Adist),3)
kurt = np.round(kurtosis(Adist),3)
median = np.round(np.median(Adist),3)
peak = np.round(mids[np.where(h == np.nanmax(h))],3)
# Plot results
if labelname[m]=='':
ax1.plot(mids,h,label=target_image[m] + "; A-par = "+ str(meanvalue) + " +/- " + str(sigmavalue) + "; Flux recovered= " + str(np.round(100.*flux/flux0,1))+"%",linewidth=3,c=IQA_colours[m])
else:
ax1.plot(mids,h,label=labelname[m] + "; A-par = "+ str(meanvalue) + " +/- " + str(sigmavalue) + "; Flux recovered = " + str(np.round(100.*flux/flux0,1))+"%",linewidth=3,c=IQA_colours[m])
# Print results on screen
print(" Target image " + str(m+1) + " : " + str(target_image[m]))
print(" Total Flux = " + str(flux) + " Jy ("+str(np.round(100.*flux/flux0,1))+"\%)")
print(" A-par:")
print(" Mean +/- Std. = " + str(meanvalue) + " +/- " + str(sigmavalue))
print(" Skewness, Kurtosis = " + str(skewness) + " , " + str(kurt) )
print("................................................")
# Add Goal line
ax1.vlines(0.,np.min(h[h>0]),hmax*1.01,linestyle="--",color="black",linewidth=2,label="Goal",alpha=1.,zorder=-2)
# Plot limits, legend, labels...
ax1.set_xlim(-1.0,1.0)
#ax1.set_yscale('log') # Make y axis in log scale
# adjust y-range if needed
yplot_min, yplot_max = plt.gca().get_ylim()
if ((adjustDR == True) & (yplot_min/yplot_max <= 1E-3)):
ax1.set_ylim(yplot_max/1E3,yplot_max*1.01)
#plt.legend(loc='lower right')
ax1.legend(bbox_to_anchor=(0.5, -0.1),loc='upper center', borderaxespad=0.)
ax1.set_xlabel("A-par",fontsize=20)
ax1.set_ylabel(r'# pixels',fontsize=20)
ax1.tick_params(direction='in',axis="both",which="both",top=True,right=True,labelsize=10)
if titlename=='':
plt.title("A-par Parameter: comparisons",fontsize=16)
else:
plt.title(titlename,fontsize=16)
# Save plot?
if save == True:
if plotname == '':
plotname="AparALL_tmp"
plt.savefig(plotname+'.png')
print(" See results: "+plotname+".png")
plt.close()
# out
print("---------------------------------------------")
print(" A-par comparisons... DONE")
print("=============================================")
return True
def Compare_Apar_signal(ref_image = '',target_image=[''],adjustDR=True,Nbins=15,
save=False, noise=0.0, plotname='',
labelname=[''], titlename=''
):
"""
Compare_Apar_signal (A. Hacar, Univ. of Vienna)
Compare all Apar images vs signal (continuum or mom0 maps).
If No. of targets = 1, the mean and std of A-par will be calculated.
This function can be applied in both cont/mom0 and cubes FITS files.
Arguments:
ref_image - image used as reference
target_image - list of images to be compared with reference
(recommended to <= 4 targets)
adjustDR - adjust dynamic range in plot (default = True)
Nbins - number of bins in plot (default = 15)
save - (optional) save plot? (default = False)
noise - (optional) if noise > 0.0 the evolution of the noise level
will be displayed
Requires:
The script will look for target_image[i]_convo2ref_Apar.fits images produced by the get_IQA() script
Results:
Apar as function of reference & target signals
Example 1: compare a list of targets
Compare_Apar_signal(ref_image = 'TP_image',target_image=['Feather.image','TP2vis.image'])
Example 2: investigate singel target (incl. A-par statistics)
Compare_Apar_signal(ref_image = 'TP_image',target_image=['Feather.image'],noise=0.5)
"""
# Reference image
print("=============================================")
print(" A-par vs Signal")
print("---------------------------------------------")
# Number of plots
Nplots = np.shape(target_image)[0]
# These plots get too crowded with a high number of targets. If No. targets > 4 then exit this function
if (Nplots > 4):
print(" Too many targets. Please use <= 4.")
print(" No plot shown.")
print("---------------------------------------------")
print(" A-par vs Signal... DONE")
print("=============================================")
return None
# Figure parameters
plt.figure(figsize=(8,14))
grid = plt.GridSpec(ncols=1,nrows=7, wspace=0.3, hspace=0.3)
# Plot #1: Reference vs A-par
ax0 = plt.subplot(grid[0:2, 0])
# Loop over all images
xmax0 = 0.0; xmin0 = 1E6 # Dummy values
for m in np.arange(Nplots):
# Images
im1 = fits.open(ref_image+"_masked.fits")
im2 = fits.open(target_image[m]+"_convo2ref_Apar.fits")
im3 = fits.open(target_image[m]+"_convo2ref.fits")
# Define plot limits
##xmin = np.min(im1[0].data[np.isnan(im1[0].data)==False])
xmin = np.percentile(im1[0].data[np.isnan(im1[0].data)==False],0.01) #np.im replaced by 0.01 percentile to avoid outlayers
xmax = np.max(im1[0].data[np.isnan(im1[0].data)==False])
if (xmax > xmax0):
xmax0=xmax+xmax/30. # Slightly larger
if (xmin < xmin0):
xmin0=xmin
if (xmin < 0.0): #Lydia's modification to avoid negative values!
xmin0=0.0001
if ((adjustDR == True) & (xmin/xmax < 1E-3)):
xmin0=xmax0/1E3 # avoid plots with dynamic range >1000
# Plot results
ax0.scatter(im1[0].data.flatten(),im2[0].data.flatten(),c=IQA_colours[m],marker="o",rasterized=True,edgecolor='none',alpha=0.01)
# Goal (A-par = 0)
ax0.hlines(0.,xmin,xmax0,linestyle="--",color="black",linewidth=3,alpha=1.,zorder=2)
# Calculate mean and sigma if there is only one target
if (Nplots == 1):
print("---------------------------------------------")
print(" A-par values per bin: ")
# Calculate bins & step in log-scale
steplog=(np.log10(xmax0)-np.log10(xmin0))/Nbins
xvalueslog=np.arange(np.log10(xmin0),np.log10(xmax0),steplog)
# back to linear scale
step=10.**steplog
xvalues=10.**xvalueslog
# Define stats vectors
means=np.zeros(len(xvalues)) # Mean
stds=np.zeros(len(xvalues)) # STD
medians=np.zeros(len(xvalues)) # Median
q1values=np.zeros(len(xvalues)) # Q1
q3values=np.zeros(len(xvalues)) # Q2
fluxreco=np.zeros(len(xvalues)) # Flux recovered per bin
# helpers for debugging
#print(xmin, xmax)
#print(xmin0, xmax0)
#print(xvalues)
count=0
for j in xvalueslog:
# Define bin ranges in log-space
idx = (im1[0].data >= 10.**j) & (im1[0].data < 10.**(j+steplog)) & (np.isnan(im1[0].data)==False) & (np.isfinite(im1[0].data)==True)
# Ref + Target_convo2ref images
values1 = im1[0].data[idx]
values1 = values1[ (np.isnan(values1)==False) & (np.isfinite(values1)==True) ] # remove Nan & Inf.
values3 = im3[0].data[idx]
values3 = values3[ (np.isnan(values3)==False) & (np.isfinite(values3)==True) ] # remove Nan & Inf.
# Apar image
values2 = im2[0].data[idx]
values2 = values2[ (np.isnan(values2)==False) & (np.isfinite(values2)==True) ] # remove Nan & Inf.
# Stats
if (np.shape(values2)[0] > 0):
means[count] = np.mean(values2) # Mean
stds[count] = np.std(values2) # STD
medians[count] = np.median(values2) # Median
q1values[count] = np.percentile(values2, 10) # 10% Quartile
q3values[count] = np.percentile(values2, 90) # 90% Quartile
fluxreco[count] = np.sum(values3)/np.sum(values1)
# Show results on screen
print("Bin "+str(count+1)+": Ref.Flux = " + str(np.round(10.**(j+steplog/2.),2)) + " ; A = " + str(np.round(means[count],2)) + " +/- " + str(np.round(stds[count],2)) + " ; [Q10,Q90] = ["+ str(np.round(q1values[count],3)) + " , " + str(np.round(q3values[count],3)) +"]; Flux recovered = " + str(np.round(100.*fluxreco[count],1))+"%")
# Counter +1
count+=1
#
# Display mean and STD
ax0.errorbar(10.**(xvalueslog+steplog/2.),means, yerr=stds, fmt='o',c="blue",label=r"|y|$\pm 1 \sigma$ ",linewidth=2,markersize=10,zorder=2,capsize=5)
#ax0.errorbar(10.**(xvalueslog+steplog/2.),medians, yerr=[q1values,q3values], fmt='o',c="cyan",label=r"[Q1,Median,Q3]",linewidth=2)
ax0.vlines(10.**(xvalueslog+steplog/2.),q1values,q3values,color="cyan",label=r"[Q10,Q90]",linewidth=5,zorder=1)
# Show noise effects?
if (noise > 0):
xvalues=np.arange(np.log10(xmin0),np.log10(xmax0),(np.log10(xmax0)-np.log10(xmin0))/20.)
xvalues=10.**xvalues
ax0.plot(xvalues,noise/np.abs(xvalues),c="blue",zorder=2,linewidth=4,linestyle="dotted")
ax0.plot(xvalues,-noise/np.abs(xvalues),c="blue",zorder=2,linewidth=4,linestyle="dotted")
# Plot limits, legend, labels...
ax0.legend()
ax0.set_yticks(np.arange(-2.,2.,0.25))
ax0.set_xlim(xmin0,xmax0)
ax0.set_ylim(-0.65, 0.65)
# Adjust ylims if the results are really bad!
if (np.mean(im2[0].data[np.isnan(im2[0].data)==False]) <= -0.5):
ax0.set_ylim(-1.5, 0.5)
ax0.set_xscale('log')
ax0.set_ylabel(r" A-par",fontsize=20)
ax0.tick_params(direction='in',axis="both",which="both",top=True,right=True,labelsize=10)
if titlename=='':
plt.title("Accuracy vs. Signal",fontsize=16)
else:
plt.title(titlename,fontsize=16)
# Plot #2: Reference vs Target
ax1 = plt.subplot(grid[2:6, 0])
# Loop over all images
#xmax0 = 0.0; xmin0 = 1E6 # Dummy values
for m in np.arange(Nplots):
# Images
im1 = fits.open(ref_image+"_masked.fits")
im2 = fits.open(target_image[m]+"_convo2ref.fits")
# Define plot limits
##xmin = np.min(im1[0].data[np.isnan(im1[0].data)==False])
xmin = np.percentile(im1[0].data[np.isnan(im1[0].data)==False],0.01) #np.im replaced by 0.01 percentile to avoid outlayers
xmax = np.max(im1[0].data[np.isnan(im1[0].data)==False])
#if (xmax > xmax0):
# xmax0=xmax+xmax/10. # Slightly larger
#if (xmin < xmin0):
# xmin0=xmin
#if (xmin < 0.0): #Lydia's modification to avoid negative values!
# xmin0=0.0001
#if ((adjustDR == True) & (xmin/xmax < 1E-3)):
# xmin0=xmax0/1E3 # avoid plots with dynamic range >1000
# Plot results
if labelname[m]=='':
ax1.scatter(im1[0].data.flatten(),im2[0].data.flatten(),c=IQA_colours[m],marker="o",rasterized=True,label=target_image[m],edgecolor='none',alpha=0.01)
else:
ax1.scatter(im1[0].data.flatten(),im2[0].data.flatten(),c=IQA_colours[m],marker="o",rasterized=True,label=labelname[m],edgecolor='none',alpha=0.01)
count=0
for j in xvalueslog:
# Define bin ranges in log-space
idx = (im1[0].data >= 10.**j) & (im1[0].data < 10.**(j+steplog)) & (np.isnan(im1[0].data)==False) & (np.isfinite(im1[0].data)==True)
values = im2[0].data[idx]
values = values[ (np.isnan(values)==False) & (np.isfinite(values)==True) ] # remove Nan & Inf.
# Stats
if (np.shape(values)[0] > 0):
means[count] = np.mean(values) # Mean
stds[count] = np.std(values) # STD
medians[count] = np.median(values) # Median
q1values[count] = np.percentile(values, 10) # 10% Quartile
q3values[count] = np.percentile(values, 90) # 90% Quartile
# Counter +1
count+=1
#
# Display mean and STD
ax1.errorbar(10.**(xvalueslog+steplog/2.),means, yerr=stds, fmt='o',c="blue",label=r"|y|$\pm 1 \sigma$ ",linewidth=2,markersize=10,zorder=2,capsize=5)
#ax0.errorbar(10.**(xvalueslog+steplog/2.),medians, yerr=[q1values,q3values], fmt='o',c="cyan",label=r"[Q1,Median,Q3]",linewidth=2)
# Show A values lines
xvalues=np.arange(xmin0,xmax0,(xmax0-xmin0)/20.)
ax1.plot(xvalues,xvalues,c="k",zorder=2,linewidth=3,linestyle="--",label="Goal (linear correlation; A-par = 0.0)")
ax1.text((xmax0-xmin0)/3.,(xmax0-xmin0)/3.,"A=0",rotation=35,ha='center',va='center',rotation_mode="anchor",bbox=dict(boxstyle='square',facecolor='white', edgecolor='black'))
# Note that the value of A=-1 needs values of Target=0, which is not allowed in ylog-plots
for k in np.array([-0.75,-0.5,-0.25,0.25,0.5,0.75,1.0]):
def Avalues(A,x):
return A*x+x
yvalues=Avalues(A=k,x=xvalues)
ax1.plot(xvalues,yvalues,c="grey",zorder=2,linestyle="dashed",alpha=0.5)
ax1.text((xmax0-xmin0)/3.,Avalues(A=k,x=(xmax0-xmin0)/3.),"A="+str(k),rotation=35,ha='center',va='center',rotation_mode="anchor",clip_on=True,size=10.,color="grey",zorder=2)
# Show noise effects?
if (noise > 0):
xvalues=np.arange(np.log10(xmin0),np.log10(xmax0),(np.log10(xmax0)-np.log10(xmin0))/20.)
xvalues=10.**xvalues
ax1.plot(xvalues,xvalues-noise,c="blue",zorder=2,linewidth=4,linestyle="dotted",label=r"White noise: $\sigma = $"+str(np.round(noise,2))+" (image units)")
ax1.plot(xvalues,xvalues+noise,c="blue",zorder=2,linewidth=4,linestyle="dotted")
# Plot limits, legend, labels...
ax1.set_xlim(xmin0,xmax0)
ax1.set_ylim(xmin0,xmax0)
ax1.set_xscale('log')
ax1.set_yscale('log')
ax1.tick_params(direction='in',axis="both",which="both",top=True,right=True,labelsize=10)
# Legend and labels
ax1.legend(bbox_to_anchor=(0.5, -0.15),loc='upper center', borderaxespad=0.)
ax1.set_ylabel(r" Target flux (image units)",fontsize=20)
ax1.set_xlabel(r" Reference flux (image units)",fontsize=20)
# Save plot?
if save == True:
if plotname == '':
plotname="Apar_signal_ALL_tmp"
plt.savefig(plotname+'.png')
print(" See results: "+plotname+".png")
plt.close()
# out
print("---------------------------------------------")
print(" A-par vs Signal... DONE")
print("=============================================")
return True
def Compare_Flux_signal(ref_image = '',target_image=[''],adjustDR=True, Nbins=15.,
save=False, noise=0.0, plotname='',
labelname=[''], titlename=''
):
"""
Compare_Flux_signal (A. Hacar, Univ. of Vienna)
Compare Flux recovery in images vs signal (continuum or mom0 maps).
This function can be applied in both cont/mom0 and cubes FITS files.
Arguments:
ref_image - image used as reference
target_image - list of images to be compared with reference
(recommended to <= 4 targets)
adjustDR - adjust dynamic range in plot (default = True)
Nbins = Number of bins in plot (default = 15)
save - (optional) save plot? (default = False)
noise - (optional) if noise > 0.0 the evolution of the noise level
will be displayed
Requires:
The script will look for target_image[i]_convo2ref_Apar.fits images produced by the get_IQA() script
Results:
Flux recovery as function of reference signals both in absolute and relative terms
Example 1: compare a list of targets
Compare_Flux_signal(ref_image = 'TP_image',target_image=['Feather.image','TP2vis.image'])
Example 2: investigate single target
Compare_Flux_signal(ref_image = 'TP_image',target_image=['Feather.image'])