-
Notifications
You must be signed in to change notification settings - Fork 1
/
datacomb.py
4017 lines (3120 loc) · 143 KB
/
datacomb.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
"""The datacomb module
Tools for different methods of interferometric/single-dish
data combination with CASA.
Based on the work at the Workshop
"Improving Image Fidelity on Astronomical Data",
Lorentz Center, Leiden, August 2019,
and subsequent follow-up work.
Run under CASA 6, no support for CASA 5
"""
import os
import math
import sys
import glob
import numpy as np
import re
from importlib import reload
import analysisUtils as au
import tp2vis as t2v
# new style
#import casatools as cto # is it used anywhere?
import casatasks as cta
# old style
from casatools import table as tbtool
from casatools import image as iatool
from casatools import quanta as qatool
from casatools import msmetadata as msmdtool
import casalith
reload(t2v)
decimal_places=6
##########################################
def get_casa_version():
"""
determine the version of the running CASA (Moser-Fischer, L.)
"""
version = casalith.version_string()
#print ("You are using " + version)
#if (version < '6.1.1'):
return version
##########################################
def export_fits(imname, clean_origin=''):
"""
standardized output from a combination method (Moser-Fischer, L.)
imname - file name base
clean_origin - file name base of intermediate cleaning products that imname is based on (e.g. feather products is based on tclean products)
"""
print('')
print('Exporting following final image products to FITS for '+imname+':')
for suffix in ['.image.pbcor', '.pb']:
if clean_origin!='' and suffix=='.pb':
os.system('cp -r '+clean_origin+suffix+' '+imname+suffix)
os.system('rm -rf '+imname+suffix+'.fits')
print('-', suffix)
cta.exportfits(imname+suffix, imname+suffix+'.fits')
print('Export done.')
print('')
return True
##########################################
def convert_JypB_JypP(sdimage):
"""
convert image brightness unit from Jy/beam to Jy/pixel (Moser-Fischer, L.)
a helper for runWSM to prepare the startmodel format
usemask - masking mode parameter as for tclean
mask - file name of mask
pbmask - PB mask cut-off level
niter - number of iterations spent on this mask
"""
myimhead = cta.imhead(sdimage)
print('Checking SD units...')
if myimhead['unit']=='Jy/beam':
print('SD units {}. OK, will convert to Jy/pixel.'.format(myimhead['unit']))
##CHECK: header units
SingleDishResolutionArcsec = myimhead['restoringbeam']['major']['value'] #in Arcsec
CellSizeArcsec = abs(myimhead['incr'][0])*206265. #in Arcsec
toJyPerPix = CellSizeArcsec**2/(1.1331*SingleDishResolutionArcsec**2)
SDEfficiency = 1.0 #--> Scaling factor
fluxExpression = "(IM0 * {0:f} / {1:f})".format(toJyPerPix,SDEfficiency)
#scaled_name = sdimage.split('/')[-1]+'.Jyperpix'
scaled_name = sdimage+'.Jyperpix'
os.system('rm -rf '+scaled_name)
cta.immath(imagename=sdimage,
outfile=scaled_name,
mode='evalexpr',
expr=fluxExpression)
hdval = 'Jy/pixel'
dummy = cta.imhead(imagename=scaled_name,
mode='put',
hdkey='BUNIT',
hdvalue=hdval)
### TO DO: MAY NEED TO REMOVE BLANK
### and/or NEGATIVE PIXELS IN SD OBSERVATIONS
return scaled_name
elif myimhead['unit']=='Jy/pixel':
print('SD units {}. SKIP conversion. '.format(myimhead['unit']))
return sdimage
else:
print('SD units {}. NOT OK, needs conversion by user to Jy/beam or Jy/pixel. '.format(myimhead['unit']))
return sys.exit()
##########################################
def derive_maxscale(vis, restfreq=''):
"""
get maxscale for multiscale-deconvolver (Moser-Fischer, L.)
a helper for runsdintimg and runtclean
usemask - masking mode parameter as for tclean
mask - file name of mask
pbmask - PB mask cut-off level
niter - number of iterations spent on this mask
"""
#file_check_vis(vis)
print('### Deriving maxscale for multiscale')
p05 = au.getBaselineStats(vis, percentile=5, verbose=False)[0]
if restfreq!='':
if 'GHz' in restfreq:
repfreq = float(restfreq.replace('GHz',''))*10**9
elif 'MHz' in restfreq:
repfreq = float(restfreq.replace('MHz',''))*10**6
elif 'kHz' in restfreq:
repfreq = float(restfreq.replace('kHz',''))*10**3
elif 'Hz' in restfreq:
repfreq = float(restfreq.replace('Hz',''))
else:
if type(vis) is str:
repfreq=au.medianFrequencyOfIntent(vis, verbose=False) #[Hz]
elif isinstance(vis, list):
refreqs=[]
for i in range(0,len(vis)):
repfreqi=au.medianFrequencyOfIntent(vis[i], verbose=False) #[Hz]
refreqs.append(refreqsi)
refreq=np.mean(refreqs)
# following ALMA technical handbook:
# maximum recoverable scale = 0.983* lambda[m]/5th_percentile_baseline[m]*206265.
c=2.99*10**8
c=299792458.0
freq= float(repfreq)
radiantoarcsec = 3600. * 180 / np.pi
mrs = 0.983 * c / freq / p05 * radiantoarcsec
mrsfac=0.5
maxscale = mrs * mrsfac
freqout=freq/10**9
print('')
print('### Maximum recoverable scale (mrs) for ' + vis + ' at', round(freqout,3) ,'GHz is', round(mrs,3), 'arcsec')
print('### Will use', mrsfac, 'of it as maxscale, i.e.', round(maxscale,3), 'arcsec' )
return maxscale
##########################################
def report_mask(usemask, mask, pbmask, niter):
"""
report selected mask used for tclean/sdint (Moser-Fischer, L.)
a helper for runsdintimg and runtclean
usemask - masking mode parameter as for tclean
mask - file name of mask
pbmask - PB mask cut-off level
niter - number of iterations spent on this mask
"""
print('')
if usemask == 'auto-multithresh':
print('### Run with {0} mask for {1} iterations ###'.format(usemask,niter))
elif usemask =='pb':
print('### Run with {0} mask on PB level {1} for {2} iterations ###'.format(usemask,pbmask,niter))
elif usemask == 'user':
if os.path.exists(mask):
print('### Run with {0} mask {1} for {2} iterations ###'.format(usemask,mask,niter))
else:
print('### WARNING: mask '+mask+' does not exist, or is not specified. ###')
#return False
else:
print("### Invalid usemask '"+usemask+"'. Please, check the mask options. ###")
return False
print('---------------------------------------------------------')
##########################################
def check_prep_tclean_param(
vis,
spw,
field,
specmode,
imsize,
cell,
phasecenter,
start,
width,
nchan,
restfreq,
threshold,
niter,
cycleniter,
usemask,
sidelobethreshold,
noisethreshold,
lownoisethreshold,
minbeamfrac,
growiterations,
negativethreshold,
mask,
pbmask,
interactive,
multiscale,
maxscale,
loadmask,
fniteronusermask
):
"""
check validity of parameters and set up tclean parameters in a uniform manner
(Moser-Fischer, L.)
a helper for runsdintimg and runtclean
Currently, it provides 'cube' and 'mfs' as spectral modes - 'mtmfs'
might be implemented later.
steps:
- check
vis
spw -
field,
specmode,
imsize,
cell,
phasecenter,
start,
width,
nchan,
restfreq,
threshold,
niter,
cycleniter,
usemask,
sidelobethreshold,
noisethreshold,
lownoisethreshold,
minbeamfrac,
growiterations,
negativethreshold,
mask,
pbmask,
interactive,
multiscale,
maxscale,
loadmask,
fniteronusermask
"""
# valid specmode?
if specmode not in ['mfs', 'cube']:
print('specmode \"'+specmode+'\" is not supported.')
return sys.exit()
# valid threshold?
if not type(threshold) == str or 'Jy' not in threshold and niter>1:
if not interactive:
print("You must provide a valid threshold, example '1mJy'")
return sys.exit()
else:
print("You have not set a valid threshold. Please do so in the graphical user interface!")
threshold = '1mJy'
# valid image and cell size?
if imsize==[] or cell=='':
cta.casalog.post('You need to provide values for the parameters imsize and cell.', 'SEVERE', origin='runsdintimg')
return sys.exit()
if loadmask==True and fniteronusermask>1.0 or fniteronusermask<0.0:
print('fniteronusermask is out of range: ' +fniteronusermask+' Please choose a value between 0 and 1 (inclusively)')
return sys.exit()
else:
pass
# # specmode, deconvolver and multiscale setup
# if multiscale:
# if specmode == 'mfs':
# mydeconvolver = 'mtmfs' # needed bc it's the only mfs mode implemented into sdint
# elif specmode == 'cube':
# mydeconvolver = 'multiscale'
# #numchan = nchan # not really needed here?
# mycell = myqa.convert(myqa.quantity(cell),'arcsec')['value']
# myscales = [0]
# for i in range(0, int(math.log(maxscale/mycell,3))):
# myscales.append(3**i*5)
#
# print("My scales (units of pixels): "+str(myscales))
#
# else:
# myscales = [0]
# if specmode == 'mfs':
# mydeconvolver = 'mtmfs' # needed bc the only mfs mode implemented into sdint
# elif specmode == 'cube':
# mydeconvolver = 'hogbom'
# #numchan = nchan # not really needed here?
# specmode, deconvolver and multiscale setup
if multiscale:
mydeconvolver = 'multiscale'
if maxscale==-1:
maxscale=derive_maxscale(vis, restfreq=restfreq)
myqa = qatool()
mycell = myqa.convert(myqa.quantity(cell),'arcsec')['value']
myscales = [0]
for i in range(0, int(math.log(maxscale/mycell,3))):
myscales.append(3**i*5)
print("My scales (units of pixels): "+str(myscales))
else:
myscales = [0]
mydeconvolver = 'hogbom'
# weighting schemes
if specmode == 'mfs':
weightingscheme ='briggs' # cont mode
elif specmode == 'cube':
if get_casa_version() >= '6.2.0':
weightingscheme ='briggsbwtaper' # special briggs for cubes --- CURRENTLY SWITCHED OFF FOR SDINT
else:
weightingscheme ='briggs'#bwtaper' # special briggs for cubes --- WAIT FOR IMPLEMENTATION IN SDINT
# others
npnt = 0
if phasecenter=='':
phasecenter = npnt
if restfreq=='':
therf = []
else:
therf = [restfreq]
clean_arg=dict(vis=vis,
field = field,
phasecenter=phasecenter,
imsize=imsize,
cell=cell,
spw=spw,
specmode=specmode,
deconvolver=mydeconvolver,
scales=myscales,
nterms=1, # nterms=1 turns mtmfs into mfs, CASA 6.2 needs nterms=2 to run (bug?)
start=start,
width=width,
nchan = nchan, # numchan,
restfreq=therf,
gridder='mosaic',
weighting = weightingscheme,
robust = 0.5,
restoringbeam = 'common', # SD-cube has only one beam - INT-cube needs it, too, else feather etc. fail
niter=niter,
cycleniter=cycleniter,
cyclefactor=2.0,
threshold=threshold,
interactive = interactive,
pbcor=True,
# Masking Parameters below this line
# --> Should be updated depending on dataset
usemask=usemask,
sidelobethreshold=sidelobethreshold,
noisethreshold=noisethreshold,
lownoisethreshold=lownoisethreshold,
minbeamfrac=minbeamfrac,
growiterations=growiterations,
negativethreshold=negativethreshold,
mask=mask,
pbmask=pbmask,
verbose=True)
return clean_arg
##########################################
def runsdintimg(vis,
sdimage,
imname,
sdpsf='',
sdgain=5,
dishdia=12.0,
spw='',
field='',
specmode='mfs',
imsize=[],
cell='',
phasecenter='',
start=0,
width=1,
nchan=-1,
restfreq='',
threshold='',
niter=0,
cycleniter=-1,
usemask= 'auto-multithresh',
sidelobethreshold=2.0,
noisethreshold=4.25,
lownoisethreshold=1.5,
minbeamfrac=0.3,
growiterations=75,
negativethreshold=0.0,
mask = '',
pbmask = 0.4,
interactive=True,
multiscale=False,
maxscale=0.,
continueclean=False,
renameexport=True,
loadmask=False,
fniteronusermask=0.3
):
"""
runsdintimg (D. Petry, ESO)
a wrapper around the CASA task "sdintimaging"
Currently, it provides 'cube' and 'mfs' as spectral modes - 'mtmfs'
might be implemented later.
steps:
- check if SD image has a beam
- if not present, create perplanebeams in SD image
- derive multiscale sizes for 'multiscale=True'
- clean parameter definition as known from tclean (analoguously to 'runtclean')
--- important fixed parameters you should be aware of:
restoring beam = common, nterms=1 (to get mfs from mtmfs),
weighting='briggs', robust = 0.5, gridder = 'mosaic'
- tidy up file names and rename to a uniform output-naming style
- exportfits pcbor
vis - the MS containing the interferometric data
sdimage - the Single Dish image
Note that in case you are creating a cube, this image must be a cube
with the same spectral grid as the one you are trying to create.
imname - the imagename of the output images
sdpsf - (optional) the SD PSF, must have the same coords as sdimage
if omitted or set to '' (empty string), a PSF will be derived
from the beam information in sdimage
sdgain - the weight of the SD data relative to the interferometric data
default: 5
'auto' - determine the scale automatically (experimental)
dishdia - in metres, (optional) used if no sdpsf is provided
default: 12.0
spw - the standard selection parameter spw of tclean
default: '' i.e. all SPWs
field - the standard selection parameter field of tclean
default: '' i.e. all fields
specmode - the standard tclean specmode parameter: supported are msf or cube
default: mfs
imsize - the standard tclean imsize parameter
should correspond to the imagesize for the most extended
interferometer config.
cell - the standard tclean cell parameter
should correspond to the cell size for the most extended
interferometer config, i.e. smallest beam / 5.
phasecenter - the standard tclean phasecenter parameter
e.g. 'J2000 12:00:00 -35.00.00.0000'
default: '' - determine from the input MS with aU.pickCellSize
start - the standard tclean start parameter
default: 0
width - the standard tclean width parameter
default: 1
nchan - the standard tclean nchan parameter
default: -1
restfreq - the restfrequency to write to the image for velocity calculations
default: None, example: '115.271GHz'
threshold - the tclean threshold
niter - the standard tclean niter parameter
default: 0, example: niter=1000000
cycleniter -
usemask - the standard tclean mask parameter. If usemask='auto-multithresh', can specify:
sidelobethreshold, noisethreshold, lownoisethreshold, minbeamfrac, growiterations -
if usemask='user', must specify mask='maskname.mask'
if usemask='pb', can specify pbmask=0.4, or some level.
default: 'auto-multithresh'
interactive - if True (default) use interactive cleaning with initial mask
set using pbmask=0.4
if False use non-interactive clean with automasking (you will
need to provide the threshold parameter)
multiscale - if False (default) use hogbom cleaning, otherwise multiscale
maxscale - for multiscale cleaning, use scales up to this value (arcsec)
Recommended value: 10 arcsec
default: 0.
continueclean - if True, continue the runsdintimg on the sdintimaging products
from a previous run. ALERT: previous run must have used renameexport=False,
else the needed products have been renamed or deleted
default: False
renameexport - sort out the relevant imaging products and rename them according to
the DC naming scheme, delete the rest.
ALERT: if you plan to call runsdintimg again to continue work on the
image products of the current run, set renameexport=False to keep the sdintimaging
products in their native output form
default: True
loadmask - run sdintimaging with user-specified mask for fniteronusermask*niter iterations
and continue with auto-masking (usemask='auto-multithresh') for the remaining
niter*(1-fniteronusermask) iterations
default: False
fniteronusermask - adjusting the amount of iterations spend on a usermask for loadmask=True
allowed values: 0.0 (none in theory, in fact: 1 iteration) - 1.0 (all)
default: 0.3
Examples: runsdintimg('gmc_120L.alma.all_int-weighted.ms','gmc_120L.sd.image',
'gmc_120L.joint-sdgain2.5', phasecenter='J2000 12:00:00 -35.00.00.0000',
sdgain=2.5, spw='0', field='0~68', imsize=[1120,1120], cell='0.21arcsec')
... will do an interactive clean for an agg. bw. image.
A pbmask at level 0.4 will be suggested as a start.
runsdintimg('gmc_120L.alma.all_int-weighted.ms','gmc_120L.sd.reimported.image',
'deepclean-automask-sdgain1.25', phasecenter='J2000 12:00:00 -35.00.00.0000',
sdgain=1.25, spw='0',field='0~68', imsize=[1120,1120], cell='0.21arcsec',
threshold='0.012Jy', interactive=False)
... will run a non-interactive clean for an agg. bw. image using automasking.
runsdintimg('ngc253.ms','ngc253-b6-tp-cube-200chan.image',
'ngc253-sdgain5', spw='0', specmode='cube', field='NGC_253',
imsize=[500, 500], cell='1.2arcsec', phasecenter=3, nchan = 200,
start=150, width=1, restfreq='230.538GHz')
... will run an interactive clean on a cube.
"""
# file checks
# if type(vis) is str:
# myvis = file_check(vis)
#
# if isinstance(vis, list):
# for i in range(0,len(vis)):
# file_check(vis[i]) # if one of the files does not exist, script will exit here
# myvis = vis
#
# #myvis = file_check(vis)
myvis = file_check_vis(vis)
mysdimage = file_check(sdimage)
mysdpsf = ''
if sdpsf!='':
mysdpsf = file_check(sdpsf)
if get_casa_version() >= '6.2.0':
if specmode == 'mfs':
print('For mysterious reasons sdintimaging in CASA versions >= 6.2.0 cannot handle mfs-mode (i.e. mtmfs with nterms=1) anymore :-( Please go back to CASA 6.1.2.7.')
#return sys.exit()
#if os.path.exists(vis):
# myvis = vis
#else:
# print(vis+' does not exist')
# return False
#
#
#if os.path.exists(sdimage):
# mysdimage = sdimage
#else:
# print(sdimage+' does not exist')
# return False
#
#mysdpsf = ''
#if sdpsf!='':
# if os.path.exists(sdpsf):
# mysdpsf = sdpsf
# else:
# print(sdpsf+' does not exist')
# return False
# # valid specmode?
# if specmode not in ['mfs', 'cube']:
# print('specmode \"'+specmode+'\" is not supported.')
# return False
#
#
# # valid threshold?
# if not type(threshold) == str or 'Jy' not in threshold:
# if not interactive:
# print("You must provide a valid threshold, example '1mJy'")
# return False
# else:
# print("You have not set a valid threshold. Please do so in the graphical user interface!")
# threshold = '1mJy'
# SDINT specific: check perplanebeams and create them if needed
myia = iatool()
myqa = qatool()
myhead = cta.imhead(mysdimage)
myaxes = list(myhead['axisnames'])
numchan = myhead['shape'][myaxes.index('Frequency')]
print('Testing whether the sd image has per channel beams ...')
myia.open(mysdimage)
try:
mybeam = myia.restoringbeam()
except:
myia.close()
cta.casalog.post('ERROR: sdimage does not contain beam information.', 'SEVERE',
origin='runsdintimg')
return False
haspcb=False
if 'beams' in mybeam.keys():
haspcb=True
cta.casalog.post("The sdimage has a per channel beam.", 'INFO',
origin='runsdintimg')
myia.close()
if not haspcb:
os.system('rm -rf '+mysdimage+'_*')
os.system('cp -R '+mysdimage+' '+mysdimage+'_copy')
if numchan == 1:
# image has only one channel; need workaround for per-channel-beam problem
myia.open(mysdimage+'_copy')
mycoords = myia.coordsys().torecord()
mycoords['spectral2']['wcs']['crval'] += mycoords['spectral2']['wcs']['cdelt']
myia.setcoordsys(mycoords)
myia.close()
tmpia = myia.imageconcat(outfile=mysdimage+'_pcb', infiles=[mysdimage, mysdimage+'_copy'],
axis=3, overwrite=True)
tmpia.close()
#mysdimage = mysdimage+'_pcb'
numchan = 2
else:
os.system('cp -R '+mysdimage+' '+mysdimage+'_pcb')
#os.system('cp -R '+mysdimage+' '+mysdimage+'_pcb')
mysdimage = mysdimage+'_pcb'
myia.open(mysdimage)
myia.setrestoringbeam(remove=True)
for i in range(numchan):
myia.setrestoringbeam(beam=mybeam, log=True, channel=i, polarization=0)
myia.close()
cta.casalog.post('Needed to give the sdimage a per-channel beam. Modifed image is in '+mysdimage, 'WARN',
origin='runsdintimg')
# # specmode, deconvolver and multiscale setup
# if multiscale:
# if specmode == 'mfs':
# mydeconvolver = 'mtmfs' # needed bc it's the only mfs mode implemented into sdint
# elif specmode == 'cube':
# mydeconvolver = 'multiscale'
# # mfs with nterms=1 uses numchan=2 despite nchan=-1
# # (due to artificial perplanebeams created above)
# # nchan=numchan is the parameter handed to sdintimaging below
# # --> set numchan=nchan, if cube
# numchan = nchan
# mycell = myqa.convert(myqa.quantity(cell),'arcsec')['value']
# myscales = [0]
# for i in range(0, int(math.log(maxscale/mycell,3))):
# myscales.append(3**i*5)
#
# print("My scales (units of pixels): "+str(myscales))
#
# else:
# myscales = [0]
# if specmode == 'mfs':
# mydeconvolver = 'mtmfs' # needed bc the only mfs mode implemented into sdint
# elif specmode == 'cube':
# mydeconvolver = 'hogbom'
# # mfs with nterms=1 uses numchan=2 despite nchan=-1
# # (due to artificial perplanebeams created above)
# # nchan=numchan is the parameter handed to sdintimaging below
# # --> set numchan=nchan, if cube
# numchan = nchan
#
#
# # weighting schemes
# if specmode == 'mfs':
# weightingscheme ='briggs' # cont mode
# elif specmode == 'cube':
# weightingscheme ='briggs'#bwtaper' # special briggs for cubes --- WAIT FOR IMPLEMENTATION IN SDINT
#
#
# # valid image and cell size?
# npnt = 0
# if imsize==[] or cell=='':
# cta.casalog.post('You need to provide values for the parameters imsize and cell.', 'SEVERE', origin='runsdintimg')
# return False
#
#
# # others
# if phasecenter=='':
# phasecenter = npnt
#
# if restfreq=='':
# therf = []
# else:
# therf = [restfreq]
if niter==0:
niter = 1
cta.casalog.post('You set niter to 0 (zero, the default), but sdintimaging can only produce an output for niter>0. niter = 1 set automatically. ', 'WARN')
# sdint_arg=dict(vis=myvis,
# imagename=imname,
# sdimage=mysdimage,
# field = field,
# phasecenter=phasecenter,
# imsize=imsize,
# cell=cell,
# spw=spw,
# specmode=specmode,
# deconvolver=mydeconvolver,
# scales=myscales,
# nterms=1, # nterms=1 turns mtmfs into mfs, CASA 6.2 needs nterms=2 to run (bug?)
# start=start,
# width=width,
# nchan = numchan,
# restfreq=therf,
# gridder='mosaic',
# #weighting='briggs',
# weighting = weightingscheme,
# robust = 0.5,
# restoringbeam = 'common', # SD-cube has only one beam - INT-cube needs it, too, else feather etc. fail
# niter=niter,
# #cycleniter = niter, # bogus if = niter
# cyclefactor=2.0,
# threshold=threshold,
# interactive = interactive,
# #perchanweightdensity=False, # better True (=default)?
# #pblimit=0.2, # default
# pbcor=True,
# sdpsf=mysdpsf,
# dishdia=dishdia,
# sdgain=sdgain,
# usedata='sdint',
# #interpolation='linear', # default
# #wprojplanes=1, # default & not needed
# usemask=usemask,
# sidelobethreshold=sidelobethreshold,
# noisethreshold=noisethreshold,
# lownoisethreshold=lownoisethreshold,
# minbeamfrac=minbeamfrac,
# growiterations=growiterations,
# negativethreshold=negativethreshold,
# mask=mask,
# pbmask=pbmask,
# verbose=True)
if specmode == 'cube':
# mfs with nterms=1 uses numchan=2 despite nchan=-1
# (due to artificial perplanebeams created above)
# nchan=numchan is the sdint_arg parameter handed to sdintimaging below
# --> set numchan=nchan, if cube
numchan = nchan
sdint_arg = check_prep_tclean_param(
myvis,
spw,
field,
specmode,
imsize,
cell,
phasecenter,
start,
width,
numchan,
restfreq,
threshold,
niter,
cycleniter,
usemask,
sidelobethreshold,
noisethreshold,
lownoisethreshold,
minbeamfrac,
growiterations,
negativethreshold,
mask,
pbmask,
interactive,
multiscale,
maxscale,
loadmask,
fniteronusermask
)
#sdint_arg['vis'] =myvis
sdint_arg['imagename'] =imname
sdint_arg['sdimage'] =mysdimage
sdint_arg['sdpsf'] =mysdpsf
sdint_arg['dishdia'] =dishdia
sdint_arg['sdgain'] =sdgain
sdint_arg['usedata'] ='sdint'
if get_casa_version() >= '6.2.0':
sdint_arg['weighting'] = 'briggs' # switch this off as soon as 'briggsbwtaper' is implemented into sdintimaging!
print('The applied weighting scheme is "briggs" and since "briggsbwtaper" is not yet implemented into sdintimaging.')
if specmode == 'mfs':
sdint_arg['deconvolver'] = 'mtmfs'
if continueclean == False:
# continueclean=True needs previous runsdint call to be executed
# with renameexport=False !!!!
os.system('rm -rf '+imname+'.*')
# if to be switched off, add command to delete "*.pbcor.fits"
if loadmask==True:
sdint_arg['usemask']='user'
if fniteronusermask==0 or fniteronusermask==0.0:
sdint_arg['niter']=1
else:
sdint_arg['niter']=int(niter*fniteronusermask)
# load mask into tclean with fniteronusermask*niter
print('')
print('### Load mask into sdintimaging with iterations = fniteronusermask*niter = ', fniteronusermask, ' * ', niter)
report_mask(sdint_arg['usemask'],sdint_arg['mask'],sdint_arg['pbmask'],sdint_arg['niter'])
tcleansresults = cta.sdintimaging(**sdint_arg)
sdint_arg['usemask']=usemask
sdint_arg['mask']=''
# if startmodel used, it would have been loaded in tclean step before
# -> clear startmodel parameter for next tclean call, else crash!
sdint_arg['startmodel']=''
sdint_arg['niter']=niter-sdint_arg['niter']
if sdint_arg['niter']<=0: #avoid negative niter values and pointless executions
pass
else:
# clean and get tclean-feedback
print('')
print('### Continue sdintimaging with iterations = (1-fniteronusermask)*niter = ', (1.0-fniteronusermask), ' * ', niter)
report_mask(sdint_arg['usemask'],sdint_arg['mask'],sdint_arg['pbmask'],sdint_arg['niter'])
tcleansresults = cta.sdintimaging(**sdint_arg)
else:
# clean and get tclean-feedback
report_mask(sdint_arg['usemask'],sdint_arg['mask'],sdint_arg['pbmask'],sdint_arg['niter'])
tcleansresults = cta.sdintimaging(**sdint_arg)
# store feedback in a file
pydict_to_file2(tcleansresults, imname)
os.system('cp -r summaryplot_1.png '+imname+'.png')
### SDINT Traditional OUTPUTS
## MTMFS - nterms=1
# *.int.cube.model/
# *.int.cube.pb/
# *.int.cube.psf/
# *.int.cube.residual/
# *.int.cube.sumwt/
# *.int.cube.weight/
# *.joint.cube.psf/
# *.joint.cube.residual/
# *.joint.multiterm.image.tt0/
# *.joint.multiterm.image.tt0.pbcor/
# *.joint.multiterm.image.tt0.pbcor.fits
# *.joint.multiterm.mask/
# *.joint.multiterm.model.tt0/
# *.joint.multiterm.pb.tt0/
# *.joint.multiterm.psf.tt0/
# *.joint.multiterm.residual.tt0/