-
Notifications
You must be signed in to change notification settings - Fork 1
/
DC_run.py
1659 lines (1217 loc) · 69.9 KB
/
DC_run.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
# do not modify the parameters in this script, instead use DC_pars.py
# See DC_script.py for an example how to use this script,
# users typically do not run this script directly
# After DC_pars.py defines the parameters this script works in two steps:
# - set up the filenames for a convention we use in the DC project
# - provide a number of snippets of code (currently 8) that can all
# or individually be selected to run. It uses routines from
# datacomb.py and standard CASA6 routines.
step_title = {0: 'Concat (optional)',
1: 'Prepare the SD-image',
2: 'Clean for Feather/Faridani',
3: 'Feather',
4: 'Faridani short spacings combination (SSC)',
5: 'Hybrid (startmodel clean + Feather)',
6: 'SDINT',
7: 'TP2VIS',
8: 'Assessment'
}
import os
import sys
import numpy as np
import casatasks as cta
from importlib import reload
import datacomb as dc
import IQA_script as iqa
# we do a reload here, because we often edit these in the same casa session
reload(dc)
reload(iqa)
import copy
import time
start = time.time()
decimal_places=6
### Tidy up old left-overs from previous runs
# switch this off, if you run multiple casa instances/DC_runs in the
# same work folder ! Else you delete files from another working process
#
#os.system('rm -rf '+pathtoimage + 'TempLattice*')
### user information
print(' ')
print('### ')
if dryrun==True:
print('Collecting filenames for assessment of ...')
else:
print('Will be executing the following steps ...')
for mystep in thesteps:
print('step ', mystep, step_title[mystep])
print('### ')
print(' ')
print(' ')
print('### ')
version = dc.get_casa_version()
print('You are running CASA version', version, '.')
if (2 in thesteps) or (5 in thesteps) or (6 in thesteps) or (7 in thesteps):
if version < '6.2.0':
print('All cleans are done with briggs weighting.')
if version >= '6.2.0':
print('All cubes are cleaned with briggsbwtaper weighting, except from sdintimaging (step 6, briggs weighting).')
print('All mfs images are cleaned with briggs weighting.')
print('sdintimaging does not offer mfs-mode in CASA >= 6.2.0')
#print('### ')
print('### ')
print(' ')
### put together file names and weights for concat, we allow 12m or 7m to be absent
thevis = []
weightscale = []
for i in range(len(a12m)):
if weight12m[i] > 0:
print("CONCAT will be using",a12m[i])
thevis.append(a12m[i])
weightscale.append(weight12m[i])
for i in range(len(a7m)):
if weight7m[i] > 0:
print("CONCAT will be using",a7m[i])
thevis.append(a7m[i])
weightscale.append(weight7m[i])
### define ms-file to perform combination on and file check
if vis=='':
vis = concatms
if not os.path.exists(vis):
if dryrun==True:
pass
elif 0 in thesteps:
pass
else:
thesteps.append(0)
thesteps.sort() # force execution of vis creation (Step 0)
print('Need to execute step 0 to generate a concatenated ms')
else:
dc.file_check(vis)
os.system('rm -rf '+vis+'.listobs')
cta.listobs(vis, listfile=vis+'.listobs')
### set up tclean parameter dictionary
general_tclean_param = dict(#overwrite = overwrite,
specmode = mode,
niter = nit,
cycleniter = t_cycleniter,
spw = t_spw,
field = t_field,
imsize = t_imsize,
cell = t_cell,
phasecenter = t_phasecenter,
start = t_start,
width = t_width,
nchan = t_nchan,
restfreq = t_restfreq,
threshold = t_threshold,
maxscale = t_maxscale,
mask = t_mask,
pbmask = t_pbmask,
sidelobethreshold = t_sidelobethreshold,
noisethreshold = t_noisethreshold,
lownoisethreshold = t_lownoisethreshold,
minbeamfrac = t_minbeamfrac,
growiterations = t_growiterations,
negativethreshold = t_negativethreshold)
### additional sdintimaging-specific parameters
sdint_tclean_param = dict(sdpsf = sdpsf,
dishdia = dishdia)
### naming scheme specific inputs:
if mode == 'mfs':
specsetup = 'nt1' # number of Taylor terms (compare mtmfs)
if inter == 'IA':
general_tclean_param['interactive'] = 1 # use 1 instead of True to get tclean feedback dictionary !
elif inter == 'nIA':
general_tclean_param['interactive'] = 0 # use 0 instead of False to get tclean feedback dictionary !
if mscale == 'HB':
general_tclean_param['multiscale'] = False
if mscale == 'MS':
general_tclean_param['multiscale'] = True # automated scale choice dependant on maxscale
############## naming convention ############
###### NONIT seems to be not needed anymore ####
cleansetup_nonit = '.'+ mode +'_'+ specsetup +'_'+ mscale +'_'+ masking +'_'+ inter
cleansetup = cleansetup_nonit +'_n'+ str(nit)
### output of combination methods ('combisetup')
tcleansetup = '.tclean'
feathersetup = '.feather_f' # added during combination: + str(sdfac)
SSCsetup = '.SSC_f' # added during combination: + str(SSCfac)
hybridsetup = '.hybrid_f' # added during combination: + str(sdfac_h)
sdintsetup = '.sdint_g' # added during combination: + str(sdg)
TP2VISsetup = '.TP2VIS_t' # added during combination: + str(TPfac)
##### intermediate products name for step 1 = gather information - no need to change!
# SD image axis-reordering, cut-out and regridding, mask names
sdreordered = sdbase +'.SD_ro.image' # SD image axis-reordering
if startchan!= None and endchan!=None and specsetup == 'SDpar':
sdbase = sdbase + '_ch'+str(startchan)+'-'+str(endchan)
else:
pass
sdreordered_cut = sdbase +'.SD_ro.image' # SD image axis-reordering
sdroregrid = sdbase +'.SD_ro-rg_'+specsetup+'.image' # SD image regridding
imnameth = imbase + '.'+mode +'_'+ specsetup +'_template' # dirty image for thershold and mask generation
threshmask = imbase + '.'+mode +'_'+ specsetup+ '_RMS' # thresold mask name
SD_mask_root = sdbase + '.'+mode +'_'+ specsetup+ '_SD' # SD mask name
combined_mask = SD_mask_root + '-RMS.mask' # SD+AM+threshold mask name
# masking mode setup
if masking == 'PB':
general_tclean_param['usemask'] = 'pb'
if masking == 'AM':
general_tclean_param['usemask'] = 'auto-multithresh'
if masking == 'UM':
#general_tclean_param['usemask'] = 'user'
general_tclean_param['usemask'] = 'auto-multithresh'
general_tclean_param['loadmask'] = True
general_tclean_param['fniteronusermask'] = fniteronusermask
if masking == 'SD-INT-AM':
if not os.path.exists(combined_mask) or not os.path.exists(threshmask+'.mask') or not os.path.exists(SD_mask_root+'.mask'):
if 1 in thesteps:
pass
else:
thesteps.append(1)
thesteps.sort() # force execution of SDint mask creation (Step 1)
print('Need to execute step 1 to generate an image mask')
general_tclean_param['usemask'] = 'auto-multithresh'
general_tclean_param['loadmask'] = True
general_tclean_param['fniteronusermask'] = fniteronusermask
# translate SD-INT-AM masks per combination method
SDAMmasks_userinput = [tclean_SDAMmask, hybrid_SDAMmask, sdint_SDAMmask, TP2VIS_SDAMmask]
for i in range(0,len(SDAMmasks_userinput)):
if SDAMmasks_userinput[i]=='INT':
SDAMmasks_userinput[i]=threshmask+'.mask'
elif SDAMmasks_userinput[i]=='SD':
SDAMmasks_userinput[i]=SD_mask_root+'.mask'
elif SDAMmasks_userinput[i]=='combined':
SDAMmasks_userinput[i]=combined_mask
else:
sys.exit()
tclean_mask, hybrid_mask, sdint_mask, TP2VIS_mask = SDAMmasks_userinput
# specsetup
if specsetup == 'SDpar':
if not os.path.exists(sdreordered_cut):
if 1 in thesteps:
pass
else:
thesteps.append(1)
thesteps.sort() # force execution of SDint mask creation (Step 1)
print('Need to execute step 1 to reorder image axes of the SD image')
elif os.path.exists(sdreordered_cut):
# read SD image frequency setup as input for tclean
cube_dict = dc.get_SD_cube_params(sdcube = sdreordered_cut) #out: {'nchan':nchan, 'start':start, 'width':width}
general_tclean_param['start'] = cube_dict['start']
general_tclean_param['width'] = cube_dict['width']
general_tclean_param['nchan'] = cube_dict['nchan']
sdimage = sdreordered_cut # for SD cube params used
elif specsetup == 'INTpar' or specsetup == 'nt1':
if not os.path.exists(sdroregrid):
if 1 in thesteps:
pass
else:
thesteps.append(1)
thesteps.sort() # force execution of SDint mask creation (Step 1)
print('Need to execute step 1 to regrid SD image')
elif os.path.exists(sdroregrid):
sdimage = sdroregrid # for INT cube params used
# mask-generation: common tclean parameters needed for creating a simple dirty image in step 1
rederivethresh=True # TP2VIS parameter to derive threshold for SD+INT.ms
mask_tclean_param = dict(phasecenter = general_tclean_param['phasecenter'],
spw = general_tclean_param['spw'],
field = general_tclean_param['field'],
imsize = general_tclean_param['imsize'],
cell = general_tclean_param['cell'],
specmode = general_tclean_param['specmode'],
start = general_tclean_param['start'],
width = general_tclean_param['width'],
nchan = general_tclean_param['nchan'],
restfreq = general_tclean_param['restfreq']
)
# mask generation: execute step 1 or 2, or use existing template
tcleanname = imbase + cleansetup + tcleansetup
if 1 in thesteps and dryrun==False:
pass
elif not os.path.exists(imnameth + '.image'): # or not os.path.exists(tcleanname + '.image'):
#elif not os.path.exists(threshmask + '.mask') or not os.path.exists(imnameth + '.image'):
#if 1 in thesteps:
# pass
#else:
thesteps.append(1)
thesteps.sort() # force execution of SDint mask creation (Step 1)
print('Need to execute step 1 to estimate a thresold')
else: #if imnameth/tcleanname + '.image' exists, simply re-derive the mask etc.
if os.path.exists(tcleanname + '.image'):
tempname = tcleanname
print('')
print('Derive mask and threshold from tcleaned image (step 2).')
else:
tempname = imnameth
print('')
print('Derive mask and threshold from dirty image (step 1).')
#thresh = dc.derive_threshold(#vis,
# imnameth , threshmask,
# #overwrite=False, # False for read-only,
# specmode = general_tclean_param['specmode'],
# smoothing = smoothing,
# threshregion = threshregion,
# RMSfactor = RMSfactor,
# cube_rms = cube_rms,
# cont_chans = cont_chans,
# #**mask_tclean_param
# makemask=True)
#
thresh = dc.make_masks_and_thresh(tempname, threshmask,
#overwrite=True,
sdimage, sdmasklev, SD_mask_root,
combined_mask,
specmode = general_tclean_param['specmode'],
smoothing = smoothing,
threshregion = threshregion,
RMSfactor = RMSfactor,
cube_rms = cube_rms,
cont_chans = cont_chans,
theoreticalRMS=theoreticalRMS,
makemask=True
)
print(' ')
if general_tclean_param['threshold'] == '': # don't forget to run *_pars_* before
rederivethresh=True # TP2VIS parameter
general_tclean_param['threshold'] = str(thresh)+'Jy'
#print('### Use mask threshold as clean threshold ', general_tclean_param['threshold'])
print('### Use INT mask threshold as clean threshold ', round(thresh, decimal_places), 'Jy' )
else:
rederivethresh=False # TP2VIS parameter
print('### Use user-defined clean threshold ', general_tclean_param['threshold'])
####### collect file names for assessment ######
tcleanims = []
featherims = []
SSCims = []
hybridims = []
sdintims = []
TP2VISims = []
# step numbers for filename suffix
thesteps2 = map(str, thesteps)
stepsjoin=''.join(thesteps2)
steps=stepsjoin.replace('0','').replace('1','').replace('8','')
steplist='_s'+steps # for assessment (step 8)
steplist2='_s'+stepsjoin # for runtime measurement
mystep = 0 ###################----- CONCAT -----####################
if mystep in thesteps:
cta.casalog.post('### ','INFO')
cta.casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
cta.casalog.post('### ','INFO')
print(' ')
print('### ------------------------------------------------')
print('Step ', mystep, step_title[mystep])
print('### ------------------------------------------------')
print(' ')
if dryrun == True:
print('Skip execution!')
else:
if thevis ==[]:
print('No data to concat!')
else:
print(' vis:')
print(*thevis, sep = "\n")
print(' concatvis:')
print(concatms)
for i in range(0,len(thevis)):
if '.aca.tp.' in thevis[i]:
print('')
print('')
print('-------------------------------- ! ERROR ! --------------------------------')
print('')
print(thevis[i]+' is a total power/single dish data set.')
print('Cannot concatenate it into an interferometric data set.')
print('')
print('-------------------- ! ABORT PROGRAM WITH SYSTEMEXIT ! --------------------')
print('')
print('')
sys.exit()
else:
dc.check_CASAcal(thevis[i])
print(' ')
print('Starting CONCAT')
os.system('rm -rf '+concatms)
cta.concat(vis = thevis, concatvis = concatms, visweightscale = weightscale)
os.system('rm -rf '+concatms+'.listobs')
cta.listobs(concatms, listfile=concatms+'.listobs')
print('--- Done! ---')
mystep = 1 #########----- PREPARE SD-IMAGE and MASKS -----##########
if mystep in thesteps:
cta.casalog.post('### ','INFO')
cta.casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
cta.casalog.post('### ','INFO')
print(' ')
print('### ------------------------------------------------')
print('Step ', mystep, step_title[mystep])
print('### ------------------------------------------------')
print(' ')
if dryrun == True:
print('Skip execution!')
else:
# axis reordering
print(' ')
print('--- Reorder SD image axes ---')
dc.reorder_axes(sdimage_input, sdreordered)
print('--- Axis reorder done! --- ')
# make a channel-cut-out from the SD image?
if sdreordered!=sdreordered_cut:
print(' ')
print('--- Make a channel-cut-out from the SD image from channel', startchan, 'to', endchan, '--- ')
dc.channel_cutout(sdreordered, sdreordered_cut, startchan = startchan,
endchan = endchan)
print('--- Channel-cut-out done! --- ')
# read SD image frequency setup as input for tclean
if specsetup == 'SDpar':
print(' ')
print('--- Read SD image frequency setup as input for tclean ---')
cube_dict = dc.get_SD_cube_params(sdcube = sdreordered_cut) #out: {'nchan':nchan, 'start':start, 'width':width}
general_tclean_param['start'] = cube_dict['start']
general_tclean_param['width'] = cube_dict['width']
general_tclean_param['nchan'] = cube_dict['nchan']
sdimage = sdreordered_cut # for SD cube params used
print('--- Tclean frequency setup done! --- ')
# make dirty image
print(' ')
print('--- Make dirty image for regridding SD image and INT mask --- ')
dc.runtclean(vis,imnameth,
niter=0, interactive=False,
**mask_tclean_param)
# regrid SD image frequency axis to tclean (requires runtclean to be run)
if specsetup == 'SDpar':
sdimage = sdreordered_cut # for SD cube params used
else:
print('')
print('--- Regrid SD image --- ')
os.system('rm -rf '+sdroregrid)
dc.regrid_SD(sdreordered_cut, sdroregrid, imnameth+'.image')
sdimage = sdroregrid # for INT cube params used
print('--- Regridding done! --- ')
## just for testing - if it fails then the common beam in regridSD didn't work
#hdr = imhead(sdimage,mode='summary')
#beam_major = hdr['restoringbeam']['major']
# Derive INT threshold, INT mask, SD mask, and combined mask
thresh = dc.make_masks_and_thresh(imnameth, threshmask,
#overwrite=True,
sdimage, sdmasklev, SD_mask_root,
combined_mask,
specmode = general_tclean_param['specmode'],
smoothing = smoothing,
threshregion = threshregion,
RMSfactor = RMSfactor,
cube_rms = cube_rms,
cont_chans = cont_chans,
theoreticalRMS=theoreticalRMS,
makemask=True
)
print(' ')
if general_tclean_param['threshold'] == '':
rederivethresh=True # TP2VIS parameter
#userthresh=False ### parameter gone?
general_tclean_param['threshold'] = str(thresh)+'Jy'
print('### Use INT mask threshold as clean threshold ', round(thresh, decimal_places), 'Jy' )
#print('Set the tclean-threshold to ', general_tclean_param['threshold'])
else:
rederivethresh=False # TP2VIS parameter
#userthresh=True ### parameter gone?
print('### Use user-defined clean threshold ', general_tclean_param['threshold'])
mystep = 2 ############----- CLEAN FOR FEATHER/SSC -----############
if mystep in thesteps:
cta.casalog.post('### ','INFO')
cta.casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
cta.casalog.post('### ','INFO')
print(' ')
print('### ------------------------------------------------')
print('Step ', mystep, step_title[mystep])
print('### ------------------------------------------------')
print(' ')
imname = imbase + cleansetup + tcleansetup
if masking == 'SD-INT-AM':
general_tclean_param['mask'] = tclean_mask
z = general_tclean_param.copy()
if dryrun == True:
print('Skip execution!')
else:
dc.runtclean(vis, imname, startmodel='',
**z)
# update masking for tcleaned image as template !
# Derive INT threshold, INT mask, SD mask, and combined mask
thresh = dc.make_masks_and_thresh(imname, threshmask,
#overwrite=True,
sdimage, sdmasklev, SD_mask_root,
combined_mask,
specmode = general_tclean_param['specmode'],
smoothing = smoothing,
threshregion = threshregion,
RMSfactor = RMSfactor,
cube_rms = cube_rms,
cont_chans = cont_chans,
theoreticalRMS=theoreticalRMS,
makemask=True
)
print(' ')
if general_tclean_param['threshold'] == '':
rederivethresh=True # TP2VIS parameter
#userthresh=False ### parameter gone?
general_tclean_param['threshold'] = str(thresh)+'Jy'
print('### Use INT mask threshold as clean threshold ', round(thresh, decimal_places), 'Jy' )
#print('Set the tclean-threshold to ', general_tclean_param['threshold'])
else:
rederivethresh=False # TP2VIS parameter
#userthresh=True ### parameter gone?
print('### Use user-defined clean threshold ', general_tclean_param['threshold'])
tcleanims.append(imname+'.image')
mystep = 3 ###################----- FEATHER -----###################
if mystep in thesteps:
cta.casalog.post('### ','INFO')
cta.casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
cta.casalog.post('### ','INFO')
print(' ')
print('### ------------------------------------------------')
print('Step ', mystep, step_title[mystep])
print('### ------------------------------------------------')
print(' ')
#intimage='/data/moser/data_combi/DC/DC_Ly_tests//pointGauss/BGauss_3L.image_ro_reg'
#intpb='/data/moser/data_combi/DC/DC_Ly_tests//pointGauss/BGauss_3L.pb_ro_reg'
intimage = imbase + cleansetup + tcleansetup + '.image'
intpb = imbase + cleansetup + tcleansetup + '.pb'
for i in range(0,len(sdfac)):
#imname = '/data/moser/data_combi/DC/DC_Ly_tests//pointGauss/BGauss_3L' + feathersetup + str(sdfac[i])
imname = imbase + cleansetup + feathersetup + str(sdfac[i])
if dryrun == True:
print('Skip execution!')
else:
dc.runfeather(intimage, intpb, sdimage, sdfactor = sdfac[i],
featherim = imname)
featherims.append(imname+'.image')
mystep = 4 ################----- FARIDANI SSC -----#################
if mystep in thesteps:
cta.casalog.post('### ','INFO')
cta.casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
cta.casalog.post('### ','INFO')
print(' ')
print('### ------------------------------------------------')
print('Step ', mystep, step_title[mystep])
print('### ------------------------------------------------')
print(' ')
#intimage='/data/moser/data_combi/DC/DC_Ly_tests//pointGauss/BGauss_3L.image_ro_reg'
#intpb='/data/moser/data_combi/DC/DC_Ly_tests//pointGauss/BGauss_3L.pb_ro_reg'
intimage = imbase + cleansetup + tcleansetup + '.image'
intpb = imbase + cleansetup + tcleansetup + '.pb'
for i in range(0,len(SSCfac)):
#imname = '/data/moser/data_combi/DC/DC_Ly_tests//pointGauss/BGauss_3L' + SSCsetup + str(SSCfac[i])
imname = imbase + cleansetup + SSCsetup + str(SSCfac[i])
if dryrun == True:
print('Skip execution!')
else:
os.system('rm -rf '+imname+'*')
dc.ssc(highres=intimage, lowres=sdimage, pb=intpb,
sdfactor = SSCfac[i], combined=imname)
SSCims.append(imname+'.image')
mystep = 5 ###################----- HYBRID -----####################
if mystep in thesteps:
cta.casalog.post('### ','INFO')
cta.casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
cta.casalog.post('### ','INFO')
print(' ')
print('### ------------------------------------------------')
print('Step ', mystep, step_title[mystep])
print('### ------------------------------------------------')
print(' ')
if masking == 'SD-INT-AM':
general_tclean_param['mask'] = hybrid_mask
z = general_tclean_param.copy()
for i in range(0,len(sdfac_h)):
imname = imbase + cleansetup + hybridsetup
if dryrun == True:
print('Skip execution!')
else:
dc.runWSM(vis, sdimage, imname, sdfactorh = sdfac_h[i],
**z)
hybridims.append(imname+str(sdfac_h[i])+'.image')
mystep = 6 ####################----- SDINT -----####################
if mystep in thesteps:
cta.casalog.post('### ','INFO')
cta.casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
cta.casalog.post('### ','INFO')
print(' ')
print('### ------------------------------------------------')
print('Step ', mystep, step_title[mystep])
print('### ------------------------------------------------')
print(' ')
if masking == 'SD-INT-AM':
general_tclean_param['mask'] = sdint_mask
z = general_tclean_param.copy()
z.update(sdint_tclean_param)
for i in range(0,len(sdg)) :
jointname = imbase + cleansetup + sdintsetup + str(sdg[i])
if dryrun == True:
print('Skip execution!')
else:
dc.runsdintimg(vis, sdimage, jointname, sdgain = sdg[0],
**z)
sdintims.append(jointname+'.image')
mystep = 7 ###################----- TP2VIS -----####################
if mystep in thesteps:
cta.casalog.post('### ','INFO')
cta.casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
cta.casalog.post('### ','INFO')
print(' ')
print('### ------------------------------------------------')
print('Step ', mystep, step_title[mystep])
print('### ------------------------------------------------')
print(' ')
# get 12m pointings to simulate TP observation as interferometric
if dryrun == True:
print('Skip execution!')
else:
if TPpointingTemplate!='' and dc.file_check_vis_str_only(TPpointingTemplate)==TPpointingTemplate: #a12m!=[]: # if 12m-data exists ...
print('Creating pointing table from template data set:', TPpointingTemplate)
#dc.ms_ptg(TPpointingTemplate, outfile=TPpointinglist, uniq=True)
dc.listobs_ptg(TPpointingTemplate, listobsOutput, TPpointinglist, Epoch=Epoch)
else:
print('Using user-provided pointing table:', TPpointinglistAlternative)
TPpointinglist = TPpointinglistAlternative
print('')
# create 'TP.ms', i.e. SD visibilities
if specsetup == 'SDpar':
imTP = sdreordered_cut
else:
imTP = sdreordered
TPresult= imTP.replace('.image','.ms')
imname1 = imbase + cleansetup + TP2VISsetup # first plot
if dryrun == True:
pass
else:
dc.create_TP2VIS_ms(imTP=imTP, TPresult=TPresult,
TPpointinglist=TPpointinglist, mode=mode,
vis=vis, imname=imname1, TPnoiseRegion=TPnoiseRegion,
TPnoiseChannels=TPnoiseChannels)
# bring TP.ms and INT.ms on same spectral reference frame before tclean
#
# models typically do not need this, so we have a new (but optional)
# no_transform = True variable in DC_pars.py
transvis = vis+'_LSRK'
if dryrun == True:
pass
else:
if not 'no_transform' in locals():
no_transform = False
if not no_transform:
dc.transform_INT_to_SD_freq_spec(TPresult, imTP, vis,
transvis, datacolumn='DATA', outframe='LSRK')
else:
transvis = vis
# make TP2VIS image (tclean)
if masking == 'SD-INT-AM':
general_tclean_param['mask'] = TP2VIS_mask
z = general_tclean_param.copy()
z['rederivethresh']=rederivethresh
for i in range(0,len(TPfac)) :
imname = imbase + cleansetup + TP2VISsetup + str(TPfac[i])
vis=transvis #!
if dryrun == True:
pass
else:
dc.runtclean_TP2VIS_INT(TPresult, TPfac[i], vis, imname,
RMSfactor=RMSfactor, threshregion=threshregion,
cube_rms=cube_rms, cont_chans = cont_chans,
theoreticalRMS=theoreticalRMS, **z)
if os.path.exists(imname+'.tweak.image'):
TP2VISims.append(imname+'.tweak.image')
else:
TP2VISims.append(imname+'.image')
mystep = 8 #################----- ASSESSMENT -----##################
if mystep in thesteps:
cta.casalog.post('### ','INFO')
cta.casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
cta.casalog.post('### ','INFO')
print(' ')
print('### ------------------------------------------------')
print('Step ', mystep, step_title[mystep])
print('### ------------------------------------------------')
print(' ')
# set assessment threshold value
if assessment_thresh == None:
if mode=='cube':
image_rms = thresh/cube_rms #*3. # 3 sigma limit
if mode=='mfs':
image_rms = thresh/RMSfactor #*3. # 3 sigma limit
clip_string = 'Clipping maps at rms level of '+str(round(image_rms,decimal_places))+ ' Jy/beam'
elif assessment_thresh == 'clean-thresh':
image_rms = float(general_tclean_param['threshold'].replace('Jy',''))
clip_string = 'Clipping maps at clean threshold level of '+str(round(image_rms,decimal_places))+ ' Jy/beam'
else:
image_rms = assessment_thresh
clip_string = 'Clipping maps at user-defined level of '+str(round(image_rms,decimal_places))+ ' Jy/beam'
print('###')
print('### Assessment: '+clip_string)
#print('### Clipping level for the assessment of the maps was at %.6f Jy/beam' %image_rms)
print('###')
print('')
#### imbase = pathtoimage + 'skymodel-b_120L
sourcename = imbase.replace(pathtoimage,'')
# folder to put the assessment images to
assessment=pathtoimage + 'assessment_'+sourcename+cleansetup+'_thresh'+str(round(image_rms,6))
os.system('mkdir '+assessment)
########## list residuals, threshold and stopping criteria ############
tcleanres = []
hybridres = []
sdintres = []
TP2VISres = []
if (2 in thesteps) or (3 in thesteps) or (4 in thesteps): # and (tcleanres != []):
tcleanres = [imbase + cleansetup + tcleansetup + '.image']
if 5 in thesteps: hybridres = [imbase + cleansetup + hybridsetup + '.image']
if 6 in thesteps: sdintres = sdintims
if 7 in thesteps: TP2VISres = TP2VISims
allcombires=tcleanres + hybridres + sdintres + TP2VISres
allcombires = [a.replace('.tweak','') for a in allcombires]
allcombires = [a.replace('.image','.residual') for a in allcombires]
allcombimask = [a.replace('.residual','.mask') for a in allcombires]
allcombitxt = [a.replace('.residual', '') for a in allcombires]
#print(allcombimask)
#print(allcombires[0])
stop_crit=[]
cleanthresh=[]
cleaniterdone = []
if mapchan==None:
mapchan=int(general_tclean_param['nchan']/2.)
if nit>0:
print(' ')
print(' ')
print('Showing residual maps and tclean masks, stopping criteria, and thresholds for ')
print(*allcombires, sep = "\n")
print(' ')
for i in range(0, len(allcombitxt)):
os.system('rm -rf ' + allcombires[i] + '.fits')
os.system('rm -rf ' + allcombimask[i] + '.fits')
cta.exportfits(imagename=allcombires[i], fitsimage=allcombires[i] + '.fits', dropdeg=True)
cta.exportfits(imagename=allcombimask[i], fitsimage=allcombimask[i] + '.fits', dropdeg=True)
tcleanresults = dc.file_to_pydict2(allcombitxt[i])
dc.pydict_to_file(tcleanresults, allcombitxt[i]) # export to human readable format
#print(tcleanresults['threshold'])
stop_crit.append(tcleanresults['stopcode'])
cleanthresh.append(tcleanresults['threshold'])
cleaniterdone.append(tcleanresults['iterdone'])
#allcombiresfits = [a.replace('.residual','.residual.fits') for a in allcombires]
#allcombimaskfits = [a.replace('.mask','.mask.fits') for a in allcombimask]
#labelnames
allcombireslabel = [a.replace(pathtoimage+sourcename+cleansetup+'.','') for a in allcombitxt]
iqa.show_residual_maps(allcombires, allcombimask,
channel=mapchan,
save=True,
plotname=assessment+'/Residual_maps_'+sourcename+cleansetup+steplist,
labelname=allcombireslabel,
titlename='Residual maps in channel '+str(mapchan)+' from the tclean instances used by the chosen \n combination methods for '+sourcename+cleansetup,
stop_crit=stop_crit,
cleanthresh=cleanthresh,
cleaniterdone=cleaniterdone)
#tcleanims = ['/data/moser/data_combi/DC/DC_Ly_tests//pointGauss/BGauss_3L.image']
#featherims = ['/data/moser/data_combi/DC/DC_Ly_tests//pointGauss/BGauss_3L.feather_f1.0.image']
#SSCims = ['/data/moser/data_combi/DC/DC_Ly_tests//pointGauss/BGauss_3L.SSC_f1.0.image']
########## Assessment with respect to SD image ############
os.system('rm -rf ' + sdroregrid + '.fits')
cta.exportfits(imagename=sdroregrid, fitsimage=sdroregrid + '.fits', dropdeg=True)
allcombims0 = tcleanims + featherims + SSCims + hybridims + sdintims + TP2VISims
#print(allcombims)
print(' ')
print(' ')
print('Running assessment with respect to SD image on ')
print(*allcombims0, sep = "\n")
print(' ')
allcombims = [a.replace('.image','.image.pbcor') for a in allcombims0]
allcombpbs = [a.replace('.image','.pb') for a in allcombims0]
allcombimsfits = [a.replace('.image.pbcor','.image.pbcor.fits') for a in allcombims]
# make comparison plots
#labelnames
allcombi = [a.replace(pathtoimage+sourcename+cleansetup+'.','').replace('.image.pbcor','') for a in allcombims]
# show combi products
combitoplot=allcombims.copy()
labeltoplot=allcombi.copy()