-
Notifications
You must be signed in to change notification settings - Fork 3
/
calibrate_image.py
3530 lines (3164 loc) · 150 KB
/
calibrate_image.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
"""
Todo:
-quality metrics:
- # of sources detected
-sub-bands & sub-exposures together
To debug:
-table output
-table output of null strings
-table output of filenames
-output of CASA calibrator file in a different directory
"""
import logging,logging.handlers,datetime,math,sys,socket,os,shutil,io,re
try:
import matplotlib
matplotlib.use('PDF')
from matplotlib import pyplot as plt
_matplotlib=True
except:
_matplotlib=False
from optparse import OptionParser,OptionGroup
import time,tempfile
import subprocess,fcntl
from astropy.table import Table,Column
import collections,glob,numpy
from astropy.io import fits
from astropy.coordinates import SkyCoord,get_sun
import astropy
from astropy import constants as c, units as u
from astropy.wcs import WCS
import extra_utils
logger=extra_utils.makelogger('calibrate_image')
import mwapy
from mwapy import metadata
from mwapy.pb import make_beam
# try to use Peter Williams' casac interface
try:
import drivecasa
_OLDCASA=True
except ImportError:
#logger.error('Unable to import drivecasa')
_OLDCASA=False
try:
import casac
_CASA=True
import pwkit.environments.casa.tasks as tasklib
import pwkit.environments.casa.util as casautil
except ImportError:
logger.warning('Unable to import casacore')
_CASA=False
try:
from AegeanTools.regions import Region
from AegeanTools import source_finder, BANE, MIMAS
# make the logging output from aegean more reasonable
logging.getLogger("Aegean").setLevel(logging.INFO)
_aegean=True
except ImportError:
logger.error('Unable to import aegean')
_aegean=False
##################################################
# default search paths for ANOKO/mwa-reduce
# the ANOKO path should contain calibrate and applysolutions
##################################################
anokopath=['~kaplan/mwa/anoko/mwa-reduce/build/',
'/usr/physics/mwa/pkg/anoko/mwa-reduce/build/']
catalogdir=os.path.join(os.path.split(os.path.abspath(__file__))[0],'catalogs')
#calmodelfile=os.path.join(catalogdir,'model_a-team.txt')
anokocatalog=os.path.join(catalogdir,'model-catalogue_new.txt')
calmodelfile=anokocatalog
anoko=None
# this defines aliases for source names in the anoko
# calibrator model file
# e.g., if the metafits says "PictorA", also look for "PicA" in the model file
# can be many -> one mapping
calmodelaliases={'PicA': ['PictorA'],
'PKS2331-41': ['J2334-4'],
'HydA': ['HydraA']}
# invert the alias dictionary for faster lookup
calmodelaliases_inverse={}
for k in calmodelaliases.keys():
for v in calmodelaliases[k]:
calmodelaliases_inverse[v]=k
# these are sources that don't calibrate well with Anoko
badanokosources=['3C444','PKS2356-61']
if not os.path.exists(calmodelfile):
logger.warning('Unable to find calibrator model file %s' % calmodelfile)
if not os.path.exists(anokocatalog):
logger.warning('Unable to find anoko autoprocess catalog file %s' % anokocatalog)
brightsources={'3C353': SkyCoord('17h20m28.1s','-00d58m47s'),
'3C409': SkyCoord('20h14m27.6s','23d34m53s'),
'3C444': SkyCoord('-01h45m34.4s','-17d01m30s'),
'CasA': SkyCoord('23h23m27.9s','58d48m42s'),
'CenA': SkyCoord('13h25m27.6s','-43d01m09s'),
'Crab': SkyCoord('05h34m32.0s','22d00m52s'),
'CygA': SkyCoord('19h59m28.4s','40d44m02s'),
'ESO362-G021': SkyCoord('05h22m58.0s','-36d27m31s'),
'ForA': SkyCoord('3h22m41.7s','-37d12m30s'),
'HerA': SkyCoord('-07h08m52.1s','04d59m16s'),
'HydA': SkyCoord('09h18m05.1s','-12d05m42s'),
'NGC253': SkyCoord('00h47m34.7s','-25d17m30s'),
'PicA': SkyCoord('05h19m30.7s','-45d45m35s'),
'PKS2153-69': SkyCoord('21h57m06.0s','-69d41m24s'),
'PKS2331-41': SkyCoord('23h34m26.2s','-41d25m24s'),
'PKS2356-61': SkyCoord('23h59m04.3s','-60d54m59s'),
'PKSJ0130-2610': SkyCoord('01h30m27.8s','-26d09m56s'),
'VirA': SkyCoord('12h30m49.4s','12d23m28s')}
##################################################
def non_block_read(output):
"""
allows for non-blocking read during a subprocess call
https://gist.github.com/sebclaeys/1232088
"""
fd = output.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
try:
return output.read()
except:
return ""
##################################################
def checkforlock(ms):
"""
checks for a CASA lock file
if it finds it, it will delete
"""
for root, dirs, files in os.walk(ms):
for name in files:
if name == 'table.lock':
logger.debug('Removing CASA table lock from %s' % os.path.join(root,name))
os.remove(os.path.join(root,name))
##################################################
def getstatus(p, output=None, error=None):
"""
pollresults=getstatus(p, output=None, error=None)
p is a list of subprocess instances
this checks if they are finished
and returns a list of False if still running or True if stopped
"""
poll=[]
for j in xrange(len(p)):
try:
poll.append(p[j].poll() is not None)
except:
poll.append(None)
if output is not None:
try:
output[j].flush()
except:
pass
if error is not None:
try:
error[j].flush()
except:
pass
return poll
##################################################
def stat_measure(image, fraction=0.5, nonan=True):
"""
median, rms = stat_measure(image, fraction=0.5, nonan=True)
uses the central fraction of the image to compute
the median and rms (using inner-quartile range)
"""
if fraction>1:
fraction=1
if isinstance(image,str):
try:
f=fits.open(image)
except Exception,e:
logger.error('Unable to open FITS image %s:\n\t%s' % (image,e))
return None,None
else:
f=image
if 'RA' in f[0].header['CTYPE1']:
data=f[0].data
else:
data=f[0].data.T
# now it should be Stokes, Freq, Dec, RA
ny,nx=data.shape[2],data.shape[3]
ytouse=ny*fraction
ystart=(ny/2)-ytouse/2
ystop=(ny/2)+ytouse/2
xtouse=nx*fraction
xstart=(nx/2)-xtouse/2
xstop=(nx/2)+xtouse/2
d=(data[:,:,int(ystart):int(ystop),int(xstart):int(xstop)]).flatten()
if nonan:
d=d[~numpy.isnan(d)]
q1,m,q2=numpy.percentile(d, [25,50,75])
return m,(q2-q1)/1.35
##################################################
def match_aegean_sources(sourcelist1, sourcelist2):
matchradius=10*u.arcsec
I1=[]
I2=[]
coords1=SkyCoord([s.ra for s in sourcelist1],
[s.dec for s in sourcelist1],unit=(u.deg,u.deg))
coords2=SkyCoord([s.ra for s in sourcelist2],
[s.dec for s in sourcelist2],unit=(u.deg,u.deg))
S1=[]
S2=[]
for i in xrange(len(coords1)):
d=coords1[i].separation(coords2)
if d.min() < matchradius:
if (not i in I1) and (not numpy.argmin(d) in I2):
I1.append(i)
I2.append(numpy.argmin(d))
for i in xrange(len(I1)):
S1.append(sourcelist1[I1[i]])
S2.append(sourcelist2[I2[i]])
return S1,S2
##################################################
def circle2mimas(ra, dec, radius, filename):
"""
circle2mimas(ra, dec, radius)
ra,dec,radius in decimal regrees
"""
r=Region()
r.add_circles(numpy.radians(ra),
numpy.radians(dec),
numpy.radians(radius))
MIMAS.save_region(r, filename)
return filename
##################################################
class ANOKOfinder():
"""
"""
path=anokopath
def __init__(self, *args):
"""
"""
if len(args)>0:
self.paths= list(args) + ANOKOfinder.path
else:
self.paths=ANOKOfinder.path
def find(self):
actualanoko=None
if os.environ.has_key('ANOKO'):
actualanoko=os.environ['ANOKO']
logger.debug('Identified ANOKO %s from $ANOKO' % actualanoko)
else:
for path in self.paths:
if path is None:
continue
path=os.path.expanduser(path)
if os.path.exists(path) and os.path.exists(os.path.join(path,'calibrate')) and os.path.exists(os.path.join(path,'applysolutions')):
actualanoko=path
logger.debug('Identified ANOKO %s' % actualanoko)
break
if actualanoko is None:
logger.error('No ANOKO identified')
return None
if not os.path.exists(actualanoko):
logger.error('ANOKO %s does not exist' % actualanoko)
return None
if not (os.path.exists(os.path.join(actualanoko,'calibrate')) and os.path.exists(os.path.join(actualanoko,'applysolutions'))):
logger.error('ANOKO executables %s and %s do not exist' % ('calibrate','applysolutions'))
return None
return actualanoko
##################################################
def makemetafits(obsid, directory=None):
"""
makemetafits(obsid)
returns metafits name on success
or None on failure
"""
m=metadata.instrument_configuration(int(obsid))
h=m.make_metafits()
if directory is None:
metafits='%s.metafits' % obsid
else:
metafits=os.path.join(directory,'%s.metafits' % obsid)
if os.path.exists(metafits):
os.remove(metafits)
try:
h.writeto(metafits)
logger.info('Metafits written to %s' % (metafits))
return metafits
except Exception, e:
logger.error('Unable to write metafits file %s:\n%s' % (metafits,e))
return None
##################################################
def get_msinfo(msfile):
"""
chanwidth, inttime, otherkeys=get_msinfo(msfile)
chanwidth is channel width in kHz
inttime is integration time in s
otherkeys is a dictionary containing other header keywords
"""
if not _CASA:
logger.error("CASA operation not possible")
return None
ms=casac.casac.ms()
ms.open(msfile)
chanwidth=ms.getspectralwindowinfo()["0"]['ChanWidth']/1e3
nchans=ms.getspectralwindowinfo()["0"]['NumChan']
inttime=ms.getscansummary()['1']['0']['IntegrationTime']
reffreq=ms.getspectralwindowinfo()["0"]['RefFreq']
ms.close()
t=casac.casac.table()
t.open(msfile)
otherkeys=t.getkeywords()
t.close()
logger.debug('Determined channel width of %d kHz for %s' % (chanwidth,msfile))
logger.debug('Determined integration time of %.1f s for %s' % (inttime,msfile))
logger.debug('Determined %d channels for %s' % (nchans,msfile))
logger.debug('Determined reference frequency of %.1f MHz for %s' % (reffreq/1e6,msfile))
return chanwidth, inttime, nchans, reffreq, otherkeys
##################################################
def check_calibrated(msfile):
"""
check_calibrated(msfile)
checks for presence of CORRECTED_DATA column in a ms file
"""
if not _CASA:
logger.error("CASA operation not possible")
return None
t=casac.casac.table()
t.open(msfile)
return "CORRECTED_DATA" in t.colnames()
##################################################
# from mwapy/casac_ft_beam
# based on mwapy/ft_beam
# Generate automatic calibration model and form a bandpass solution
# Natasha Hurley-Walker 10/07/2013
# Updated 08/08/2013 to scale the YY and XX beams separately
# Updated 01/10/2013 Use the field name as the calibrator name if the calibrator wasn't filled in properly during scheduling
# Updated 21/11/2013 Added sub-calibrators to complex fields (but didn't find much improvement)
# Updated 02/12/2013 Added a spectral beam option; turned subcalibrators off by default
# Updated 10/03/2014 Try to get the calibrator information from the metafits file
# Updated 18/08/2014 Improved astropy/pyfits compatibility and added option to switch off beam correction
# updated 18/08/2016 to use Peter William's casa python bindings instead of being called from within casa environment (DLK)
##################################################
def importfits(fitsimage, imagename):
"""
A simplified version of task_importfits
"""
ia = casautil.tools.image ()
ia.fromfits(imagename, fitsimage)
##################################################
def ft_beam(vis=None,refant='Tile012',clobber=True,correct_beam=True,
spectral_beam=False,
subcalibrator=False,uvrange='>0.03klambda',
outdir='./'):
"""
def ft_beam(vis=None,refant='Tile012',clobber=True,correct_beam=True
spectral_beam=False,
subcalibrator=False,uvrange='>0.03klambda',outdir='./'):
# Reference antenna
refant='Tile012'
# Overwrite files
clobber=True
# Option to correct for the attenuation effects of the primary beam
correct_beam=True
# Option to include the spectral index of the primary beam
spectral_beam=False
# Option to add more sources to the field
"""
modeldir=os.environ['MWA_CODE_BASE']+'/MWA_Tools/Models/'
if not os.path.exists(modeldir):
logger.error('Model directory %s does not exist' % modeldir)
return None
qa = casautil.tools.quanta()
# output calibration solution
caltable=os.path.join(outdir,re.sub('ms','cal',vis))
if vis is None or len(vis)==0 or not os.path.exists(vis):
logger.error('Input visibility must be defined')
return None
# Get the frequency information of the measurement set
ms=casac.casac.ms()
ms.open(vis)
rec = ms.getdata(['axis_info'])
df,f0 = (rec['axis_info']['freq_axis']['resolution'][len(rec['axis_info']['freq_axis']['resolution'])/2],rec['axis_info']['freq_axis']['chan_freq'][len(rec['axis_info']['freq_axis']['resolution'])/2])
F =rec['axis_info']['freq_axis']['chan_freq'].squeeze()/1e6
df=df[0]*len(rec['axis_info']['freq_axis']['resolution'])
f0=f0[0]
rec_time=ms.getdata(['time'])
sectime=qa.quantity(rec_time['time'][0],unitname='s')
midfreq=f0
bandwidth=df
if isinstance(qa.time(sectime,form='fits'),list):
dateobs=qa.time(sectime,form='fits')[0]
else:
dateobs=qa.time(sectime,form='fits')
if spectral_beam:
# Start and end of the channels so we can make the spectral beam image
startfreq=f0-df/2
endfreq=f0+df/2
freq_array=[midfreq,startfreq,endfreq]
else:
freq_array=[midfreq]
# Get observation number directly from the measurement set
tb=casac.casac.table()
tb.open(vis+'/OBSERVATION')
obsnum=int(tb.getcol('MWA_GPS_TIME'))
tb.close
# Try getting the calibrator information from the metafits file
metafits=str(obsnum)+'.metafits'
calibrator=""
if os.path.exists(metafits):
hdu_in=fits.open(metafits)
try:
calibrator=hdu_in[0].header['CALIBSRC']
str_delays=hdu_in[0].header['DELAYS']
delays=[int(x) for x in str_delays.split(',')]
except:
logger.warning('Unable to retrieve calibrator from metafits file.')
if not calibrator:
logger.warning('Could not use the metafits file: trying the observation database.')
info=metadata.MWA_Observation(obsnum)
logger.info('Retrieved observation info for %d...\n%s\n' % (obsnum,info))
# Calibrator information
if info.calibration:
calibrator=info.calibrators
else:
# Observation wasn't scheduled properly so calibrator field is missing: try parsing the fieldname
# assuming it's something like 3C444_81
calibrator=info.filename.rsplit('_',1)[0]
# Delays
delays=info.delays
str_delays=','.join(map(str,delays))
logger.info('Calibrator is %s...' % calibrator)
logger.info('Delays are: %s' % str_delays)
# subcalibrators not yet improving the calibration, probably due to poor beam model
if subcalibrator and calibrator=='PKS0408-65':
subcalibrator='PKS0410-75'
elif subcalibrator and calibrator=='HerA':
subcalibrator='3C353'
else:
subcalibrator=False
# Start models are 150MHz Jy/pixel fits files in a known directory
model=modeldir+calibrator+'.fits'
# With a corresponding spectral index map
spec_index=modeldir+calibrator+'_spec_index.fits'
if not os.path.exists(model):
logger.error('Could not find calibrator model %s' % model)
return None
# load in the model FITS file as a template for later
ftemplate=fits.open(model)
# do this for the start, middle, and end frequencies
for freq in freq_array:
freqstring=str(freq/1.0e6) + 'MHz'
# We'll generate images in the local directory at the right frequency for this ms
outname=os.path.join(outdir,calibrator+'_'+freqstring)
outnt2=os.path.join(outdir,calibrator+'_'+freqstring+'_nt2')
# import model, edit header so make_beam generates the right beam in the right place
if os.path.exists(outname + '.fits') and clobber:
os.remove(outname + '.fits')
shutil.copy(model,outname + '.fits')
fp=fits.open(outname + '.fits','update')
try:
fp[0].header['CRVAL3']=freq
fp[0].header['CDELT3']=bandwidth
fp[0].header['DATE-OBS']=dateobs
except KeyError:
fp[0].header.update('CRVAL3',freq)
fp[0].header.update('CDELT3',bandwidth)
fp[0].header.update('DATE-OBS',dateobs)
fp.flush()
logger.info('Creating primary beam models...')
beamarray=make_beam.make_beam(outname + '.fits',
model='analytic',
delays=delays)
# delete the temporary model
os.remove(outname + '.fits')
beamimage={}
for stokes in ['XX','YY']:
beamimage[stokes]=os.path.join(outdir, calibrator + '_' + freqstring + '_beam' + stokes + '.fits')
# scale by the primary beam
# Correct way of doing this is to generate separate models for XX and YY
# Unfortunately, ft doesn't really understand cubes
# So instead we just use the XX model, and then scale the YY solution later
freq=midfreq
freqstring=str(freq/1.0e6)+'MHz'
outname=os.path.join(outdir,calibrator+'_'+freqstring)
outnt2=os.path.join(outdir,calibrator+'_'+freqstring+'_nt2')
if isinstance(outname, unicode):
outname=outname.encode('ascii')
if isinstance(outnt2, unicode):
outnt2=outnt2.encode('ascii')
# divide to make a ratio beam, so we know how to scale the YY solution later
fbeamX=fits.open(beamimage['XX'])
fbeamY=fits.open(beamimage['YY'])
if correct_beam:
ratiovalue=(fbeamX[0].data/fbeamY[0].data).mean()
logger.info('Found <XX/YY>=%.2f' % ratiovalue)
else:
ratiovalue=1.0
logger.info('Not correcting for the beam: using <XX/YY>=%.2f' % ratiovalue)
# Models are at 150MHz
# Generate scaled image at correct frequency
if os.path.exists(outname + '.fits') and clobber:
os.remove(outname + '.fits')
# Hardcoded to use the XX beam in the model
fbeam=fbeamX
fmodel=fits.open(model)
fspec_index=fits.open(spec_index)
if correct_beam:
ftemplate[0].data=fbeam[0].data * fmodel[0].data/((150000000/f0)**(fspec_index[0].data))
else:
ftemplate[0].data=fmodel[0].data/((150000000/f0)**(fspec_index[0].data))
try:
ftemplate[0].header['CRVAL3']=freq
ftemplate[0].header['CDELT3']=bandwidth
ftemplate[0].header['DATE-OBS']=dateobs
ftemplate[0].header['CRVAL4']=1
except KeyError:
ftemplate[0].header.update('CRVAL3',freq)
ftemplate[0].header.update('CDELT3',bandwidth)
ftemplate[0].header.update('DATE-OBS',dateobs)
ftemplate[0].header.update('CRVAL4',1)
ftemplate.writeto(outname + '.fits')
logger.info('Wrote scaled model to %s' % (outname + '.fits'))
foutname=fits.open(outname + '.fits')
# Generate 2nd Taylor term
if os.path.exists(outnt2 + '.fits') and clobber:
os.remove(outnt2 + '.fits')
if correct_beam:
if spectral_beam:
# Generate spectral image of the beam
fcalstart=fits.open(calibrator+'_'+str(startfreq/1.0e6)+'MHz_beamXX.fits')
fcalend=fits.open(calibrator+'_'+str(endfreq/1.0e6)+'MHz_beamXX.fits')
ftemplate[0].data=(numpy.log(fcalstart[0].data/fcalend[0].data)/
numpy.log((f0-df/2)/(f0+df/2)))
beam_spec='%s_%sMHz--%sMHz_beamXX.fits' % (calibrator,
str(startfreq/1.0e6),
str(endfreq/1.0e6))
if os.path.exists(beam_spec):
os.remove(beam_spec)
ftemplate.writeto(beam_spec)
fbeam_spec=fits.open(beam_spec)
ftemplate[0].data=foutname[0].data * fbeam[0].data * (fspec_index[0].data+fbeam_spec[0].data)
else:
ftemplate[0].data=foutname[0].data * fbeam[0].data * fspec_index[0].data
else:
ftemplate[0].data=foutname[0].data
try:
ftemplate[0].header['DATE-OBS']=dateobs
except KeyError:
ftemplate[0].header.update('DATE-OBS',dateobs)
ftemplate.writeto(outnt2 + '.fits')
logger.info('Wrote scaled Taylor term to %s' % (outnt2 + '.fits'))
# import as CASA images
if os.path.exists(outname + '.im') and clobber:
shutil.rmtree(outname + '.im')
if os.path.exists(outnt2 + '.im') and clobber:
shutil.rmtree(outnt2 + '.im')
# use the local versions of this
# that I defined above
importfits(outname + '.fits',outname + '.im')
importfits(outnt2 + '.fits',outnt2 + '.im')
if not os.path.exists(outname + '.im'):
logger.error('Cannot find %s' % (outname + '.im'))
return None
if not os.path.exists(outnt2 + '.im'):
logger.error('Cannot find %s' % (outnt2 + '.im'))
return None
logger.info('Fourier transforming model...')
cfg=tasklib.FtConfig()
cfg.vis=vis
cfg.model=[outname + '.im',outnt2+'.im']
cfg.usescratch=True
tasklib.ft(cfg)
logger.info('Calibrating...')
cfg=tasklib.GaincalConfig()
cfg.vis=vis
cfg.caltable=caltable
cfg.refant=refant
cfg.uvrange=uvrange
cfg.gaintype = 'B'
cfg.combine = ['scan']
cfg.solint = 'inf'
cfg.solnorm = False
tasklib.gaincal(cfg)
logger.info('Scaling YY solutions by beam ratio...')
# Scale YY solution by the ratio
tb.open(caltable)
G = tb.getcol('CPARAM')
tb.close()
new_gains = numpy.empty(shape=G.shape, dtype=numpy.complex128)
# XX gains stay the same
new_gains[0,:,:]=G[0,:,:]
# YY gains are scaled
new_gains[1,:,:]=ratiovalue*G[1,:,:]
tb.open(caltable,nomodify=False)
tb.putcol('CPARAM',new_gains)
tb.putkeyword('MODEL',model)
tb.putkeyword('SPECINDX',spec_index)
tb.putkeyword('BMRATIO',ratiovalue)
try:
tb.putkeyword('MWAVER',mwapy.__version__)
except:
pass
tb.close()
logger.info('Created %s!' % caltable)
return caltable
##################################################
def calibrate_casa(obsid, directory=None, minuv=60):
"""
calibrate_casa(obsid, directory=None, minuv=60)
minuv in meters
returns name of calibration (gain) file on success
returns None on failure
"""
if not _CASA:
logger.error("CASA operation not possible")
return None
basedir=os.path.abspath(os.curdir)
if directory is None:
directory=basedir
if minuv is not None:
result=ft_beam(vis='%s.ms' % obsid,
uvrange='>%dm' % minuv,
outdir='%s' % directory)
else:
result=ft_beam(vis='%s.ms' % obsid,
outdir='%s' % directory)
if result is None:
logger.error('Unable to create calibration table')
return None
else:
outfile=result
# that file should be the same as the expected output
if not os.path.split(outfile)[-1] == '%s.cal' % obsid:
logger.error('CASA calibration produced %s, but expected %s.cal' % (outfile,
obsid))
return None
return outfile
##################################################
def selfcalibrate_casa(obsid, suffix=None, directory=None, minuv=60):
"""
selfcalibrate_casa(obsid, directory=None, minuv=60)
minuv in meters
returns name of calibration (gain) file on success
returns None on failure
"""
if not _CASA:
logger.error("CASA operation not possible")
return None
if suffix is None:
calfile='%s.cal' % obsid
else:
calfile='%s_%s.cal' % (obsid,suffix)
if directory is not None:
calfile=os.path.join(directory, calfile)
basedir=os.path.abspath(os.curdir)
if directory is None:
directory=basedir
if minuv is not None:
uvrange='>%dm' % minuv
else:
uvrange=''
cfg=tasklib.GaincalConfig()
cfg.vis='%s.ms' % obsid
cfg.caltable=calfile
cfg.refant='Tile012'
cfg.uvrange=uvrange
cfg.gaintype = 'B'
cfg.combine = ['scan']
cfg.solint = 'inf'
cfg.solnorm = False
try:
tasklib.gaincal(cfg)
except:
return None
if not os.path.exists(calfile):
logger.error('Expected CASA output %s does not exist' % calfile)
return None
return calfile
##################################################
def applycal_casa(obsid, calfile):
"""
applycal_casa(obsid, calfile)
returns True on success, None on failure
"""
if not _CASA:
logger.error("CASA operation not possible")
return None
basedir=os.path.abspath(os.curdir)
cfg=tasklib.ApplycalConfig()
cfg.vis='%s.ms' % obsid
cfg.gaintable=[calfile]
try:
tasklib.applycal(cfg)
except:
return None
return True
##################################################
def extract_calmodel(filename, sourcename):
"""
extract_calmodel(filename, sourcename)
extracts just the data for given <sourcename> from the
master model file <filename>
returns the corresponding lines or None on failure
"""
logger.debug('Extracting calibration model for %s from file %s' % (sourcename,
filename))
try:
f=open(filename)
except Exception, e:
logger.error('Unable to read calibrator model file %s:\n\t%s' % (filename,e))
return None
lines=f.readlines()
i=0
istart=None
iend=None
while i < len(lines):
if lines[i].startswith('source'):
d=lines[i+1].split()
if d[0]=='name' and (sourcename in d[1] or (sourcename in calmodelaliases_inverse.keys() and calmodelaliases_inverse[sourcename] in d[1])):
istart=i
i+=1
while i < len(lines):
if lines[i][0]=='}':
break
i+=1
iend=i
break
i+=1
if istart is None or iend is None:
logger.error('Unable to find source "%s" in calibrator model file %s' % (sourcename,
filename))
return None
return [lines[0]]+lines[istart:iend+1]
##################################################
def write_calmodelfile(calibrator_name, directory=None):
"""
write_calmodelfile(calibrator_name, directory=None)
extracts the relevant info from the master calibrator model file
and writes it to a single-source file
returns the name of that file on success, or None on failure
"""
# get a model file
calibrator_modeldata=extract_calmodel(calmodelfile,
calibrator_name)
if calibrator_modeldata is None:
logger.error('No calibrator data found')
return None
outputcalmodelfile='%s_%s.model' % (calibrator_name,
datetime.datetime.now().strftime('%Y%m%d'))
if directory is not None:
outputcalmodelfile=os.path.join(directory,outputcalmodelfile)
try:
f=open(outputcalmodelfile,'w')
except Exception, e:
logger.error('Unable to open file %s for writing:\n\t%s' % (outputcalmodelfile,e))
return None
for line in calibrator_modeldata:
f.write(line)
f.close()
logger.debug('Wrote calibration model file %s' % outputcalmodelfile)
return outputcalmodelfile
##################################################
def calibrate_anoko(obsid,outputcalmodelfile=None,
minuv=60,
suffix=None,
corrected=False,
directory=None,
ncpus=32):
"""
calibrate_anoko(obsid,outputcalmodelfile=None, minuv=60,
suffix=None,
corrected=False,
directory=None,
ncpus=32)
returns name of calibration (gain) file on success
"""
if suffix is None:
calfile='%s.cal' % obsid
else:
calfile='%s_%s.cal' % (obsid,suffix)
if directory is not None:
calfile=os.path.join(directory, calfile)
calibratecommand=[os.path.join(anoko,'calibrate')]
if minuv is not None and minuv > 0:
calibratecommand+=['-minuv',
str(minuv)]
if corrected:
calibratecommand+=['-datacolumn',
'CORRECTED_DATA']
calibratecommand+=['-j',
str(ncpus),
'-a',
'0.001',
'0.0001']
if outputcalmodelfile is not None:
calibratecommand+=['-m',
outputcalmodelfile]
calibratecommand+=['%s.ms' % obsid,
calfile]
logger.info('Will run:\n\t%s' % ' '.join(calibratecommand))
p=subprocess.Popen(' '.join(calibratecommand),
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
shell=True,
close_fds=False)
while True:
p.stdout.flush()
p.stderr.flush()
for l in p.stdout.readlines():
logger.debug(l.rstrip())
for l in p.stderr.readlines():
logger.error(l.rstrip())
returncode=p.poll()
if returncode is not None:
break
time.sleep(1)
return calfile
##################################################
def applycal_anoko(obsid, calfile, corrected=False):
"""
applycal_anoko(obsid, calfile, corrected=False):
returns True on success
"""
applycalcommand=[os.path.join(anoko,'applysolutions')]
if corrected:
applycalcommand+=['-datacolumn',
'CORRECTED_DATA']
applycalcommand+=['-copy',
'%s.ms' % obsid,
calfile]
logger.info('Will run:\n\t%s' % ' '.join(applycalcommand))
p=subprocess.Popen(' '.join(applycalcommand),
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
shell=True,
close_fds=False)
while True:
p.stdout.flush()
p.stderr.flush()
for l in p.stdout.readlines():
logger.debug(l.rstrip())
for l in p.stderr.readlines():
logger.error(l.rstrip())
returncode=p.poll()
if returncode is not None:
break
time.sleep(1)
return True
######################################################################
def identify_calibrators(observation_data):
calibrators=numpy.where(observation_data['iscalibrator'])[0]
notcalibrators=numpy.where(~observation_data['iscalibrator'])[0]
if len(calibrators)==0:
logger.warning('No calibrators identified')
return calibrators, notcalibrators, {}
cal_observations={}
for i in notcalibrators:
# find which match in freq and are not calibrators
good=(observation_data['channel']==observation_data[i]['channel']) & observation_data['iscalibrator']
if good.sum() > 0:
logger.info('For observation %d (channel=%d) identified %d matching calibrator observations' % (observation_data[i]['obsid'],
observation_data[i]['channel'],
good.sum()))
if good.sum()>1:
# find the closest in time
dt=numpy.abs(observation_data[i]['obsid']-observation_data[good]['obsid'])
closest=observation_data[good][dt==dt.min()]
logger.info('Will use %d (separation=%d s) for calibration of %s' % (closest['obsid'],
numpy.abs(closest['obsid']-observation_data[i]['obsid']),
observation_data[i]['obsid']))
cal_observations[observation_data[i]['obsid']]=closest['obsid']
else:
logger.info('Will use %d for calibration of %s' % (observation_data[good]['obsid'],
observation_data[i]['obsid']))
cal_observations[observation_data[i]['obsid']]=observation_data[good]['obsid']
else:
logger.info('For observation %d (channel=%d) identified no matching calibrator observations' % (observation_data[i]['obsid'],
observation_data[i]['channel']))
cal_observations[observation_data[i]['obsid']]=None
return calibrators, notcalibrators, cal_observations
######################################################################
class Observation(metadata.MWA_Observation):
##############################
def __init__(self, obsid,
caltype='anoko',
outputdir='./', ncpus=32,
memfraction=50,
clobber=False, delete=False):