-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkat7vis.py
executable file
·1766 lines (1471 loc) · 78.6 KB
/
kat7vis.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
#! /usr/bin/env python
"""= kat7vis.py - visualization of kat-7 data
& claw
: Unknown
+
Script to load and visualize kat-7 data
--
"""
import sys, string, os, shutil
import cProfile
from os.path import join
#import mirtask
#from mirtask import uvdat, keys, util
from mirexec import TaskInvert, TaskClean, TaskRestore, TaskImFit, TaskCgDisp, TaskImStat, TaskUVFit
import miriad, pickle
import numpy as n
import pylab as p
import scipy.optimize as opt
import scipy.stats.morestats as morestats
#from threading import Thread
#from matplotlib.font_manager import fontManager, FontProperties
#font= FontProperties(size='x-small');
class kat7:
def __init__(self, file, nints=1000, nskip=0, nocal=False, nopass=False):
# initialize
self.nchan = 625
nchan = self.nchan
self.chans = n.arange(10,501)
self.nbl = 10
nbl = self.nbl
self.nints = nints
initsize = nints*self.nbl # number of integrations to read in a single chunk
self.sfreq = 1.5498 # freq for first channel in GHz
self.sdf = -0.000391 # dfreq per channel in GHz
self.approxuvw = True # flag to make template visibility file to speed up writing of dm track data
self.baseline_pairs =[(0, 1), (0, 2), (1, 2), (0, 3), (1, 3), (2, 3), (0, 4), (1, 4), (2, 4), (3, 4)]
# corresponding baselines ?? # poco: (1,2),(1,5),(2,5),(1,6),(2,6),(5,6),(1,3),(2,3),(3,6)] (miriad numbering)
self.pulsewidth = 0 * n.ones(len(self.chans)) # pulse width of crab and m31 candidates
# set dmarr
# self.dmarr = n.arange(5,45,3)
self.dmarr = [68.0] # crab
# self.tshift = 0.2 # not implemented yet
self.nskip = int(nskip*self.nbl) # number of iterations to skip (for reading in different parts of buffer)
nskip = int(self.nskip)
self.file = file
# load data
vis = miriad.VisData(file,)
da = n.zeros((initsize,nchan),dtype='complex64')
fl = n.zeros((initsize,nchan),dtype='bool')
pr = n.zeros((initsize,5),dtype='float64')
# read data into python arrays
i = 0
for inp, preamble, data, flags in vis.readLowlevel ('dsl3', False, nocal=nocal, nopass=nopass):
# Loop to skip some data and read shifted data into original data arrays
if i == 0:
# get few general variables
self.nants0 = inp.getScalar ('nants', 0)
self.inttime0 = inp.getScalar ('inttime', 10.0)
self.nspect0 = inp.getScalar ('nspect', 0)
self.nwide0 = inp.getScalar ('nwide', 0)
self.sdf0 = inp.getScalar ('sdf', self.nspect0)
self.nschan0 = inp.getScalar ('nschan', self.nspect0)
self.ischan0 = inp.getScalar ('ischan', self.nspect0)
self.sfreq0 = inp.getScalar ('sfreq', self.nspect0)
self.restfreq0 = inp.getScalar ('restfreq', self.nspect0)
self.pol0 = inp.getScalar ('pol')
if i < nskip:
i = i+1
continue
if (i-nskip) < initsize:
da[i-nskip] = data
fl[i-nskip] = flags
pr[i-nskip] = preamble
else:
break # stop at initsize
if not (i % (nbl*1000)):
print 'Read integration ', str(i/nbl)
i = i+1
if i < initsize:
print 'Array smaller than initialized array. Trimming.'
da = da[0:i-nskip]
fl = fl[0:i-nskip]
pr = pr[0:i-nskip]
try:
self.rawdata = da.reshape((i-nskip)/nbl,nbl,nchan)
self.flags = fl.reshape((i-nskip)/nbl,nbl,nchan)
self.preamble = pr
time = self.preamble[::nbl,3]
self.reltime = 24*3600*(time - time[0]) # relative time array in seconds
print
print 'Data read!'
print 'Shape of raw data, flags, time:'
print self.rawdata.shape, self.flags.shape, self.reltime.shape
print
except ValueError:
print 'Could not reshape data arrays. Incomplete read?'
def prep(self):
"""
Reshapes data for usage by other functions.
Note that it assumes that any integration with bad data has an entire baseline flagged.
"""
rawdata = self.rawdata
flags = self.flags
data = (rawdata)[:,:,self.chans]
# totallen = data[flags[:,:,self.chans]].shape[0]
# tlen = data.shape[0]
# chlen = len(self.chans)
# print tlen,totallen/(tlen*chlen), chlen,totallen
# self.data = n.reshape(data[flags[:,:,self.chans]], (tlen, totallen/(tlen*chlen), chlen)) # data is what is typically needed
self.data = data
self.dataph = (self.data.mean(axis=1)).real #dataph is summed and detected to form TP beam at phase center
self.rawdata = rawdata
print 'Data flagged, trimmed in channels, and averaged across baselines.'
print 'New rawdata, data, dataph shapes:'
print self.rawdata.shape, self.data.shape, self.dataph.shape
def spec(self, save=0):
chans = self.chans
reltime = self.reltime
mean = self.dataph.mean()
std = self.dataph.std()
# abs = (self.dataph - mean)/std
abs = self.dataph
print 'Data mean, std: %f, %f' % (mean, std)
p.figure(1)
ax = p.imshow(n.rot90(abs), aspect='auto', origin='upper', interpolation='nearest', extent=(min(reltime),max(reltime),0,len(chans)))
p.colorbar(ax)
p.yticks(n.arange(0,len(self.chans),50), (self.chans[(n.arange(0,len(self.chans), 50))]))
p.xlabel('Relative time (s)')
p.ylabel('Channel')
if save:
savename = self.file.split('.')[:-1]
savename.append(str(self.nskip/self.nbl) + '.spec.png')
savename = string.join(savename,'.')
print 'Saving file as ', savename
p.savefig(savename)
else:
p.show()
def fitspec(self, obsrms=0, save=0):
"""
Fits a powerlaw to the mean spectrum at the phase center.
Returns fit parameters.
"""
# logname = self.file.split('_')[0:3]
# logname.append('fitsp.txt')
# logname = string.join(logname,'_')
# log = open(logname,'a')
freq = self.sfreq + self.chans * self.sdf # freq array in GHz
# estimate of vis rms per channel from spread in imag space at phase center
if obsrms == 0:
print 'estimating obsrms from imaginary part of data...'
# obsrms = n.std((((self.data).mean(axis=1)).mean(axis=0)).imag)/n.sqrt(2) # sqrt(2) scales it to an amplitude error. indep of signal.
obsrms = n.std((((self.data).mean(axis=1)).mean(axis=0)).imag) # std of imag part is std of real part
# spec = n.abs((((self.data).mean(axis=1))).mean(axis=0))
spec = ((((self.data).mean(axis=1))).mean(axis=0)).real
print 'obsrms = %.2f' % (obsrms)
plaw = lambda a, b, x: a * (x/x[0]) ** b
# fitfunc = lambda p, x, rms: n.sqrt(plaw(p[0], p[1], x)**2 + rms**2) # for ricean-biased amplitudes
# errfunc = lambda p, x, y, rms: ((y - fitfunc(p, x, rms))/rms)**2
fitfunc = lambda p, x: plaw(p[0], p[1], x) # for real part of data
errfunc = lambda p, x, y, rms: ((y - fitfunc(p, x))/rms)**2
p0 = [100.,-5.]
p1, success = opt.leastsq(errfunc, p0[:], args = (freq, spec, obsrms))
print 'Fit results: ', p1
chisq = errfunc(p1, freq, spec, obsrms).sum()/(len(freq) - 2)
print 'Reduced chisq: ', chisq
p.figure(2)
p.errorbar(freq, spec, yerr=obsrms*n.ones(len(spec)), fmt='.')
p.plot(freq, fitfunc(p1, freq), label='Fit: %.1f, %.2f. Noise: %.1f, $\chi^2$: %.1f' % (p1[0], p1[1], obsrms, chisq))
p.xlabel('Frequency')
p.ylabel('Flux Density (Jy)')
p.legend()
if save == 1:
savename = self.file.split('.')[:-1]
savename.append(str(self.nskip/self.nbl) + '.fitsp.png')
savename = string.join(savename,'.')
print 'Saving file as ', savename
p.savefig(savename)
# print >> log, savename, 'Fit results: ', p1, '. obsrms: ', obsrms, '. $\Chi^2$: ', chisq
else:
pass
# print >> log, self.file, 'Fit results: ', p1, '. obsrms: ', obsrms, '. $\Chi^2$: ', chisq
def dmtrack(self, dm = 0., t0 = 0., show=0):
"""Takes dispersion measure in pc/cm3 and time offset from first integration in seconds.
t0 defined at first (unflagged) channel. Need to correct by flight time from there to freq=0 for true time.
Returns an array of (timebin, channel) to select from the data array.
"""
reltime = self.reltime
chans = self.chans
tint = self.reltime[1] - self.reltime[0]
# tint = self.inttime0 # could do this instead...?
freq = self.sfreq + chans * self.sdf # freq array in GHz
# given freq, dm, dfreq, calculate pulse time and duration
pulset_firstchan = 4.2e-3 * dm * freq[len(freq)-1]**(-2) # used to start dmtrack at highest-freq unflagged channel
pulset = 4.2e-3 * dm * freq**(-2) + t0 - pulset_firstchan # time in seconds
pulsedt = n.sqrt( (8.3e-6 * dm * (1000*self.sdf) * freq**(-3))**2 + self.pulsewidth**2) # dtime in seconds
timebin = []
chanbin = []
for ch in range(len(chans)):
# ontime = n.where(((pulset[ch] + pulsedt[ch]/2.) >= reltime) & ((pulset[ch] - pulsedt[ch]/2.) <= reltime))
ontime = n.where(((pulset[ch] + pulsedt[ch]/2.) >= reltime - tint/2.) & ((pulset[ch] - pulsedt[ch]/2.) <= reltime + tint/2.))
timebin = n.concatenate((timebin, ontime[0]))
chanbin = n.concatenate((chanbin, (ch * n.ones(len(ontime[0]), dtype=int))))
track = (list(timebin), list(chanbin))
# print 'timebin, chanbin: ', timebin, chanbin
if show:
p.plot(track[1], track[0])
return track
def tracksub(self, dmbin, tbin, bgwindow = 0):
"""Reads data along dmtrack and optionally subtracts background like writetrack method.
Returns the difference of the data in the on and off tracks as a single integration with all bl and chans.
Nominally identical to writetrack, but gives visibilities values off at the 0.01 (absolute) level. Good enough for now.
"""
data = self.data
trackon = self.dmtrack(dm=self.dmarr[dmbin], t0=self.reltime[tbin], show=0)
if ((trackon[1][0] != 0) | (trackon[1][len(trackon[1])-1] != len(self.chans)-1)):
# print 'Track does not span all channels. Skipping.'
return [0]
dataon = data[trackon[0], :, trackon[1]]
# set up bg track
if bgwindow:
# measure max width of pulse (to avoid in bgsub)
twidths = []
for k in trackon[1]:
twidths.append(len(n.array(trackon)[0][list(n.where(n.array(trackon[1]) == k)[0])]))
bgrange = range(-bgwindow/2 - max(twidths) + tbin, -max(twidths) + tbin) + range(max(twidths) + tbin, max(twidths) + bgwindow/2 + tbin + 1)
for k in bgrange: # build up super track for background subtraction
if bgrange.index(k) == 0: # first time through
trackoff = self.dmtrack(dm=self.dmarr[dmbin], t0=self.reltime[k], show=0)
else: # then extend arrays by next iterations
tmp = self.dmtrack(dm=self.dmarr[dmbin], t0=self.reltime[k], show=0)
trackoff[0].extend(tmp[0])
trackoff[1].extend(tmp[1])
dataoff = data[trackoff[0], :, trackoff[1]]
# compress time axis, then subtract on and off tracks
for ch in n.unique(trackon[1]):
indon = n.where(trackon[1] == ch)
if bgwindow:
indoff = n.where(trackoff[1] == ch)
datadiff = dataon[indon].mean(axis=0) - dataoff[indoff].mean(axis=0)
else:
datadiff = dataon[indon].mean(axis=0)
if ch == 0:
datadiffarr = [datadiff]
else:
datadiffarr = n.append(datadiffarr, [datadiff], axis=0)
datadiffarr = n.array([datadiffarr.transpose()])
return datadiffarr
def setstd(self, dmbin, bgwindow=10):
"""
Measures the observed std of the mean of the mean dedispersed spectrum. Uses the std of the imaginary part of differenced data.
"""
obsrms = []
for bgi in range(bgwindow, self.nints-bgwindow, self.nints/15):
datadiff = self.tracksub(dmbin, bgi, bgwindow=bgwindow) # arbitrary offset to measure typical noise in bg
obsrms.append(n.std(datadiff[0].mean(axis=1).imag)) # std of imag part is std of real part
self.obsrms = n.median(obsrms)/n.sqrt(len(datadiff[0]))
print 'Measured observed std of mean visibility as:', self.obsrms
def writetrack(self, dmbin, tbin, tshift=0, bgwindow=0, show=0):
"""Writes data from track out as miriad visibility file.
Optional background subtraction bl-by-bl over bgwindow integrations. Note that this is bgwindow *dmtracks* so width is bgwindow+track width
Optional spectrum plot with source and background dmtracks
"""
# prep data and track
rawdatatrim = self.rawdata[:,:,self.chans]
track = self.dmtrack(dm=self.dmarr[dmbin], t0=self.reltime[tbin-tshift], show=0)
if ((track[1][0] != 0) | (track[1][len(track[1])-1] != len(self.chans)-1)):
# print 'Track does not span all channels. Skipping.'
return 0
twidths = []
for i in track[1]:
twidths.append(len(n.array(track)[0][list(n.where(n.array(track[1]) == i)[0])]))
if bgwindow > 0:
bgrange = range(-bgwindow/2 - max(twidths) + tbin - tshift, -max(twidths) + tbin - tshift) + range(max(twidths) + tbin - tshift, max(twidths) + bgwindow/2 + tbin - tshift + 1)
# bgrange = range(int(-bgwindow/2.) + tbin - tshift, int(bgwindow/2.) + tbin - tshift + 1)
# bgrange.remove(tbin - tshift); bgrange.remove(tbin - tshift + 1); bgrange.remove(tbin - tshift - 1); bgrange.remove(tbin - tshift + 2); bgrange.remove(tbin - tshift - 2); bgrange.remove(tbin - tshift + 3); bgrange.remove(tbin - tshift - 3)
for i in bgrange: # build up super track for background subtraction
if bgrange.index(i) == 0: # first time through
trackbg = self.dmtrack(dm=self.dmarr[dmbin], t0=self.reltime[i], show=0)
else: # then extend arrays by next iterations
tmp = self.dmtrack(dm=self.dmarr[dmbin], t0=self.reltime[i], show=0)
trackbg[0].extend(tmp[0])
trackbg[1].extend(tmp[1])
else:
print 'Not doing any background subtraction.'
if show:
# show source and background tracks on spectrum
p.figure(1)
p.plot(self.reltime[track[0]], track[1], 'w.')
if bgwindow > 0:
p.plot(self.reltime[trackbg[0]], trackbg[1], 'r.')
self.spec(save=0)
# define input metadata source and output visibility file names
outname = string.join(self.file.split('.')[:-1], '.') + '.' + str(self.nskip/self.nbl) + '-' + 'dm' + str(dmbin) + 't' + str(tbin) + '.mir'
shutil.rmtree(outname, ignore_errors=True)
vis = miriad.VisData(self.file,)
i = 0
int0 = int(self.nskip + (track[0][len(track[0])/2] + tshift) * self.nbl) # choose integration at center of dispersed track
for inp, preamble, data, flags in vis.readLowlevel ('dsl3', False, nocal=True, nopass=True):
if i == 0:
# create output vis file
shutil.rmtree(outname, ignore_errors=True)
out = miriad.VisData(outname)
dOut = out.open ('c')
# set variables
dOut.setPreambleType ('uvw', 'time', 'baseline')
dOut.writeVarInt ('nants', self.nants0)
dOut.writeVarFloat ('inttime', self.inttime0)
dOut.writeVarInt ('nspect', self.nspect0)
dOut.writeVarDouble ('sdf', self.sdf0)
dOut.writeVarInt ('nwide', self.nwide0)
dOut.writeVarInt ('nschan', self.nschan0)
dOut.writeVarInt ('ischan', self.ischan0)
dOut.writeVarDouble ('sfreq', self.sfreq0)
dOut.writeVarDouble ('restfreq', self.restfreq0)
dOut.writeVarInt ('pol', self.pol0)
# inp.copyHeader (dOut, 'history') # **hack**
inp.initVarsAsInput (' ') # ???
inp.copyLineVars (dOut)
if i < int0: # need to grab only integration at pulse+intoff
i = i+1
continue
elif i < int0 + self.nbl:
# write out track, if not flagged
if n.any(flags):
bgarr = []
for j in range(self.nchan):
if j in self.chans:
matches = n.where( j == n.array(self.chans[track[1]]) )[0] # hack, since chans are from 0-64, but track is in trimmed chan space
raw = rawdatatrim[track[0], i-int0, track[1]][matches] # all baselines for the known pulse
raw = raw.mean(axis=0) # create spectrum for each baseline by averaging over time
if bgwindow > 0: # same as above, but for bg
matchesbg = n.where( j == n.array(self.chans[trackbg[1]]) )[0]
rawbg = rawdatatrim[trackbg[0], i-int0, trackbg[1]][matchesbg]
rawbg = rawbg.mean(axis=0)
bgarr.append(rawbg)
data[j] = raw - rawbg
else:
data[j] = raw
else:
flags[j] = False
# ants = util.decodeBaseline (preamble[4])
# print preamble[3], ants
# dOut.write (self.preamble[i], data, flags) # not working right here...?
dOut.write (preamble, data, flags)
i = i+1 # essentially a baseline*int number
elif i >= int0 + self.nbl:
break
dOut.close ()
return 1
def writetrack2(self, dmbin, tbin, tshift=0, bgwindow=0, show=0):
"""Writes data from track out as miriad visibility file.
Alternative to writetrack that uses stored, approximate preamble used from start of pulse, not middle.
Optional background subtraction bl-by-bl over bgwindow integrations. Note that this is bgwindow *dmtracks* so width is bgwindow+track width
"""
# create bgsub data
datadiffarr = self.tracksub(dmbin, tbin, bgwindow=bgwindow)
if n.shape(datadiffarr) == n.shape([0]): # if track doesn't cross band, ignore this iteration
return 0
data = n.zeros(self.nchan, dtype='complex64') # default data array. gets overwritten.
data0 = n.zeros(self.nchan, dtype='complex64') # zero data array for flagged bls
flags = n.zeros(self.nchan, dtype='bool')
# define output visibility file names
outname = string.join(self.file.split('.')[:-1], '.') + '.' + str(self.nskip/self.nbl) + '-' + 'dm' + str(dmbin) + 't' + str(tbin) + '.mir'
print outname
vis = miriad.VisData(self.file,)
int0 = int((tbin + tshift) * self.nbl)
flags0 = []
i = 0
for inp, preamble, data, flags in vis.readLowlevel ('dsl3', False, nocal=True, nopass=True):
if i == 0:
# prep for temp output vis file
shutil.rmtree(outname, ignore_errors=True)
out = miriad.VisData(outname)
dOut = out.open ('c')
# set variables
dOut.setPreambleType ('uvw', 'time', 'baseline')
dOut.writeVarInt ('nants', self.nants0)
dOut.writeVarFloat ('inttime', self.inttime0)
dOut.writeVarInt ('nspect', self.nspect0)
dOut.writeVarDouble ('sdf', self.sdf0)
dOut.writeVarInt ('nwide', self.nwide0)
dOut.writeVarInt ('nschan', self.nschan0)
dOut.writeVarInt ('ischan', self.ischan0)
dOut.writeVarDouble ('sfreq', self.sfreq0)
dOut.writeVarDouble ('restfreq', self.restfreq0)
dOut.writeVarInt ('pol', self.pol0)
# inp.copyHeader (dOut, 'history') # **hack**
inp.initVarsAsInput (' ') # ???
inp.copyLineVars (dOut)
if i < self.nbl:
flags0.append(flags.copy())
i = i+1
else:
break
l = 0
for i in range(len(flags0)): # iterate over baselines
# write out track, if not flagged
if n.any(flags0[i]):
k = 0
for j in range(self.nchan):
if j in self.chans:
data[j] = datadiffarr[0, l, k]
# flags[j] = flags0[i][j]
k = k+1
else:
data[j] = 0 + 0j
# flags[j] = False
l = l+1
else:
data = data0
# flags = n.zeros(self.nchan, dtype='bool')
dOut.write (self.preamble[int0 + i], data, flags0[i])
dOut.close ()
return 1
def makedmt0(self):
"""Integrates data at dmtrack for each pair of elements in dmarr, time.
Not threaded. Uses dmthread directly.
Stores mean of detected signal after dmtrack, effectively forming beam at phase center.
"""
dmarr = self.dmarr
# reltime = n.arange(2*len(self.reltime))/2. # danger!
reltime = self.reltime
chans = self.chans
dmt0arr = n.zeros((len(dmarr),len(reltime)), dtype='float64')
for i in range(len(dmarr)):
for j in range(len(reltime)):
dmtrack = self.dmtrack(dm=dmarr[i], t0=reltime[j])
if ((dmtrack[1][0] == 0) & (dmtrack[1][len(dmtrack[1])-1] == len(self.chans)-1)): # use only tracks that span whole band
# dmt0arr[i,j] = n.abs((((self.data).mean(axis=1))[dmtrack[0],dmtrack[1]]).mean())
dmt0arr[i,j] = ((((self.data).mean(axis=1))[dmtrack[0],dmtrack[1]]).mean()).real # use real part to detect on axis, but keep gaussian dis'n
print 'dedispersed for ', dmarr[i]
self.dmt0arr = dmt0arr
def plotdmt0(self, save=0):
"""calculates rms noise in dmt0 space, then plots circles for each significant point
save=1 means plot to file.
"""
dmarr = self.dmarr
arr = self.dmt0arr
reltime = self.reltime
peaks = self.peaks
tbuffer = 7 # number of extra iterations to trim from edge of dmt0 plot
# Trim data down to where dmt0 array is nonzero
arreq0 = n.where(arr == 0)
trimt = arreq0[1].min()
arr = arr[:,:trimt - tbuffer]
reltime = reltime[:trimt - tbuffer]
print 'dmt0arr/time trimmed to new shape: ',n.shape(arr), n.shape(reltime)
mean = arr.mean()
std = arr.std()
arr = (arr - mean)/std
peakmax = n.where(arr == arr.max())
# Plot
# p.clf()
ax = p.imshow(arr, aspect='auto', origin='lower', interpolation='nearest', extent=(min(reltime),max(reltime),min(dmarr),max(dmarr)))
p.colorbar()
if len(peaks[0]) > 0:
print 'Peak of %f at DM=%f, t0=%f' % (arr.max(), dmarr[peakmax[0][0]], reltime[peakmax[1][0]])
for i in range(len(peaks[1])):
ax = p.imshow(arr, aspect='auto', origin='lower', interpolation='nearest', extent=(min(reltime),max(reltime),min(dmarr),max(dmarr)))
p.axis((min(reltime),max(reltime),min(dmarr),max(dmarr)))
p.plot([reltime[peaks[1][i]]], [dmarr[peaks[0][i]]], 'o', markersize=2*arr[peaks[0][i],peaks[1][i]], markerfacecolor='white', markeredgecolor='blue', alpha=0.5)
p.xlabel('Time (s)')
p.ylabel('DM (pc/cm3)')
p.title('Summed Spectra in DM-t0 space')
if save:
savename = self.file.split('.')[:-1]
savename.append(str(self.nskip/self.nbl) + '.dmt0.png')
savename = string.join(savename,'.')
p.savefig(savename)
def peakdmt0(self, sig=5.):
""" Method to find peaks in dedispersed data (in dmt0 space).
Clips noise, also.
"""
arr = self.dmt0arr
reltime = self.reltime
tbuffer = 7 # number of extra iterations to trim from edge of dmt0 plot
# Trim data down to where dmt0 array is nonzero
arreq0 = n.where(arr == 0)
trimt = arreq0[1].min()
arr = arr[:,:trimt - tbuffer]
reltime = reltime[:trimt - tbuffer]
print 'dmt0arr/time trimmed to new shape: ',n.shape(arr), n.shape(reltime)
# single iteration of sigma clip to find mean and std, skipping zeros
mean = arr.mean()
std = arr.std()
print 'initial mean, std: ', mean, std
cliparr = n.where((arr < mean + 5*std) & (arr > mean - 5*std))
mean = arr[cliparr].mean()
std = arr[cliparr].std()
print 'final mean, sig, std: ', mean, sig, std
# Recast arr as significance array
# arr = n.sqrt((arr-mean)**2 - std**2)/std # PROBABLY WRONG
arr = (arr-mean)/std # for real valued trial output (gaussian dis'n)
# Detect peaks
self.peaks = n.where(arr > sig)
peakmax = n.where(arr == arr.max())
print 'peaks: ', self.peaks
return self.peaks,arr[self.peaks]
def imagedmt0(self, dmbin, t0bin, tshift=0, bgwindow=10, show=0, clean=1, mode='dirty'):
""" Makes and fits an background subtracted image for a given dmbin and t0bin.
tshift can shift the actual t0bin earlier to allow reading small chunks of data relative to pickle.
"""
# set up
outroot = string.join(self.file.split('.')[:-1], '.') + '.' + str(self.nskip/self.nbl) + '-dm' + str(dmbin) + 't' + str(t0bin)
shutil.rmtree (outroot+'.map', ignore_errors=True); shutil.rmtree (outroot+'.beam', ignore_errors=True); shutil.rmtree (outroot+'.clean', ignore_errors=True); shutil.rmtree (outroot+'.restor', ignore_errors=True)
if self.approxuvw:
status = self.writetrack2(dmbin, t0bin, tshift=tshift, bgwindow=bgwindow) # output file at dmbin, trelbin
else:
status = self.writetrack(dmbin, t0bin, tshift=tshift, bgwindow=bgwindow) # output file at dmbin, trelbin
if not status: # if writetrack fails, exit this iteration
return 0
try:
# make image, clean, restor, fit point source
print
print 'Making dirty image for nskip=%d, dm[%d]=%.1f, and trel[%d] = %.3f.' % (self.nskip/self.nbl, dmbin, self.dmarr[dmbin], t0bin-tshift, self.reltime[t0bin-tshift])
txt = TaskInvert (vis=outroot+'.mir', map=outroot+'.map', beam=outroot+'.beam', mfs=True, double=True, cell=70, imsize=160).snarf() # good for m31 search
if show: txt = TaskCgDisp (in_=outroot+'.map', device='/xs', wedge=True, beambl=True).snarf ()
txt = TaskImStat (in_=outroot+'.map').snarf() # get dirty image stats
if mode == 'clean':
# print 'cleaning image'
thresh = 2*float(txt[0][10][41:47]) # set thresh to 2*noise level in dirty image. hack! OMG!!
# txt = TaskClean (beam=outroot+'.beam', map=outroot+'.map', out=outroot+'.clean', cutoff=thresh, region='relpix,boxes(-10,-10,10,10)').snarf () # targeted clean
txt = TaskClean (beam=outroot+'.beam', map=outroot+'.map', out=outroot+'.clean', cutoff=thresh).snarf ()
print 'Cleaned to %.2f Jy after %d iterations' % (thresh, int(txt[0][-4][19:]))
txt = TaskRestore (beam=outroot+'.beam', map=outroot+'.map', model=outroot+'.clean', out=outroot+'.restor').snarf ()
if show: txt = TaskCgDisp (in_=outroot+'.restor', device='/xs', wedge=True, beambl=True, labtyp='hms,dms').snarf ()
txt = TaskImFit (in_=outroot+'.restor', object='point').snarf ()
# parse output of imfit
# print '012345678901234567890123456789012345678901234567890123456789'
peak = float(txt[0][16][30:36])
epeak = float(txt[0][16][44:])
off_ra = float(txt[0][17][28:39])
eoff_ra = float(txt[0][18][30:39])
off_dec = float(txt[0][17][40:])
eoff_dec = float(txt[0][18][40:])
print 'Fit cleaned image peak %.2f +- %.2f' % (peak, epeak)
return peak, epeak, off_ra, eoff_ra, off_dec, eoff_dec
elif mode == 'dirty':
# print 'stats of dirty image'
peak = float(txt[0][10][50:57]) # get peak of dirty image
epeak = float(txt[0][10][41:47]) # note that epeak is biased by any true flux
print 'Individual dirty image peak %.2f +- %.2f' % (peak, epeak)
if clean:
shutil.rmtree (outroot + '.mir', ignore_errors=True)
# shutil.rmtree (outroot+'.map', ignore_errors=True)
shutil.rmtree (outroot+'.beam', ignore_errors=True); shutil.rmtree (outroot+'.clean', ignore_errors=True); shutil.rmtree (outroot+'.restor', ignore_errors=True)
return peak, epeak
except:
print 'Something broke with imaging!'
return 0
def imsearch(self, dmind, tind, sig=5., show=0, edge=0, mode='dirty'):
"""
Reproduce search result of pulse_search_image.
"""
bgwindow = 10 # where bg subtraction is made
if mode == 'dirty':
# define typical dirty image noise level for this dm
print 'For DM = %.1f, measuring median image noise level' % (self.dmarr[dmind])
bgpeak = []; bgepeak = []
for bgi in range(bgwindow, self.nints-bgwindow, self.nints/15):
print 'Measuring noise in integration %d' % (bgi)
outname = string.join(self.file.split('.')[:-1], '.') + '.' + str(self.nskip/self.nbl) + '-' + 'dm' + str(dmind) + 't' + str(bgi) + '.mir'
shutil.rmtree (outname, ignore_errors=True); shutil.rmtree (outname+'.map', ignore_errors=True); shutil.rmtree (outname+'.beam', ignore_errors=True)
status = self.writetrack2(dmind, bgi, bgwindow=bgwindow) # output file at dmbin, trelbin
try:
txt = TaskInvert (vis=outname, map=outname+'.map', beam=outname+'.beam', mfs=True, double=True, cell=80, imsize=250).snarf()
txt = TaskImStat (in_=outname+'.map').snarf() # get dirty image stats
bgpeak.append(float(txt[0][10][51:61])) # get peak of dirty image
bgepeak.append(float(txt[0][10][41:51])) # note that epeak is biased by any true flux
shutil.rmtree (outname, ignore_errors=True)
shutil.rmtree (outname+'.map', ignore_errors=True)
shutil.rmtree (outname+'.beam', ignore_errors=True)
except:
pass
print 'Dirty image noises and their median', bgepeak, n.median(bgepeak)
# now make dirty image
results = self.imagedmt0(dmind, tind, show=show, bgwindow=bgwindow, clean=1, mode=mode)
if mode == 'clean':
peak, epeak, off_ra, eoff_ra, off_dec, eoff_dec = results
elif mode == 'dirty': # need to develop more... needs to be ~10ms processing per int!
peak, epeak = results
epeak = n.median(bgepeak)
if peak/epeak >= sig:
print '\tDetection!'
if mode == 'clean':
print self.nskip/self.nbl, self.nints, (dmind, tind), 'Peak, (sig), RA, Dec: ', peak, epeak, '(', peak/epeak, ') ', off_ra, eoff_ra, off_dec, eoff_dec
elif mode == 'dirty':
print self.nskip/self.nbl, self.nints, (dmind, tind), 'Peak, (sig): ', peak, epeak, '(', peak/epeak, ')'
def uvfitdmt0(self, dmbin, t0bin, bgwindow=10, tshift=0, show=1, mode='fit'):
""" Makes and fits a point source to background subtracted visibilities for a given dmbin and t0bin.
tshift can shift the actual t0bin earlier to allow reading small chunks of data relative to pickle.
"""
# set up
outroot = string.join(self.file.split('.')[:-1], '.') + '.' + str(self.nskip/self.nbl) + '-dm' + str(dmbin) + 't' + str(t0bin)
shutil.rmtree (outroot + '.mir', ignore_errors=True)
if self.approxuvw:
status = self.writetrack2(dmbin, t0bin, tshift=tshift, bgwindow=bgwindow) # output file at dmbin, trelbin
else:
status = self.writetrack(dmbin, t0bin, tshift=tshift, bgwindow=bgwindow) # output file at dmbin, trelbin
if not status: # if writetrack fails, exit this iteration
return 0
if mode == 'fit':
try:
# fit point source model to visibilities
print
print 'UVfit for nskip=%d, dm[%d] = %.1f, and trel[%d] = %.3f.' % (self.nskip/self.nbl, dmbin, self.dmarr[dmbin], t0bin-tshift, self.reltime[t0bin-tshift])
txt = TaskUVFit (vis=outroot+'.mir', object='point', select='-auto').snarf()
# parse output of imfit
# print '012345678901234567890123456789012345678901234567890123456789'
peak = float(txt[0][8][30:38])
epeak = float(txt[0][8][46:])
off_ra = float(txt[0][9][30:38])
eoff_ra = float(txt[0][10][31:42])
off_dec = float(txt[0][9][40:])
eoff_dec = float(txt[0][10][42:])
print 'Fit peak %.2f +- %.2f' % (peak, epeak)
shutil.rmtree (outroot + '.mir', ignore_errors=True)
return peak, epeak, off_ra, eoff_ra, off_dec, eoff_dec
except:
print 'Something broke in/after uvfit!'
shutil.rmtree (outroot + '.mir', ignore_errors=True)
return 0
elif mode == 'grid':
llen = 150
mlen = 150
linspl = n.linspace(-4000,4000,llen)
linspm = n.linspace(-4000,4000,mlen)
snrarr = n.zeros((llen, mlen))
for i in range(llen):
print 'Starting loop ', i
for j in range(mlen):
try:
txt = TaskUVFit (vis=outroot+'.mir', object='point', select='-auto', spar='0,'+str(linspl[i])+','+str(linspm[j]), fix='xy').snarf()
# print txt[0][8:10]
peak = float(txt[0][8][30:38])
epeak = float(txt[0][8][46:])
off_ra = float(txt[0][9][30:38])
off_dec = float(txt[0][9][40:])
snrarr[i, j] = peak/epeak
except:
print 'Something broke in/after uvfit!'
peak = n.where(snrarr == snrarr.max())
print 'Peak: ', snrarr[peak]
print 'Location: ', peak, (linspl[peak[0]], linspm[peak[1]])
print
print 'Center SNR: ', snrarr[llen/2,llen/2]
log = open('log.txt','a')
print >> log, outroot, snrarr[peak], peak, (linspl[peak[0]], linspm[peak[1]])
log.close()
ax = p.imshow(snrarr, aspect='auto', origin='lower', interpolation='nearest')
p.colorbar()
p.savefig(outroot + '.png')
def uvfitdmt02 (self, dmbin, t0bin, bgwindow=10, tshift=0, show=1, mode='default'):
"""Experimental alternative function to do uvfitting of visibilities.
Reads in data from dispersion track, then fits uv model of point source in python.
mode defines the optimization approach.
"""
datadiffarr = self.tracksub(dmbin, t0bin, bgwindow=bgwindow)
int0 = int((t0bin + tshift) * self.nbl)
meanfreq = n.mean(self.sfreq + self.sdf * self.chans )
obsrms = self.obsrms
if show:
p.figure(1)
p.plot(datadiffarr[0].mean(axis=1).real, datadiffarr[0].mean(axis=1).imag, '.')
# get flags to help select good ants
vis = miriad.VisData(self.file,)
flags0 = []
i = 0
for inp, preamble, data, flags in vis.readLowlevel ('dsl3', False, nocal=True, nopass=True):
if i < self.nbl:
flags0.append(flags.copy())
i = i+1
else:
break
goodants = n.where( n.any(n.array(flags0), axis=1) == True)
u = []; v = []; w = []
for i in range(self.nbl):
u.append(self.preamble[int0 + i][0]) # in units of ns
v.append(self.preamble[int0 + i][1]) # in units of ns
w.append(self.preamble[int0 + i][2]) # in units of ns
u = n.array(u); v = n.array(v); w = n.array(w)
u = meanfreq * u[goodants]; v = meanfreq * v[goodants]; w = meanfreq * w[goodants]
data = (datadiffarr[0]).mean(axis=1)
print
print 'UVfit2 for nskip=%d, dm[%d] = %.1f, and trel[%d] = %.3f.' % (self.nskip/self.nbl, dmbin, self.dmarr[dmbin], t0bin-tshift, self.reltime[t0bin-tshift])
vi = lambda a, l, m, u, v, w: a * n.exp(-2j * n.pi * (u*l + v*m)) # + w*n.sqrt(1 - l**2 - m**2))) # ignoring w term
phi = lambda l, m, u, v: 2 * n.pi * (l*u + m*v)
amp = lambda vi, l, m, u, v, w: n.mean(n.real(vi) * n.cos(phi(l, m, u, v)) + n.imag(vi) * n.sin(phi(l, m, u, v)))
def errfunc (p, u, v, w, y, obsrms):
a, l, m = p
err = (y - vi(a, l, m, u, v, w))/obsrms
return err.real + err.imag
def errfunc2 (p, l, m, u, v, w, y):
a = p
err = (y - vi(a, l, m, u, v, w))
return err.real + err.imag
def ltoa (l):
a = n.arcsin(l) * 180 / n.pi * 3600
return a
if mode == 'default':
p0 = [100.,0.,0.]
out = opt.leastsq(errfunc, p0, args = (u, v, w, data, obsrms), full_output=1)
p1 = out[0]
covar = out[1]
print 'Fit results (Jy, arcsec, arcsec):', p1[0], ltoa(p1[1]), ltoa(p1[2])
print 'Change in sumsq: %.2f to %.2f' % (n.sum(errfunc(p0, u, v, w, data, obsrms)**2), n.sum(errfunc(p1, u, v, w, data, obsrms)**2))
print 'here\'s some stuff...'
print covar
print n.sqrt(covar[0][0])
print n.sqrt(covar[1][1])
elif mode =='directi':
llen = 60
mlen = 60
linspl = n.linspace(-0.01,0.01,llen) # dl=0.026 => 1.5 deg (half ra width of andromeda)
linspm = n.linspace(-0.01,0.01,mlen) # dl=0.01 => 0.57 deg (half dec width of andromeda)
amparr = n.zeros((llen, mlen))
p0 = [100.]
for i in range(llen):
for j in range(mlen):
out = amp(data, linspl[i], linspm[j], u, v, w)
amparr[i, j] = out
maxs = n.where(amparr >= 0.9*amparr.max())
print 'Peak: ', amparr.max()
print 'Location: ', maxs, (ltoa(linspl[maxs[0]]), ltoa(linspm[maxs[1]]))
print 'SNR: ', amparr.max()/obsrms
if show:
p.figure(2)
ax = p.imshow(amparr, aspect='auto', origin='lower', interpolation='nearest')
p.colorbar()
p.show()
elif mode =='peaki':
llen = 60
mlen = 60
linspl = n.linspace(-0.01,0.01,llen) # dl=0.026 => 1.5 deg (half ra width of andromeda)
linspm = n.linspace(-0.01,0.01,mlen) # dl=0.01 => 0.57 deg (half dec width of andromeda)
amparr = n.zeros((llen, mlen))
p0 = [100.]
peak = 0.
imax = 0
jmax = 0
for i in range(llen):
for j in range(mlen):
aa = amp(data, linspl[i], linspm[j], u, v, w)
if peak < aa:
peak = aa
imax = i
jmax = j
print 'Peak: ', peak
print 'Location: ', ltoa(linspl[imax]), ltoa(linspm[jmax])
print 'SNR: ', peak/obsrms
if show:
p.show()
elif mode == 'map':
p0 = [100.,0.,0.]
out = opt.leastsq(errfunc, p0, args = (u, v, w, data, obsrms), full_output=1)
p1 = out[0]
covar = out[1]
llen = 20
mlen = 20
sumsq = n.zeros((llen, mlen))
linspl = n.linspace(-0.005,0.005,llen) # dl=0.026 => 1.5 deg (half ra width of andromeda)
linspm = n.linspace(-0.005,0.005,mlen) # dl=0.01 => 0.57 deg (half dec width of andromeda)
for i in range(llen):
for j in range(mlen):
sumsq[i, j] = n.sum(errfunc([p1[0], linspl[i], linspm[j]], u, v, w, data, obsrms)**2)
mins = n.where(sumsq < 1.01 * sumsq.min())
print 'Best fit: ', p1
print 'Red. chisq: ', sumsq[mins][0]/(9-3)
print 'Location: ', mins, (ltoa(linspl[mins[0]])[0], ltoa(linspm[mins[1]])[0])
if show:
p.figure(2)
p.plot(mins[1], mins[0], 'w.')
p.imshow(sumsq)
p.colorbar()
p.show()
elif mode == 'lsgrid':
llen = 30
mlen = 30
linspl = n.linspace(-0.005,0.005,llen) # dl=0.026 => 1.5 deg (half ra width of andromeda)
linspm = n.linspace(-0.005,0.005,mlen) # dl=0.01 => 0.57 deg (half dec width of andromeda)
amparr = n.zeros((llen, mlen))
p0 = [100.]
for i in range(llen):
for j in range(mlen):
out = opt.leastsq(errfunc2, p0, args = (linspl[i], linspm[j], u, v, w, data), full_output=1)
amparr[i, j] = out[0]
maxs = n.where(amparr >= 0.9*amparr.max())
print 'Peak: ', amparr.max()
print 'Location: ', maxs, (ltoa(linspl[maxs[0]]), ltoa(linspm[maxs[1]]))
print 'SNR: ', amparr.max()/obsrms
print
print 'Center: ', amparr[15,15]
print 'Center SNR: ', amparr[15,15]/obsrms
if show:
p.figure(2)
ax = p.imshow(amparr, aspect='auto', origin='lower', interpolation='nearest')
p.colorbar()
p.show()
def closure(self, dmbin, bgwindow=0, show=0):
"""Calculates the closure phase or bispectrum for each integration, averaging over all channels (for now).
Detection can be done by averaging closure phases (bad) or finding when all triples have SNR over a threshold.
"""
triph = lambda d,i,j,k: n.mod(n.angle(d[i]) + n.angle(d[j]) - n.angle(d[k]), 2*n.pi) # triple phase
# use triples
bisp = lambda d,i,j,k: d[i] * d[j] * n.conj(d[k]) # bispectrum w/o normalization
triples = [(0,7,6),(0,2,1),(0,4,3),(6,8,3),(1,5,3)] # antenna triples for good poco data: 123, 125, 126, 136, 156 (correct! miriad numbering). 6 true triples for n=5 is 123 125 126 135 136 156
# option 1: triple phase average over frequency
# triarr = n.zeros((len(triples), len(self.data)))
# option 2: triple phase no freq avg
# triarr = n.zeros((len(self.data)-2*bgwindow-1, len(triples), len(self.data[0,0])))
# option 3: bispectrum
bisparr = n.zeros((len(triples), len(self.data)), dtype=n.dtype('complex'))
print 'Building closure quantity array...'
for int in range(len(self.data)):
diff = self.tracksub(dmbin, int, bgwindow=bgwindow)
if len(n.shape(diff)) == 1: # no track
continue
diffmean = diff[0].mean(axis=1) # option 1, 3
for tr in range(len(triples)):
# use triples
(i,j,k) = triples[tr]
bisparr[tr,int] = complex(bisp(diffmean, i, j, k)) # option 3
bispstd = n.array( [n.sqrt((n.abs(bisparr[i]**2).mean())) for i in range(len(triples))] )
print 'First pass, bispstd: ', bispstd
threesig = n.array( [n.where( bisparr[i] < 3*bisparr[i].std() )[0] for i in range(len(triples))] )
bispstd = n.array( [n.sqrt((n.abs(bisparr[i,threesig[i]]**2).mean())) for i in range(len(triples))] )
print 'Second pass, bispstd: ', bispstd
bispsnr = n.array( [2*bisparr[i].real/bispstd[i] for i in range(len(triples))] )
# normalize SNR by average of all triples?
bispsnr = bispsnr.mean(axis=0)
peaks = n.where( bispsnr > 5 ) # significant pulse for bispectrum with snr > 5
# peakswhere = n.array([], dtype='int')
# peaksint = []