-
Notifications
You must be signed in to change notification settings - Fork 0
/
findContinuum.py
4461 lines (4309 loc) · 218 KB
/
findContinuum.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
import os
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
mpl.use('Agg')
"""
Demonstration of algorithm to determine continuum channel ranges to
use from a CASA image cube (dirty or clean). All dependencies on
analysisUtils functions have been pasted into this file for convenience.
This function is meant to be run inside CASA. Simple usage:
import findContinuum as fc
fc.findContinuum('my_dirty_cube.image')
This file can be found in a typical pipeline distribution directory, e.g.:
/lustre/naasc/sciops/comm/rindebet/pipeline/branches/trunk/pipeline/extern
"""
import os
try:
# pyfits is only needed to support reading spectra from FITS tables,
# which is not a use case exercised by the pipeline.
import pyfits
except:
print 'WARNING: pyfits not available!'
import numpy as np
import matplotlib.pyplot as pl
import matplotlib.ticker
#matplotlib.use('Agg')
import time as timeUtilities
from taskinit import *
from imhead_cli import imhead_cli as imhead
from imregrid_cli import imregrid_cli as imregrid
from imstat_cli import imstat_cli as imstat # used by computeMadSpectrum
import warnings
import subprocess
import casadef # This still works in CASA 5.0, but might not someday.
import scipy
import glob
from scipy.stats import scoreatpercentile, percentileofscore
from scipy.ndimage.filters import gaussian_filter
# The following still works in CASA 5 and is backward compatible
# to CASA 4:
casaMajorVersion = int(casadef.casa_version.split('.')[0])
if casaMajorVersion < 5:
from scipy.stats import nanmean as scipy_nanmean
else:
# scipy.nanmean exists, but is deprecated in favor of numpy's version
from numpy import nanmean as scipy_nanmean
maxTrimDefault = 20
_proc_status = '/proc/%d/status' % os.getpid()
_scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
'KB': 1024.0, 'MB': 1024.0*1024.0}
def version(showfile=True):
"""
Returns the CVS revision number.
"""
myversion = "$Id: findContinuum.py,v 1.167 2017/08/04 12:40:52 thunter Exp $"
if (showfile):
print "Loaded from %s" % (__file__)
return myversion
def _VmB(VmKey):
global _proc_status, _scale
# get pseudo file /proc/<pid>/status
try:
t = open(_proc_status)
v = t.read()
t.close()
except:
return 0.0 # non-Linux?
# get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
i = v.index(VmKey)
v = v[i:].split(None, 3) # whitespace
if len(v) < 3:
return 0.0 # invalid format?
# convert Vm value to bytes
return float(v[1]) * _scale[v[2]]
def memoryUsage(since=0.0):
'''Return memory usage in gigabytes.
'''
return (_VmB('VmSize:') - since)/(1024.**3)
def residentMemoryUsage(since=0.0):
'''Return resident memory usage in gigabytes.
'''
return (_VmB('VmRSS:') - since)/(1024.**3)
def casalogPost(mystring, debug=True):
if (debug): print mystring
token = version(False).split()
origin = token[1].replace(',','_') + token[2]
casalog.post(mystring.replace('\n',''), origin=origin)
def is_binary(filename):
"""
Return true if the given filename appears to be binary.
File is considered to be binary if it contains a NULL byte.
This approach returns True for .fits files, but
incorrectly reports UTF-16 as binary.
"""
with open(filename, 'rb') as f:
for block in f:
if '\0' in block:
return True
return False
def getMemorySize():
try:
return(os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES'))
except ValueError:
# SC_PHYS_PAGES can be missing on OS X
return int(subprocess.check_output(['sysctl', '-n', 'hw.memsize']).strip())
def findContinuum(img='', spw='', transition='', baselineModeA='min', baselineModeB='min',
sigmaCube=3, nBaselineChannels=0.19, sigmaFindContinuum='auto',
verbose=False, png='', pngBasename=False, nanBufferChannels=1,
source='', useAbsoluteValue=True, trimChannels='auto',
percentile=20, continuumThreshold=None, narrow='auto',
separator=';', overwrite=False, titleText='',
showAverageSpectrum=False, maxTrim=maxTrimDefault, maxTrimFraction=1.0,
meanSpectrumFile='', centralArcsec='auto', alternateDirectory='.',
header='', plotAtmosphere='transmission', airmass=1.5, pwv=1.0,
channelFractionForSlopeRemoval=0.75, mask='',
invert=False, meanSpectrumMethod='auto',peakFilterFWHM=10,
skyTempThreshold=1.2, # was 1.5 in C4R2, reduced after slope removal added
skyTransmissionThreshold=0.08, maxGroupsForSkyThreshold=5,
minBandwidthFractionForSkyThreshold=0.2, regressionTest=False,
quadraticFit=True, triangleFraction=0.83, maxMemory=-1,
tdmSkyTempThreshold=0.65, negativeThresholdFactor=1.15,
vis='', singleContinuum=False, applyMaskToMask=False,
plotBaselinePoints=False, dropBaselineChannels=2.0,
madRatioUpperLimit=1.5, madRatioLowerLimit=1.15, interactive=False,
projectCode=''):
"""
This function calls functions to:
1) compute the mean spectrum of a dirty cube
2) find the continuum channels
3) plot the results
It calls runFindContinuum up to 2 times. It runs it a second time with a
reduced field size if it finds only one range of continuum channels.
Returns:
* A channel selection string suitable for the spw parameter of clean.
* The name of the final png produced.
* The aggregate bandwidth in continuum in GHz.
Inputs:
img: the image cube to operate upon
spw: the spw name or number to put in the x-axis label
transition: the name of the spectral transition (for the plot title)
baselineModeA: 'min' or 'edge', method to define the baseline in meanSpectrum()
baselineModeB: 'min' or 'edge', method to define the baseline in findContinuumChannels()
sigmaCube: multiply this value by the rms to get the threshold above which a pixel
is included in the mean spectrum
nBaselineChannels: if integer, then the number of channels to use in:
a) computing the mean spectrum with the 'meanAboveThreshold' methods.
b) computing the MAD of the lowest/highest channels in findContinuumChannels
if float, then the fraction of channels to use (i.e. the percentile)
default = 0.19, which is 24 channels (i.e. 12 on each side) of a TDM window
sigmaFindContinuum: passed to findContinuumChannels, 'auto' starts with 3.5
verbose: if True, then print additional information during processing
png: the name of the png to produce ('' yields default name)
pngBasename: if True, then remove the directory from img name before generating png name
nanBufferChannels: when removing or replacing NaNs, do this many extra channels
beyond their extent
source: the name of the source, to be shown in the title of the spectrum.
if None, then use the filename, up to the first underscore.
useAbsoluteValue: passed to meanSpectrum, then avgOverCube -- take absolute value of
the cube before producing mean spectrum
findContinuum: if True, then find the continuum channels before plotting
overwrite: if True, or ASCII file does not exist, then recalculate the mean spectrum
writing it to <img>.meanSpectrum
if False, then read the mean spectrum from the existing ASCII file
trimChannels: after doing best job of finding continuum, remove this many
channels from each edge of each block of channels found (for margin of safety)
If it is a float between 0..1, then trim this fraction of channels in each
group (rounding up). If it is 'auto', use 0.1 but not more than maxTrim channels
and not more than maxTrimFraction
percentile: control parameter used with baselineMode='min'
continuumThreshold: if specified, only use pixels above this intensity level
separator: the character to use to separate groups of channels in the string returned
narrow: the minimum number of channels that a group of channels must have to survive
if 0<narrow<1, then it is interpreted as the fraction of all
channels within identified blocks
if 'auto', then use int(ceil(log10(nchan)))
titleText: default is img name and transition and the control parameter values
showAverageSpectrum: make a two-panel plot, showing the raw mean spectrum in black
maxTrim: in trimChannels='auto', this is the max channels to trim per group for TDM spws; it is automatically scaled upward for FDM spws.
maxTrimFraction: in trimChannels='auto', the max fraction of channels to trim per group
meanSpectrumMethod: 'auto', 'peakOverMad', 'peakOverRms', 'meanAboveThreshold',
'meanAboveThresholdOverRms', 'meanAboveThresholdOverMad',
where 'peak' refers to the peak in a spatially-smoothed version of cube
'auto' currently invokes 'meanAboveThreshold' unless sky temperature range (max-min)
from the atmospheric model is more than skyTempThreshold
skyTempThreshold: rms value in Kelvin, above which meanSpectrumMethod is changed in 'auto' mode to peakOverMad
for non-TDM spectra.
tdmSkyTempThreshold: rms value in Kelvin (for TDM spectra)
skyTransmissionThreshold: threshold on (max-min)/mean, above which meanSpectrumMethod is changed in 'auto' mode to peakOverMad
peakFilterFWHM: value used by 'peakOverRms' and 'peakOverMad' methods to presmooth
each plane with a Gaussian kernel of this width (in pixels). Set to 1 to not do any
smoothing. Default = 10 which is typically about 2 synthesized beams.
meanSpectrumFile: an alternative ASCII text file to use for the mean spectrum.
Must also set img=''.
centralArcsec: radius of central box within which to compute the mean spectrum
default='auto' means start with whole field, then reduce to 1/10 if only
one window is found (unless mask is specified); or 'fwhm' for the central square
with the same radius as the PB FWHM; or a floating point value in arcseconds
mask: a mask image preferably equal in shape to the parent image that is used to determine
the region to compute the noise (outside the mask, i.e. mask=0) and
(in the 'meanAboveThresholdMethod') the mean spectrum (inside the mask, i.e. mask=1).
The spatial union of all masked pixels in all channels is used as the mask for each channel.
Option 'auto' will look for the <filename>.mask that matches the <filename>.image
and if it finds it, it will use it; otherwise it will use no mask.
If the mask does not match in shape but is multi-channel, it will be regridded to match
and written out as <filename>.mask.regrid.
If it matches spatially but is single-channel, this channel will be used for all.
To convert a .crtf file to a mask, use:
makemask(mode='copy', inpimage=img, inpmask='chariklo.crtf', output=img+'.mask')
header: dictionary created by imhead(img, mode='list')
plotAtmosphere: '', 'tsky', or 'transmission'
airmass: for plot of atmospheric transmission
pwv: in mm (for plot of atmospheric transmission)
channelFractionForSlopeRemoval: if this many channels are initially selected, then fit
and remove a linear slope and re-identify continuum channels (for the
meanAboveThreshold methods only)
invert: if reading previous meanSpectrum file, then invert the sign and add the minimum
quadraticFit: if True, fit quadratic polynomial to the noise regions when appropriate;
otherwise fit only a linear slope
triangleFraction: MAD of dual-linfit residual must be less than this fraction*originalMAD
maxMemory: behave as if the machine has this many GB of memory
negativeThresholdFactor: scale the nominal negative threshold by this factor (to adjust
sensitivity to absorption features: smaller values=more sensitive)
vis: comma-delimited list or python list of measurement sets to use to convert channel
ranges to topocentric frequency ranges (for use in uvcontfit or uvcontsub)
singleContinuum: if True, treat the cube as having come from a Single_Continuum setup;
For testing purpose. This option is overridden by the contents of vis (if specified).
applyMaskToMask: if True, apply the mask inside the user mask image to set its masked pixels to 0
plotBaselinePoints: if True, then plot the baseline-defining points as black dots
dropBaselineChannels: percentage of extreme values to drop in baseline mode 'min'
interactive: if True, then stop after first iteration, and wait for input
"""
if type(centralArcsec) == str:
if centralArcsec.isdigit():
centralArcsecValue = centralArcsec
centralArcsec = float(centralArcsec)
else:
centralArcsecValue = "'"+centralArcsec+"'"
else:
centralArcsecValue = str(centralArcsec)
casalogPost("\n BEGINNING: findContinuum.findContinuum('%s', centralArcsec=%s, mask='%s', overwrite=%s, sigmaFindContinuum='%s', meanSpectrumMethod='%s', peakFilterFWHM=%.0f, meanSpectrumFile='%s', triangleFraction=%.2f, singleContinuum=%s)" % (img, centralArcsecValue, mask, overwrite, str(sigmaFindContinuum), meanSpectrumMethod, peakFilterFWHM, meanSpectrumFile, triangleFraction, singleContinuum))
casalogPost("0) Current memory usage: %.3f GB, resident: %.3f GB" % (memoryUsage(), residentMemoryUsage()))
img = img.rstrip('/')
imageInfo = [] # information returned from getImageInfo
if (len(vis) > 0):
# vis is a non-blank list or non-blank string
if (type(vis) == str):
vis = vis.split(',')
# vis is now assured to be a non-blank list
for v in vis:
if not os.path.exists(v):
print "Could not find measurement set: ", v
return
if (img != ''):
if (not os.path.exists(img)):
casalogPost("Could not find image = %s" % (img))
return
result = getImageInfo(img, header)
if (result is None):
return result
imageInfo, header = result
bmaj, bmin, bpa, cdelt1, cdelt2, naxis1, naxis2, freq = imageInfo
chanInfo = numberOfChannelsInCube(img, returnChannelWidth=True, returnFreqs=True,
header=header)
nchan,firstFreq,lastFreq,channelWidth = chanInfo
if (nchan < 2):
casalogPost("You must have more than one channel in the image.")
return
channelWidth = abs(channelWidth)
else:
header = []
chanInfo = []
channelWidth = 0
firstFreq = 0
lastFreq = 0
if (mask == 'auto'):
mask = img.rstrip('.image') + '.mask'
if (not os.path.exists(mask)):
mask = ''
else:
maskInfo, maskhead = getImageInfo(mask)
if (maskhead['shape'] == header['shape']).all():
# are there any unmasked pixels?
if (maskhead['datamax'] >= 0.5):
casalogPost("Will use the clean mask to limit the pixels averaged.")
centralArcsec = -1
else:
casalogPost("No valid pixels in the mask. Will ignore it.")
mask = ''
else:
casalogPost("Shape of mask (%s) does not match the image (%s)." % (maskhead['shape'],header['shape']))
casalogPost("If you want to automatically regrid the mask, then set its name explicitly.")
return
else:
if mask == False:
mask = ''
if (len(mask) > 0):
if (not os.path.exists(mask)):
casalogPost("Could not find image mask = %s" % (mask))
return
maskInfo, maskhead = getImageInfo(mask)
if (maskhead['shape'] == header['shape']).all():
casalogPost("Shape of mask matches the image.")
else:
casalogPost("Shape of mask (%s) does not match the image (%s)." % (maskhead['shape'],header['shape']))
# check if the spatial dimension matches. If so, then simply add channels
if (maskhead['shape'][0] == header['shape'][0] and
maskhead['shape'][1] == header['shape'][1]):
myia = createCasaTool(iatool)
myia.open(img)
axis = findSpectralAxis(myia)
if (header['shape'][axis] != 1):
if (os.path.exists(mask+'.regrid') and not overwrite):
casalogPost("Regridded mask already exists, will use it.")
else:
casalogPost("Regridding the spectral axis of the mask with replicate.")
imregrid(mask, output=mask+'.regrid', template=img, axes=[axis], replicate=True, interpolation='nearest', overwrite=overwrite)
else:
casalogPost("This single plane mask will be used for all channels.")
else:
casalogPost("Regridding the mask spatially and spectrally.")
imregrid(mask, output=mask+'.regrid', template=img, asvelocity=False, interpolation='nearest')
mask = mask+'.regrid'
maskInfo, maskhead = getImageInfo(mask)
bytes = getMemorySize()
try:
hostname = os.getenv('HOST')
except:
hostname = "?"
casalogPost("Total memory on %s = %.3f GB" % (hostname,bytes/(1024.**3)))
if (maxMemory > 0 and maxMemory < bytes/(1024.**3)):
bytes = maxMemory*(1024.**3)
casalogPost("but behaving as if it has only %.3f GB" % (bytes/(1024.**3)))
meanSpectrumMethodRequested = meanSpectrumMethod
meanSpectrumMethodMessage = ''
if img != '':
npixels = float(nchan)*naxis1*naxis2
else:
npixels = 1
maxpixels = bytes/67 # float(1024)*1024*960
triangularPatternSeen = False
if (meanSpectrumMethod.find('auto') >= 0):
meanSpectrumMethod = 'meanAboveThreshold'
if (img != ''):
a,b,c,d,e = atmosphereVariation(img, header, chanInfo,
airmass=airmass, pwv=pwv)
if (b > skyTransmissionThreshold or e > skyTempThreshold):
meanSpectrumMethod = 'peakOverMad'
meanSpectrumMethodMessage = "Set meanSpectrumMethod='%s' since atmos. variation %.2f>%.2f or %.3f>%.1fK." % (meanSpectrumMethod,b,skyTransmissionThreshold,e,skyTempThreshold)
elif (e > tdmSkyTempThreshold and abs(channelWidth*nchan) > 1e9): # tdmSpectrum(channelWidth,nchan)):
meanSpectrumMethod = 'peakOverMad'
meanSpectrumMethodMessage = "Set meanSpectrumMethod='%s' since atmos. variation %.2f>%.2f or %.3f>%.2fK." % (meanSpectrumMethod,b,skyTransmissionThreshold,e,tdmSkyTempThreshold)
else:
# Maybe comment this out once thresholds are stable
if abs(channelWidth*nchan > 1e9): # tdmSpectrum(channelWidth,nchan):
myThreshold = tdmSkyTempThreshold
else:
myThreshold = skyTempThreshold
triangularPatternSeen, value = checkForTriangularWavePattern(img,header,triangleFraction)
if (triangularPatternSeen):
meanSpectrumMethod = 'peakOverMad'
meanSpectrumMethodMessage = "Set meanSpectrumMethod='%s' since triangular pattern was seen (%.2f<%.2f)." % (meanSpectrumMethod, value, triangleFraction)
else:
if value == False:
triangleMsg = 'slopeTest=F'
else:
triangleMsg = '%.2f>%.2f' % (value,triangleFraction)
meanSpectrumMethodMessage = "Did not change meanSpectrumMethod since atmos. variation %.2f<%.2f & %.3f<%.1fK (%s)." % (b,skyTransmissionThreshold,e,myThreshold,triangleMsg)
casalogPost(meanSpectrumMethodMessage)
centralArcsecField = centralArcsec
centralArcsecLimitedField = -1
if (centralArcsec == 'auto' and img != ''):
if (npixels > maxpixels): # and meanSpectrumMethod.find('meanAboveThreshold')>=0):
casalogPost("Excessive number of pixels (%.0f > %.0f) %dx%dx%d" % (npixels,maxpixels,naxis1,naxis2,nchan))
totalWidthArcsec = abs(cdelt2*naxis2)
if (mask == ''):
centralArcsecField = totalWidthArcsec*maxpixels/npixels
else:
casalogPost("Finding size of the central square that fully contains the mask.")
centralArcsecField = widthOfMaskArcsec(mask)
newWidth = int(naxis2*centralArcsecField/totalWidthArcsec)
centralArcsecLimitedField = float(centralArcsecField) # Remember in case we need to reinvoke later
if (header['maxpixpos'][0] > naxis2/2 - newWidth/2 and
header['maxpixpos'][0] < naxis2/2 + newWidth/2 and
header['maxpixpos'][1] > naxis2/2 - newWidth/2 and
header['maxpixpos'][1] < naxis2/2 + newWidth/2):
npixels = float(nchan)*newWidth*newWidth
casalogPost('Data max is within the smaller field')
casalogPost("Reducing image width examined from %.2f to %.2f arcsec to avoid memory problems." % (totalWidthArcsec,centralArcsecField))
else:
centralArcsecField = centralArcsec
if (meanSpectrumMethod == 'peakOverMad'):
casalogPost('Data max is NOT within the smaller field. Keeping meanSpectrumMethod of peakOverMad over full field.')
else:
meanSpectrumMethod = 'peakOverMad'
meanSpectrumMethodMessage = "Data max NOT within the smaller field. Switch to meanSpectrumMethod='peakOverMad'"
casalogPost(meanSpectrumMethodMessage)
else:
casalogPost("Using whole field since npixels=%d < maxpixels=%d" % (npixels, maxpixels))
centralArcsecField = -1 # use the whole field
elif (centralArcsec == 'fwhm' and img != ''):
centralArcsecField = primaryBeamArcsec(frequency=np.mean([firstFreq,lastFreq]),
showEquation=False)
npixels = float(nchan)*(centralArcsecField**2/abs(cdelt2)/abs(cdelt1))
else:
centralArcsecField = centralArcsec
if img != '':
npixels = float(nchan)*(centralArcsec**2/abs(cdelt2)/abs(cdelt1))
iteration = 0
fullLegend = False
casalogPost('---------- runFindContinuum iteration %d' % (iteration))
if vis != '':
singleContinuum = isSingleContinuum(vis, spw)
result = runFindContinuum(img, spw, transition, baselineModeA,baselineModeB,
sigmaCube, nBaselineChannels, sigmaFindContinuum,
verbose, png, pngBasename, nanBufferChannels,
source, useAbsoluteValue, trimChannels,
percentile, continuumThreshold, narrow,
separator, overwrite, titleText,
showAverageSpectrum, maxTrim, maxTrimFraction,
meanSpectrumFile, centralArcsecField,channelWidth,
alternateDirectory, imageInfo, chanInfo, header,
plotAtmosphere, airmass, pwv,
channelFractionForSlopeRemoval, mask,
invert, meanSpectrumMethod, peakFilterFWHM,
fullLegend, iteration, meanSpectrumMethodMessage,
regressionTest=regressionTest, quadraticFit=quadraticFit,
megapixels=npixels*1e-6, triangularPatternSeen=triangularPatternSeen,
maxMemory=maxMemory, negativeThresholdFactor=negativeThresholdFactor,
byteLimit=bytes, singleContinuum=singleContinuum,
applyMaskToMask=applyMaskToMask, plotBaselinePoints=plotBaselinePoints,
dropBaselineChannels=dropBaselineChannels,
madRatioUpperLimit=madRatioUpperLimit,
madRatioLowerLimit=madRatioLowerLimit, projectCode=projectCode)
if result is None:
return
selection, mypng, slope, channelWidth, nchan, useLowBaseline = result
if png == '':
png = mypng
mytest = False
if (centralArcsec == 'auto' and img != '' and len(selection.split(separator)) < 2):
# Only one range was found, so look closer into the center for a line
casalogPost("Only one range of channels was found")
print "Only one range found....."
myselection = selection.split(separator)[0]
if (myselection.find('~') > 0):
a,b = [int(i) for i in myselection.split('~')]
print "Comparing range of %d~%d to %d/2" % (a,b,nchan)
mytest = b-a+1 > nchan/2
else:
mytest = True
if (mytest):
reductionFactor = 10.0
if (naxis1 > 1*6*reductionFactor): # reduced field must be at least 1 beam across (assuming 6 pix per beam)
# reduce the field size to one tenth of the previous
bmaj, bmin, bpa, cdelt1, cdelt2, naxis1, naxis2, freq = imageInfo # getImageInfo(img)
imageWidthArcsec = 0.5*(np.abs(naxis2*cdelt2) + np.abs(naxis1*cdelt1))
npixels /= reductionFactor**2
centralArcsecField = imageWidthArcsec/reductionFactor
casalogPost("Reducing the field size to 1/10 of previous (%f arcsec to %f arcsec) (%d to %d pixels)" % (imageWidthArcsec,centralArcsecField,naxis1,naxis1/10))
# could change the 128 to tdmSpectrum(channelWidth,nchan), but this heuristic may also help
# for excerpts of larger cubes with narrower channel widths.
if (nBaselineChannels < 1 and nchan <= 128):
nBaselineChannels = float(np.min([0.5, nBaselineChannels*1.5]))
overwrite = True
casalogPost("Re-running findContinuum over central %.1f arcsec with nBaselineChannels=%g" % (centralArcsecField,nBaselineChannels))
iteration += 1
if interactive:
ignore = raw_input("Press return to continue")
result = runFindContinuum(img, spw, transition, baselineModeA, baselineModeB,
sigmaCube, nBaselineChannels, sigmaFindContinuum,
verbose, png, pngBasename, nanBufferChannels,
source, useAbsoluteValue, trimChannels,
percentile, continuumThreshold, narrow,
separator, overwrite, titleText,
showAverageSpectrum, maxTrim, maxTrimFraction,
meanSpectrumFile, centralArcsecField, channelWidth,
alternateDirectory, imageInfo, chanInfo, header,
plotAtmosphere, airmass, pwv,
channelFractionForSlopeRemoval, mask,
invert, meanSpectrumMethod, peakFilterFWHM,
fullLegend,iteration,meanSpectrumMethodMessage,
regressionTest=regressionTest, quadraticFit=quadraticFit,
megapixels=npixels*1e-6, triangularPatternSeen=triangularPatternSeen,
maxMemory=maxMemory, negativeThresholdFactor=negativeThresholdFactor,
byteLimit=bytes, singleContinuum=singleContinuum,
applyMaskToMask=applyMaskToMask, plotBaselinePoints=plotBaselinePoints,
dropBaselineChannels=dropBaselineChannels,
madRatioUpperLimit=madRatioUpperLimit,
madRatioLowerLimit=madRatioLowerLimit, projectCode=projectCode)
if result is None:
return
selection, mypng, slope, channelWidth, nchan, useLowBaseline = result
if png == '':
png = mypng
print "************ b) png passed into initial call was blank"
else:
casalogPost("*** Not reducing field size since it would be less than 1 beam across")
else:
casalogPost("*** Not reducing field size since more than 1 range found")
aggregateBandwidth = computeBandwidth(selection, channelWidth, 0)
if (meanSpectrumMethodRequested == 'auto'):
# Here we check to see if we need to switch the method of computing the mean spectrum
# based on any undesirable characteristics of the results, and if so, re-run it.
groups = len(selection.split(separator))
if (aggregateBandwidth <= 0.00001 or
# the following line was an attempt to solve CAS-9269 case reported by Ilsang Yoon for SCOPS-2571
# (mytest and meanSpectrumMethod!='peakOverMad' and groups < 2) or
(not useLowBaseline and meanSpectrumMethod=='peakOverMad' and not tdmSpectrum(channelWidth,nchan)) or
(meanSpectrumMethod=='peakOverMad' and meanSpectrumMethodMessage != ''
and groups > maxGroupsForSkyThreshold
# the following line maintains peakOverMad for dataset in CAS-8908 (and also OMC1_NW spw39 in CAS-8720)
and aggregateBandwidth < minBandwidthFractionForSkyThreshold*nchan*channelWidth*1e-9
and not tdmSpectrum(channelWidth,nchan))):
# If less than 10 kHz is found (or two other situations), then try the other approach.
if (meanSpectrumMethod == 'peakOverMad'):
meanSpectrumMethod = 'meanAboveThreshold'
if (aggregateBandwidth <= 0.00001):
meanSpectrumMethodMessage = "Reverted to meanSpectrumMethod='%s' because no continuum found." % (meanSpectrumMethod)
casalogPost("Re-running findContinuum with the other meanSpectrumMethod: %s (because aggregateBW=%eGHz is less than 10kHz)" % (meanSpectrumMethod,aggregateBandwidth))
elif (not useLowBaseline and meanSpectrumMethod=='peakOverMad' and not tdmSpectrum(channelWidth,nchan)):
meanSpectrumMethodMessage = "Reverted to meanSpectrumMethod='%s' because useLowBaseline=F." % (meanSpectrumMethod)
casalogPost("Re-running findContinuum with the other meanSpectrumMethod: %s (because useLowBaseline=False)" % (meanSpectrumMethod))
elif (aggregateBandwidth < minBandwidthFractionForSkyThreshold*nchan*channelWidth*1e-9 and groups>maxGroupsForSkyThreshold):
meanSpectrumMethodMessage = "Reverted to meanSpectrumMethod='%s' because groups=%d>%d and not TDM." % (meanSpectrumMethod,groups,maxGroupsForSkyThreshold)
casalogPost("Re-running findContinuum with the other meanSpectrumMethod: %s because it is an FDM spectrum with many groups (%d>%d) and aggregate bandwidth (%f GHz) < %.2f of total bandwidth." % (meanSpectrumMethod,groups,maxGroupsForSkyThreshold,aggregateBandwidth,minBandwidthFractionForSkyThreshold))
else:
if groups < 2:
if sigmaFindContinuum == 'auto':
# Fix for CAS-9639: strong line near band edge and odd noise characteristic
sigmaFindContinuum = 6.5
casalogPost('Setting sigmaFindContinuum = %.1f since groups < 2' % sigmaFindContinuum)
else:
sigmaFindContinuum += 3.0
meanSpectrumMethodMessage = "Increasing sigmaFindContinuum to %.1f because groups=%d<2 and not TDM." % (sigmaFindContinuum,groups)
casalogPost("Re-running findContinuum with meanSpectrumMethod: %s because groups=%d<2. Increasing sigmaFindContinuum to %.1f." % (meanSpectrumMethod,groups,sigmaFindContinuum))
elif groups > maxGroupsForSkyThreshold:
# hot core FDM case
meanSpectrumMethodMessage = "Reverted to meanSpectrumMethod='%s' because groups=%d>%d and not TDM." % (meanSpectrumMethod,groups,maxGroupsForSkyThreshold)
casalogPost("Re-running findContinuum with meanSpectrumMethod: %s." % (meanSpectrumMethod))
else:
meanSpectrumMethodMessage = "Reverted to meanSpectrumMethod='%s' because groups=%d and not TDM." % (meanSpectrumMethod,groups)
casalogPost("Re-running findContinuum with meanSpectrumMethod: %s." % (meanSpectrumMethod))
if (centralArcsecLimitedField > 0):
# Re-establish the previous limit
centralArcsecField = centralArcsecLimitedField
casalogPost("Re-establishing the limit on field width determined earlier: %f arcsec" %(centralArcsecField))
else:
meanSpectrumMethod = 'peakOverMad'
if (mytest and groups < 2):
centralArcsecField = -1
casalogPost("Re-running findContinuum with meanSpectrumMethod: %s (because still only 1 group found after zoom)" % (meanSpectrumMethod))
else:
casalogPost("Re-running findContinuum with the other meanSpectrumMethod: %s (because aggregateBW=%eGHz is less than 10kHz)" % (meanSpectrumMethod,aggregateBandwidth))
iteration += 1
if os.path.exists(png):
os.remove(png)
if interactive:
ignore = raw_input("Press return to continue")
result = runFindContinuum(img, spw, transition, baselineModeA, baselineModeB,
sigmaCube, nBaselineChannels, sigmaFindContinuum,
verbose, png, pngBasename, nanBufferChannels,
source, useAbsoluteValue, trimChannels,
percentile, continuumThreshold, narrow,
separator, overwrite, titleText,
showAverageSpectrum, maxTrim, maxTrimFraction,
meanSpectrumFile, centralArcsecField, channelWidth,
alternateDirectory, imageInfo, chanInfo, header,
plotAtmosphere, airmass, pwv,
channelFractionForSlopeRemoval, mask,
invert, meanSpectrumMethod, peakFilterFWHM,
fullLegend, iteration,
meanSpectrumMethodMessage,
regressionTest=regressionTest, quadraticFit=quadraticFit,
megapixels=npixels*1e-6, triangularPatternSeen=triangularPatternSeen,
maxMemory=maxMemory, negativeThresholdFactor=negativeThresholdFactor,
byteLimit=bytes, singleContinuum=singleContinuum,
applyMaskToMask=applyMaskToMask, plotBaselinePoints=plotBaselinePoints,
dropBaselineChannels=dropBaselineChannels,
madRatioUpperLimit=madRatioUpperLimit,
madRatioLowerLimit=madRatioLowerLimit, projectCode=projectCode)
selection, mypng, slope, channelWidth, nchan, useLowBaseline = result
if png == '':
png = mypng
print "************ c) png passed into initial call was blank"
else:
casalogPost("Not re-running findContinuum with the other method because the results are deemed acceptable.")
# Write summary of results to text file
if (meanSpectrumFile == ''):
meanSpectrumFile = buildMeanSpectrumFilename(img, meanSpectrumMethod, peakFilterFWHM)
writeContDat(meanSpectrumFile, selection, png, aggregateBandwidth,
firstFreq, lastFreq, channelWidth, img, vis)
casalogPost("Current memory usage: %.3f GB, resident: %.3f GB" % (memoryUsage(), residentMemoryUsage()))
casalogPost("Finished findContinuum.py.")
return(selection, png, aggregateBandwidth)
def maskArgumentMismatch(mask, meanSpectrumFile):
"""
Determines if the requested mask does not match what was used to generate
the specified meanSpectrumFile.
Returns: True or False
"""
if (mask == '' or mask == False):
if (grep(meanSpectrumFile,'mask')[0] != ''):
# mask was used previously, but we did not request one this time
return True
else:
# mask was not used previously and we are not requesting one this time
False
elif (grep(meanSpectrumFile,mask)[0] == ''):
# requested mask was not used previously
return True
else:
# requested mask was used previously. Except if the new mask is a subset
# of the old name, so check for that possibility.
tokens = grep(meanSpectrumFile,mask)[0].split()
if mask not in tokens:
return True
else:
return False
def centralArcsecArgumentMismatch(centralArcsec, meanSpectrumFile, iteration):
"""
Determines if the requested centralArcsec value does not match what was used to
generate the specified meanSpectrumFile.
Returns: True or False
"""
if (centralArcsec == 'auto' or centralArcsec == -1):
if (grep(meanSpectrumFile,'centralArcsec=auto')[0] == '' and
grep(meanSpectrumFile,'centralArcsec=-1')[0] == ''):
casalogPost("request for auto but 'centralArcsec=auto' not found and 'centralArcsec=-1' not found")
return True
else:
result = grep(meanSpectrumFile,'centralArcsec=auto')[0]
if (iteration == 0 and result != ''):
# This will force re-run of any result that went to a smaller size.
token = result.split('=auto')
if (len(token) > 1):
if (token[1].strip().replace('.','').isdigit()):
return True
else:
return False
else:
return False
else:
return False
elif (grep(meanSpectrumFile,'centralArcsec=auto %s'%(str(centralArcsec)))[0] == '' and
grep(meanSpectrumFile,'centralArcsec=%s'%(str(centralArcsec)))[0] == ''):
token = grep(meanSpectrumFile,'centralArcsec=')[0].split('centralArcsec=')
if (len(token) < 2):
# This should never happen, but if it does, prevent a crash by returning now.
casalogPost("Did not find string 'centralArcsec=' with a value in the meanSpectrum file.")
return True
value = token[1].replace('auto ','').split()[0]
try:
previousRequest = float(value)
centralArcsecThresholdPercent = 2
if (100*abs(previousRequest-centralArcsec)/centralArcsec < centralArcsecThresholdPercent):
casalogPost("request for specific value (%s) and previous value (%s) is within %d percent" % (str(centralArcsec),str(previousRequest),centralArcsecThresholdPercent))
return False
else:
casalogPost("request for specific value but 'centralArcsec=auto %s' not within %d percent" % (str(centralArcsec),centralArcsecThresholdPercent))
return True
except:
# If there is any trouble reading the previous value, then return now.
casalogPost("Failed to parse floating point value.")
return True
else:
return False
def writeContDat(meanSpectrumFile, selection, png, aggregateBandwidth,
firstFreq, lastFreq, channelWidth, img, vis='',
numchan=None, chanInfo=None, lsrkwidth=None):
"""
Writes out an ASCII file called <meanSpectrumFile>_findContinuum.dat
that contains the selected channels, the png name and the aggregate
bandwidth in GHz.
Returns: None
"""
if (meanSpectrumFile.find('.meanSpectrum') > 0):
contDat = meanSpectrumFile.split('.meanSpectrum')[0] + '_findContinuum.dat'
else:
contDat = meanSpectrumFile + '_findContinuum.dat'
contDatDir = os.path.dirname(contDat)
if (firstFreq > lastFreq and channelWidth > 0):
# restore negative channel widths if appropriate
channelWidth *= -1
lsrkfreqs = 1e-9*np.arange(firstFreq, lastFreq+channelWidth*0.5, channelWidth)
if (len(contDatDir) < 1):
contDatDir = '.'
if (not os.access(contDatDir, os.W_OK) and contDatDir != '.'):
# Tf there is no write permission, then use the directory of the png
# since this has been established as writeable in runFindContinuum.
contDat = os.path.dirname(png) + '/' + os.path.basename(contDat)
# try:
if True:
f = open(contDat, 'w')
f.write('%s %s %g\n' % (selection, png, aggregateBandwidth))
if (len(vis) > 0):
# vis is a non-blank list or non-blank string
if (type(vis) == str):
vis = vis.split(',')
# vis is now assured to be a non-blank list
for v in vis:
casalogPost("Converting from LSRK to TOPO for vis = %s" % (v))
vselection = ''
for i,s in enumerate(selection.split(';')):
c0,c1 = [int(j) for j in s.split('~')]
minFreq = np.min([lsrkfreqs[c0],lsrkfreqs[c1]])-0.5*abs(channelWidth*1e-9)
maxFreq = np.max([lsrkfreqs[c0],lsrkfreqs[c1]])+0.5*abs(channelWidth*1e-9)
# print "Read channels: ", c0, c1
freqRange = '%.5fGHz~%.5fGHz' % (minFreq,maxFreq)
casalogPost("LSRK freqRange = %s" % str(freqRange))
result = cubeLSRKToTopo(img, freqRange, vis=v)*1e-9
# pipeline calls uvcontfit with GHz label only on upper freq
freqRange = '%.5f~%.5fGHz' % (np.min(result),np.max(result))
casalogPost("Topo freqRange = %s" % str(freqRange))
if (i > 0): vselection += ';'
vselection += freqRange
f.write('%s %s\n' % (v,vselection))
f.close()
casalogPost("Wrote %s" % (contDat))
# except:
# casalogPost("Failed to write %s" % (contDat))
def drawYlabel(img, typeOfMeanSpectrum, meanSpectrumMethod, meanSpectrumThreshold,
peakFilterFWHM, fontsize):
"""
Draws a descriptive y-axis label based on the origin and type of mean spectrum used.
Returns: None
"""
if (img == ''):
label = 'Mean spectrum passed in as ASCII file'
else:
if (meanSpectrumMethod.find('meanAboveThreshold') >= 0):
if (meanSpectrumMethod.find('OverMad') > 0):
label = '(Average spectrum > threshold=(%g))/MAD' % (roundFigures(meanSpectrumThreshold,3))
elif (meanSpectrumMethod.find('OverRms') > 0):
label = '(Average spectrum > threshold=(%g))/RMS' % (roundFigures(meanSpectrumThreshold,3))
else:
label = 'Average spectrum > threshold=(%g)' % (roundFigures(meanSpectrumThreshold,3))
elif (meanSpectrumMethod.find('peakOverMad')>=0):
if peakFilterFWHM > 1:
label = 'Per-channel (Peak / MAD) of image smoothed by FWHM=%d pixels' % (peakFilterFWHM)
else:
label = 'Per-channel (Peak / MAD)'
elif (meanSpectrumMethod.find('peakOverRms')>=0):
if peakFilterFWHM > 1:
label = 'Per-channel (Peak / RMS) of image smoothed by FWHM=%d pixels' % (peakFilterFWHM)
else:
label = 'Per-channel (Peak / RMS)'
pl.ylabel(typeOfMeanSpectrum+' '+label, size=fontsize)
def computeBandwidth(selection, channelWidth, loc=-1):
"""
selection: a string of format: '5~6;9~20'
channelWidth: in Hz
Returns: bandwidth in GHz
"""
# print "***%d***** Called computeBandwidth('%s', %s)" % (loc,selection, str(channelWidth))
ranges = selection.split(';')
channels = 0
for r in ranges:
result = r.split('~')
if (len(result) == 2):
a,b = result
channels += int(b)-int(a)+1
aggregateBW = channels * abs(channelWidth) * 1e-9
# print "********** channels = %d, channelWidth=%s, aggregateBW=%g" % (channels,str(channelWidth), aggregateBW)
return(aggregateBW)
def buildMeanSpectrumFilename(img, meanSpectrumMethod, peakFilterFWHM):
"""
Creates the name of the meanSpectrumFile to search for and/or create.
Returns: a string
"""
if (meanSpectrumMethod.find('peak')>=0):
return(img + '.meanSpectrum.'+meanSpectrumMethod+'_%d'%peakFilterFWHM)
else:
if (meanSpectrumMethod == 'meanAboveThreshold'):
return(img + '.meanSpectrum')
else:
return(img + '.meanSpectrum.'+meanSpectrumMethod)
def tdmSpectrum(channelWidth, nchan):
"""
Use 15e6 instead of 15.625e6 because LSRK channel width can be slightly narrower than TOPO.
Returns: True or False
"""
if ((channelWidth >= 15e6/2. and nchan>240) or # 1 pol TDM, must avoid 240-chan FDM
(channelWidth >= 15e6)):
# (channelWidth >= 15e6 and nchan<96) or # 2 pol TDM (128 chan)
# (channelWidth >= 30e6 and nchan<96)): # 4 pol TDM (64 chan)
return True
else:
return False
def atmosphereVariation(img, header, chanInfo, airmass=1.5, pwv=-1, removeSlope=True):
"""
Computes the absolute and percentage variation in atmospheric transmission
and sky temperature across an image cube.
Returns 5 values: max(Trans)-min(Trans), and as percentage of mean,
Max(Tsky)-min(Tsky), and as percentage of mean,
standard devation of Tsky
"""
freqs, values = CalcAtmTransmissionForImage(img, header, chanInfo, airmass=airmass, pwv=pwv, value='transmission')
if removeSlope:
slope, intercept = linfit(freqs, values, values*0.001)
casalogPost("Computed atmospheric variation and determined slope: %f per GHz (%.0f,%.2f)" % (slope,freqs[0],values[0]))
values = values - (freqs*slope + intercept) + np.mean(values)
maxMinusMin = np.max(values)-np.min(values)
percentage = maxMinusMin/np.mean(values)
freqs, values = CalcAtmTransmissionForImage(img, header, chanInfo, airmass=airmass, pwv=pwv, value='tsky')
if removeSlope:
slope, intercept = linfit(freqs, values, values*0.001)
values = values - (freqs*slope + intercept) + np.mean(values)
TmaxMinusMin = np.max(values)-np.min(values)
Tpercentage = TmaxMinusMin*100/np.mean(values)
stdValues = np.std(values)
return(maxMinusMin, percentage, TmaxMinusMin, Tpercentage, stdValues)
def runFindContinuum(img='', spw='', transition='', baselineModeA='min', baselineModeB='min',
sigmaCube=3, nBaselineChannels=0.19, sigmaFindContinuum='auto',
verbose=False, png='', pngBasename=False, nanBufferChannels=2,
source='', useAbsoluteValue=True, trimChannels='auto',
percentile=20, continuumThreshold=None, narrow='auto',
separator=';', overwrite=False, titleText='',
showAverageSpectrum=False, maxTrim=maxTrimDefault, maxTrimFraction=1.0,
meanSpectrumFile='', centralArcsec=-1, channelWidth=0,
alternateDirectory='.', imageInfo=[], chanInfo=[],
header='', plotAtmosphere='transmission', airmass=1.5, pwv=1.0,
channelFractionForSlopeRemoval=0.75, mask='',
invert=False, meanSpectrumMethod='peakOverMad',
peakFilterFWHM=15, fullLegend=False, iteration=0,
meanSpectrumMethodMessage='', minSlopeToRemove=1e-8,
minGroupsForSFCAdjustmentInPeakOverMad=10,
regressionTest=False, quadraticFit=False, megapixels=0,
triangularPatternSeen=False, maxMemory=-1, negativeThresholdFactor=1.15,
byteLimit=-1, singleContinuum=False, applyMaskToMask=False,
plotBaselinePoints=False, dropBaselineChannels=2.0,
madRatioUpperLimit=1.5, madRatioLowerLimit=1.15, projectCode=''):
"""
This function calls functions to:
1) compute the mean spectrum of a dirty cube
2) find the continuum channels
3) plot the results
Inputs: channelWidth: in Hz
Returns: 6 items
* A channel selection string suitable for the spw parameter of clean.
* The name of the png produced.
* The slope of the linear fit (or None if no fit attempted).
* The channel width in Hz (only necessary for the fitsTable option).
* nchan in the cube (only necessary for the fitsTable option).
* Boolean: True if it used low values as the baseline (as opposed to high values)
Inputs:
img: the image cube to operate upon
spw: the spw name or number to put in the x-axis label
transition: the name of the spectral transition (for the plot title)
baselineModeA: 'min' or 'edge', method to define the baseline in meanSpectrum()
baselineModeB: 'min' or 'edge', method to define the baseline in findContinuumChannels()
sigmaCube: multiply this value by the rms to get the threshold above which a pixel
is included in the mean spectrum
nBaselineChannels: if integer, then the number of channels to use in:
a) computing the mean spectrum with the 'meanAboveThreshold' methods.
b) computing the MAD of the lowest/highest channels in findContinuumChannels
if float, then the fraction of channels to use (i.e. the percentile)
default = 0.19, which is 24 channels (i.e. 12 on each side) of a TDM window
sigmaFindContinuum: passed to findContinuumChannels, 'auto' starts with 3.5
verbose: if True, then print additional information during processing
png: the name of the png to produce ('' yields default name)
pngBasename: if True, then remove the directory from img name before generating png name
nanBufferChannels: when removing or replacing NaNs, do this many extra channels
beyond their extent
source: the name of the source, to be shown in the title of the spectrum.
if None, then use the filename, up to the first underscore.
findContinuum: if True, then find the continuum channels before plotting
overwrite: if True, or ASCII file does not exist, then recalculate the mean spectrum
writing it to <img>.meanSpectrum
if False, then read the mean spectrum from the existing ASCII file
trimChannels: after doing best job of finding continuum, remove this many
channels from each edge of each block of channels found (for margin of safety)
If it is a float between 0..1, then trim this fraction of channels in each
group (rounding up). If it is 'auto', use 0.1 but not more than maxTrim channels
and not more than maxTrimFraction
percentile: control parameter used with baselineMode='min'
continuumThreshold: if specified, only use pixels above this intensity level
separator: the character to use to separate groups of channels in the string returned
narrow: the minimum number of channels that a group of channels must have to survive
if 0<narrow<1, then it is interpreted as the fraction of all
channels within identified blocks
if 'auto', then use int(ceil(log10(nchan)))
titleText: default is img name and transition and the control parameter values
showAverageSpectrum: make a two-panel plot, showing the raw mean spectrum in black
maxTrim: in trimChannels='auto', this is the max channels to trim per group for TDM spws; it is automatically scaled upward for FDM spws.
maxTrimFraction: in trimChannels='auto', the max fraction of channels to trim per group
meanSpectrumFile: an alternative ASCII text file to use for the mean spectrum.
Must also set img=''.
meanSpectrumMethod: 'peakOverMad', 'peakOverRms', 'meanAboveThreshold',
'meanAboveThresholdOverRms', 'meanAboveThresholdOverMad',
where 'peak' refers to the peak in a spatially-smoothed version of cube
peakFilterFWHM: value used by 'peakOverRms' and 'peakOverMad' to presmooth
each plane with a Gaussian kernel of this width (in pixels)
Set to 1 to not do any smoothing.
centralArcsec: radius of central box within which to compute the mean spectrum
default='auto' means start with whole field, then reduce to 1/10 if only
one window is found (unless mask is specified); or 'fwhm' for the central square
with the same radius as the PB FWHM; or a floating point value in arcseconds
mask: a mask image equal in shape to the parent image that is used to determine the
region to compute the noise (outside the mask) and the mean spectrum (inside the mask)
option 'auto' will look for the <filename>.mask that matches the <filename>.image
and if it finds it, it will use it; otherwise it will use no mask
plotAtmosphere: '', 'tsky', or 'transmission'
airmass: for plot of atmospheric transmission
pwv: in mm (for plot of atmospheric transmission)
channelFractionForSlopeRemoval: if at least this many channels are initially selected, or
if there are only 1-2 ranges found and the widest range has > nchan*0.3 channels, then
fit and remove a linear slope and re-identify continuum channels.
quadraticFit: if True, fit quadratic polynomial to the noise regions when appropriate;
otherwise fit only a linear slope
megapixels: simply used to label the plot
triangularPatternSeen: if True, then slightly boost sigmaFindContinuum if it is in 'auto' mode
maxMemory: only used to name the png if it is set
negativeThresholdFactor: scale the nominal negative threshold by this factor (to adjust
sensitivity to absorption features: smaller values=more sensitive)
applyMaskToMask: if True, apply the mask inside the user mask image to set its masked pixels to 0
plotBaselinePoints: if True, then plot the baseline-defining points as black dots
dropBaselineChannels: percentage of extreme values to drop in baseline mode 'min'
"""
casalogPost("%d) Current memory usage: %.3f GB, resident: %.3f GB" % (iteration+1, memoryUsage(), residentMemoryUsage()))
startTime = timeUtilities.time()
slope=None
replaceNans = True # This used to be a command-line option, but no longer.
img = img.rstrip('/')
fitsTable = False
typeOfMeanSpectrum = 'Existing'
narrowValueModified = None
if (meanSpectrumFile != '' and os.path.exists(meanSpectrumFile)):
casalogPost("Using existing meanSpectrumFile = %s" % (meanSpectrumFile))
if (is_binary(meanSpectrumFile)):
fitsTable = True
if ((type(nBaselineChannels) == float or type(nBaselineChannels) == np.float64) and not fitsTable):
# chanInfo will be == [] if an ASCII meanSpectrumFile is specified
if len(chanInfo) >= 4:
nchan, firstFreq, lastFreq, channelWidth = chanInfo
channelWidth = abs(channelWidth)
nBaselineChannels = int(round(nBaselineChannels*nchan))
casalogPost("Found %d channels in the cube" % (nchan))
if (nBaselineChannels < 2 and not fitsTable and len(chanInfo) >= 4):
casalogPost("You must have at least 2 edge channels (nBaselineChannels = %d)" % (nBaselineChannels))
return
if (meanSpectrumFile == ''):
meanSpectrumFile = buildMeanSpectrumFilename(img, meanSpectrumMethod, peakFilterFWHM)
elif (not os.path.exists(meanSpectrumFile)):
if (len(os.path.dirname(img)) > 0):
meanSpectrumFile = os.path.dirname(img) + '/' + os.path.basename(meanSpectrumFile)
if not overwrite:
if (os.path.exists(meanSpectrumFile) and img != ''):
if (maskArgumentMismatch(mask, meanSpectrumFile) and not fitsTable):
casalogPost("Regenerating the meanSpectrum since there is a mismatch in the mask argument.")
overwrite = True
else:
casalogPost("No mismatch in the mask argument vs. the meanSpectrum file.")
if (centralArcsecArgumentMismatch(centralArcsec, meanSpectrumFile, iteration) and not fitsTable):
casalogPost("Regenerating the meanSpectrum since there is a mismatch in the centralArcsec argument (%s)." % (str(centralArcsec)))
overwrite = True
else:
casalogPost("No mismatch in the centralArcsec argument vs. the meanSpectrum file.")
elif (img != ''):
casalogPost("Did not find mean spectrum file = %s" % (meanSpectrumFile))
if ((overwrite or not os.path.exists(meanSpectrumFile)) and not fitsTable):
casalogPost("A) Current memory usage: %.3f GB, resident: %.3f GB" % (memoryUsage(), residentMemoryUsage()))
if (overwrite):
casalogPost("Regenerating the mean spectrum file with centralArcsec=%s, mask='%s'." % (str(centralArcsec),mask))
else:
casalogPost("Generating the mean spectrum file with centralArcsec=%s, mask='%s'." % (str(centralArcsec),mask))
typeOfMeanSpectrum = 'Computed'
result = meanSpectrum(img, nBaselineChannels, sigmaCube, verbose,
nanBufferChannels,useAbsoluteValue,