-
Notifications
You must be signed in to change notification settings - Fork 0
/
evlavis.py
executable file
·2061 lines (1725 loc) · 97.7 KB
/
evlavis.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
"""= evlavis.py - visualization of evla fast dump data
& claw
: Unknown
+
Script to load and visualize evla data
--
"""
import sys, string, os, shutil
#import cProfile
from os.path import join
import pickle
import numpy as n
import pylab as p
import scipy.optimize as opt
import scipy.stats.morestats as morestats
try:
import aipy
except ImportError:
print 'No aipy available. Can\'t image ms data.'
#from threading import Thread
#from matplotlib.font_manager import fontManager, FontProperties
if len(sys.argv) != 2:
try:
from casa import ms
from casa import quanta as qa
except:
from mirtask import util
from mirexec import TaskInvert, TaskClean, TaskRestore, TaskImFit, TaskCgDisp, TaskImStat, TaskUVFit
import miriad
else:
from mirtask import util
from mirexec import TaskInvert, TaskClean, TaskRestore, TaskImFit, TaskCgDisp, TaskImStat, TaskUVFit
import miriad
def sigma_clip(arr,sigma=3):
"""Function takes 1d array of values and returns the sigma-clipped min and max scaled by value "sigma".
"""
cliparr = range(len(arr)) # initialize
arr = n.append(arr,[1]) # append superfluous item to trigger loop
while len(cliparr) != len(arr):
arr = arr[cliparr]
mean = arr.mean()
std = arr.std()
cliparr = n.where((arr < mean + sigma*std) & (arr > mean - sigma*std))[0]
return mean - sigma*std, mean + sigma*std
class evla:
def __init__(self, file, nints=1000, nskip=0, nocal=False, nopass=False, ddid=[-1], selectpol=['RR','LL'], scan=0, datacol='data'):
"""Initializes the class according to the file type. Miriad or Measurement Set?
Note that CASA stuff only works if this is run from within casapy.
Scan is zero-based selection based on scan order, not actual scan number.
"""
# initialize
self.approxuvw = True # flag to make template visibility file to speed up writing of dm track data
# self.dmarr = [30.,56.8,90.] # [56.8] # crab
# self.pulsewidth = 0.006 # pulse width of crab and m31 candidates. later turned into array of len(chans)
self.dmarr = [44,88.] # j0628+09
self.pulsewidth = 0.0
self.file = file
self.scan = scan
if file.split('.')[-1][:3] == 'mir':
self.data_type = 'mir'
print 'Loading miriad file.'
self.miriad_init(file, nints=nints, nskip=nskip, nocal=nocal, nopass=nopass)
elif file.split('.')[-1][:2] == 'ms':
self.data_type = 'ms'
print 'Loading ms file.'
status = self.casa_init(file, nints=nints, nskip=nskip, ddid=ddid, selectpol=selectpol, scan=scan, datacol=datacol)
if status:
print 'Stopping init...'
return
# set up ur tracks
self.dmtrack0 = {}
self.twidths = {}
for dmbin in range(len(self.dmarr)):
self.dmtrack0[dmbin] = self.dmtrack(self.dmarr[dmbin],0)
self.twidths[dmbin] = 0
for k in self.dmtrack0[dmbin][1]:
self.twidths[dmbin] = max(self.twidths[dmbin], len(n.where(n.array(self.dmtrack0[dmbin][1]) == k)[0]))
def miriad_init(self, file, nints, nskip, nocal, nopass):
"""Reads in Miriad data using miriad-python.
Seems to have some small time (~1 integration) errors in light curves and spectrograms,
as compared to CASA-read data.
"""
vis = miriad.VisData(self.file,)
# li = range(1,13) + range(14,23) + range(24,62)
li = range(64)
self.chans = n.array(li)
# read data into python arrays
i = 0
for inp, preamble, data, flags in vis.readLowlevel ('dsl3', False, nocal=True, nopass=True):
# 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')
self.sfreq = self.sfreq0
self.sdf = self.sdf0
self.npol = 1
self.nchan = len(data)
print 'Initializing nchan:', self.nchan
bls = []
# build complete list of baselines
bls.append(preamble[4])
# end here. assume at least one instance of each bl occurs before ~three integrations
if len(bls) == 3*len(n.unique(bls)):
blarr = []
for bl in n.unique(bls):
blarr.append(util.decodeBaseline (bl))
self.blarr = n.array(blarr)
bldict = dict( zip(n.unique(bls), n.arange(len(blarr))) )
break
i = i+1
# Initialize more stuff...
self.freq = self.sfreq + self.sdf * self.chans
self.pulsewidth = self.pulsewidth * n.ones(len(self.chans)) # pulse width of crab and m31 candidates
# good baselines
self.nbl = len(self.blarr)
print 'Initializing nbl:', self.nbl
self.ants = n.unique(self.blarr)
self.nants = len(self.ants)
print 'Initializing nants:', self.nants
self.nskip = int(nskip*self.nbl) # number of iterations to skip (for reading in different parts of buffer)
nskip = int(self.nskip)
# define data arrays
da = n.zeros((nints,self.nbl,self.nchan),dtype='complex64')
fl = n.zeros((nints,self.nbl,self.nchan),dtype='bool')
pr = n.zeros((nints*self.nbl,5),dtype='float64')
print
# go back and read data into 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 < nskip:
i = i+1
continue
# assumes ints in order, but may skip. after nbl iterations, it fills next row, regardless of number filled.
if (i-nskip) < nints*self.nbl:
da[(i-nskip)//self.nbl,bldict[preamble[4]]] = data
fl[(i-nskip)//self.nbl,bldict[preamble[4]]] = flags
pr[i-nskip] = preamble
else:
break # stop at nints
if not (i % (self.nbl*100)):
print 'Read spectrum ', str(i)
i = i+1
# build final data structures
# good = n.where ( (self.blarr[:,0] != 5) & (self.blarr[:,1] != 5) & (self.blarr[:,0] != 10) & (self.blarr[:,1] != 10) )[0] # remove bad ants?
self.rawdata = n.expand_dims(da, 3) # hack to get superfluous pol axis
self.flags = n.expand_dims(fl, 3)
self.data = self.rawdata[:,:,self.chans,:] # [:,good,:,:] # remove bad ants?
# self.blarr = self.blarr[good] # remove bad ants?
self.preamble = pr
self.u = (pr[:,0] * self.freq.mean()).reshape(nints, self.nbl)
self.v = (pr[:,1] * self.freq.mean()).reshape(nints, self.nbl)
self.w = (pr[:,2] * self.freq.mean()).reshape(nints, self.nbl)
# could add uvw, too... preamble index 0,1,2 in units of ns
self.dataph = (self.data.mean(axis=3).mean(axis=1)).real #dataph is summed and detected to form TP beam at phase center, multi-pol
time = self.preamble[::self.nbl,3]
self.reltime = 24*3600*(time - time[0]) # relative time array in seconds. evla times change...?
# print summary info
print
print 'Data read!\n'
print 'Shape of raw data, flagged, time:'
print self.rawdata.shape, self.data.shape, self.reltime.shape
self.min = self.dataph.min()
self.max = self.dataph.max()
print 'Dataph min, max:'
print self.min, self.max
def casa_init(self, file, nints=1000, nskip=0, ddid=[-1], selectpol=['RR','LL'], scan=0, datacol='data'):
"""Reads in Measurement Set data using CASA.
ddid is list of subbands. zero-based.
Scan is zero-based selection based on scan order, not actual scan number.
"""
# open file and read a bit of data to define data structure
ants = range(0,28)
self.dmtrack0 = 0 # initialize ur-track
# get spw info. either load pickled version (if found) or make new one
pklname = string.join(file.split('.')[:-1], '.') + '_init.pkl'
# pklname = pklname.split('/')[-1] # hack to remove path and write locally
if os.path.exists(pklname):
print 'Pickle of initializing info found. Loading...'
pkl = open(pklname, 'r')
try:
(self.npol_orig, self.npol, self.nbl, self.blarr, self.ants, self.nants, self.nants0, self.inttime, self.inttime0, spwinfo, scansummary) = pickle.load(pkl)
except EOFError:
print 'Bad pickle file. Exiting...'
return 1
scanlist = scansummary['summary'].keys()
starttime_mjd = scansummary['summary'][scanlist[scan]]['0']['BeginTime']
self.nskip = int(nskip*self.nbl) # number of iterations to skip (for reading in different parts of buffer)
self.npol = len(selectpol)
else:
print 'No pickle of initializing info found. Making anew...'
pkl = open(pklname, 'wb')
ms.open(self.file)
spwinfo = ms.getspectralwindowinfo()
scansummary = ms.getscansummary()
scanlist = scansummary['summary'].keys()
starttime_mjd = scansummary['summary'][scanlist[scan]]['0']['BeginTime']
starttime0 = qa.getvalue(qa.convert(qa.time(qa.quantity(starttime_mjd+0/(24.*60*60),'d'),form=['ymd'], prec=9), 's'))
stoptime0 = qa.getvalue(qa.convert(qa.time(qa.quantity(starttime_mjd+0.5/(24.*60*60), 'd'), form=['ymd'], prec=9), 's'))
ms.selectinit(datadescid=0) # initialize to initialize params
selection = {'time': [starttime0, stoptime0], 'antenna1': ants, 'antenna2': ants}
ms.select(items = selection)
da = ms.getdata([datacol,'axis_info'], ifraxis=True)
ms.close()
self.npol_orig = da[datacol].shape[0]
self.npol = len(selectpol)
self.nbl = da[datacol].shape[2]
print 'Initializing %d of %d polarizations' % (self.npol, self.npol_orig)
print 'Initializing nbl:', self.nbl
# good baselines
bls = da['axis_info']['ifr_axis']['ifr_shortname']
self.blarr = n.array([[int(bls[i].split('-')[0]),int(bls[i].split('-')[1])] for i in range(len(bls))])
self.ants = n.unique(self.blarr)
self.nants = len(self.ants)
self.nants0 = len(self.ants)
print 'Initializing nants:', self.nants
self.nskip = int(nskip*self.nbl) # number of iterations to skip (for reading in different parts of buffer)
# set integration time
ti0 = da['axis_info']['time_axis']['MJDseconds']
# self.inttime = n.mean([ti0[i+1] - ti0[i] for i in range(len(ti0)-1)])
self.inttime = scansummary['summary'][scanlist[scan]]['0']['IntegrationTime']
self.inttime0 = self.inttime
print 'Initializing integration time (s):', self.inttime
pickle.dump((self.npol_orig, self.npol, self.nbl, self.blarr, self.ants, self.nants, self.nants0, self.inttime, self.inttime0, spwinfo, scansummary), pkl)
pkl.close()
# set desired spw
if (len(ddid) == 1) & (ddid[0] == -1):
ddidlist = range(len(spwinfo['spwInfo']))
else:
ddidlist = ddid
freq = n.array([])
for ddid in ddidlist:
nch = spwinfo['spwInfo'][str(ddid)]['NumChan']
ch0 = spwinfo['spwInfo'][str(ddid)]['Chan1Freq']
chw = spwinfo['spwInfo'][str(ddid)]['ChanWidth']
freq = n.concatenate( (freq, (ch0 + chw * n.arange(nch)) * 1e-9) )
# self.chans = n.array(range(2,62)) # can flag by omitting channels here
self.chans = n.arange(nch*len(ddidlist)) # default is to take all chans
# self.chans = self.chans[range(5,31)+range(32,41)+range(42,59)+range(69,123)]
self.chans = self.chans[range(5,31)+range(32,41)+range(42,59)]
# self.chans = self.chans[range(69,123)]
self.freq = freq[self.chans]
self.nchan = len(self.freq)
print 'Initializing nchan:', self.nchan
# set requested time range based on given parameters
timeskip = self.inttime*nskip
starttime = qa.getvalue(qa.convert(qa.time(qa.quantity(starttime_mjd+timeskip/(24.*60*60),'d'),form=['ymd'], prec=9), 's'))
stoptime = qa.getvalue(qa.convert(qa.time(qa.quantity(starttime_mjd+(timeskip+nints*self.inttime)/(24.*60*60), 'd'), form=['ymd'], prec=9), 's'))
print 'First integration of scan:', qa.time(qa.quantity(starttime_mjd,'d'),form=['ymd'],prec=9)
print
print 'Reading scan', str(scanlist[scan]) ,'for times', qa.time(qa.quantity(starttime_mjd+timeskip/(24.*60*60),'d'),form=['hms'], prec=9), 'to', qa.time(qa.quantity(starttime_mjd+(timeskip+nints*self.inttime)/(24.*60*60), 'd'), form=['hms'], prec=9)
# read data into data structure
ms.open(self.file)
ms.selectinit(datadescid=ddidlist[0]) # reset select params for later data selection
selection = {'time': [starttime, stoptime], 'antenna1': ants, 'antenna2': ants}
ms.select(items = selection)
print 'Reading %s column, SB %d, polarization %s...' % (datacol, ddidlist[0], selectpol)
ms.selectpolarization(selectpol)
da = ms.getdata([datacol,'axis_info','u','v','w'], ifraxis=True)
u = da['u']; v = da['v']; w = da['w']
# da = ms.getdata(['data','axis_info'], ifraxis=False)
if da == {}:
print 'No data found.'
return 1
newda = n.transpose(da[datacol], axes=[3,2,1,0]) # if using multi-pol data.
# newda = n.transpose(da['data'], axes=[2,1,0]) # if using multi-pol data.
# scale=2.3 # hack!
if len(ddidlist) > 1:
for ddid in ddidlist[1:]:
ms.selectinit(datadescid=ddid) # reset select params for later data selection
ms.select(items = selection)
print 'Reading %s column, SB %d, polarization %s...' % (datacol, ddid, selectpol)
ms.selectpolarization(selectpol)
da = ms.getdata([datacol,'axis_info'], ifraxis=True)
newda = n.concatenate( (newda, n.transpose(da[datacol], axes=[3,2,1,0])), axis=2 )
# da = ms.getdata(['data','axis_info'], ifraxis=False)
# newda = n.concatenate( (newda, n.transpose(da['data'], axes=[2,1,0])), axis=1 )
ms.close()
# Initialize more stuff...
self.nschan0 = self.nchan
self.pulsewidth = self.pulsewidth * n.ones(self.nchan) # pulse width of crab and m31 candidates
# set variables for later writing data **some hacks here**
self.nspect0 = 1
self.nwide0 = 0
self.sdf0 = da['axis_info']['freq_axis']['resolution'][0][0] * 1e-9
self.sdf = self.sdf0
self.ischan0 = 1
self.sfreq0 = da['axis_info']['freq_axis']['chan_freq'][0][0] * 1e-9
self.sfreq = self.sfreq0
self.restfreq0 = 0.0
self.pol0 = -1 # assumes single pol?
# self.rawdata = newda[len(newda)/2:] # hack to remove autos
self.u = u.transpose() * (-self.freq.mean()*1e9/3e8) # uvw are in m on ground. scale by -wavelenth to get projected lamba uvw (as in miriad?)
self.v = v.transpose() * (-self.freq.mean()*1e9/3e8)
self.w = w.transpose() * (-self.freq.mean()*1e9/3e8)
self.rawdata = newda
self.data = self.rawdata[:,:,self.chans]
self.dataph = (self.data.mean(axis=3).mean(axis=1)).real # multi-pol
self.min = self.dataph.min()
self.max = self.dataph.max()
print 'Shape of rawdata, data:'
print self.rawdata.shape, self.data.shape
print 'Dataph min, max:'
print self.min, self.max
# set integration time and time axis
ti = da['axis_info']['time_axis']['MJDseconds']
self.reltime = ti - ti[0]
# self.reltime = self.reltime[len(self.reltime)/2:] # hack to remove autos
def spec(self, ind=[], save=0, pathout='./'):
reltime = self.reltime
abs = self.dataph
print 'Data mean, std: %f, %f' % (self.dataph.mean(), self.dataph.std())
(vmin, vmax) = sigma_clip(abs.ravel())
# p.figure(1,figsize=(11,6),dpi=120)
p.figure(1)
p.clf()
ax = p.axes()
ax.set_position([0.2,0.2,0.7,0.7])
if len(ind) > 0:
for i in ind:
p.subplot(len(ind),1,list(ind).index(i)+1)
intmin = n.max([0,i-50])
intmax = n.min([len(self.reltime),i+50])
im = p.imshow(n.rot90(abs[intmin:intmax]), aspect='auto', origin='upper', interpolation='nearest', extent=(intmin,intmax,0,len(self.chans)), vmin=vmin, vmax=vmax)
p.subplot(len(ind),1,1)
else:
im = p.imshow(n.rot90(abs), aspect='auto', origin='upper', interpolation='nearest', extent=(0,len(self.reltime),0,len(self.chans)), vmin=vmin, vmax=vmax)
p.title(str(self.scan) + ' scan, ' +str(self.nskip/self.nbl) + ' nskip, candidates ' + str(ind))
# cb = p.colorbar(im, use_gridspec=True)
cb = p.colorbar(im)
cb.set_label('Flux Density (Jy)',fontsize=12,fontweight="bold")
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_position(('outward', 20))
ax.spines['left'].set_position(('outward', 30))
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
p.yticks(n.arange(0,len(self.chans),4), (self.chans[(n.arange(0,len(self.chans), 4))]))
p.xlabel('Time (integration number)',fontsize=12,fontweight="bold")
p.ylabel('Frequency Channel',fontsize=12,fontweight="bold")
if save:
savename = self.file.split('.')[:-1]
savename.append(str(self.scan) + '_' + str(self.nskip/self.nbl) + '.spec.png')
savename = string.join(savename,'.')
print 'Saving file as ', savename
p.savefig(pathout+savename)
def drops(self, chan=0, pol=0, show=1):
"""Displays info on missing baselines.
"""
nints = float(len(self.reltime))
bllen = []
if self.data_type == 'mir':
bls = self.preamble[:,4]
for bl in n.unique(bls):
bllen.append(n.shape(n.where(bls == bl))[1])
elif self.data_type == 'ms':
for i in range(len(self.blarr)):
bllen.append(len(n.where(self.data[:,i,chan,pol] != 0.00)[0]))
bllen = n.array(bllen)
if show:
p.clf()
for i in range(self.nbl):
p.text(self.blarr[i,0], self.blarr[i,1], s=str(100*(bllen[i]/nints - 1)), horizontalalignment='center', verticalalignment='center', fontsize=9)
p.axis((0,29,0,29))
p.plot([0,29],[0,29],'b--')
# p.xticks(int(self.blarr[:,0]), self.blarr[:,0])
# p.yticks(int(self.blarr[:,1]), self.blarr[:,1])
p.xlabel('Ant 1')
p.ylabel('Ant 2')
p.title('Drop fraction for chan %d, pol %d' % (chan, pol))
# p.show()
return self.blarr,bllen
def fitspec(self, obsrms=0, save=0, pol=0, pathout='./'):
"""
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')
# estimage 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=3)).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 = (self.freq, spec, obsrms))
print 'Fit results: ', p1
chisq = errfunc(p1, self.freq, spec, obsrms).sum()/(self.nchan - 2)
print 'Reduced chisq: ', chisq
p.figure(2)
p.errorbar(self.freq, spec, yerr=obsrms*n.ones(len(spec)), fmt='.')
p.plot(self.freq, fitfunc(p1, self.freq), label='Fit: %.1f, %.2f. Noise: %.1f, chisq: %.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(pathout+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 = 2.0*(self.reltime[1] - self.reltime[0])
# tint = self.inttime0 # could do this instead...?
# given freq, dm, dfreq, calculate pulse time and duration
pulset_firstchan = 4.2e-3 * dm * self.freq[len(self.chans)-1]**(-2) # used to start dmtrack at highest-freq unflagged channel
pulset = 4.2e-3 * dm * self.freq**(-2) + t0 - pulset_firstchan # time in seconds
pulsedt = n.sqrt( (8.3e-6 * dm * (1000*self.sdf) * self.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 - 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])
p.plot(track[0], track[1], 'w*')
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)
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[0] # remove time axis, since it is always length 1
def tracksub2(self, dmbin, tbin, bgwindow = 0):
"""Trying to speed up tracksub...
"""
data = self.data
track0,track1 = self.dmtrack0[dmbin]
trackon = (list(n.array(track0)+tbin), track1)
twidth = self.twidths[dmbin]
dataon = data[trackon[0], :, trackon[1]]
# 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]
# set up bg track
if bgwindow:
# measure max width of pulse (to avoid in bgsub)
bgrange = range(-bgwindow/2 - twidth + tbin, - twidth + tbin) + range(twidth + tbin, twidth + bgwindow/2 + tbin)
for k in bgrange: # build up super track for background subtraction
if bgrange.index(k) == 0: # first time through
trackoff = (list(n.array(track0)+k), track1)
else: # then extend arrays by next iterations
trackoff = (trackoff[0] + list(n.array(track0)+k), trackoff[1] + track1)
dataoff = data[trackoff[0], :, trackoff[1]]
datadiffarr = n.zeros((self.nchan, self.nbl, self.npol),dtype='complex')
# 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)
meanon = dataon[indon].mean(axis=0)
meanoff = dataoff[indoff].mean(axis=0)
datadiffarr[ch] = meanon - meanoff
zeros = n.where( (meanon == 0j) | (meanoff == 0j) ) # find baselines and pols with zeros for meanon or meanoff
datadiffarr[ch][zeros] = 0j # set missing data to zero # hack! but could be ok if we can ignore zeros later...
else:
datadiffarr[ch] = dataon[indon].mean(axis=0)
return n.transpose(datadiffarr, axes=[2,1,0])
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
if bgwindow > 0:
bgrange = range(-bgwindow/2 - twidths + tbin - tshift, -twidths + tbin - tshift) + range(twidths + tbin - tshift, 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')
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, pol=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')
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[pol, 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.
Probably ok for multipol data...
"""
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, pathout='./'):
"""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(pathout+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
min,max = sigma_clip(arr.flatten())
cliparr = n.where((arr < max) & (arr > min))
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=4, show=0, clean=1, mode='dirty', code='aipy'):
""" 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.
code can be 'aipy' or 'miriad'
"""
# 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 code == 'aipy':
tr = self.tracksub2(dmbin, t0bin, bgwindow=bgwindow)[0].mean(axis=1)
size = 48000; res = 500 # size=16000 => 13" resolution, res=500 => 7' fov
fov = n.degrees(1./res)*3600.
# make image
ai = aipy.img.Img(size=size, res=res)
ai.put( (self.u[t0bin],self.v[t0bin],self.w[t0bin]), tr)
image = ai.image(center = (size/res/2, size/res/2))
# clean image
beam = ai.bm_image()
beamgain = aipy.img.beam_gain(beam[0])
(clean, dd) = aipy.deconv.clean(image, beam[0], verbose=True, gain=0.01, tol=1e-4) # light cleaning
kernel = n.where(beam[0] >= 0.4*beam[0].max(), beam[0], 0.) # take only peak (gaussian part) pixels of beam image
restored = aipy.img.convolve2d(clean, kernel)
image_restored = (restored + dd['res']).real/beamgain
if show:
p.clf()
ax = p.imshow(image_restored, aspect='auto', origin='upper', interpolation='nearest', extent=[-fov/2, fov/2, -fov/2, fov/2])
p.colorbar()
p.xlabel('Offset (arcsec)')
p.ylabel('Offset (arcsec)')
peak = n.where(n.max(image_restored) == image_restored)
print 'Image peak of %e at (%d,%d)' % (n.max(image_restored), peak[0][0], peak[1][0])
print 'Peak/RMS = %e' % (image_restored.max()/image_restored.std())
return image_restored
elif code == 'miriad':
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).snarf() # good for m31 search
if show: txt = TaskCgDisp (in_=outroot+'.map', device='/xs', wedge=True, beambl=True, labtyp='hms,dms', region='relpix,boxes(-100,-100,100,100)').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(-100,-100,100,100)').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', region='relpix,boxes(-100,-100,100,100)').snarf ()
txt = TaskImFit (in_=outroot+'.restor', object='point').snarf ()
# parse output of imfit
# print '012345678901234567890123456789012345678901234567890123456789'
peak = float(txt[0][16][30:36]) # 16 -> 14 (etc.) for some images?
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