-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinvert.py
717 lines (694 loc) · 38.1 KB
/
invert.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
import os
import logger as log
import sources
import calculations
import math
import globals
import startupTeardown
from threading import Thread
import random
import peakLocator
import continuumSubtraction
import miriadClasses
from copy import deepcopy
try :
import preferences as p
except ImportError:
import defaultPreferences as p
cellsize = None
imsize = None
continDone = False
regions = dict()
rmsList = dict()
"""
Module to invert uv data and produce images
Part of the CARMA data reduction pipeline
Current Version (this file): 1.1
Released with pipeline version: 1.1
Author: D. N. Friedel
"""
class invertWindowThread(Thread) :
def __init__(self,source,window,iterate,AvgBaseline = 0,csub = False) :
Thread.__init__(self)
self.source = source
self.window = window
self.iterate = iterate
self.avgBaseline = AvgBaseline
self.csub = csub
def run(self) :
invert(self.source,self.window,self.iterate,self.csub,self.avgBaseline)
class cleanWindowThread(Thread) :
def __init__(self,source,window,csub = False) :
Thread.__init__(self)
self.source = source
self.window = window
self.csub = csub
def run(self) :
cleanWindow(self.source,self.window,self.csub)
class invertContinuumThread(Thread) :
def __init__(self,objects, obsFreq, avgBaseline ,window) :
Thread.__init__(self)
self.objects = objects
self.window = window
self.obsFreq = obsFreq
self.avgBaseline = avgBaseline
def run(self) :
invertContinuum(self.objects, self.obsFreq, self.avgBaseline, [self.window], individual = True)
def invert(source,window,iterate,csub,avgBaseline = 0) :
""" Method to invert a spectral window
input :
source - the source data
window - which window is being inverted
iterate - should we iterate to minimize the number of bad data
csub - has continuum subtraction been done
returns :
none
"""
global cellsize
global imsize
global continDone
addon = ""
noise = 0.5
if(csub) :
addon = ".cs"
fileEnd = str(random.randint(1,100000))
startChan = 1
numChan = source._numChans[window - 1]
if(source._bandwidths[window - 1] == 62) :
startChan = 4
numChan = source._numChans[window - 1] - 6
# remove any flagged data we can
args = []
args.append(globals.Variable("vis",source._file, addon +".w%i" % (window)))
args.append(globals.Variable("options","unflagged"))
args.append(globals.Variable("out","temp.w%i.%s; sleep 3; rm -rf " % (window,fileEnd)))
args.append(globals.Variable(None,source._file,addon + ".w%i/*; rm -rf " % (window)))
args.append(globals.Variable(None,source._file,addon + ".w%i; sleep 3; mv " % (window)))
args.append(globals.Variable(None,"temp.w%i.%s" % (window,fileEnd)))
args.append(globals.Variable(None,source._file,addon + ".w%i" % (window)))
log.run("uvcat",args,fatal=True)
ok = False
lastbad = 0
# invert until the number of rejected visibilities is minimized
while(not ok) :
log.run("invert vis=%s.w%i map=%s.w%i.map beam=%s.w%i.beam imsize=%i cell=%f sup=0 options=systemp,double,mosaic line=channel,%i,%i,1,1 >& junk" % (source._file+addon, window, source._file+addon, window, source._file+addon, window,imsize,cellsize,numChan, startChan),[],fatal=True,logit=False)
input = open("junk",'r')
fileList = input.readlines()
input.close()
found = False
while(len(fileList) > 0 and iterate) :
line = fileList.pop()
if("Theoretical rms" in line) :
noise = float(line.split(":")[1])
if(not found) :
ok = True
log.writeComment("Using an image size of %f for %s" % (imsize, source._name))
args = []
args.append(globals.Variable("vis",source._file,addon + ".w%i" % (window)))
args.append(globals.Variable("map",source._file,addon + ".w%i.map" % (window)))
args.append(globals.Variable("beam",source._file,addon + ".w%i.beam" % (window)))
args.append(globals.Variable("imsize",str(imsize)))
args.append(globals.Variable("cell",str(cellsize)))
args.append(globals.Variable("sup","0"))
args.append(globals.Variable("options","systemp,double,mosaic"))
args.append(globals.Variable("line","channel,%i,%i,1,1" % (numChan,startChan)))
log.run("invert",args,execute=False)
# use mossdi to clean
lastIter = 10000.0
log.run("mossdi map=%s.w%i.map beam=%s.w%i.beam out=%s.w%i.clean niters=50000 cutoff=%f region=quarter" % (source._file+addon, window, source._file+addon, window, source._file+addon, window,noise*2.5),[],fatal=True,logit=False)
# determine the synthsized beam size
log.run("mospsf beam=%s.w%i.beam out=%s.w%i.bm""" % (source._file+addon, window, source._file+addon, window),[],fatal=True,logit=False)
log.run("imfit in=%s.w%i.bm object=beam region=arcsec,box'('-5,-5,5,5')' > fit.log.%s" % (source._file+addon, window,fileEnd),[],fatal=True,logit=False)
input = open("fit.log.%s" % (fileEnd),'r')
fileList = input.readlines()
input.close()
majorAxis = 0.0
minorAxis = 0.0
positionAngle = 0.0
while(len(fileList) > 0) :
line = fileList.pop()
if("Position angle" in line) :
splitLine = line.split()
positionAngle = float(splitLine[3])
elif("Minor axis" in line) :
splitLine = line.split()
minorAxis = float(splitLine[3])
elif("Major axis" in line) :
splitLine = line.split()
majorAxis = float(splitLine[3])
log.run("restor model=%s.w%i.clean map=%s.w%i.map beam=%s.w%i.beam fwhm=%f,%f pa=%f out=%s.w%i.finalmap" % (source._file+addon, window, source._file+addon, window, source._file+addon, window, majorAxis,minorAxis,positionAngle, source._file+addon, window),[],logit=False)
region = dict()
region[0] = "%i,%i,%i,%i" % (int(math.floor(imsize/4)),int(math.floor((imsize/4) + (imsize/6))),int(math.floor((imsize/4) + (imsize/6))),int(math.floor((imsize/4) + (imsize/3))))
region[1] = "%i,%i,%i,%i" % (int(math.floor((imsize/4) + (imsize/6))),int(math.floor((imsize/4) + (imsize/3))),int(math.floor((imsize/4) + (imsize/3))),int(math.floor(3*imsize/4)))
region[2] = "%i,%i,%i,%i" % (int(math.floor((imsize/4) + (imsize/3))),int(math.floor((imsize/4) + (imsize/6))),int(math.floor(3*imsize/4)),int(math.floor((imsize/4) + (imsize/3))))
region[3] = "%i,%i,%i,%i" % (int(math.floor((imsize/4) + (imsize/6))),int(math.floor(imsize/4)),int(math.floor((imsize/4) + (imsize/3))),int(math.floor((imsize/4) + (imsize/6))))
rms = 1000000.0
best = 0
# determine the initial rms noise
for j in range(4) :
#log.writeLog("Locating best region for noise calculation.")
log.run("imstat in=%s.w%i.finalmap region=box'('%s')' device=/NULL > rms.log.%s""" % (source._file+addon, window, region.get(j),fileEnd),[],logit=False)
input = open("rms.log.%s" % (fileEnd),'r')
fileList = input.readlines()
input.close()
fileList.reverse()
while(len(fileList) > 0) :
line = fileList.pop()
if("Frequency" in line) :
line = fileList.pop()
temprms = float(line[42:51])
if(temprms < rms) :
rms = temprms
best = j
converged = False
# get the clean region
if(source.getCleanRegion() == None) :
if(not source._mosaic) :
if(p.preferences.get("doAutoCleanRegion")) :
regions[window] = peakLocator.findCleanRegion("%s.w%i.finalmap" % (source._file+addon,window),rms,"%s.w%i.bm" % (source._file+addon,window),self._pointingCenters)
elif(p.preferences.get("cleanRegion") == "quarter") :
source.setCleanRegion("quarter")
else :
boxsize = int(p.preferences.get("cleanRegion"))
source.setCleanRegion("arcsec,box'(-%f,-%f,%f,%f)'" % (boxsize,boxsize,boxsize,boxsize))
# treat mosaics differently
else :
offset = [int(miriadClasses.imhead("%s.map" % source._file+addon,"crpix1")),int(miriadClasses.imhead("%s.map" % source._file+addon,"crpix2"))]
source.setCleanRegion(calculations.calculateMosaicCleanRegion(source._pointingCenters,cellsize,imsize,offset))
log.run("rm -rf %s.w%i.clean %s.w%i.finalmap %s.w%i.bm; sleep 3" % (source._file+addon, window, source._file+addon, window, source._file+addon, window),[],fatal=True,logit=False)
def cleanWindow(source,window,csub) :
""" Method to clean a spectral window
input :
source - the source data
window - which window to clean
csub - has contuinuum subtraction been done
returns :
none
"""
global rmsList
lastIter = 10000.0
addon = ""
fileEnd = str(random.randint(1,100000))
if(csub) :
addon = ".cs"
# do the initial clean
log.run("mossdi map=%s.w%i.map beam=%s.w%i.beam out=%s.w%i.clean niters=100 region=%s" % (source._file+addon, window, source._file+addon, window, source._file+addon, window,source.getCleanRegion()),[],fatal=True,logit=False)
# get the beam size
log.run("mospsf beam=%s.w%i.beam out=%s.w%i.bm""" % (source._file+addon, window, source._file+addon, window),[],fatal=True,logit=False)
log.run("imfit in=%s.w%i.bm object=beam region=arcsec,box'('-5,-5,5,5')' > fit.log.%s" % (source._file+addon, window,fileEnd),[],fatal=True,logit=False)
input = open("fit.log.%s" % (fileEnd),'r')
fileList = input.readlines()
input.close()
majorAxis = 0.0
minorAxis = 0.0
positionAngle = 0.0
while(len(fileList) > 0) :
line = fileList.pop()
if("Position angle" in line) :
splitLine = line.split()
positionAngle = float(splitLine[3])
elif("Minor axis" in line) :
splitLine = line.split()
minorAxis = float(splitLine[3])
elif("Major axis" in line) :
splitLine = line.split()
majorAxis = float(splitLine[3])
log.run("restor model=%s.w%i.clean map=%s.w%i.map beam=%s.w%i.beam fwhm=%f,%f pa=%f out=%s.w%i.finalmap" % (source._file+addon, window, source._file+addon, window, source._file+addon, window, majorAxis,minorAxis,positionAngle, source._file+addon, window),[],logit=False)
region = dict()
region[0] = "%i,%i,%i,%i" % (int(math.floor(imsize/4)),int(math.floor((imsize/4) + (imsize/6))),int(math.floor((imsize/4) + (imsize/6))),int(math.floor((imsize/4) + (imsize/3))))
region[1] = "%i,%i,%i,%i" % (int(math.floor((imsize/4) + (imsize/6))),int(math.floor((imsize/4) + (imsize/3))),int(math.floor((imsize/4) + (imsize/3))),int(math.floor(3*imsize/4)))
region[2] = "%i,%i,%i,%i" % (int(math.floor((imsize/4) + (imsize/3))),int(math.floor((imsize/4) + (imsize/6))),int(math.floor(3*imsize/4)),int(math.floor((imsize/4) + (imsize/3))))
region[3] = "%i,%i,%i,%i" % (int(math.floor((imsize/4) + (imsize/6))),int(math.floor(imsize/4)),int(math.floor((imsize/4) + (imsize/3))),int(math.floor((imsize/4) + (imsize/6))))
rms = 1000000.0
best = 0
# determine the rms noise
for j in range(4) :
log.run("imstat in=%s.w%i.finalmap region=box'('%s')' device=/NULL > rms.log.%s""" % (source._file+addon, window, region.get(j),fileEnd),[],logit=False)
input = open("rms.log.%s" % (fileEnd),'r')
fileList = input.readlines()
input.close()
fileList.reverse()
while(len(fileList) > 0) :
line = fileList.pop()
if("Frequency" in line) :
line = fileList.pop()
temprms = float(line[42:51])
if(temprms < rms) :
rms = temprms
best = j
converged = False
run = 1
cutoff = 1000.0
# loop over clean and restor until the noise level settles down or until 10 iterations are complete
while((not converged) and (run <= 5)) :
cutoff = rms * p.preferences.get("cleanThreshold")
log.run("rm -rf %s.w%i.clean %s.w%i.finalmap; sleep 3" % (source._file+addon, window, source._file+addon, window),[],fatal=True,logit=False)
log.run("mossdi map=%s.w%i.map beam=%s.w%i.beam out=%s.w%i.clean niters=50000 cutoff=%f region=%s" % (source._file+addon, window, source._file+addon, window, source._file+addon, window, cutoff,source.getCleanRegion()),[],fatal=True,logit=False)
log.run("restor model=%s.w%i.clean map=%s.w%i.map beam=%s.w%i.beam fwhm=%f,%f pa=%f out=%s.w%i.finalmap" % (source._file+addon, window, source._file+addon, window, source._file+addon, window, majorAxis,minorAxis,positionAngle, source._file+addon, window),[],fatal=True,logit=False)
log.run("imstat in=%s.w%i.finalmap region=box'('%s')' device=/NULL > rms.log.%s" % (source._file+addon, window, region.get(best),fileEnd),[],logit=False)
input = open("rms.log.%s" % (fileEnd),'r')
fileList = input.readlines()
input.close()
fileList.reverse()
while(len(fileList) > 0) :
line = fileList.pop()
if("cube" in line) :
line = fileList.pop()
temprms = float(line[42:51])
if(abs(temprms-rms) < 0.05 * rms) : # there must be less than a 5 % change
converged = True
else :
rms = temprms
run += 1
log.writeComment("Cleaning window %i" % (window))
if(run > 5) :
log.writeComment("Did not reach noise level cutoff, performed 5 iterations.")
args = []
args.append(globals.Variable("map",source._file,addon + ".w%i.map" % (window)))
args.append(globals.Variable("beam",source._file,addon + ".w%i.beam" % (window)))
args.append(globals.Variable("out",source._file,addon + ".w%i.clean" % (window)))
args.append(globals.Variable("niters","50000"))
args.append(globals.Variable("cutoff",str(cutoff)))
args.append(globals.Variable("region",source.getCleanRegion()))
log.run("mossdi",args,execute=False)
args = []
args.append(globals.Variable("model",source._file,addon + ".w%i.clean" % (window)))
args.append(globals.Variable("map",source._file,addon + ".w%i.map" % (window)))
args.append(globals.Variable("beam",source._file,addon + ".w%i.beam" % (window)))
args.append(globals.Variable("fwhm","%f,%f" % (majorAxis,minorAxis)))
args.append(globals.Variable("pa",str(positionAngle)))
args.append(globals.Variable("out",source._file,addon + ".w%i.finalmap" % (window)))
log.run("restor",args,execute=False)
args = []
args.append(globals.Variable("in",source._file,addon + ".w%i.finalmap" % (window)))
args.append(globals.Variable("op","xyout"))
args.append(globals.Variable("out",source._file,addon + ".w%i.fits" % (window)))
log.run("fits",args,logit=False)
log.writeScript("\n")
log.writeLog("Data reduction of %s window %i complete. Final map(%s.w%i.finalmap) has a noise level of %f Jy/beam\n" % (source._name, window, source._file+addon, window, rms))
rmsList[window] = rms
startupTeardown.endFile("%s.w%i.finalmap" % (source._file+addon,window))
def invertContinuum(objects, obsFreq, avgBaseline, windows, individual = False) :
""" Method to create continuum maps
input :
objects - the objects
obsFreq - observing frequency in GHz
avgBaseline - average baseline in lambda
windows - which windows to invert
individual - whther we are only inverting individual windows
returns :
none
"""
global cellsize
global imsize
global continDone
fileEnd = str(random.randint(1,100000))
# calculate the optimal cell size, based on the median baseline in klambda, want at least 5 pixels across the beam
# but only if the user did not specify it in the preferences file
if(p.preferences.get("cellSize") < 0 and cellsize == None) :
cellsize = calculations.calcCellSize(avgBaseline,0.0)
log.writeComment("Based on average baseline of %f, using a cell size of %f arcseconds." % (avgBaseline, cellsize))
elif(cellsize == None) :
cellsize = p.preferences.get("cellSize")
log.writeComment("Using cellsize %f" % (cellsize))
iterate = True
# calculate the optimal image size, based on the cell size and observing frequency
# but only if the user did not specify an image size in the preferences file
if(p.preferences.get("imageSize") < 0 and imsize == None) :
imsize = calculations.calcImsize(obsFreq, cellsize)
elif(imsize == None) :
iterate = False
imsize = p.preferences.get("imageSize")
# invert each source in turn
sourceList = deepcopy(objects._sources)
if(not individual) :
sourceList.append(deepcopy(objects._gaincals[0]))
for source in sourceList :
log.writeComment("Inverting continuum of %s" % (source._name))
if(isinstance(source,sources.Source)) :
if(source._mosaic) :
if(imsize > 1000) :
imsize = int(imsize * 1.5)
else :
imsize = int(imsize * 2.0)
continDone = True
invertString = ""
invertList = []
startChan = 1
numChan = source._numChans[0]
# make sure we start at the correct channel number
if(source.haveSuper() and not individual) :
for ending in ["LSB","USB"] :
if(not source._lsbGood and ending == "LSB") :
continue
if(not source._usbGood and ending == "USB") :
continue
startChan = 1
numChan = source.getSuperNumChans()
invertString = invertString + ",%s.%s" % (source._file, ending)
invertList.append([source._file,".%s" % (ending)])
args = []
args.append(globals.Variable("vis",source._file,".%s" % (ending)))
args.append(globals.Variable("options","unflagged"))
args.append(globals.Variable("out","temp." + fileEnd + "; sleep 3; rm -rf "))
args.append(globals.Variable(None,source._file,".%s/*; rm -rf " % (ending)))
args.append(globals.Variable(None,source._file,".%s; sleep 3; mv " % (ending)))
args.append(globals.Variable(None,"temp." + fileEnd))
args.append(globals.Variable(None,source._file,".%s" % (ending)))
log.run("uvcat",args,fatal=True)
elif(len(windows) != 0) :
for window in windows :
if(source._bandwidths[window - 1] == 62) :
startChan = 4
numChan = source._numChans[window - 1] - 6
invertString = invertString + ",%s.w%i" % (source._file, window)
invertList.append([source._file,".w%i" % (window)])
args = []
args.append(globals.Variable("vis",source._file,".w%i" % (window)))
args.append(globals.Variable("options","unflagged"))
args.append(globals.Variable("out","temp." + fileEnd + "; sleep 3; rm -rf "))
args.append(globals.Variable(None,source._file,".w%i/*; rm -rf " % (window)))
args.append(globals.Variable(None,source._file,".w%i; sleep 3; mv " % (window)))
args.append(globals.Variable(None,"temp." + fileEnd))
args.append(globals.Variable(None,source._file,".w%i" % (window)))
log.run("uvcat",args,fatal=True)
else :
for window in range(globals.STARTWINDOW, globals.ENDWINDOW + 1) :
if(source._bandwidths[window - 1] == 62) :
startChan = 4
numChan = source._numChans[window - 1] - 6
invertString = invertString + ",%s.w%i" % (source._file, window)
invertList.append([source._file,".w%i" % (window)])
args = []
args.append(globals.Variable("vis",source._file,".w%i" % (window)))
args.append(globals.Variable("options","unflagged"))
args.append(globals.Variable("out","temp." + fileEnd + "; sleep 3; rm -rf "))
args.append(globals.Variable(None,source._file,".w%i/*; rm -rf " % (window)))
args.append(globals.Variable(None,source._file,".w%i; sleep 3; mv " % (window)))
args.append(globals.Variable(None,"temp." + fileEnd))
args.append(globals.Variable(None,source._file,".w%i" % (window)))
log.run("uvcat",args,fatal=True)
invertString = invertString[1:]
lastbad = 0
noise = 0.5
endings = [""]
selects=[""]
tempCell = cellsize
tempImg = imsize
if(globals.isSci2 and not individual) :
endings.append(".short")
if(globals.obsFreq() < 50.0) :
selects.append(" select=uvrange'('0,2')'")
selects.append(" select=uvrange'('2,2000000')'")
else :
selects.append(" select=uvrange'('0,6')'")
selects.append(" select=uvrange'('6,6000000')'")
endings.append(".long")
# keep inverting until we minimize the number of rejected visibilities
fileName = source._file
for i in range(0,len(endings)) :
if(endings[i].find(".short") >= 0) :
cellsize = calculations.calcCellSize(globals.avgShortBaseline(),0.0)
imsize = calculations.calcImsize(obsFreq, cellsize)
elif(endings[i].find(".long") >= 0) :
cellsize = calculations.calcCellSize(globals.avgLongBaseline(),0.0)
imsize = calculations.calcImsize(obsFreq, cellsize)
else :
cellsize = tempCell
imsize = tempImg
fName = ""
fEnd = ""
ok = False
end = endings[i]
select = selects[i]
if(individual) :
fName = fileName
fEnd = ".contin.w%i" % (windows[0])
fileName += ".contin.w%i" % (windows[0])
while(not ok) :
log.run("invert vis=%s map=%s.map beam=%s.beam imsize=%i cell=%f sup=0%s options=systemp,double,mfs,mosaic line=channel,1,%i,%i >& junk" % (invertString, fileName + end, fileName + end,imsize,cellsize,select, startChan, numChan),[],fatal=True,logit=False)
input = open("junk",'r')
fileList = input.readlines()
input.close()
found = False
while(len(fileList) > 0 and iterate) :
line = fileList.pop()
if("Visibilities rejected" in line) :
splitLine = line.split()
if(lastbad != int(splitLine[5])) :
cellsize = calculations.calcCellSize(avgBaseline,cellsize)
log.run("rm -rf %s %s; sleep 3" % (fileName + end + ".map", fileName + end + ".beam"),[],logit=False)
found = True
else :
cellsize *= 1.1
log.run("invert vis=%s map=%s.map beam=%s.beam imsize=%i cell=%f sup=0%s options=systemp,double,mfs,mosaic line=channel,1,%i,%i >& junk" % (invertString, fileName + end, fileName + end, imsize,cellsize, select, startChan, numChan),[],fatal=True,logit=False)
if("Theoretical rms" in line) :
noise = float(line.split(":")[1])
if(not found) :
ok = True
log.writeLog("Using an image size of %f for %s" % (imsize, source._name))
args = []
args.append(globals.Variable("vis",invertList[0][0],invertList[0][1]))
temp = invertList.pop(0)
for vis in invertList :
args.append(globals.Variable("ADD",vis[0],vis[1]))
invertList.append(temp)
if(individual) :
args.append(globals.Variable("map",fName,fEnd + ".map"))
args.append(globals.Variable("beam",fName,fEnd + ".beam"))
else :
args.append(globals.Variable("map",source._file,end + ".map"))
args.append(globals.Variable("beam",source._file,end + ".beam"))
args.append(globals.Variable("imsize",str(imsize)))
args.append(globals.Variable("cell",str(cellsize)))
args.append(globals.Variable("sup","0"))
if(select != "") :
args.append(globals.Variable(None,select))
args.append(globals.Variable("options","systemp,double,mfs,mosaic"))
args.append(globals.Variable("line","channel,1,%i,%i" % (startChan, numChan)))
log.run("invert",args,execute=False)
lastIter = 10000.0
# treat multipoint mosics differently
log.run("mossdi map=%s.map beam=%s.beam out=%s.clean niters=50000 cutoff=%f region=quarter" % (fileName + end, fileName + end, fileName + end,noise*2.5),[],fatal=True,logit=False)
# calculate the correst synthesized beam
log.run("mospsf beam=%s.beam out=%s.bm" % (fileName + end, fileName + end),[],fatal=True,logit=False)
log.run("imfit in=%s.bm object=beam region=arcsec,box'('-5,-5,5,5')' > fit.log.%s" % (fileName + end,fileEnd),[],fatal=True,logit=False)
input = open("fit.log.%s" % (fileEnd),'r')
fileList = input.readlines()
input.close()
majorAxis = 0.0
minorAxis = 0.0
positionAngle = 0.0
# get the beam parameters
while(len(fileList) > 0) :
line = fileList.pop()
if("Position angle" in line) :
splitLine = line.split()
positionAngle = float(splitLine[3])
elif("Minor axis" in line) :
splitLine = line.split()
minorAxis = float(splitLine[3])
elif("Major axis" in line) :
splitLine = line.split()
majorAxis = float(splitLine[3])
log.run("restor model=%s.clean map=%s.map beam=%s.beam fwhm=%f,%f pa=%f out=%s.finalmap" % (fileName + end, fileName + end, fileName + end, majorAxis,minorAxis,positionAngle, fileName + end),[],logit=False)
# get the initial noise level
region = dict()
region[0] = "%i,%i,%i,%i" % (int(math.floor(imsize/4)),int(math.floor((imsize/4) + (imsize/6))),int(math.floor((imsize/4) + (imsize/6))),int(math.floor((imsize/4) + (imsize/3))))
region[1] = "%i,%i,%i,%i" % (int(math.floor((imsize/4) + (imsize/6))),int(math.floor((imsize/4) + (imsize/3))),int(math.floor((imsize/4) + (imsize/3))),int(math.floor(3*imsize/4)))
region[2] = "%i,%i,%i,%i" % (int(math.floor((imsize/4) + (imsize/3))),int(math.floor((imsize/4) + (imsize/6))),int(math.floor(3*imsize/4)),int(math.floor((imsize/4) + (imsize/3))))
region[3] = "%i,%i,%i,%i" % (int(math.floor((imsize/4) + (imsize/6))),int(math.floor(imsize/4)),int(math.floor((imsize/4) + (imsize/3))),int(math.floor((imsize/4) + (imsize/6))))
rms = 1000000.0
best = 0
for j in range(4) :
#log.writeComment("Locating best region for noise calculation.")
log.run("imstat in=%s.finalmap region=box'('%s')' device=/NULL > rms.log.%s" % (fileName + end, region.get(j),fileEnd),[],logit=False)
input = open("rms.log.%s" % (fileEnd),'r')
fileList = input.readlines()
input.close()
fileList.reverse()
while(len(fileList) > 0) :
line = fileList.pop()
if("Frequency" in line) :
line = fileList.pop()
temprms = float(line[42:51])
if(temprms < rms) :
rms = temprms
best = j
#log.writeComment("Found region %i is best: %s" % (best, region.get(best)))
# determine the clean region either from user input, number of pointings, or automatically from the data
cleanReg = ""
if(isinstance(source,sources.Source)) :
if(source.getContinuumCleanRegion() == None) :
if(not source._mosaic) :
if(p.preferences.get("doAutoCleanRegion")) :
source.setContinuumCleanRegion(peakLocator.findCleanRegion("%s.finalmap" % (fileName + end),rms,"%s.bm" % (fileName),source._pointingCenters))
if(source.getContinuumCleanRegion() == "quarter") :
source.setCleanRegion("quarter")
elif(p.preferences.get("cleanRegion") == "quarter") :
source.setContinuumCleanRegion("quarter")
source.setCleanRegion("quarter")
else :
boxsize = int(p.preferences.get("cleanRegion"))
source.setContinuumCleanRegion("arcsec,box'(-%f,-%f,%f,%f)'" % (boxsize,boxsize,boxsize,boxsize))
source.setCleanRegion("arcsec,box'(-%f,-%f,%f,%f)'" % (boxsize,boxsize,boxsize,boxsize))
else :
if(p.preferences.get("doAutoCleanRegion")) :
print "AUTOCLEAN+++++++++++++++++++++++++++++"#################POINTING CENTERS
print source._pointingCenters
source.setContinuumCleanRegion(peakLocator.findCleanRegion("%s.finalmap" % (fileName + end),rms,"%s.bm" % (fileName + end),source._pointingCenters))
source.setCleanRegion(source.getContinuumCleanRegion())
else :
offset = [int(miriadClasses.imhead("%s.map" % fileName+end+addon,"crpix1")),int(miriadClasses.imhead("%s.map" % fileName+end+addon,"crpix2"))]
source.setContinuumCleanRegion(calculations.calculateMosaicCleanRegion(source._pointingCenters,cellsize,obsFreq,offset))
source.setCleanRegion(source.getContinuumCleanRegion())
log.writeLog("mosaic " + source.getCleanRegion())
cleanReg = source.getCleanRegion()
else :
# we are mapping a calibrator
cleanReg = "quarter"
converged = False
log.writeComment("Cleaning image to %f times the noise level, or 100000 iterations, whichever comes first" % (p.preferences.get("cleanThreshold")))
run = 1
cutoff = 1000.0
# loop over clean and restor until the noise level settles down or until 5 iterations are done
while((not converged) and (run <= 5)) :
cutoff = rms * p.preferences.get("cleanThreshold")
log.run("rm -rf %s.clean %s.finalmap; sleep 3" % (fileName + end, fileName + end),[],fatal=True,logit=False)
log.run("mossdi map=%s.map beam=%s.beam out=%s.clean niters=50000 cutoff=%f region=%s" % (fileName + end, fileName + end, fileName + end, cutoff,cleanReg),[],fatal=True,logit=False)
log.run("restor model=%s.clean map=%s.map beam=%s.beam fwhm=%f,%f pa=%f out=%s.finalmap" % (fileName + end,fileName + end, fileName + end, majorAxis,minorAxis,positionAngle,fileName + end),[],fatal=True,logit=False)
log.run("imstat in=%s.finalmap region=box'('%s')' device=/NULL > rms.log.%s" % (fileName + end, region.get(best),fileEnd),[],logit=False)
input = open("rms.log.%s" % (fileEnd),'r')
fileList = input.readlines()
input.close()
fileList.reverse()
while(len(fileList) > 0) :
line = fileList.pop()
if("Frequency" in line) :
line = fileList.pop()
temprms = float(line[42:51])
if(abs(temprms-rms) < 0.05 * rms) : # there must be less than a 5 % change
converged = True
else :
rms = temprms
run += 1
if(run > 5) :
log.writeComment("Did not reach noise level cutoff, performed 5 iterations.")
args = []
if(individual) :
args.append(globals.Variable("map",fName,fEnd + ".map"))
args.append(globals.Variable("beam",fName,fEnd + ".beam"))
args.append(globals.Variable("out",fName,fEnd + ".clean"))
else :
args.append(globals.Variable("map",source._file,end + ".map"))
args.append(globals.Variable("beam",source._file,end + ".beam"))
args.append(globals.Variable("out",source._file,end + ".clean"))
args.append(globals.Variable("niters","50000"))
args.append(globals.Variable("cutoff",str(cutoff)))
args.append(globals.Variable("region",cleanReg))
log.run("mossdi",args,execute=False)
args = []
if(individual) :
args.append(globals.Variable("model",fName,fEnd + ".clean"))
args.append(globals.Variable("map",fName,fEnd + ".map"))
args.append(globals.Variable("beam",fName,fEnd + ".beam"))
args.append(globals.Variable("out",fName,fEnd + ".finalmap"))
else :
args.append(globals.Variable("model",source._file,end + ".clean"))
args.append(globals.Variable("map",source._file,end + ".map"))
args.append(globals.Variable("beam",source._file,end + ".beam"))
args.append(globals.Variable("out",source._file,end + ".finalmap"))
args.append(globals.Variable("fwhm","%f,%f" % (majorAxis,minorAxis)))
args.append(globals.Variable("pa",str(positionAngle)))
log.run("restor",args,execute=False)
args = []
if(individual) :
args.append(globals.Variable("in",fName,fEnd + ".finalmap"))
args.append(globals.Variable("out",fName,fEnd + ".fits"))
else :
args.append(globals.Variable("in",source._file,end + ".finalmap"))
args.append(globals.Variable("out",source._file,end + ".fits"))
args.append(globals.Variable("op","xyout"))
log.run("fits",args,logit=False)
log.writeComment("Data reduction of %s complete. Final map(%s.finalmap) has a noise level of %f Jy/beam" % (source._name, fileName + end, rms))
startupTeardown.endFile("%s.finalmap" % (fileName + end))
def invertSpectra(objects, obsFreq, avgBaseline, windows) :
""" Method to create spectral line channel maps
input:
objects - the objetcs
obsFreq - observing frequency in GHz
avgBaseline - average baseline in lambda
windows - which windows to map
returns :
none
"""
global cellsize
global imsize
global continDone
global regions
global rmsList
# calculate the optimal cell size, based on the median baseline in klambda, want at least 5 pixels across the beam
# but only if the user did not specify it in the preferences file
if(p.preferences.get("cellSize") < 0 and cellsize == None) :
cellsize = calculations.calcCellSize(avgBaseline,0.0)
log.writeComment("Based on average baseline of %f, using a cell size of %f arcseconds." % (avgBaseline, cellsize))
elif(cellsize == None) :
cellsize = p.preferences.get("cellSize")
iterate = True
# calculate the optimal image size from the cell size and observing frequency
# but only if it was not specified by the user in the preferences file
if(p.preferences.get("imageSize") < 0 and imsize == None) :
imsize = calculations.calcImsize(obsFreq, cellsize)
elif(imsize == None) :
iterate = False
imsize = p.preferences.get("imageSize")
for source in objects._sources :
if(source._mosaic and not continDone) :
if(imsize > 1000) :
imsize = int(imsize * 1.5)
else :
imsize = int(imsize * 2.0)
threadList = []
for window in windows :
current = invertWindowThread(source,window,iterate,AvgBaseline=avgBaseline)
threadList.append(current)
current.start()
for thread in threadList :
thread.join()
if(len(regions) > 0) :
# get clean region
regions[0] = source.getContinuumCleanRegion()
source.setCleanRegion(peakLocator.compactCleanRegions(regions,[imsize,imsize]))
del threadList[:]
log.writeComment("Cleaning images to %f times the noise level, or 100000 iterations, whichever comes first" % (p.preferences.get("cleanThreshold")))
log.writeComment("Note that these are threaded and may appear out of window order")
for window in windows :
current = cleanWindowThread(source,window)
threadList.append(current)
current.start()
for thread in threadList :
thread.join()
regions.clear()
# now do continuum subtraction
if(p.preferences.get("doContinuumSubtraction")) :
del threadList[:]
for window in windows :
current = continuumSubtraction.continuumSubtractionThread(source, window, 3.0*rmsList[window])
threadList.append(current)
current.start()
for thread in threadList :
thread.join()
del threadList[:]
for window in windows :
current = cleanWindowThread(source,window,True)
threadList.append(current)
current.start()
for thread in threadList :
thread.join()
del threadList[:]
for window in windows :
current = invertWindowThread(source,window,True)
threadList.append(current)
current.start()
for thread in threadList :
thread.join()