-
Notifications
You must be signed in to change notification settings - Fork 1
/
tp2vis.py
1998 lines (1642 loc) · 79 KB
/
tp2vis.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
# Taken from the Quick Array Combinations (QAC)
# https://github.com/teuben/QAC/blob/master/contrib/tp2vis.py
#
#
#
# A collection of TP2VIS functions to aid in combining ALMA
# Total Power and Visibilities in a Joint Deconvolution
#
# Authors: Peter Teuben & Jin Koda (hacked version)
#
# Public functions:
# tp2vis_version()
# tp2vis(imagename, msname, ptg, maxuv=10.0, rms=None, nvgrp=4, deconv=True)
# tp2visbl(imagename, ptg, maxuv=10.0, nvgrp=4, deconv=True)
# tp2viswt(mslist,mode='stat',value=0.5)
# tp2vistweak(dirtyname,cleanname,pbcut=0.8)
# tp2vispl(mslist,ampPlot=True,show=False)
#
# Helper functions:
# tp2vis_version()
# getptg()
# axinorder()
# arangeax()
# guessarray()
#
import os, sys, shutil, re, time, datetime
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from scipy.ndimage import distance_transform_edt
__version__ = "14-apr-2021 PJT/LMF"
try:
# casa5
from tasks import imhead, immath
from taskinit import msmdtool, casalog, qatool, tbtool, mstool, iatool, vptool, smtool
vp = vptool()
msmd = msmdtool()
ms = mstool()
qa = qatool()
tb = tbtool()
ia = iatool()
sm = smtool()
print("tp2vis for CASA5 [%s]" % __version__)
except:
try:
# casa6
from casatasks import imhead
from casatasks import immath
from casatasks import imstat
from casatools import msmetadata as msmdtool
from casatools import ms as mstool
from casatools import vpmanager as vptool
from casatools import quanta as qatool
from casatools import table as tbtool
from casatools import image as iatool
from casatools import simulator as smtool
from casatools import measures as metool
vp = vptool()
msmd = msmdtool()
ms = mstool()
qa = qatool()
tb = tbtool()
ia = iatool()
sm = smtool()
me = metool()
print("tp2vis for CASA6 [%s]" % __version__)
except:
print("WARNING: tp2vis will not function")
## ===========================================
## Global parameters: observatory & telescopes
## ===========================================
# Following assumes uniform, non-heterogeneous, dish size
t2v_arrays = {}
# ALMA 12m array parameters
apara = {'observatory':'ALMA', # observatory name
'antList': ['DA','DV','A00'], # list of ant names (DA##, DV##, A##) PM## also possible
'dish': 12.0, # dish diam [meters]
'fwhm100': 65.2, # fwhm@100GHz [56.5"@115.2GHz]
'maxRad': 999.0} # cutoff rad of FoV [arcsec]
t2v_arrays['ALMA12'] = apara.copy()
# ALMA 7m
apara = {'observatory':'ALMA',
'antList': ['CM','A00'], # CM## (A## are from simobserve)
'dish': 7.0,
'fwhm100': 105.0, # fwhm@100GHz [35"@300GHz]
'maxRad': 999.0}
t2v_arrays['ALMA07'] = apara.copy()
# ALMA TP [to deal with single-dish TP cube]
apara = {'observatory':'ALMA',
'antList': ['TP'],
'dish': 12.0,
# 'fwhm100': 65.2, # fwhm@100GHz [56.5"@115.2GHz]
'fwhm100': 58.3, # fwhm@100GHz [before SF conv]
'maxRad': 999.0}
t2v_arrays['ALMATP'] = apara.copy()
# VIRTUAL TP2VIS array [for TP visibilities]
# see also qac_vp()
use_vp = False
if use_vp:
apara = {'observatory':'VIRTUAL', # a primary beam of
'antList': ['VIRTUAL'], # virtual interferometer
'dish': 12.0, # should be defined here.
'fwhm100': 65.2,
# 'fwhm100': 58.3,
'maxRad': 150.0}
vp.reset() # reset vpmanager
vp.setpbgauss(telescope='OTHER',
othertelescope=apara['antList'][0],# set PB of VI in vpmanager
halfwidth=str(apara['fwhm100'])+'arcsec',
maxrad=str(apara['maxRad'])+'arcsec',
reffreq='100.0GHz',
dopb=True)
# antnames='DV00' etc.
vp.summarizevps()
else: # without vpmanager working,
apara = {'observatory':'ALMA', # use ALMA for now
'antList': ['ALMA'], # experiment with 'DV01' (an Airy function)
'dish': 12.0,
# 'fwhm100': 65.2,
'fwhm100': 58.3,
'maxRad': 999.0}
t2v_arrays['VIRTUAL'] = apara.copy()
# softer dish sampling instead of the VIRTUAL dish size
dish3 = None
# see also qac_vp()
use_schwab = False
## =================
## Support functions
## =================
def tp2vis_version():
print("tp2vis: %s" % __version__)
def axinorder(image):
"""
Ensure we have the image in RA-DEC-POL-FREQ axes order.
Helper function for tp2vis()
"""
ia.open(image)
h0 = ia.summary()
ia.done()
axname = h0['axisnames']
print("AXIS NAMES:",axname)
print("AXIS SHAPES:",list(h0['shape']))
order = ''
for ax in ['Right Ascension','Declination','Stokes','Frequency']:
if not ax in axname:
raise Exception("ERROR: No %s axis in %s" % (ax,image))
else:
iax = list(axname).index(ax)
order = order + '%1d' % (iax)
if order == '0123':
return True
else:
return False
def arangeax(image):
"""
Re-arrange axes and make a RA-DEC-POL-FREQ cube. assume
axinorder() is already run and 4 axes exist in order.
Helper function for tp2vis()
input: image
output: temporary image name
"""
dd = ''.join(re.findall('[0-9]',str(datetime.datetime.now())))
imageout = 'tmp_arangeax_' + dd + '.im'
os.system('rm -rf %s' % imageout)
ia.open(image)
h0 = ia.summary()
axname = h0['axisnames']
order = ''
for ax in ['Right Ascension','Declination','Stokes','Frequency']:
if ax in axname:
iax = list(axname).index(ax)
order = order + '%1d' % (iax)
if len(order) == 4: # all axes exist
# on older CASA before 5.0 you will loose beam and
# object name (bugs.txt #017)
print("transpose order=%s" % order)
ia2 = ia.transpose(outfile=imageout,order=order)
ia2.done()
ia.done()
print("Written transposed ",imageout)
else:
print("bad transpose order=%d" % order)
return None
return imageout
def getptg(pfile):
""" get the ptg's (CASA pointings) from a ptg file into a list
'J2000 19h00m00.00000 -030d00m00.000000',...
Helper function for tp2vis()
"""
fp = open(pfile)
lines = fp.readlines()
fp.close()
ptg = []
for line in lines:
if line[0] == '#': continue
w = line.strip().split()
ptg.append("%s %s %s" % (w[0],w[1],w[2]))
return ptg
def guessarray(msfile):
""" guess array name from MS
this function uses the definitions of known arrays at the beginning
of this code. See t2v_arrays[]
msfile: measurement set name
Helper function for tp2vis()
CAVEAT: analysis of the ANTENNA table is no guarentee that a dish
is used in the correlations.
"""
# Read antenna names in MS
if not os.path.exists(msfile): # make sure MS exists
print("GUESSARRAY ERROR: no %s exists" % (msfile))
return None
tb.open(msfile+'/ANTENNA') # open MS
antnames = tb.getcol('NAME') # read ant names
sizes = tb.getcol('DISH_DIAMETER') # and dish sizes
tb.close() # close MS
# Calculate likelihood of each array type
probs = {}
for iarray in list(t2v_arrays.keys()): # loop over known arrays
nant = 0 # reset counter
for iant in t2v_arrays[iarray]['antList']: # how many ants of each
nant += sum([(iant in x) for x in antnames]) # known array in MS
frac = float(nant) / len(antnames) # frac of ants of known array
probs[iarray] = frac
# Pick array and return
mostlikelyarray = max(probs,key=probs.get) # most likely array
if antnames[0] == 'A00': # special case for simobserve()
if sizes[0] == 7.0: mostlikelyarray = 'ALMA07'
if sizes[0] == 12.0: mostlikelyarray = 'ALMA12'
print("guessarray %s %g -> %s" % (antnames[0],sizes[0],mostlikelyarray))
return mostlikelyarray
def schwab_spheroidal(alpha,m,rscale,dist2d):
""" return 2d kernel image of schwab's spheroidal function (Schwab 1984)
CASA's sdimaging() uses the tabulated approx. of spheroidal function
in Schwab 1984. Schwab's definition is different from the common
definition as used in scipy. Within Schwab, the definition of
key parameters (e.g., alpha, m) are not consistent in text and in table.
Using the definition in the Schwab's table, the Schwab's spheroidal
function is related to the scipy's as:
Schwab(alpha,m,eta) =
(1-eta^2)^((2-alpha)/2) * scipy.special.pro_ang1(0, 0, m*pi/2, eta)[0]
This means in the scipy's notation, n=0, alpha=m=0, and gamma=m*pi/2.
In our definition, dist2d is eta, and the new parameter rscale to
Note again that this alpha and m are different from Schwab's.
Required:
---------
alpha Schwab's parameter alpha
m Schwab's parameter m
rscale size of kernel - it becomes zero at pixel=rscale
dist2d 2d image that contains distances from center
"""
gamma = m * np.pi / 2.0
schwab = (1.0-(dist2d/rscale)**2)**((2.0-alpha)/2.0) * \
sp.special.pro_ang1(0,0,gamma,(dist2d/rscale))[0]
bad = np.isnan(schwab)
schwab[bad] = 0.0
schwab = schwab / np.sum(schwab)
return schwab
## ==========================================================
## TP2VIS: main function to convert TP cube into visibilities
## ==========================================================
def tp2vis(infile, outfile, ptg, maxuv=10.0, rms=None, nvgrp=4, deconv=True, winpix=0):
"""
Required:
---------
infile Input IM filename, in Jy/beam. Must exist
outfile Output MS filename. Must not exist
ptg this can be one of:
None: NOT ALLOWED ANYMORE UNTIL RE-IMPLEMENTED TO AUTO_FILL
string: ptg file (or list of strings?) - see also qtp_ms_ptg() [OK]
list: list of strings (from e.g. qtp_ms_ptg()) [OK]
ms: MS containing the pointings [not implemented]
Optional:
---------
maxuv maximum uv distance of TP vis distribution (in m)
default=10m for 12m ALMA dish
rms set the RMS (by default this will be ignored) in the infile
in order to compute an initial guess for the weights
Should be Jy/beam
See also tp2viswt(mode=3)
nvgrp Number of visibility group (nvis = 1035*nvgrp)
The number of antenna is hardcoded as 46
deconv Use deconvolution as input model? (True)
When you have a Jy/pixel map, you want to set deconv=False
winpix Width of the Tukey window to reduce aliasing [=0 for no window],
Number of pixels from each edge
Some Technical Background:
--------------------------
There are 46 virtual antennas, each pointing will be visited 'nvgrp' times before
going to the next field. Within each there are gaussian distributed 1035 visibilities
as we don't store auto-correlations. Antenna positions are arbitrary, we only randomize
the distribution in UV, and force a (0,0) for total flux. Thus UV is not derived from
the antpos.
"""
# CASA bug fixes
# ==============
bug001_Fixed = False
bug028_Fixed = True
# Parameters
# ==========
seed = 123 # for random number
seed = 987 # for random number
seed = 1
seed = 2
seed = 3
seed = 123
# Query the input image
# =====================
# Check if exists - do we really mean this? file and directory or os.path.isdir
# if os.path.isfile(outfile) or os.path.isdir(outfile):
if os.path.isfile(outfile):
print("Cannot overwrite",outfile)
return
# Ensure RA-DEC-POL-FREQ axis order (CASA simulator needs it)
if axinorder(infile): # if 4 axes in order
imagename = infile # use original file
delimage = False
else: # if not, rearrange
imagename = arangeax(infile) # and use re-aranged data
delimage = True
# Parameters from TP cube header
# ==============================
cms = qa.constants('c')['value'] # speed of light in m/s
h0 = imhead(imagename,mode='list')
cb_shape = h0['shape'] # cube shape
cb_nx = h0['shape'][0] # num of pixels, RA
cb_ny = h0['shape'][1] # , DEC
cb_dx = np.abs(h0['cdelt1']) # pixel size [radian]!
cb_dy = np.abs(h0['cdelt2'])
cb_objname = h0['object'] # object name
cb_nchan = h0['shape'][3] # num of channels
cb_fstart = h0['crval4']-h0['crpix4']*h0['cdelt4'] # start freq [Hz]
cb_fwidth = h0['cdelt4'] # chan width [Hz]
cb_reffreq = cb_fstart + 0.5*cb_fwidth # chan central freq [Hz]
cb_refwave = cms / (cb_reffreq) # wavelength [m]
cb_refcode = h0['reffreqtype'] # e.g. 'LSRK'
cb_bunit = h0['bunit'].upper() # JY/BEAM or JY/PIXEL
cb_fstart = cb_fstart /1.0e9 # Hz -> GHz
cb_fwidth = cb_fwidth /1.0e9
cb_reffreq = cb_reffreq/1.0e9
# Parameters for TP and virtual interferometer (VI) primary beams
# ===============================================================
twopi = 2.0*np.pi
apr = qa.convert('1.0rad','arcsec')['value'] # arcsec per radian
stof = 2.0*np.sqrt(2.0*np.log(2.0)) # FWHM=stof*sigma
# TP beam
fwhm100 = t2v_arrays['ALMATP']['fwhm100'] # FWHM at 100GHz [arcsec]
tp_beamFWHM = fwhm100*(100.0/cb_reffreq) # at obs freq [arcsec]
tp_beamSigma = tp_beamFWHM/stof/apr # sigma of TP beam [rad]
tp_beamSigFT = 1.0/(twopi*tp_beamSigma) # sigma in fourier [lambda]
print("tp_sigma [rad], tp_sigmaFT [lambda]: ",tp_beamSigma,tp_beamSigFT)
# VI beam
vi_antname = t2v_arrays['VIRTUAL']['observatory'] # VI observatory
vi_dish = t2v_arrays['VIRTUAL']['dish']# VI dish size [m]
fwhm100 = t2v_arrays['VIRTUAL']['fwhm100'] # FWHM at 100GHz [arcsec]
vi_beamFWHM = fwhm100*(100.0/cb_reffreq) # at reffreq [arcsec]
vi_beamSigma = vi_beamFWHM/stof/apr # sigma of VI beam [rad]
vi_beamSigFT = 1.0/(twopi*vi_beamSigma) # sigma in fourier [lambda]
print("vi_sigma [rad], vi_sigmaFT [lambda]: ",vi_beamSigma,vi_beamSigFT)
# Obtain pointing coordinates
# ===========================
print("Using ptg = ",ptg)
if type(ptg) == type([]):
pointings = ptg # list of J2000/RA/DEC strings
else:
pointings = getptg(ptg) # convert file to list
# Deconvolution of TP cube (images) by TP beam
# (if deconv=False the input image will be used instead)
# ========================================================
# Check unit of TP cube
if deconv:
if cb_bunit != 'JY/BEAM':
print("ERROR: unit should be 'Jy/beam' when deconv=True",cb_bunit)
return
else:
if cb_bunit != 'JY/PIXEL':
print("ERROR: unit should be 'Jy/pixel' when deconv=False",cb_bunit)
return
# Constants
apr = qa.convert('1.0rad','arcsec')['value'] # arcsec per radian
cbm = np.pi/(4.0*np.log(2.0)) # beamarea=cbm*bmaj*bmin
# Number of pixels per TP beam
apixel = np.abs((cb_dx*apr)*(cb_dy*apr)) # area in pixel [arcsec2]
abeam = cbm*tp_beamFWHM**2 # area of TP beam [arcsec2]
nppb = abeam/apixel # To convert Jy/bm to Jy/pix
print("Number of pixels per beam:",nppb)
# Cutoff length of TP's gaussian beam tail
eps = 0.01 # cutoff amp of gauss tail
uvcut = np.sqrt(-2.0*tp_beamSigFT**2*np.log(eps)) # uvdist there
uvcut = np.minimum(maxuv/cb_refwave,uvcut) # compare with maxuv
print("UVCUT:", uvcut/1000.0,"kLambda")
# Generate uvdist^2 image [notice: x-axis runs vertically]
frqx = np.fft.fftfreq(cb_nx,cb_dx) # frequency in x
frqy = np.fft.fftfreq(cb_ny,cb_dy) # frequency in y
vgrd,ugrd = np.meshgrid(frqy,frqx) # make grids
uvgrd2 = ugrd**2+vgrd**2 # uvdist^2 image
del frqx,frqy,vgrd,ugrd
# Open TP cube (@todo: this can go inside the if deconv)
ia.open(imagename)
# Output deconvolved cube
if deconv:
dd = ''.join(re.findall('[0-9]',str(datetime.datetime.now())))
imagedecname = 'tmp_imagedec_' + dd + '.im'
ia2 = ia.newimagefromimage(imagename,imagedecname,overwrite=True)
if use_schwab:
print("Using Schwab's spheroidal function in TP deconvolution")
# Schwab's spheroidal function [pixel unit]
# @todo make sure we can use /, or do we need // in python3
# make sure odd numbers work
x0 = np.arange(-cb_nx//2,-cb_nx//2+cb_nx) # get cb_nx pix
y0 = np.arange(-cb_ny//2,-cb_ny//2+cb_ny) # get cb_ny pix
xx,yy = np.meshgrid(x0,y0)
xygrid = np.sqrt(xx*xx + yy*yy)
schwab = schwab_spheroidal(1.0,6.0,3.0,xygrid) # alpha=1, m=6
schwab_ft = np.fft.fft2(np.fft.ifftshift(schwab))
del x0,y0,xx,yy,xygrid,schwab
# Loop over channels
print("Deconvolution loop starts")
for iz in range(cb_nchan):
# Beam in Fourier domain
freq = cb_fstart+cb_fwidth*(0.5+iz) # chan cen freq [GHz]
beamSigFT = tp_beamSigFT * freq/cb_reffreq
beamFT = np.exp(-uvgrd2/(2.0*beamSigFT**2))
if use_schwab:
beamFT = beamFT * schwab_ft # Gauss * Schwab
# Channel image to be deconvolved
image = ia.getchunk([-1,-1,-1,iz],[-1,-1,-1,iz])
image = image[:,:,0,0] # image[ix][iy][0][0]
image = image / nppb # scale to Jy/pixel
# Apply Tukey window
if winpix > 0:
nwin = winpix
mask = ia.getchunk([-1,-1,-1,iz],[-1,-1,-1,iz],getmask=True)
mask = mask[:,:,0,0] # mask[ix][iy][0,0]
nnx = mask.shape[0]
nny = mask.shape[1]
maskexp = np.zeros([nnx+2,nny+2]) # add 1pix each edge
maskexp[1:nnx+1,1:nny+1] = mask # edge = 0 (blank)
dist = distance_transform_edt(maskexp)-1. # dist. from blanks
dist[dist<0] = 0 # outside/blanks=0
dist[dist>nwin] = nwin # deep inside=nwin
dist = dist/nwin # normalize to [0,1]
dist = dist[1:nnx+1,1:nny+1] # trim the expansion
mask = 0.5*(1.0-np.cos(np.pi*dist)) # Tukey window
image = image * mask # apply
del dist,mask
# Deconvolution
imageFT = np.fft.fft2(image,axes=(0,1))
imageFTdec = imageFT.copy()
idx0 = (uvgrd2 > (uvcut**2)) # idx of outer uv
idx1 = np.logical_not(idx0) # idx of inner uv
imageFTdec[idx1] = imageFT[idx1]/beamFT[idx1] # just for inner uv
imageFTdec[idx0] = 0.0 # set outer uv zero
imagedec = np.fft.ifft2(imageFTdec)
ia2.putchunk(np.real(imagedec), blc=[0,0,0,iz])
ia2.close()
imhead(imagedecname,mode='put',hdkey='bunit',hdvalue='Jy/pixel')
# unit=Jy/pixel
ia.close()
# List parameters for virtual interferometric obs
# ===============================================
# Due to CASA construction, we cannot set some params directly
# and have to define many indirect params. E.g., Nvis cannot be set,
# but is calculated as Nvis=npair*(ttot/tint), where npair=num of ant
# pairs, ttot=total integ time, and tint=integ time per vis.
nant = 46 # # of fake antennas
npair = (nant*(nant-1))//2 # # of baselines
nvis = npair * nvgrp # # of vis per point
source = cb_objname # object name
npnt = len(pointings)
# Spectral windows
spw_nchan = cb_nchan # # of channels
spw_fstart = cb_fstart # start freq [GHz]
spw_fwidth = cb_fwidth # freq width [GHz]
spw_fresolution = cb_fwidth
spw_fband = 'bandtp' # fake name
spw_stokes = 'I' # 1 pol axis (or e.g. 'XX YY')
spw_refcode = cb_refcode # e.g. 'LSRK'
# Feed
fed_mode = 'perfect X Y'
fed_pol = ['']
# Fields
fld_calcode = 'OBJ'
fld_distance = '0m' # infinite distance
# Observatory
if use_vp:
obs_obsname = 'WSRT' # picking this results in no data in pure tp2vis even
obs_obsname = 'ALMA'
obs_obspos = me.observatory(obs_obsname) # coordinate
obs_obsname = t2v_arrays['VIRTUAL']['observatory'] # observatory
else:
obs_obsname = t2v_arrays['VIRTUAL']['observatory'] # observatory
obs_obspos = me.observatory(obs_obsname) # coordinate
# Telescopes
tel_pbFWHM = t2v_arrays['VIRTUAL']['fwhm100']*(100./spw_fstart) # asec
tel_mounttype = 'alt-az'
tel_coordsystem = 'local' # coordinate of antpos
tel_antname = t2v_arrays['VIRTUAL']['antList'][0]
tel_dish = t2v_arrays['VIRTUAL']['dish']
if dish3 != None:
print("WARNING: using non-standard tel_dish = %g for antname = %s" % (dish3,tel_antname))
tel_dish = dish3
# Fake antenna parms
tel_antposx = np.arange(nant)*1000.0 # fake ant positions
tel_antposy = np.arange(nant)*1000.0 # the UV's will be random
tel_antposz = np.arange(nant)*1000.0 # later one
tel_antdiam = [tel_dish] * nant # all dish sizes the same
# Numbers of vis per pointing and for all pointings
tvis = 1.0 # integ time per vis
tpnt = tvis * nvgrp # integ time per ptgs
ttot = tpnt * npnt # tot int time for all pnt
tstart = -ttot/2 # set start/end time of obs,
tend = +ttot/2 # so that (tend-tstart)/tvis
# = num of vis per point
# Print parameters
# ================
print( "TP2VIS Parameters")
print( " input image name: %s" % (imagename))
print( " image shape: %s" % (repr(cb_shape)))
print( " output measurement set name: %s" % (outfile))
print( " number of pointings: %d" % (npnt))
print( " number of visibilities per pointing: %d" % (tpnt*npair))
print( " start frequency [GHz]: %f" % (spw_fstart))
print( " frequency width [GHz]: %f" % (spw_fwidth))
print( " frequency resolution [GHz]: %f" % (spw_fresolution))
print( " freq channels: %d" % (spw_nchan))
print( " polarizations: %s" % (spw_stokes))
print( " antenna name: %s" % (tel_antname))
print( " VI primary beam fwhm [arcsec]: %f" % (tel_pbFWHM))
print( " VI primary beam sigmaFT [m]: %f" % (vi_beamSigFT*cb_refwave))
print( " ttot %f" % (ttot))
print( " frame: %s" % (spw_refcode))
print( " seed: %d" % (seed))
print( " use_vp: %s" % (repr(use_vp)))
print( " use_schwab: %s" % (repr(use_schwab)))
# Set parameters in CASA
# ======================
spw_fstart = str(spw_fstart) + 'GHz'
spw_fwidth = str(spw_fwidth) + 'GHz'
spw_fresolution = str(spw_fresolution) + 'GHz'
if seed >= 0:
np.random.seed(seed)
sm.open(outfile)
if use_vp:
vptable = outfile + '/TP2VISVP'
vp.saveastable(vptable)
else:
vptable = None
print("OBS/TEL:",obs_obsname, obs_obspos, tel_antname, tel_mounttype, tel_coordsystem, tel_antdiam)
sm.setconfig(telescopename=obs_obsname,
referencelocation=obs_obspos,
antname=tel_antname,
mount=tel_mounttype,
coordsystem=tel_coordsystem,
x=tel_antposx,y=tel_antposy,z=tel_antposz,
dishdiameter=tel_antdiam)
sm.setspwindow(spwname=spw_fband,
freq=spw_fstart,
deltafreq=spw_fwidth,
freqresolution=spw_fresolution,
nchannels=spw_nchan,
refcode=spw_refcode,
stokes=spw_stokes)
sm.setfeed(mode=fed_mode,
pol=fed_pol)
for k in range(0,npnt):
this_pointing = pointings[k]
src = source + '_%d' % (k)
# src = source # uniq field ID's are not neeed (Petry 2019)
sm.setfield(sourcename=src,
sourcedirection=this_pointing,
calcode=fld_calcode,
distance=fld_distance)
sm.setlimits(shadowlimit=0.001,
elevationlimit='10deg')
sm.setauto(autocorrwt=0.0)
sm.settimes(integrationtime=str(tvis)+'s',
usehourangle=True,
referencetime=me.epoch('utc', 'today'))
# Generate (empty) visibilities
# =============================
# This step generates (u,v,w), based on target coord and antpos
# following current CASA implementation, but (u,v,w) will be
# replaced in the next step.
print("Running sm.observemany")
sources = []
starttimes = []
stoptimes = []
tstart_src = tstart
tend_src = tstart_src + tpnt
for k in range(npnt):
src = source + '_%d' % (k)
sources.append(src)
starttimes.append(str(tstart_src)+'s')
stoptimes.append(str(tend_src)+'s')
tstart_src = tstart_src + tpnt
tend_src = tstart_src + tpnt
sm.observemany(sourcenames=sources,
spwname=spw_fband,
starttimes=starttimes,
stoptimes=stoptimes)
# Genarate (replace) (u,v,w) to follow Gaussian
# =============================================
# Beam size in uv [m]
beamSigFT = vi_beamSigFT*cb_refwave # sigmaF=D/lambda -> D [m]
# Include (u,v) = (0,0)
uu = np.array([0.0])
vv = np.array([0.0])
# Rest follows Gaussian distribution with < uvcut^2
nuv = 1 # (0,0) exists already
uvcut2 = (uvcut*cb_refwave)**2 # 1/lambda -> meter
while (nuv<nvis): # loop until enough
nrest = nvis-nuv
utmp,vtmp = np.random.normal(scale=beamSigFT,size=(2,nrest))
ok = utmp**2+vtmp**2 < uvcut2 # generate gauss and
uu = np.append(uu,utmp[ok]) # ok for uvdist<uvcut
vv = np.append(vv,vtmp[ok])
nuv = uu.size
uu = uu[:nvis]
vv = vv[:nvis]
ww = np.zeros(nvis)
del utmp,vtmp, ok
# Replicate the same uv set for all pointings
if npnt > 1:
uu = np.ravel([uu,]*npnt)
vv = np.ravel([vv,]*npnt)
ww = np.ravel([ww,]*npnt)
nuvw = uu.shape[0]
tb.open(outfile,nomodify=False)
uvw = tb.getcol('UVW')
print("UVW shape",uvw.shape,nuvw,uvw[:,1]) # IndexError: too many indices for array
if len(np.ravel(uvw)) > 0:
nrow = uvw.shape[1]
if nrow == nuvw:
uvw = np.array([uu,vv,ww])
tb.putcol('UVW',uvw)
print("UVW0",uu[1],vv[1],ww[1])
else:
print("Bad UVW",nrow,nuvw)
else:
print("WARNING: no uvw?")
# Set WEIGHT and SIGMA columns temporarily
# ========================================
# Adjust weights
# weight of individual vis = sqrt(nvis)*rmsJy
# after natural wtg --> sqrt(nvis)*rmsJy / sqrt(nvis) = rmsJy
if rms != None:
print("Adjusting the weights using rms = %g nvis=%d" % (rms,nvis))
weight = tb.getcol('WEIGHT')
w = rms * np.sqrt(nvis)
w = 1.0/(w*w)
print("WEIGHT: Old=%s New=%g Nvis=%d" % (weight[0,0],w,nvis))
weight[:,:] = w # weight[npol,nvis*npnt]
tb.putcol('WEIGHT',weight) # set WEIGHT
sigma = 1/np.sqrt(weight) # SIGMA
tb.putcol('SIGMA',sigma) # set SIGMA
else:
print("The WEIGHT column is not filled, all 1.0")
tb.close()
del uvw
# Fill vis amp/phase based on deconvolved TP image
# ================================================
sm.setdata(fieldid=list(range(0,npnt))) # set all fields
if use_vp: # set primary beam
# according to Kumar
sm.setvp(dovp=True,usedefaultvp=False, vptable=vptable)
else:
sm.setvp(dovp=True,usedefaultvp=False)
print("Running sm.predict") # Replace amp/pha - key task
if deconv:
sm.predict(imagename=imagedecname) # deconvolved cube
os.system('rm -rf %s' % imagedecname) # remove the temp file
else:
sm.predict(imagename=imagename) # input TP cube
# Print Summary
sm.summary()
# Save PB info
# ============
f = open(outfile + '/TP2VIS.ascii','w') # save VP/PB info
f.write('TP2VIS definition of VIRTUAL interferometer\n')
for key in list(t2v_arrays['VIRTUAL'].keys()):
f.write('%s:%s\n' % (key, str(t2v_arrays['VIRTUAL'][key])))
f.close()
# Close measurement set
# =====================
sm.done()
# Corrections on CASA header
# Most of following should not be necessary if CASA has no bug
# ==============================================================
if not bug001_Fixed:
print("Correcting CASA header inconsistencies [bug001]")
# REST_FREQUENCY in /SOURCE
# Having REST_FREQUENCY in header does not make sense (since
# multiple lines, but CASA MS does have it. So, put it in.
h0 = imhead(imagename,mode='list')
if 'restfreq' in list(h0.keys()):
restfreq = h0['restfreq'][0] # restfreq from image header
else:
if h0['cunit4'] == 'Hz': # set it to ref freq [Hz]
restfreq = h0['crval4']
elif h0['cunit4'] == 'MHz':
restfreq = h0['crval4'] * 1.0e6
elif h0['cunit4'] == 'GHz':
restfreq = h0['crval4'] * 1.0e9
print("SET RESTFREQ:::",restfreq/1e9," GHz")
print(" Set restfreq= in (t)clean manually if this restfreq is incorrect")
tb.open(outfile + '/SOURCE',nomodify=False)
rf = tb.getcol('REST_FREQUENCY')
rf = rf * 0 + restfreq
tb.putcol('REST_FREQUENCY',rf)
tb.close()
# REF_FREQUENCY in /SPECTRAL_WINDOW
# Not clear what should be in this data column, but all ALMA data
# seem to have REF_FREQUENCY = REST_FREQUENCY, so we follow.
tb.open(outfile + '/SPECTRAL_WINDOW',nomodify=False)
rf = tb.getcol('REF_FREQUENCY')
rf = rf * 0 + restfreq
tb.putcol('REF_FREQUENCY',rf)
tb.close()
if not bug028_Fixed:
print("Set offset time stamps between fields [bug028]")
# clean task requires different time stamps for different fields
tb.open(outfile,nomodify=False)
time0 = tb.getcol("TIME")
time1 = tb.getcol("TIME_CENTROID")
t0 = time0[0]
time0 = [t0 + 1.*ii for ii in range(len(time0))]
time1 = time0
tb.putcol('TIME',time0)
tb.putcol('TIME_CENTROID',time1)
tb.close()
if delimage:
os.system('rm -rf %s' % imagename)
#-end of tp2vis()
## =======================================================
## TP2VISBL: Return baselines (a primitive of tp2vis)
## =======================================================
def tp2visbl(infile, ptg=None, dish=12.0, maxuv=10.0, nvgrp=4, seed=123):
"""
Return just a set of baselines from a single pointing TP2VIS, a hacked version of tp2vis()
Required:
---------
infile Input IM filename. The WCS of this file is used to set the RA,DEC and spectral
axis of the MS.
Optional:
---------
ptg string: the RA,DEC of the source to be observed, if to override from infile
dish Dish size (12m for ALMA)
maxuv maximum uv distance of TP vis distribution (in m)
default=10m for 12m ALMA dish
nvgrp Number of visibility group (nvis = 1035*nvgrp)
The number of antenna is hardcoded as 46
"""
def qac_tpdish(name, size=None):
"""
A patch to work with dishes that are not 12m (currently hardcoded in tp2vis.py)
@todo explain relationship to qac_vp()
E.g. for GBT (a 100m dish) you would need to do:
qac_tpdish('ALMATP',100.0)
qac_tpdish('VIRTUAL',100.0)
Note that ALMATP and VIRTUAL need to already exist.
"""
if size == None:
if name in t2v_arrays.keys():
print(t2v_arrays[name])
else:
print("'%s' not a valid dish name, valid are : %s" % (name,str(t2v_arrays.keys())))
return
old_size = t2v_arrays[name]['dish']
old_fwhm = t2v_arrays[name]['fwhm100']
r = size/old_size
t2v_arrays[name]['dish'] = size
t2v_arrays[name]['fwhm100']= old_fwhm / r
print("QAC_DISH: %s %g %g -> %g %g" % (name,old_size, old_fwhm, size, old_fwhm/r))
# Parameters
# ==========
seed = 123 # for random number
# Dish cheat
# ==========
qac_tpdish('ALMATP',dish)
qac_tpdish('VIRTUAL',dish)
# Query the input image
# =====================
# Ensure RA-DEC-POL-FREQ axis order (CASA simulator needs it)
if axinorder(infile): # if 4 axes in order
imagename = infile # use original file
delimage = False
else: # if not, rearrange
imagename = arangeax(infile) # and use re-aranged data
delimage = True
# Parameters from TP cube header
# ==============================
cms = qa.constants('c')['value'] # speed of light in m/s
h0 = imhead(imagename,mode='list')
cb_shape = h0['shape'] # cube shape
cb_nx = h0['shape'][0] # num of pixels, RA
cb_ny = h0['shape'][1] # , DEC
cb_dx = np.abs(h0['cdelt1']) # pixel size [radian]!
cb_dy = np.abs(h0['cdelt2'])
cb_objname = h0['object'] # object name
cb_nchan = h0['shape'][3] # num of channels
cb_fstart = h0['crval4']-h0['crpix4']*h0['cdelt4'] # start freq [Hz]
cb_fwidth = h0['cdelt4'] # chan width [Hz]
cb_reffreq = cb_fstart + 0.5*cb_fwidth # chan central freq [Hz]
cb_refwave = cms / (cb_reffreq) # wavelength [m]
cb_refcode = h0['reffreqtype'] # e.g. 'LSRK'
cb_bunit = h0['bunit'].upper() # JY/BEAM or JY/PIXEL
cb_fstart = cb_fstart /1.0e9 # Hz -> GHz
cb_fwidth = cb_fwidth /1.0e9
cb_reffreq = cb_reffreq/1.0e9
# Parameters for TP and virtual interferometer (VI) primary beams
# ===============================================================
twopi = 2.0*np.pi
apr = qa.convert('1.0rad','arcsec')['value'] # arcsec per radian
stof = 2.0*np.sqrt(2.0*np.log(2.0)) # FWHM=stof*sigma
# TP beam
fwhm100 = t2v_arrays['ALMATP']['fwhm100'] # FWHM at 100GHz [arcsec]
tp_beamFWHM = fwhm100*(100.0/cb_reffreq) # at obs freq [arcsec]
tp_beamSigma = tp_beamFWHM/stof/apr # sigma of TP beam [rad]
tp_beamSigFT = 1.0/(twopi*tp_beamSigma) # sigma in fourier [lambda]
print("tp_sigma [rad], tp_sigmaFT [lambda]: ",tp_beamSigma,tp_beamSigFT)
# VI beam
vi_antname = t2v_arrays['VIRTUAL']['observatory'] # VI observatory
vi_dish = t2v_arrays['VIRTUAL']['dish']# VI dish size [m]
fwhm100 = t2v_arrays['VIRTUAL']['fwhm100'] # FWHM at 100GHz [arcsec]
vi_beamFWHM = fwhm100*(100.0/cb_reffreq) # at reffreq [arcsec]
vi_beamSigma = vi_beamFWHM/stof/apr # sigma of VI beam [rad]
vi_beamSigFT = 1.0/(twopi*vi_beamSigma) # sigma in fourier [lambda]
print("vi_sigma [rad], vi_sigmaFT [lambda]: ",vi_beamSigma,vi_beamSigFT)
# Obtain pointing coordinates (@todo fix this so it uses crval1,crval2)
# ===========================
if ptg == None:
ptg = '%gdeg %gdeg' % (h0['crval1']*360/twopi,h0['crval2']*360/twopi)