-
Notifications
You must be signed in to change notification settings - Fork 3
/
ClassSaveResults.py
328 lines (292 loc) · 18.1 KB
/
ClassSaveResults.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
from astropy.time import Time
from astropy import units as uni
from astropy.io import fits
from astropy.wcs import WCS
from astropy import coordinates as coord
from astropy import constants as const
import numpy as np
import glob, os
#import pylab
from DDFacet.Other import MyLogger
log=MyLogger.getLogger("ClassSaveResults")
from DDFacet.ToolsDir.rad2hmsdms import rad2hmsdms
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as pylab
from DDFacet.Other.progressbar import ProgressBar
from pyrap.images import image
from dynspecms_version import version
class ClassSaveResults():
def __init__(self, DynSpecMS):
self.DynSpecMS=DynSpecMS
self.DIRNAME="DynSpecs_%s"%self.DynSpecMS.OutName
#image = self.DynSpecMS.Image
#self.ImageData=np.squeeze(fits.getdata(image, ext=0))
self.im=image(self.DynSpecMS.Image)
self.ImageData=self.im.getdata()[0,0]
os.system("rm -rf %s"%self.DIRNAME)
os.system("mkdir -p %s/TARGET"%self.DIRNAME)
os.system("mkdir -p %s/OFF"%self.DIRNAME)
#os.system("mkdir -p %s/PNG"%self.DIRNAME)
def tarDirectory(self):
print>>log,"Taring the result directory"
ss="tar -zcvf %s.tgz %s > /dev/null 2>&1"%(self.DIRNAME,self.DIRNAME)
print>>log," ... executing %s"%ss
os.system(ss)
def WriteFits(self):
for iDir in range(self.DynSpecMS.NDir):
self.WriteFitsThisDir(iDir)
self.WriteFitsThisDir(0,Weight=True)
def GiveSubDir(self,Type):
SubDir="OFF"
if Type!="Off": SubDir="TARGET"
return SubDir
def WriteFitsThisDir(self,iDir,Weight=False):
""" Store the dynamic spectrum in a FITS file
"""
ra,dec=self.DynSpecMS.PosArray.ra[iDir],self.DynSpecMS.PosArray.dec[iDir]
strRA=rad2hmsdms(ra,Type="ra").replace(" ",":")
strDEC=rad2hmsdms(dec,Type="dec").replace(" ",":")
fitsname = "%s/%s/%s_%s_%s.fits"%(self.DIRNAME,self.GiveSubDir(self.DynSpecMS.PosArray.Type[iDir]),self.DynSpecMS.OutName, strRA, strDEC)
if Weight:
fitsname = "%s/%s.fits"%(self.DIRNAME,"Weights")
# Create the fits file
prihdr = fits.Header()
prihdr.set('CTYPE1', 'Time', 'Time')
prihdr.set('CRPIX1', 1., 'Reference')
prihdr.set('CRVAL1', 0., 'Time at the reference pixel (sec since OBS-STAR)')
deltaT = (Time(self.DynSpecMS.times[1]/(24*3600.), format='mjd', scale='utc') - Time(self.DynSpecMS.times[0]/(24*3600.), format='mjd', scale='utc')).sec
prihdr.set('CDELT1', deltaT, 'Delta time (sec)')
prihdr.set('CUNIT1', 'Time', 'unit')
prihdr.set('CTYPE2', 'Frequency', 'Frequency')
prihdr.set('CRPIX2', 1., 'Reference')
prihdr.set('CRVAL2', self.DynSpecMS.fMin*1e-6, 'Frequency at the reference pixel (MHz)')
prihdr.set('CDELT2', self.DynSpecMS.ChanWidth*1e-6, 'Delta freq (MHz)')
prihdr.set('CUNIT2', 'MHz', 'unit')
prihdr.set('CTYPE3', 'Stokes parameter', '1=I, 2=Q, 3=U, 4=V')
prihdr.set('CRPIX3', 1., 'Reference')
prihdr.set('CRVAL3', 1., 'frequence at the reference pixel')
prihdr.set('CDELT3', 1., 'Delta stokes')
prihdr.set('CUNIT3', '', 'unit')
prihdr.set('DATE-CRE', Time.now().iso.split()[0], 'Date of file generation')
prihdr.set('OBSID', self.DynSpecMS.OutName, 'LOFAR Observation ID')
prihdr.set('CHAN-WID', self.DynSpecMS.ChanWidth, 'Frequency channel width')
prihdr.set('FRQ-MIN', self.DynSpecMS.fMin, 'Minimal frequency')
prihdr.set('FRQ-MAX', self.DynSpecMS.fMax, 'Maximal frequency')
prihdr.set('OBS-STAR', self.DynSpecMS.tStart, 'Observation start date')
prihdr.set('OBS-STOP', self.DynSpecMS.tStop, 'Observation end date')
prihdr.set('RA_RAD', ra, 'Pixel right ascension')
prihdr.set('DEC_RAD', dec, 'Pixel declination')
prihdr.set('ORIGIN', 'DynSpecMS '+version(),'Created by')
if Weight:
Gn = self.DynSpecMS.DicoGrids["GridWeight"][iDir,:, :, :].real # dir, time, freq, pol
else:
Gn = self.DynSpecMS.GOut[iDir,:, :, :].real
hdu = fits.PrimaryHDU(np.rollaxis(Gn, 2), header=prihdr)
hdu.writeto(fitsname, clobber=True)
def PlotSpec(self):
# Pdf file of target positions
pdfname = "%s/%s_TARGET.pdf"%(self.DIRNAME,self.DynSpecMS.OutName)
print>>log,"Making pdf overview: %s"%pdfname
pBAR = ProgressBar(Title="Making pages")
NPages=self.DynSpecMS.NDirSelected #Selected
iDone=0
pBAR.render(0, NPages)
with PdfPages(pdfname) as pdf:
for iDir in range(self.DynSpecMS.NDir):
self.fig = pylab.figure(1, figsize=(15, 15))
if self.DynSpecMS.PosArray.Type[iDir]=="Off": continue
self.PlotSpecSingleDir(iDir)
pdf.savefig(bbox_inches='tight')
pylab.close()
iDone+=1
pBAR.render(iDone, NPages)
# Pdf file of off positions
pdfname = "%s/%s_OFF.pdf"%(self.DIRNAME,self.DynSpecMS.OutName)
print>>log,"Making pdf overview: %s"%pdfname
pBAR = ProgressBar(Title="Making pages")
NPages=self.DynSpecMS.NDir-self.DynSpecMS.NDirSelected #Off pix
pBAR.render(0, NPages)
iDone=0
with PdfPages(pdfname) as pdf:
for iDir in range(self.DynSpecMS.NDir):
self.fig = pylab.figure(1, figsize=(15, 15))
if self.DynSpecMS.PosArray.Type[iDir]!="Off": continue
self.PlotSpecSingleDir(iDir)
pdf.savefig(bbox_inches='tight')
pylab.close()
iDone+=1
pBAR.render(iDone, NPages)
def PlotSpecSingleDir(self, iDir=0):
label = ["I", "Q", "U", "V"]
pylab.clf()
pylab.rc('text', usetex=True)
font = {'family':'serif', 'serif': ['Times']}
pylab.rc('font', **font)
# Figure properties
bigfont = 8
smallfont = 6
ra, dec = np.degrees(self.DynSpecMS.PosArray.ra[iDir]), np.degrees(self.DynSpecMS.PosArray.dec[iDir])
strRA = rad2hmsdms(self.DynSpecMS.PosArray.ra[iDir], Type="ra").replace(" ", ":")
strDEC = rad2hmsdms(self.DynSpecMS.PosArray.dec[iDir], Type="dec").replace(" ", ":")
#freqs = self.DynSpecMS.FreqsAll.ravel() * 1.e-6 # in MHz
t0 = Time(self.DynSpecMS.times[0]/(24*3600.), format='mjd', scale='utc')
t1 = Time(self.DynSpecMS.times[-1]/(24*3600.), format='mjd', scale='utc')
times = np.linspace(0, (t1-t0).sec/60., num=self.DynSpecMS.GOut[0, :, :, 0].shape[1], endpoint=True)
freqs = np.linspace(self.DynSpecMS.fMin,self.DynSpecMS.fMax,num=self.DynSpecMS.GOut[0, :, :, 0].shape[0], endpoint=True)*1e-6
image = self.DynSpecMS.Image
if (image is None) | (not os.path.isfile(image)):
# Just plot a series of dynamic spectra
for ipol in range(4):
# Gn = self.DynSpecMS.GOut[iDir,:, :, ipol].T.real
# sig = np.median(np.abs(Gn))
# mean = np.median(Gn)
# pylab.subplot(2, 2, ipol+1)
# pylab.imshow(Gn, interpolation="nearest", aspect="auto", vmin=mean-3*sig, vmax=mean+10*sig)
# pylab.title(label[ipol])
# pylab.colorbar()
# pylab.ylabel("Time bin")
# pylab.xlabel("Freq bin")
Gn = self.DynSpecMS.GOut[iDir,:, :, ipol].real
sig = np.std(np.abs(Gn))
mean = np.median(Gn)
ax1 = pylab.subplot(2, 2, ipol+1)
spec = pylab.pcolormesh(times, freqs, Gn, cmap='bone_r', vmin=mean-3*sig, vmax=mean+10*sig, rasterized=True)
ax1.axis('tight')
cbar = pylab.colorbar()
cbar.ax.tick_params(labelsize=6)
pylab.text(times[-1]-0.1*(times[-1]-times[0]), freqs[-1]-0.1*(freqs[-1]-freqs[0]), label[ipol], horizontalalignment='center', verticalalignment='center', fontsize=bigfont)
if ipol==2 or ipol==3:
pylab.xlabel("Time (min since %s)"%(t0.iso), fontsize=bigfont)
pylab.ylabel("Frequency (MHz)", fontsize=bigfont)
pylab.setp(ax1.get_xticklabels(), rotation='horizontal', fontsize=smallfont)
pylab.setp(ax1.get_yticklabels(), rotation='horizontal', fontsize=smallfont)
else:
# Plot the survey image and the dynamic spectra series
# ---- Dynamic spectra I ----
axspec = pylab.subplot2grid((5, 2), (2, 0), colspan=2)
Gn = self.DynSpecMS.GOut[iDir,:, :, 0].real
sig = np.std(np.abs(Gn))
mean = np.median(Gn)
#spec = pylab.pcolormesh(times, freqs, Gn, cmap='bone_r', vmin=mean-3*sig, vmax=mean+10*sig, rasterized=True)
spec = pylab.imshow(Gn, cmap='bone_r', vmin=mean-3*sig, vmax=mean+10*sig, extent=(times[0],times[-1],self.DynSpecMS.fMin*1.e-6,self.DynSpecMS.fMax*1.e-6),rasterized=True)
axspec.axis('tight')
cbar = pylab.colorbar(fraction=0.046, pad=0.01)
cbar.ax.tick_params(labelsize=smallfont)
cbar.set_label(r'Flux density (Jy)', fontsize=8, horizontalalignment='center')
pylab.text(times[-1]-0.02*(times[-1]-times[0]), freqs[-1]-0.1*(freqs[-1]-freqs[0]), 'I', horizontalalignment='center', verticalalignment='center', fontsize=bigfont+2)
pylab.text(times[0]+0.02*(times[-1]-times[0]), freqs[0]+0.1*(freqs[-1]-freqs[0]), r"$\sigma =$ %.3f Jy"%sig, horizontalalignment='left', verticalalignment='center', fontsize=bigfont+2)
pylab.xlabel("Time (min since %s)"%(t0.iso), fontsize=bigfont)
pylab.ylabel("Frequency (MHz)", fontsize=bigfont)
pylab.setp(axspec.get_xticklabels(), rotation='horizontal', fontsize=smallfont)
pylab.setp(axspec.get_yticklabels(), rotation='horizontal', fontsize=smallfont)
# ---- Dynamic spectra L ----
axspec = pylab.subplot2grid((5, 2), (3, 0), colspan=2)
Gn = np.sqrt(self.DynSpecMS.GOut[iDir,:, :, 1].real**2. + self.DynSpecMS.GOut[iDir,:, :, 2].real**2.)
sig = np.std(np.abs(Gn))
mean = np.median(Gn)
#spec = pylab.pcolormesh(times, freqs, Gn, cmap='bone_r', vmin=0, vmax=mean+10*sig, rasterized=True)
spec = pylab.imshow(Gn, cmap='bone_r', vmin=mean-3*sig, vmax=mean+10*sig, extent=(times[0],times[-1],self.DynSpecMS.fMin*1.e-6,self.DynSpecMS.fMax*1.e-6), rasterized=True)
axspec.axis('tight')
cbar = pylab.colorbar(fraction=0.046, pad=0.01)
cbar.ax.tick_params(labelsize=smallfont)
cbar.set_label(r'Flux density (Jy)', fontsize=8, horizontalalignment='center')
pylab.text(times[-1]-0.02*(times[-1]-times[0]), freqs[-1]-0.1*(freqs[-1]-freqs[0]), 'L', horizontalalignment='center', verticalalignment='center', fontsize=bigfont+2)
pylab.text(times[0]+0.02*(times[-1]-times[0]), freqs[0]+0.1*(freqs[-1]-freqs[0]), r"$\sigma =$ %.3f Jy"%sig, horizontalalignment='left', verticalalignment='center', fontsize=bigfont+2)
pylab.xlabel("Time (min since %s)"%(t0.iso), fontsize=bigfont)
pylab.ylabel("Frequency (MHz)", fontsize=bigfont)
pylab.setp(axspec.get_xticklabels(), rotation='horizontal', fontsize=smallfont)
pylab.setp(axspec.get_yticklabels(), rotation='horizontal', fontsize=smallfont)
# ---- Dynamic spectra V ----
axspec = pylab.subplot2grid((5, 2), (4, 0), colspan=2)
Gn = self.DynSpecMS.GOut[iDir,:, :, 3].real
sig = np.std(np.abs(Gn))
mean = np.median(Gn)
#spec = pylab.pcolormesh(times, freqs, Gn, cmap='bone_r', vmin=mean-3*sig, vmax=mean+10*sig, rasterized=True)
spec = pylab.imshow(Gn, cmap='bone_r', vmin=mean-5*sig, vmax=mean+5*sig, extent=(times[0],times[-1],self.DynSpecMS.fMin*1.e-6,self.DynSpecMS.fMax*1.e-6), rasterized=True)
axspec.axis('tight')
cbar = pylab.colorbar(fraction=0.046, pad=0.01)
cbar.ax.tick_params(labelsize=smallfont)
cbar.set_label(r'Flux density (Jy)', fontsize=8, horizontalalignment='center')
pylab.text(times[-1]-0.02*(times[-1]-times[0]), freqs[-1]-0.1*(freqs[-1]-freqs[0]), 'V', horizontalalignment='center', verticalalignment='center', fontsize=bigfont+2)
pylab.text(times[0]+0.02*(times[-1]-times[0]), freqs[0]+0.1*(freqs[-1]-freqs[0]), r"$\sigma =$ %.3f Jy"%sig, horizontalalignment='left', verticalalignment='center', fontsize=bigfont+2)
pylab.xlabel("Time (min since %s)"%(t0.iso), fontsize=bigfont)
pylab.ylabel("Frequency (MHz)", fontsize=bigfont)
pylab.setp(axspec.get_xticklabels(), rotation='horizontal', fontsize=smallfont)
pylab.setp(axspec.get_yticklabels(), rotation='horizontal', fontsize=smallfont)
# ---- Plot mean vs time ----
ax2 = pylab.subplot2grid((5, 2), (0, 1))
Gn_i = self.DynSpecMS.GOut[iDir,:, :, 0].real
meantime = np.mean(Gn_i, axis=0)
stdtime = np.std(Gn_i, axis=0)
ax2.fill_between(times, meantime-stdtime, meantime+stdtime, facecolor='#B6CAC8', edgecolor='none', zorder=-10)
pylab.plot(times, meantime, color='black')
pylab.axhline(y=0, color='black', linestyle=':')
pylab.xlabel("Time (min since %s)"%(t0.iso), fontsize=bigfont)
pylab.ylabel("Mean (Stokes I)", fontsize=bigfont)
pylab.setp(ax2.get_xticklabels(), rotation='horizontal', fontsize=smallfont)
pylab.setp(ax2.get_yticklabels(), rotation='horizontal', fontsize=smallfont)
ymin, vv = np.percentile((meantime-stdtime).ravel(), [5, 95])
vv, ymax = np.percentile((meantime+stdtime).ravel(), [5, 95])
ax2.set_ylim([ymin, ymax])
ax2.set_xlim([times[0], times[-1]])
# ---- Plot mean vs frequency ----
ax3 = pylab.subplot2grid((5, 2), (1, 1))
meanfreq = np.mean(Gn_i, axis=1)
stdfreq = np.std(Gn_i, axis=1)
ax3.fill_between(freqs.ravel(), meanfreq-stdfreq, meanfreq+stdfreq, facecolor='#B6CAC8', edgecolor='none', zorder=-10)
ax3.plot(freqs.ravel(), meanfreq, color='black')
ax3.axhline(y=0, color='black', linestyle=':')
pylab.xlabel("Frequency (MHz)", fontsize=bigfont)
pylab.ylabel("Mean (Stokes I)", fontsize=bigfont)
pylab.setp(ax3.get_xticklabels(), rotation='horizontal', fontsize=smallfont)
pylab.setp(ax3.get_yticklabels(), rotation='horizontal', fontsize=smallfont)
ymin, vv = np.percentile((meanfreq-stdfreq).ravel(), [5, 95])
vv, ymax = np.percentile((meanfreq+stdfreq).ravel(), [5, 95])
ax3.set_ylim([ymin,ymax])
ax3.set_xlim([freqs.ravel()[0], freqs.ravel()[-1]])
# ---- Image ----
npix = 1000
header = fits.getheader(image)
data = self.ImageData # A VERIFIER
f,p,_,_=self.im.toworld([0,0,0,0])
_,_,xc,yc=self.im.topixel([f,p,self.DynSpecMS.PosArray.dec[iDir], self.DynSpecMS.PosArray.ra[iDir]])
yc,xc=int(xc),int(yc)
wcs = WCS(header).celestial
#cenpixra, cenpixdec = wcs.wcs_world2pix(np.degrees(self.DynSpecMS.PosArray.ra[iDir]), np.degrees(self.DynSpecMS.PosArray.dec[iDir]), 1)
#print("central pixels {}, {}".format(cenpixx, cenpixy))
#print>>log, "central pixels {}, {}".format(cenpixx, cenpixy)
nn=self.ImageData.shape[-1]
box=100
def giveBounded(x):
x=np.max([0,x])
return np.min([x,nn-1])
x0=giveBounded(xc-box)
x1=giveBounded(xc+box)
y0=giveBounded(yc-box)
y1=giveBounded(yc+box)
DataBoxed=self.ImageData[y0:y1,x0:x1]
if DataBoxed.size>100:
std=1.6*np.median(np.abs(DataBoxed))
vMin, vMax = (-5.*std, 30*std)
ax1 = pylab.subplot2grid((5, 2), (0, 0), rowspan=2, projection=wcs)
im = pylab.imshow(DataBoxed, interpolation="nearest", cmap='bone_r', aspect="auto", vmin=vMin, vmax=vMax, origin='lower', rasterized=True)
#pylab.text((ra_crop[1]-ra_crop[0])/16, (dec_crop[1]-dec_crop[0])/16, r"$\sigma =$ %.3f mJy"%rms, horizontalalignment='left', verticalalignment='center', fontsize=bigfont+2)
cbar = pylab.colorbar()#(fraction=0.046*2., pad=0.01*4.)
ax1.set_xlabel(r'RA (J2000)')
raax = ax1.coords[0]
raax.set_major_formatter('hh:mm:ss')
raax.set_ticklabel(size=smallfont)
ax1.set_ylabel(r'Dec (J2000)')
decax = ax1.coords[1]
decax.set_major_formatter('dd:mm:ss')
decax.set_ticklabel(size=smallfont)
ax1.autoscale(False)
# newcenpixra, newcenpixdec = wcs.wcs_world2pix(np.degrees(self.DynSpecMS.PosArray.ra[iDir]), np.degrees(self.DynSpecMS.PosArray.dec[iDir]), 1)
# pylab.plot(newcenpixra, newcenpixdec, 'o', markerfacecolor='none', markeredgecolor='red', markersize=bigfont) # plot a circle at the target
cbar.set_label(r'Flux density (mJy)', fontsize=bigfont, horizontalalignment='center')
cbar.ax.tick_params(labelsize=smallfont)
pylab.setp(ax1.get_xticklabels(), rotation='horizontal', fontsize=smallfont)
pylab.setp(ax1.get_yticklabels(), rotation='horizontal', fontsize=smallfont)
#pylab.subplots_adjust(wspace=0.15, hspace=0.30)
pylab.figtext(x=0.5, y=0.92, s="Name: %s, Type: %s, RA: %s, Dec: %s"%(self.DynSpecMS.PosArray.Name[iDir].replace('_', ' '), self.DynSpecMS.PosArray.Type[iDir], strRA, strDEC), fontsize=bigfont+2, horizontalalignment='center', verticalalignment='bottom')
#pylab.suptitle("Name: %s, Type: %s, RA: %s, Dec: %s"%(self.DynSpecMS.PosArray.Name[iDir], self.DynSpecMS.PosArray.Type[iDir], self.DynSpecMS.PosArray.ra[iDir], self.DynSpecMS.PosArray.dec[iDir]))