-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyxis-rwlsims.py
228 lines (170 loc) · 7.05 KB
/
pyxis-rwlsims.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
## Telescope Simulator
## Sphesihle Makhathini ([email protected])
# import Pyxis essentials
import Pyxis
import ms
import im
import mqt
import lsm
from Pyxis.ModSupport import *
# import python essentials
import os
import sys
import numpy
import math
# some useful constants
PI = math.pi
FWHM = math.sqrt( math.log(256) )
# other python packages
import pyfits
# use simms to create empty MSs (https://github.com/SpheMakh/simms)
import simms
import im.lwimager
import im.argo
def make_empty_ms(msname='$MS', observatory='$OBSERVATORY', antennas='$ANTENNAS',
synthesis='$SYNTHESIS', dtime='$DTIME', freq0='$FREQ0',
dfreq='$DFREQ', nchan='$NCHAN', **kw):
""" creates an empty MS """
msname, observatory, antennas, synthesis, dtime, freq0, dfreq, nchan =\
interpolate_locals('msname observatory antennas synthesis dtime freq0 dfreq nchan')
if not exists(msname) or MS_REDO:
info("Creating empty MS $msname")
simms.create_empty_ms(tel=observatory, pos=antennas, msname=msname, synthesis=float(synthesis),
dtime=float(dtime), freq0=freq0, dfreq=dfreq, nchan=int(nchan), **kw)
v.MS = msname
return msname
def simsky(msname='$MS', lsmname='$LSM', tdlsec='$TDLSEC', tdlconf='$TDLCONF',
column='$COLUMN', noise=0,recenter_lsm=True, args=[],**kw):
""" Simulates visibilities into an MS """
msname, lsmname, column, tdlsec, tdlconf = \
interpolate_locals('msname lsmname column tdlsec tdlconf')
fits = True if verify_sky(lsmname) is 'FITS' else False
v.MS = msname
# use LWIMAGER to predict visibilities is skymodel is a FITS file
if fits:
lsmname = conform(fitsname=lsmname)
v.LSM = lsmname
_column = 'MODEL_DATA' if noise else column
im.lwimager.predict_vis(image=lsmname, wprojplanes=128, column=_column, padding=1.5,**kw)
if noise:
simnoise(noise=noise, addToCol=_column, column=column)
# use MeqTrees to predict visibilities if skymodel is Tigger Model or an ASCII file
else:
if recenter_lsm:
# save temp lsm in temporary file
tlsm = tempfile.NamedTemporaryFile(suffix='.lsm.html')
tlsm.flush
tlsmname = tlsm.name
x.sh('tigger-convert --recenter=$DIRECTION $lsmname $tlsmname -f')
v.LSM = lsmname
else:
v.LSM = lsmname
args = ["${ms.MS_TDL} ${lsm.LSM_TDL}"] + list(args)
options = {}
options['ms_sel.output_column'] = column
if noise:
options['noise_stddev'] = noise
options.update(kw)
mqt.run(SIMCRIPT, job='_tdl_job_1_simulate_MS',
config=tdlconf, section=tdlsec, options=options, args=args)
tlsm.close()
document_globals(simsky,"MS LSM COLUMN TDLSEC TDLCONF")
def driver():
make_empty_ms()
simsky()
im.lwimager.make_image()
def conform(msname='$MS',fitsname='$LSM',outfile=None,size=None,flux=None):
""" conforms FITS file to a structure acceptable to LWIMAGER.
This assunes a 2D FITS file. It will also work with a 3D FITS file,
with the 3rd axis being frequency.
"""
msname, fitsname = interpolate_locals('msname fitsname')
flux = flux or SCALEFLUX
size = size or SCALESIZE
hdu = pyfits.open(fitsname)
hdr0 = hdu[0].header
npix = hdr0["NAXIS1"]
## Insure conformance by letting LWIMAGER create the header
# Lets use a temp file
tf = tempfile.NamedTemporaryFile(suffix='.fits',dir='.')
im.argo.make_empty_image(msname=msname, image=tf.name, npix=npix,cellsize="%.4garcsec"%size)
hdr = pyfits.open(tf.name)[0].header # header from the lwimager empty image
data = hdu[0].data
shape = list(data.shape)
ndim = len(shape)
imslice = [slice(None)]*ndim
imslice[:-2] = [0]*(ndim-2)
data = (data[imslice]*flux)[numpy.newaxis,numpy.newaxis,...]
# Fix FITS WCS
for key in "CDELT1 CDELT2 CRPIX1 CRPIX2".split():
try:
hdr[key] = hdr0[key]
except KeyError:
warn("NO Cordinate system in FITS file, using pyxis-*conf defaults")
break
outfile = outfile or fitsname.replace(".fits","_4d.fits")
pyfits.writeto(outfile, data, hdr, clobber=True)
return outfile
def fitsInfo(fits):
""" Returs FITS image basic info """
hdr = pyfits.open(fits)[0].header
ra = hdr['CRVAL1']
dec = hdr['CRVAL2']
naxis = hdr['NAXIS']
if naxis>3: freq_ind = 3 if hdr['CTYPE3'].startswith('FREQ') else 4
else:
freq_ind = 3
if hdr['CRTYPE3'].startswith('FREQ') is False:
return (ra,dec), (False, False, False) , naxis
nchan = hdr['NAXIS%d'%freq_ind]
dfreq = hdr['CDELT%d'%freq_ind]
freq0 = hdr['CRVAL%d'%freq_ind] + hdr['CRPIX%d'%freq_ind]*dfreq
return (ra, dec),(freq0, dfreq, nchan), naxis
def verify_sky(fname):
""" verify if skymodel is compitable with simulator """
ext = fname.split('.')[-1]
if ext.lower() == 'fits':
return 'FITS'
elif ext.lower() == 'txt' or fname.endswith('.lsm.html'):
return 'TIGGER'
else:
raise TypeError('Sky model "%s" has to be either one of FITS,ASCII,Tigger Model (lsm.html) '%fname)
def compute_vis_noise (noise=0,sefd=None):
"""Computes nominal per-visibility noise"""
tab = ms.ms()
spwtab = ms.ms(subtable="SPECTRAL_WINDOW")
sefd = sefd or SEFD
freq0 = spwtab.getcol("CHAN_FREQ")[ms.SPWID,0]
wavelength = 300e+6/freq0
bw = DFREQ or spwtab.getcol("CHAN_WIDTH")[ms.SPWID,0]
dt = DTIME or tab.getcol("EXPOSURE",0,1)[0]
dtf = (tab.getcol("TIME",tab.nrows()-1,1)-tab.getcol("TIME",0,1))[0]
# close tables properly, else the calls below will hang waiting for a lock...
tab.close()
spwtab.close()
info(">>> $MS freq %.2f MHz (lambda=%.2fm), bandwidth %.2g kHz, %.2fs integrations, %.2fh synthesis"%(freq0*1e-6,wavelength,bw*1e-3,dt,dtf/3600))
if not noise:
noise = sefd/math.sqrt(2*bw*dt)
info(">>> SEFD of %.2f Jy gives per-visibility noise of %.2f mJy"%(sefd,noise*1000))
else:
info(">>> using per-visibility noise of %.2f mJy"%(noise*1000))
return noise
def simnoise (noise=0,rowchunk=100000,skipnoise=False,addToCol=None,scale_noise=1.0,column='MODEL_DATA'):
""" generate noise and add to a given column in the MS """
spwtab = ms.ms(subtable="SPECTRAL_WINDOW")
freq0 = spwtab.getcol("CHAN_FREQ")[ms.SPWID,0]/1e6
tab = ms.msw()
dshape = list(tab.getcol('DATA').shape)
nrows = dshape[0]
noise = noise or compute_vis_noise()
if addToCol: colData = tab.getcol(addToCol)
for row0 in range(0,nrows,rowchunk):
nr = min(rowchunk,nrows-row0)
dshape[0] = nr
data = noise*(numpy.random.randn(*dshape) + 1j*numpy.random.randn(*dshape)) * scale_noise
if addToCol:
data+=colData[row0:(row0+nr)]
info(" $addToCol + noise --> $column (rows $row0 to %d)"%(row0+nr-1))
else : info("Adding noise to $column (rows $row0 to %d)"%(row0+nr-1))
tab.putcol(column,data,row0,nr);
tab.close()