[1846] | 1 | """This module defines the scantable class.""" |
---|
| 2 | |
---|
[1697] | 3 | import os |
---|
[2751] | 4 | import re |
---|
[2315] | 5 | import tempfile |
---|
[1948] | 6 | import numpy |
---|
[1691] | 7 | try: |
---|
| 8 | from functools import wraps as wraps_dec |
---|
| 9 | except ImportError: |
---|
| 10 | from asap.compatibility import wraps as wraps_dec |
---|
| 11 | |
---|
[1824] | 12 | from asap.env import is_casapy |
---|
[876] | 13 | from asap._asap import Scantable |
---|
[2004] | 14 | from asap._asap import filler, msfiller |
---|
[1824] | 15 | from asap.parameters import rcParams |
---|
[1862] | 16 | from asap.logging import asaplog, asaplog_post_dec |
---|
[1824] | 17 | from asap.selector import selector |
---|
| 18 | from asap.linecatalog import linecatalog |
---|
[1600] | 19 | from asap.coordinate import coordinate |
---|
[1859] | 20 | from asap.utils import _n_bools, mask_not, mask_and, mask_or, page |
---|
[1907] | 21 | from asap.asapfitter import fitter |
---|
[102] | 22 | |
---|
[1689] | 23 | def preserve_selection(func): |
---|
[1691] | 24 | @wraps_dec(func) |
---|
[1689] | 25 | def wrap(obj, *args, **kw): |
---|
| 26 | basesel = obj.get_selection() |
---|
[1857] | 27 | try: |
---|
| 28 | val = func(obj, *args, **kw) |
---|
| 29 | finally: |
---|
| 30 | obj.set_selection(basesel) |
---|
[1689] | 31 | return val |
---|
| 32 | return wrap |
---|
| 33 | |
---|
[1846] | 34 | def is_scantable(filename): |
---|
| 35 | """Is the given file a scantable? |
---|
[1689] | 36 | |
---|
[1846] | 37 | Parameters: |
---|
| 38 | |
---|
| 39 | filename: the name of the file/directory to test |
---|
| 40 | |
---|
| 41 | """ |
---|
[1883] | 42 | if ( os.path.isdir(filename) |
---|
| 43 | and os.path.exists(filename+'/table.info') |
---|
| 44 | and os.path.exists(filename+'/table.dat') ): |
---|
| 45 | f=open(filename+'/table.info') |
---|
| 46 | l=f.readline() |
---|
| 47 | f.close() |
---|
[2753] | 48 | match_pattern = '^Type = (Scantable)? *$' |
---|
[2751] | 49 | if re.match(match_pattern,l): |
---|
[1883] | 50 | return True |
---|
| 51 | else: |
---|
| 52 | return False |
---|
| 53 | else: |
---|
| 54 | return False |
---|
| 55 | ## return (os.path.isdir(filename) |
---|
| 56 | ## and not os.path.exists(filename+'/table.f1') |
---|
| 57 | ## and os.path.exists(filename+'/table.info')) |
---|
[1697] | 58 | |
---|
[1883] | 59 | def is_ms(filename): |
---|
| 60 | """Is the given file a MeasurementSet? |
---|
[1697] | 61 | |
---|
[1883] | 62 | Parameters: |
---|
| 63 | |
---|
| 64 | filename: the name of the file/directory to test |
---|
| 65 | |
---|
| 66 | """ |
---|
| 67 | if ( os.path.isdir(filename) |
---|
| 68 | and os.path.exists(filename+'/table.info') |
---|
| 69 | and os.path.exists(filename+'/table.dat') ): |
---|
| 70 | f=open(filename+'/table.info') |
---|
| 71 | l=f.readline() |
---|
| 72 | f.close() |
---|
| 73 | if ( l.find('Measurement Set') != -1 ): |
---|
| 74 | return True |
---|
| 75 | else: |
---|
| 76 | return False |
---|
| 77 | else: |
---|
| 78 | return False |
---|
[2186] | 79 | |
---|
| 80 | def normalise_edge_param(edge): |
---|
| 81 | """\ |
---|
| 82 | Convert a given edge value to a one-dimensional array that can be |
---|
| 83 | given to baseline-fitting/subtraction functions. |
---|
| 84 | The length of the output value will be an even because values for |
---|
| 85 | the both sides of spectra are to be contained for each IF. When |
---|
| 86 | the length is 2, the values will be applied to all IFs. If the length |
---|
| 87 | is larger than 2, it will be 2*ifnos(). |
---|
| 88 | Accepted format of edge include: |
---|
| 89 | * an integer - will be used for both sides of spectra of all IFs. |
---|
| 90 | e.g. 10 is converted to [10,10] |
---|
[2277] | 91 | * an empty list/tuple [] - converted to [0, 0] and used for all IFs. |
---|
[2186] | 92 | * a list/tuple containing an integer - same as the above case. |
---|
| 93 | e.g. [10] is converted to [10,10] |
---|
| 94 | * a list/tuple containing two integers - will be used for all IFs. |
---|
| 95 | e.g. [5,10] is output as it is. no need to convert. |
---|
| 96 | * a list/tuple of lists/tuples containing TWO integers - |
---|
| 97 | each element of edge will be used for each IF. |
---|
[2277] | 98 | e.g. [[5,10],[15,20]] - [5,10] for IF[0] and [15,20] for IF[1]. |
---|
| 99 | |
---|
| 100 | If an element contains the same integer values, the input 'edge' |
---|
| 101 | parameter can be given in a simpler shape in the following cases: |
---|
[2186] | 102 | ** when len(edge)!=2 |
---|
[2277] | 103 | any elements containing the same values can be replaced |
---|
| 104 | to single integers. |
---|
| 105 | e.g. [[15,15]] can be simplified to [15] (or [15,15] or 15 also). |
---|
| 106 | e.g. [[1,1],[2,2],[3,3]] can be simplified to [1,2,3]. |
---|
[2186] | 107 | ** when len(edge)=2 |
---|
| 108 | care is needed for this case: ONLY ONE of the |
---|
| 109 | elements can be a single integer, |
---|
| 110 | e.g. [[5,5],[10,10]] can be simplified to [5,[10,10]] |
---|
[2277] | 111 | or [[5,5],10], but can NOT be simplified to [5,10]. |
---|
[2186] | 112 | when [5,10] given, it is interpreted as |
---|
[2277] | 113 | [[5,10],[5,10],[5,10],...] instead, as shown before. |
---|
[2186] | 114 | """ |
---|
| 115 | from asap import _is_sequence_or_number as _is_valid |
---|
| 116 | if isinstance(edge, list) or isinstance(edge, tuple): |
---|
| 117 | for edgepar in edge: |
---|
| 118 | if not _is_valid(edgepar, int): |
---|
| 119 | raise ValueError, "Each element of the 'edge' tuple has \ |
---|
| 120 | to be a pair of integers or an integer." |
---|
| 121 | if isinstance(edgepar, list) or isinstance(edgepar, tuple): |
---|
| 122 | if len(edgepar) != 2: |
---|
| 123 | raise ValueError, "Each element of the 'edge' tuple has \ |
---|
| 124 | to be a pair of integers or an integer." |
---|
| 125 | else: |
---|
| 126 | if not _is_valid(edge, int): |
---|
| 127 | raise ValueError, "Parameter 'edge' has to be an integer or a \ |
---|
| 128 | pair of integers specified as a tuple. \ |
---|
| 129 | Nested tuples are allowed \ |
---|
| 130 | to make individual selection for different IFs." |
---|
| 131 | |
---|
| 132 | |
---|
| 133 | if isinstance(edge, int): |
---|
| 134 | edge = [ edge, edge ] # e.g. 3 => [3,3] |
---|
| 135 | elif isinstance(edge, list) or isinstance(edge, tuple): |
---|
| 136 | if len(edge) == 0: |
---|
| 137 | edge = [0, 0] # e.g. [] => [0,0] |
---|
| 138 | elif len(edge) == 1: |
---|
| 139 | if isinstance(edge[0], int): |
---|
| 140 | edge = [ edge[0], edge[0] ] # e.g. [1] => [1,1] |
---|
| 141 | |
---|
| 142 | commonedge = True |
---|
| 143 | if len(edge) > 2: commonedge = False |
---|
| 144 | else: |
---|
| 145 | for edgepar in edge: |
---|
| 146 | if isinstance(edgepar, list) or isinstance(edgepar, tuple): |
---|
| 147 | commonedge = False |
---|
| 148 | break |
---|
| 149 | |
---|
| 150 | if commonedge: |
---|
| 151 | if len(edge) > 1: |
---|
| 152 | norm_edge = edge |
---|
| 153 | else: |
---|
| 154 | norm_edge = edge + edge |
---|
| 155 | else: |
---|
| 156 | norm_edge = [] |
---|
| 157 | for edgepar in edge: |
---|
| 158 | if isinstance(edgepar, int): |
---|
| 159 | norm_edge += [edgepar, edgepar] |
---|
| 160 | else: |
---|
| 161 | norm_edge += edgepar |
---|
| 162 | |
---|
| 163 | return norm_edge |
---|
| 164 | |
---|
| 165 | def raise_fitting_failure_exception(e): |
---|
| 166 | msg = "The fit failed, possibly because it didn't converge." |
---|
| 167 | if rcParams["verbose"]: |
---|
| 168 | asaplog.push(str(e)) |
---|
| 169 | asaplog.push(str(msg)) |
---|
| 170 | else: |
---|
| 171 | raise RuntimeError(str(e)+'\n'+msg) |
---|
| 172 | |
---|
[2189] | 173 | def pack_progress_params(showprogress, minnrow): |
---|
| 174 | return str(showprogress).lower() + ',' + str(minnrow) |
---|
| 175 | |
---|
[876] | 176 | class scantable(Scantable): |
---|
[1846] | 177 | """\ |
---|
| 178 | The ASAP container for scans (single-dish data). |
---|
[102] | 179 | """ |
---|
[1819] | 180 | |
---|
[1862] | 181 | @asaplog_post_dec |
---|
[2315] | 182 | def __init__(self, filename, average=None, unit=None, parallactify=None, |
---|
| 183 | **args): |
---|
[1846] | 184 | """\ |
---|
[102] | 185 | Create a scantable from a saved one or make a reference |
---|
[1846] | 186 | |
---|
[102] | 187 | Parameters: |
---|
[1846] | 188 | |
---|
| 189 | filename: the name of an asap table on disk |
---|
| 190 | or |
---|
| 191 | the name of a rpfits/sdfits/ms file |
---|
| 192 | (integrations within scans are auto averaged |
---|
| 193 | and the whole file is read) or |
---|
| 194 | [advanced] a reference to an existing scantable |
---|
| 195 | |
---|
| 196 | average: average all integrations withinb a scan on read. |
---|
| 197 | The default (True) is taken from .asaprc. |
---|
| 198 | |
---|
[484] | 199 | unit: brightness unit; must be consistent with K or Jy. |
---|
[1846] | 200 | Over-rides the default selected by the filler |
---|
| 201 | (input rpfits/sdfits/ms) or replaces the value |
---|
| 202 | in existing scantables |
---|
| 203 | |
---|
[1920] | 204 | antenna: for MeasurementSet input data only: |
---|
[2349] | 205 | Antenna selection. integer (id) or string |
---|
| 206 | (name or id). |
---|
[1846] | 207 | |
---|
[2349] | 208 | parallactify: Indicate that the data had been parallactified. |
---|
| 209 | Default (false) is taken from rc file. |
---|
[1846] | 210 | |
---|
[710] | 211 | """ |
---|
[976] | 212 | if average is None: |
---|
[710] | 213 | average = rcParams['scantable.autoaverage'] |
---|
[1593] | 214 | parallactify = parallactify or rcParams['scantable.parallactify'] |
---|
[1259] | 215 | varlist = vars() |
---|
[876] | 216 | from asap._asap import stmath |
---|
[1819] | 217 | self._math = stmath( rcParams['insitu'] ) |
---|
[876] | 218 | if isinstance(filename, Scantable): |
---|
| 219 | Scantable.__init__(self, filename) |
---|
[181] | 220 | else: |
---|
[1697] | 221 | if isinstance(filename, str): |
---|
[976] | 222 | filename = os.path.expandvars(filename) |
---|
| 223 | filename = os.path.expanduser(filename) |
---|
| 224 | if not os.path.exists(filename): |
---|
| 225 | s = "File '%s' not found." % (filename) |
---|
| 226 | raise IOError(s) |
---|
[1697] | 227 | if is_scantable(filename): |
---|
| 228 | ondisk = rcParams['scantable.storage'] == 'disk' |
---|
| 229 | Scantable.__init__(self, filename, ondisk) |
---|
| 230 | if unit is not None: |
---|
| 231 | self.set_fluxunit(unit) |
---|
[2008] | 232 | if average: |
---|
| 233 | self._assign( self.average_time( scanav=True ) ) |
---|
[1819] | 234 | # do not reset to the default freqframe |
---|
| 235 | #self.set_freqframe(rcParams['scantable.freqframe']) |
---|
[1883] | 236 | elif is_ms(filename): |
---|
[1916] | 237 | # Measurement Set |
---|
| 238 | opts={'ms': {}} |
---|
[2753] | 239 | mskeys=['getpt','antenna','freq_tolsr'] |
---|
[1916] | 240 | for key in mskeys: |
---|
| 241 | if key in args.keys(): |
---|
| 242 | opts['ms'][key] = args[key] |
---|
| 243 | self._fill([filename], unit, average, opts) |
---|
[1893] | 244 | elif os.path.isfile(filename): |
---|
[1916] | 245 | self._fill([filename], unit, average) |
---|
[2350] | 246 | # only apply to new data not "copy constructor" |
---|
| 247 | self.parallactify(parallactify) |
---|
[1883] | 248 | else: |
---|
[1819] | 249 | msg = "The given file '%s'is not a valid " \ |
---|
| 250 | "asap table." % (filename) |
---|
[1859] | 251 | raise IOError(msg) |
---|
[1118] | 252 | elif (isinstance(filename, list) or isinstance(filename, tuple)) \ |
---|
[976] | 253 | and isinstance(filename[-1], str): |
---|
[1916] | 254 | self._fill(filename, unit, average) |
---|
[1586] | 255 | self.parallactify(parallactify) |
---|
[1259] | 256 | self._add_history("scantable", varlist) |
---|
[102] | 257 | |
---|
[1862] | 258 | @asaplog_post_dec |
---|
[876] | 259 | def save(self, name=None, format=None, overwrite=False): |
---|
[1846] | 260 | """\ |
---|
[1280] | 261 | Store the scantable on disk. This can be an asap (aips++) Table, |
---|
| 262 | SDFITS or MS2 format. |
---|
[1846] | 263 | |
---|
[116] | 264 | Parameters: |
---|
[1846] | 265 | |
---|
[2431] | 266 | name: the name of the outputfile. For format 'ASCII' |
---|
[1093] | 267 | this is the root file name (data in 'name'.txt |
---|
[497] | 268 | and header in 'name'_header.txt) |
---|
[1855] | 269 | |
---|
[116] | 270 | format: an optional file format. Default is ASAP. |
---|
[1855] | 271 | Allowed are: |
---|
| 272 | |
---|
| 273 | * 'ASAP' (save as ASAP [aips++] Table), |
---|
| 274 | * 'SDFITS' (save as SDFITS file) |
---|
| 275 | * 'ASCII' (saves as ascii text file) |
---|
| 276 | * 'MS2' (saves as an casacore MeasurementSet V2) |
---|
[2315] | 277 | * 'FITS' (save as image FITS - not readable by |
---|
| 278 | class) |
---|
[1855] | 279 | * 'CLASS' (save as FITS readable by CLASS) |
---|
| 280 | |
---|
[411] | 281 | overwrite: If the file should be overwritten if it exists. |
---|
[256] | 282 | The default False is to return with warning |
---|
[411] | 283 | without writing the output. USE WITH CARE. |
---|
[1855] | 284 | |
---|
[1846] | 285 | Example:: |
---|
| 286 | |
---|
[116] | 287 | scan.save('myscan.asap') |
---|
[1118] | 288 | scan.save('myscan.sdfits', 'SDFITS') |
---|
[1846] | 289 | |
---|
[116] | 290 | """ |
---|
[411] | 291 | from os import path |
---|
[1593] | 292 | format = format or rcParams['scantable.save'] |
---|
[256] | 293 | suffix = '.'+format.lower() |
---|
[1118] | 294 | if name is None or name == "": |
---|
[256] | 295 | name = 'scantable'+suffix |
---|
[718] | 296 | msg = "No filename given. Using default name %s..." % name |
---|
| 297 | asaplog.push(msg) |
---|
[411] | 298 | name = path.expandvars(name) |
---|
[256] | 299 | if path.isfile(name) or path.isdir(name): |
---|
| 300 | if not overwrite: |
---|
[718] | 301 | msg = "File %s exists." % name |
---|
[1859] | 302 | raise IOError(msg) |
---|
[451] | 303 | format2 = format.upper() |
---|
| 304 | if format2 == 'ASAP': |
---|
[116] | 305 | self._save(name) |
---|
[2029] | 306 | elif format2 == 'MS2': |
---|
| 307 | msopt = {'ms': {'overwrite': overwrite } } |
---|
| 308 | from asap._asap import mswriter |
---|
| 309 | writer = mswriter( self ) |
---|
| 310 | writer.write( name, msopt ) |
---|
[116] | 311 | else: |
---|
[989] | 312 | from asap._asap import stwriter as stw |
---|
[1118] | 313 | writer = stw(format2) |
---|
| 314 | writer.write(self, name) |
---|
[116] | 315 | return |
---|
| 316 | |
---|
[102] | 317 | def copy(self): |
---|
[1846] | 318 | """Return a copy of this scantable. |
---|
| 319 | |
---|
| 320 | *Note*: |
---|
| 321 | |
---|
[1348] | 322 | This makes a full (deep) copy. scan2 = scan1 makes a reference. |
---|
[1846] | 323 | |
---|
| 324 | Example:: |
---|
| 325 | |
---|
[102] | 326 | copiedscan = scan.copy() |
---|
[1846] | 327 | |
---|
[102] | 328 | """ |
---|
[876] | 329 | sd = scantable(Scantable._copy(self)) |
---|
[113] | 330 | return sd |
---|
| 331 | |
---|
[1093] | 332 | def drop_scan(self, scanid=None): |
---|
[1846] | 333 | """\ |
---|
[1093] | 334 | Return a new scantable where the specified scan number(s) has(have) |
---|
| 335 | been dropped. |
---|
[1846] | 336 | |
---|
[1093] | 337 | Parameters: |
---|
[1846] | 338 | |
---|
[1093] | 339 | scanid: a (list of) scan number(s) |
---|
[1846] | 340 | |
---|
[1093] | 341 | """ |
---|
| 342 | from asap import _is_sequence_or_number as _is_valid |
---|
| 343 | from asap import _to_list |
---|
| 344 | from asap import unique |
---|
| 345 | if not _is_valid(scanid): |
---|
[2315] | 346 | raise RuntimeError( 'Please specify a scanno to drop from the' |
---|
| 347 | ' scantable' ) |
---|
[1859] | 348 | scanid = _to_list(scanid) |
---|
| 349 | allscans = unique([ self.getscan(i) for i in range(self.nrow())]) |
---|
| 350 | for sid in scanid: allscans.remove(sid) |
---|
| 351 | if len(allscans) == 0: |
---|
| 352 | raise ValueError("Can't remove all scans") |
---|
| 353 | sel = selector(scans=allscans) |
---|
| 354 | return self._select_copy(sel) |
---|
[1093] | 355 | |
---|
[1594] | 356 | def _select_copy(self, selection): |
---|
| 357 | orig = self.get_selection() |
---|
| 358 | self.set_selection(orig+selection) |
---|
| 359 | cp = self.copy() |
---|
| 360 | self.set_selection(orig) |
---|
| 361 | return cp |
---|
| 362 | |
---|
[102] | 363 | def get_scan(self, scanid=None): |
---|
[1855] | 364 | """\ |
---|
[102] | 365 | Return a specific scan (by scanno) or collection of scans (by |
---|
| 366 | source name) in a new scantable. |
---|
[1846] | 367 | |
---|
| 368 | *Note*: |
---|
| 369 | |
---|
[1348] | 370 | See scantable.drop_scan() for the inverse operation. |
---|
[1846] | 371 | |
---|
[102] | 372 | Parameters: |
---|
[1846] | 373 | |
---|
[513] | 374 | scanid: a (list of) scanno or a source name, unix-style |
---|
| 375 | patterns are accepted for source name matching, e.g. |
---|
| 376 | '*_R' gets all 'ref scans |
---|
[1846] | 377 | |
---|
| 378 | Example:: |
---|
| 379 | |
---|
[513] | 380 | # get all scans containing the source '323p459' |
---|
| 381 | newscan = scan.get_scan('323p459') |
---|
| 382 | # get all 'off' scans |
---|
| 383 | refscans = scan.get_scan('*_R') |
---|
| 384 | # get a susbset of scans by scanno (as listed in scan.summary()) |
---|
[1118] | 385 | newscan = scan.get_scan([0, 2, 7, 10]) |
---|
[1846] | 386 | |
---|
[102] | 387 | """ |
---|
| 388 | if scanid is None: |
---|
[1859] | 389 | raise RuntimeError( 'Please specify a scan no or name to ' |
---|
| 390 | 'retrieve from the scantable' ) |
---|
[102] | 391 | try: |
---|
[946] | 392 | bsel = self.get_selection() |
---|
| 393 | sel = selector() |
---|
[102] | 394 | if type(scanid) is str: |
---|
[946] | 395 | sel.set_name(scanid) |
---|
[1594] | 396 | return self._select_copy(sel) |
---|
[102] | 397 | elif type(scanid) is int: |
---|
[946] | 398 | sel.set_scans([scanid]) |
---|
[1594] | 399 | return self._select_copy(sel) |
---|
[381] | 400 | elif type(scanid) is list: |
---|
[946] | 401 | sel.set_scans(scanid) |
---|
[1594] | 402 | return self._select_copy(sel) |
---|
[381] | 403 | else: |
---|
[718] | 404 | msg = "Illegal scanid type, use 'int' or 'list' if ints." |
---|
[1859] | 405 | raise TypeError(msg) |
---|
[102] | 406 | except RuntimeError: |
---|
[1859] | 407 | raise |
---|
[102] | 408 | |
---|
| 409 | def __str__(self): |
---|
[2315] | 410 | tempFile = tempfile.NamedTemporaryFile() |
---|
| 411 | Scantable._summary(self, tempFile.name) |
---|
| 412 | tempFile.seek(0) |
---|
| 413 | asaplog.clear() |
---|
| 414 | return tempFile.file.read() |
---|
[102] | 415 | |
---|
[2315] | 416 | @asaplog_post_dec |
---|
[976] | 417 | def summary(self, filename=None): |
---|
[1846] | 418 | """\ |
---|
[102] | 419 | Print a summary of the contents of this scantable. |
---|
[1846] | 420 | |
---|
[102] | 421 | Parameters: |
---|
[1846] | 422 | |
---|
[1931] | 423 | filename: the name of a file to write the putput to |
---|
[102] | 424 | Default - no file output |
---|
[1846] | 425 | |
---|
[102] | 426 | """ |
---|
| 427 | if filename is not None: |
---|
[256] | 428 | if filename is "": |
---|
| 429 | filename = 'scantable_summary.txt' |
---|
[415] | 430 | from os.path import expandvars, isdir |
---|
[411] | 431 | filename = expandvars(filename) |
---|
[2286] | 432 | if isdir(filename): |
---|
[718] | 433 | msg = "Illegal file name '%s'." % (filename) |
---|
[1859] | 434 | raise IOError(msg) |
---|
[2286] | 435 | else: |
---|
| 436 | filename = "" |
---|
| 437 | Scantable._summary(self, filename) |
---|
[710] | 438 | |
---|
[1512] | 439 | def get_spectrum(self, rowno): |
---|
[1471] | 440 | """Return the spectrum for the current row in the scantable as a list. |
---|
[1846] | 441 | |
---|
[1471] | 442 | Parameters: |
---|
[1846] | 443 | |
---|
[1573] | 444 | rowno: the row number to retrieve the spectrum from |
---|
[1846] | 445 | |
---|
[1471] | 446 | """ |
---|
| 447 | return self._getspectrum(rowno) |
---|
[946] | 448 | |
---|
[1471] | 449 | def get_mask(self, rowno): |
---|
| 450 | """Return the mask for the current row in the scantable as a list. |
---|
[1846] | 451 | |
---|
[1471] | 452 | Parameters: |
---|
[1846] | 453 | |
---|
[1573] | 454 | rowno: the row number to retrieve the mask from |
---|
[1846] | 455 | |
---|
[1471] | 456 | """ |
---|
| 457 | return self._getmask(rowno) |
---|
| 458 | |
---|
| 459 | def set_spectrum(self, spec, rowno): |
---|
[1938] | 460 | """Set the spectrum for the current row in the scantable. |
---|
[1846] | 461 | |
---|
[1471] | 462 | Parameters: |
---|
[1846] | 463 | |
---|
[1855] | 464 | spec: the new spectrum |
---|
[1846] | 465 | |
---|
[1855] | 466 | rowno: the row number to set the spectrum for |
---|
| 467 | |
---|
[1471] | 468 | """ |
---|
[2348] | 469 | assert(len(spec) == self.nchan(self.getif(rowno))) |
---|
[1471] | 470 | return self._setspectrum(spec, rowno) |
---|
| 471 | |
---|
[1600] | 472 | def get_coordinate(self, rowno): |
---|
| 473 | """Return the (spectral) coordinate for a a given 'rowno'. |
---|
[1846] | 474 | |
---|
| 475 | *Note*: |
---|
| 476 | |
---|
[1600] | 477 | * This coordinate is only valid until a scantable method modifies |
---|
| 478 | the frequency axis. |
---|
| 479 | * This coordinate does contain the original frequency set-up |
---|
| 480 | NOT the new frame. The conversions however are done using the user |
---|
| 481 | specified frame (e.g. LSRK/TOPO). To get the 'real' coordinate, |
---|
| 482 | use scantable.freq_align first. Without it there is no closure, |
---|
[1846] | 483 | i.e.:: |
---|
[1600] | 484 | |
---|
[1846] | 485 | c = myscan.get_coordinate(0) |
---|
| 486 | c.to_frequency(c.get_reference_pixel()) != c.get_reference_value() |
---|
| 487 | |
---|
[1600] | 488 | Parameters: |
---|
[1846] | 489 | |
---|
[1600] | 490 | rowno: the row number for the spectral coordinate |
---|
| 491 | |
---|
| 492 | """ |
---|
| 493 | return coordinate(Scantable.get_coordinate(self, rowno)) |
---|
| 494 | |
---|
[946] | 495 | def get_selection(self): |
---|
[1846] | 496 | """\ |
---|
[1005] | 497 | Get the selection object currently set on this scantable. |
---|
[1846] | 498 | |
---|
| 499 | Example:: |
---|
| 500 | |
---|
[1005] | 501 | sel = scan.get_selection() |
---|
| 502 | sel.set_ifs(0) # select IF 0 |
---|
| 503 | scan.set_selection(sel) # apply modified selection |
---|
[1846] | 504 | |
---|
[946] | 505 | """ |
---|
| 506 | return selector(self._getselection()) |
---|
| 507 | |
---|
[1576] | 508 | def set_selection(self, selection=None, **kw): |
---|
[1846] | 509 | """\ |
---|
[1005] | 510 | Select a subset of the data. All following operations on this scantable |
---|
| 511 | are only applied to thi selection. |
---|
[1846] | 512 | |
---|
[1005] | 513 | Parameters: |
---|
[1697] | 514 | |
---|
[1846] | 515 | selection: a selector object (default unset the selection), or |
---|
[2431] | 516 | any combination of 'pols', 'ifs', 'beams', 'scans', |
---|
| 517 | 'cycles', 'name', 'query' |
---|
[1697] | 518 | |
---|
[1846] | 519 | Examples:: |
---|
[1697] | 520 | |
---|
[1005] | 521 | sel = selector() # create a selection object |
---|
[1118] | 522 | self.set_scans([0, 3]) # select SCANNO 0 and 3 |
---|
[1005] | 523 | scan.set_selection(sel) # set the selection |
---|
| 524 | scan.summary() # will only print summary of scanno 0 an 3 |
---|
| 525 | scan.set_selection() # unset the selection |
---|
[1697] | 526 | # or the equivalent |
---|
| 527 | scan.set_selection(scans=[0,3]) |
---|
| 528 | scan.summary() # will only print summary of scanno 0 an 3 |
---|
| 529 | scan.set_selection() # unset the selection |
---|
[1846] | 530 | |
---|
[946] | 531 | """ |
---|
[1576] | 532 | if selection is None: |
---|
| 533 | # reset |
---|
| 534 | if len(kw) == 0: |
---|
| 535 | selection = selector() |
---|
| 536 | else: |
---|
| 537 | # try keywords |
---|
| 538 | for k in kw: |
---|
| 539 | if k not in selector.fields: |
---|
[2320] | 540 | raise KeyError("Invalid selection key '%s', " |
---|
| 541 | "valid keys are %s" % (k, |
---|
| 542 | selector.fields)) |
---|
[1576] | 543 | selection = selector(**kw) |
---|
[946] | 544 | self._setselection(selection) |
---|
| 545 | |
---|
[1819] | 546 | def get_row(self, row=0, insitu=None): |
---|
[1846] | 547 | """\ |
---|
[1819] | 548 | Select a row in the scantable. |
---|
| 549 | Return a scantable with single row. |
---|
[1846] | 550 | |
---|
[1819] | 551 | Parameters: |
---|
[1846] | 552 | |
---|
| 553 | row: row no of integration, default is 0. |
---|
| 554 | insitu: if False a new scantable is returned. Otherwise, the |
---|
| 555 | scaling is done in-situ. The default is taken from .asaprc |
---|
| 556 | (False) |
---|
| 557 | |
---|
[1819] | 558 | """ |
---|
[2349] | 559 | if insitu is None: |
---|
| 560 | insitu = rcParams['insitu'] |
---|
[1819] | 561 | if not insitu: |
---|
| 562 | workscan = self.copy() |
---|
| 563 | else: |
---|
| 564 | workscan = self |
---|
| 565 | # Select a row |
---|
[2349] | 566 | sel = selector() |
---|
[1992] | 567 | sel.set_rows([row]) |
---|
[1819] | 568 | workscan.set_selection(sel) |
---|
| 569 | if not workscan.nrow() == 1: |
---|
[2349] | 570 | msg = "Could not identify single row. %d rows selected." \ |
---|
| 571 | % (workscan.nrow()) |
---|
[1819] | 572 | raise RuntimeError(msg) |
---|
| 573 | if insitu: |
---|
| 574 | self._assign(workscan) |
---|
| 575 | else: |
---|
| 576 | return workscan |
---|
| 577 | |
---|
[1862] | 578 | @asaplog_post_dec |
---|
[1907] | 579 | def stats(self, stat='stddev', mask=None, form='3.3f', row=None): |
---|
[1846] | 580 | """\ |
---|
[135] | 581 | Determine the specified statistic of the current beam/if/pol |
---|
[102] | 582 | Takes a 'mask' as an optional parameter to specify which |
---|
| 583 | channels should be excluded. |
---|
[1846] | 584 | |
---|
[102] | 585 | Parameters: |
---|
[1846] | 586 | |
---|
[1819] | 587 | stat: 'min', 'max', 'min_abc', 'max_abc', 'sumsq', 'sum', |
---|
| 588 | 'mean', 'var', 'stddev', 'avdev', 'rms', 'median' |
---|
[1855] | 589 | |
---|
[135] | 590 | mask: an optional mask specifying where the statistic |
---|
[102] | 591 | should be determined. |
---|
[1855] | 592 | |
---|
[1819] | 593 | form: format string to print statistic values |
---|
[1846] | 594 | |
---|
[1907] | 595 | row: row number of spectrum to process. |
---|
| 596 | (default is None: for all rows) |
---|
[1846] | 597 | |
---|
[1907] | 598 | Example: |
---|
[113] | 599 | scan.set_unit('channel') |
---|
[1118] | 600 | msk = scan.create_mask([100, 200], [500, 600]) |
---|
[135] | 601 | scan.stats(stat='mean', mask=m) |
---|
[1846] | 602 | |
---|
[102] | 603 | """ |
---|
[1593] | 604 | mask = mask or [] |
---|
[876] | 605 | if not self._check_ifs(): |
---|
[1118] | 606 | raise ValueError("Cannot apply mask as the IFs have different " |
---|
| 607 | "number of channels. Please use setselection() " |
---|
| 608 | "to select individual IFs") |
---|
[1819] | 609 | rtnabc = False |
---|
| 610 | if stat.lower().endswith('_abc'): rtnabc = True |
---|
| 611 | getchan = False |
---|
| 612 | if stat.lower().startswith('min') or stat.lower().startswith('max'): |
---|
| 613 | chan = self._math._minmaxchan(self, mask, stat) |
---|
| 614 | getchan = True |
---|
| 615 | statvals = [] |
---|
[1907] | 616 | if not rtnabc: |
---|
| 617 | if row == None: |
---|
| 618 | statvals = self._math._stats(self, mask, stat) |
---|
| 619 | else: |
---|
| 620 | statvals = self._math._statsrow(self, mask, stat, int(row)) |
---|
[256] | 621 | |
---|
[1819] | 622 | #def cb(i): |
---|
| 623 | # return statvals[i] |
---|
[256] | 624 | |
---|
[1819] | 625 | #return self._row_callback(cb, stat) |
---|
[102] | 626 | |
---|
[1819] | 627 | label=stat |
---|
| 628 | #callback=cb |
---|
| 629 | out = "" |
---|
| 630 | #outvec = [] |
---|
| 631 | sep = '-'*50 |
---|
[1907] | 632 | |
---|
| 633 | if row == None: |
---|
| 634 | rows = xrange(self.nrow()) |
---|
| 635 | elif isinstance(row, int): |
---|
| 636 | rows = [ row ] |
---|
| 637 | |
---|
| 638 | for i in rows: |
---|
[1819] | 639 | refstr = '' |
---|
| 640 | statunit= '' |
---|
| 641 | if getchan: |
---|
| 642 | qx, qy = self.chan2data(rowno=i, chan=chan[i]) |
---|
| 643 | if rtnabc: |
---|
| 644 | statvals.append(qx['value']) |
---|
| 645 | refstr = ('(value: %'+form) % (qy['value'])+' ['+qy['unit']+'])' |
---|
| 646 | statunit= '['+qx['unit']+']' |
---|
| 647 | else: |
---|
| 648 | refstr = ('(@ %'+form) % (qx['value'])+' ['+qx['unit']+'])' |
---|
| 649 | |
---|
| 650 | tm = self._gettime(i) |
---|
| 651 | src = self._getsourcename(i) |
---|
| 652 | out += 'Scan[%d] (%s) ' % (self.getscan(i), src) |
---|
| 653 | out += 'Time[%s]:\n' % (tm) |
---|
[1907] | 654 | if self.nbeam(-1) > 1: out += ' Beam[%d] ' % (self.getbeam(i)) |
---|
| 655 | if self.nif(-1) > 1: out += ' IF[%d] ' % (self.getif(i)) |
---|
| 656 | if self.npol(-1) > 1: out += ' Pol[%d] ' % (self.getpol(i)) |
---|
[1819] | 657 | #outvec.append(callback(i)) |
---|
[1907] | 658 | if len(rows) > 1: |
---|
| 659 | # out += ('= %'+form) % (outvec[i]) +' '+refstr+'\n' |
---|
| 660 | out += ('= %'+form) % (statvals[i]) +' '+refstr+'\n' |
---|
| 661 | else: |
---|
| 662 | # out += ('= %'+form) % (outvec[0]) +' '+refstr+'\n' |
---|
| 663 | out += ('= %'+form) % (statvals[0]) +' '+refstr+'\n' |
---|
[1819] | 664 | out += sep+"\n" |
---|
| 665 | |
---|
[1859] | 666 | import os |
---|
| 667 | if os.environ.has_key( 'USER' ): |
---|
| 668 | usr = os.environ['USER'] |
---|
| 669 | else: |
---|
| 670 | import commands |
---|
| 671 | usr = commands.getoutput( 'whoami' ) |
---|
| 672 | tmpfile = '/tmp/tmp_'+usr+'_casapy_asap_scantable_stats' |
---|
| 673 | f = open(tmpfile,'w') |
---|
| 674 | print >> f, sep |
---|
| 675 | print >> f, ' %s %s' % (label, statunit) |
---|
| 676 | print >> f, sep |
---|
| 677 | print >> f, out |
---|
| 678 | f.close() |
---|
| 679 | f = open(tmpfile,'r') |
---|
| 680 | x = f.readlines() |
---|
| 681 | f.close() |
---|
| 682 | asaplog.push(''.join(x), False) |
---|
| 683 | |
---|
[1819] | 684 | return statvals |
---|
| 685 | |
---|
| 686 | def chan2data(self, rowno=0, chan=0): |
---|
[1846] | 687 | """\ |
---|
[1819] | 688 | Returns channel/frequency/velocity and spectral value |
---|
| 689 | at an arbitrary row and channel in the scantable. |
---|
[1846] | 690 | |
---|
[1819] | 691 | Parameters: |
---|
[1846] | 692 | |
---|
[1819] | 693 | rowno: a row number in the scantable. Default is the |
---|
| 694 | first row, i.e. rowno=0 |
---|
[1855] | 695 | |
---|
[1819] | 696 | chan: a channel in the scantable. Default is the first |
---|
| 697 | channel, i.e. pos=0 |
---|
[1846] | 698 | |
---|
[1819] | 699 | """ |
---|
| 700 | if isinstance(rowno, int) and isinstance(chan, int): |
---|
| 701 | qx = {'unit': self.get_unit(), |
---|
| 702 | 'value': self._getabcissa(rowno)[chan]} |
---|
| 703 | qy = {'unit': self.get_fluxunit(), |
---|
| 704 | 'value': self._getspectrum(rowno)[chan]} |
---|
| 705 | return qx, qy |
---|
| 706 | |
---|
[1118] | 707 | def stddev(self, mask=None): |
---|
[1846] | 708 | """\ |
---|
[135] | 709 | Determine the standard deviation of the current beam/if/pol |
---|
| 710 | Takes a 'mask' as an optional parameter to specify which |
---|
| 711 | channels should be excluded. |
---|
[1846] | 712 | |
---|
[135] | 713 | Parameters: |
---|
[1846] | 714 | |
---|
[135] | 715 | mask: an optional mask specifying where the standard |
---|
| 716 | deviation should be determined. |
---|
| 717 | |
---|
[1846] | 718 | Example:: |
---|
| 719 | |
---|
[135] | 720 | scan.set_unit('channel') |
---|
[1118] | 721 | msk = scan.create_mask([100, 200], [500, 600]) |
---|
[135] | 722 | scan.stddev(mask=m) |
---|
[1846] | 723 | |
---|
[135] | 724 | """ |
---|
[1118] | 725 | return self.stats(stat='stddev', mask=mask); |
---|
[135] | 726 | |
---|
[1003] | 727 | |
---|
[1259] | 728 | def get_column_names(self): |
---|
[1846] | 729 | """\ |
---|
[1003] | 730 | Return a list of column names, which can be used for selection. |
---|
| 731 | """ |
---|
[1259] | 732 | return list(Scantable.get_column_names(self)) |
---|
[1003] | 733 | |
---|
[1730] | 734 | def get_tsys(self, row=-1): |
---|
[1846] | 735 | """\ |
---|
[113] | 736 | Return the System temperatures. |
---|
[1846] | 737 | |
---|
| 738 | Parameters: |
---|
| 739 | |
---|
| 740 | row: the rowno to get the information for. (default all rows) |
---|
| 741 | |
---|
[113] | 742 | Returns: |
---|
[1846] | 743 | |
---|
[876] | 744 | a list of Tsys values for the current selection |
---|
[1846] | 745 | |
---|
[113] | 746 | """ |
---|
[1730] | 747 | if row > -1: |
---|
| 748 | return self._get_column(self._gettsys, row) |
---|
[876] | 749 | return self._row_callback(self._gettsys, "Tsys") |
---|
[256] | 750 | |
---|
[2406] | 751 | def get_tsysspectrum(self, row=-1): |
---|
| 752 | """\ |
---|
| 753 | Return the channel dependent system temperatures. |
---|
[1730] | 754 | |
---|
[2406] | 755 | Parameters: |
---|
| 756 | |
---|
| 757 | row: the rowno to get the information for. (default all rows) |
---|
| 758 | |
---|
| 759 | Returns: |
---|
| 760 | |
---|
| 761 | a list of Tsys values for the current selection |
---|
| 762 | |
---|
| 763 | """ |
---|
| 764 | return self._get_column( self._gettsysspectrum, row ) |
---|
| 765 | |
---|
[1730] | 766 | def get_weather(self, row=-1): |
---|
[1846] | 767 | """\ |
---|
| 768 | Return the weather informations. |
---|
| 769 | |
---|
| 770 | Parameters: |
---|
| 771 | |
---|
| 772 | row: the rowno to get the information for. (default all rows) |
---|
| 773 | |
---|
| 774 | Returns: |
---|
| 775 | |
---|
| 776 | a dict or list of of dicts of values for the current selection |
---|
| 777 | |
---|
| 778 | """ |
---|
| 779 | |
---|
[1730] | 780 | values = self._get_column(self._get_weather, row) |
---|
| 781 | if row > -1: |
---|
| 782 | return {'temperature': values[0], |
---|
| 783 | 'pressure': values[1], 'humidity' : values[2], |
---|
| 784 | 'windspeed' : values[3], 'windaz' : values[4] |
---|
| 785 | } |
---|
| 786 | else: |
---|
| 787 | out = [] |
---|
| 788 | for r in values: |
---|
| 789 | |
---|
| 790 | out.append({'temperature': r[0], |
---|
| 791 | 'pressure': r[1], 'humidity' : r[2], |
---|
| 792 | 'windspeed' : r[3], 'windaz' : r[4] |
---|
| 793 | }) |
---|
| 794 | return out |
---|
| 795 | |
---|
[876] | 796 | def _row_callback(self, callback, label): |
---|
| 797 | out = "" |
---|
[1118] | 798 | outvec = [] |
---|
[1590] | 799 | sep = '-'*50 |
---|
[876] | 800 | for i in range(self.nrow()): |
---|
| 801 | tm = self._gettime(i) |
---|
| 802 | src = self._getsourcename(i) |
---|
[1590] | 803 | out += 'Scan[%d] (%s) ' % (self.getscan(i), src) |
---|
[876] | 804 | out += 'Time[%s]:\n' % (tm) |
---|
[1590] | 805 | if self.nbeam(-1) > 1: |
---|
| 806 | out += ' Beam[%d] ' % (self.getbeam(i)) |
---|
| 807 | if self.nif(-1) > 1: out += ' IF[%d] ' % (self.getif(i)) |
---|
| 808 | if self.npol(-1) > 1: out += ' Pol[%d] ' % (self.getpol(i)) |
---|
[876] | 809 | outvec.append(callback(i)) |
---|
| 810 | out += '= %3.3f\n' % (outvec[i]) |
---|
[1590] | 811 | out += sep+'\n' |
---|
[1859] | 812 | |
---|
| 813 | asaplog.push(sep) |
---|
| 814 | asaplog.push(" %s" % (label)) |
---|
| 815 | asaplog.push(sep) |
---|
| 816 | asaplog.push(out) |
---|
[1861] | 817 | asaplog.post() |
---|
[1175] | 818 | return outvec |
---|
[256] | 819 | |
---|
[1947] | 820 | def _get_column(self, callback, row=-1, *args): |
---|
[1070] | 821 | """ |
---|
| 822 | """ |
---|
| 823 | if row == -1: |
---|
[1947] | 824 | return [callback(i, *args) for i in range(self.nrow())] |
---|
[1070] | 825 | else: |
---|
[1819] | 826 | if 0 <= row < self.nrow(): |
---|
[1947] | 827 | return callback(row, *args) |
---|
[256] | 828 | |
---|
[1070] | 829 | |
---|
[1948] | 830 | def get_time(self, row=-1, asdatetime=False, prec=-1): |
---|
[1846] | 831 | """\ |
---|
[113] | 832 | Get a list of time stamps for the observations. |
---|
[1938] | 833 | Return a datetime object or a string (default) for each |
---|
| 834 | integration time stamp in the scantable. |
---|
[1846] | 835 | |
---|
[113] | 836 | Parameters: |
---|
[1846] | 837 | |
---|
[1348] | 838 | row: row no of integration. Default -1 return all rows |
---|
[1855] | 839 | |
---|
[1348] | 840 | asdatetime: return values as datetime objects rather than strings |
---|
[1846] | 841 | |
---|
[2349] | 842 | prec: number of digits shown. Default -1 to automatic |
---|
| 843 | calculation. |
---|
[1948] | 844 | Note this number is equals to the digits of MVTime, |
---|
| 845 | i.e., 0<prec<3: dates with hh:: only, |
---|
| 846 | <5: with hh:mm:, <7 or 0: with hh:mm:ss, |
---|
[1947] | 847 | and 6> : with hh:mm:ss.tt... (prec-6 t's added) |
---|
| 848 | |
---|
[113] | 849 | """ |
---|
[1175] | 850 | from datetime import datetime |
---|
[1948] | 851 | if prec < 0: |
---|
| 852 | # automagically set necessary precision +1 |
---|
[2349] | 853 | prec = 7 - \ |
---|
| 854 | numpy.floor(numpy.log10(numpy.min(self.get_inttime(row)))) |
---|
[1948] | 855 | prec = max(6, int(prec)) |
---|
| 856 | else: |
---|
| 857 | prec = max(0, prec) |
---|
| 858 | if asdatetime: |
---|
| 859 | #precision can be 1 millisecond at max |
---|
| 860 | prec = min(12, prec) |
---|
| 861 | |
---|
[1947] | 862 | times = self._get_column(self._gettime, row, prec) |
---|
[1348] | 863 | if not asdatetime: |
---|
[1392] | 864 | return times |
---|
[1947] | 865 | format = "%Y/%m/%d/%H:%M:%S.%f" |
---|
| 866 | if prec < 7: |
---|
| 867 | nsub = 1 + (((6-prec)/2) % 3) |
---|
| 868 | substr = [".%f","%S","%M"] |
---|
| 869 | for i in range(nsub): |
---|
| 870 | format = format.replace(substr[i],"") |
---|
[1175] | 871 | if isinstance(times, list): |
---|
[1947] | 872 | return [datetime.strptime(i, format) for i in times] |
---|
[1175] | 873 | else: |
---|
[1947] | 874 | return datetime.strptime(times, format) |
---|
[102] | 875 | |
---|
[1348] | 876 | |
---|
| 877 | def get_inttime(self, row=-1): |
---|
[1846] | 878 | """\ |
---|
[1348] | 879 | Get a list of integration times for the observations. |
---|
| 880 | Return a time in seconds for each integration in the scantable. |
---|
[1846] | 881 | |
---|
[1348] | 882 | Parameters: |
---|
[1846] | 883 | |
---|
[1348] | 884 | row: row no of integration. Default -1 return all rows. |
---|
[1846] | 885 | |
---|
[1348] | 886 | """ |
---|
[1573] | 887 | return self._get_column(self._getinttime, row) |
---|
[1348] | 888 | |
---|
[1573] | 889 | |
---|
[714] | 890 | def get_sourcename(self, row=-1): |
---|
[1846] | 891 | """\ |
---|
[794] | 892 | Get a list source names for the observations. |
---|
[714] | 893 | Return a string for each integration in the scantable. |
---|
| 894 | Parameters: |
---|
[1846] | 895 | |
---|
[1348] | 896 | row: row no of integration. Default -1 return all rows. |
---|
[1846] | 897 | |
---|
[714] | 898 | """ |
---|
[1070] | 899 | return self._get_column(self._getsourcename, row) |
---|
[714] | 900 | |
---|
[794] | 901 | def get_elevation(self, row=-1): |
---|
[1846] | 902 | """\ |
---|
[794] | 903 | Get a list of elevations for the observations. |
---|
| 904 | Return a float for each integration in the scantable. |
---|
[1846] | 905 | |
---|
[794] | 906 | Parameters: |
---|
[1846] | 907 | |
---|
[1348] | 908 | row: row no of integration. Default -1 return all rows. |
---|
[1846] | 909 | |
---|
[794] | 910 | """ |
---|
[1070] | 911 | return self._get_column(self._getelevation, row) |
---|
[794] | 912 | |
---|
| 913 | def get_azimuth(self, row=-1): |
---|
[1846] | 914 | """\ |
---|
[794] | 915 | Get a list of azimuths for the observations. |
---|
| 916 | Return a float for each integration in the scantable. |
---|
[1846] | 917 | |
---|
[794] | 918 | Parameters: |
---|
[1348] | 919 | row: row no of integration. Default -1 return all rows. |
---|
[1846] | 920 | |
---|
[794] | 921 | """ |
---|
[1070] | 922 | return self._get_column(self._getazimuth, row) |
---|
[794] | 923 | |
---|
| 924 | def get_parangle(self, row=-1): |
---|
[1846] | 925 | """\ |
---|
[794] | 926 | Get a list of parallactic angles for the observations. |
---|
| 927 | Return a float for each integration in the scantable. |
---|
[1846] | 928 | |
---|
[794] | 929 | Parameters: |
---|
[1846] | 930 | |
---|
[1348] | 931 | row: row no of integration. Default -1 return all rows. |
---|
[1846] | 932 | |
---|
[794] | 933 | """ |
---|
[1070] | 934 | return self._get_column(self._getparangle, row) |
---|
[794] | 935 | |
---|
[1070] | 936 | def get_direction(self, row=-1): |
---|
| 937 | """ |
---|
| 938 | Get a list of Positions on the sky (direction) for the observations. |
---|
[1594] | 939 | Return a string for each integration in the scantable. |
---|
[1855] | 940 | |
---|
[1070] | 941 | Parameters: |
---|
[1855] | 942 | |
---|
[1070] | 943 | row: row no of integration. Default -1 return all rows |
---|
[1855] | 944 | |
---|
[1070] | 945 | """ |
---|
| 946 | return self._get_column(self._getdirection, row) |
---|
| 947 | |
---|
[1391] | 948 | def get_directionval(self, row=-1): |
---|
[1846] | 949 | """\ |
---|
[1391] | 950 | Get a list of Positions on the sky (direction) for the observations. |
---|
| 951 | Return a float for each integration in the scantable. |
---|
[1846] | 952 | |
---|
[1391] | 953 | Parameters: |
---|
[1846] | 954 | |
---|
[1391] | 955 | row: row no of integration. Default -1 return all rows |
---|
[1846] | 956 | |
---|
[1391] | 957 | """ |
---|
| 958 | return self._get_column(self._getdirectionvec, row) |
---|
| 959 | |
---|
[1862] | 960 | @asaplog_post_dec |
---|
[102] | 961 | def set_unit(self, unit='channel'): |
---|
[1846] | 962 | """\ |
---|
[102] | 963 | Set the unit for all following operations on this scantable |
---|
[1846] | 964 | |
---|
[102] | 965 | Parameters: |
---|
[1846] | 966 | |
---|
| 967 | unit: optional unit, default is 'channel'. Use one of '*Hz', |
---|
| 968 | 'km/s', 'channel' or equivalent '' |
---|
| 969 | |
---|
[102] | 970 | """ |
---|
[484] | 971 | varlist = vars() |
---|
[1118] | 972 | if unit in ['', 'pixel', 'channel']: |
---|
[113] | 973 | unit = '' |
---|
| 974 | inf = list(self._getcoordinfo()) |
---|
| 975 | inf[0] = unit |
---|
| 976 | self._setcoordinfo(inf) |
---|
[1118] | 977 | self._add_history("set_unit", varlist) |
---|
[113] | 978 | |
---|
[1862] | 979 | @asaplog_post_dec |
---|
[484] | 980 | def set_instrument(self, instr): |
---|
[1846] | 981 | """\ |
---|
[1348] | 982 | Set the instrument for subsequent processing. |
---|
[1846] | 983 | |
---|
[358] | 984 | Parameters: |
---|
[1846] | 985 | |
---|
[710] | 986 | instr: Select from 'ATPKSMB', 'ATPKSHOH', 'ATMOPRA', |
---|
[407] | 987 | 'DSS-43' (Tid), 'CEDUNA', and 'HOBART' |
---|
[1846] | 988 | |
---|
[358] | 989 | """ |
---|
| 990 | self._setInstrument(instr) |
---|
[1118] | 991 | self._add_history("set_instument", vars()) |
---|
[358] | 992 | |
---|
[1862] | 993 | @asaplog_post_dec |
---|
[1190] | 994 | def set_feedtype(self, feedtype): |
---|
[1846] | 995 | """\ |
---|
[1190] | 996 | Overwrite the feed type, which might not be set correctly. |
---|
[1846] | 997 | |
---|
[1190] | 998 | Parameters: |
---|
[1846] | 999 | |
---|
[1190] | 1000 | feedtype: 'linear' or 'circular' |
---|
[1846] | 1001 | |
---|
[1190] | 1002 | """ |
---|
| 1003 | self._setfeedtype(feedtype) |
---|
| 1004 | self._add_history("set_feedtype", vars()) |
---|
| 1005 | |
---|
[1862] | 1006 | @asaplog_post_dec |
---|
[276] | 1007 | def set_doppler(self, doppler='RADIO'): |
---|
[1846] | 1008 | """\ |
---|
[276] | 1009 | Set the doppler for all following operations on this scantable. |
---|
[1846] | 1010 | |
---|
[276] | 1011 | Parameters: |
---|
[1846] | 1012 | |
---|
[276] | 1013 | doppler: One of 'RADIO', 'OPTICAL', 'Z', 'BETA', 'GAMMA' |
---|
[1846] | 1014 | |
---|
[276] | 1015 | """ |
---|
[484] | 1016 | varlist = vars() |
---|
[276] | 1017 | inf = list(self._getcoordinfo()) |
---|
| 1018 | inf[2] = doppler |
---|
| 1019 | self._setcoordinfo(inf) |
---|
[1118] | 1020 | self._add_history("set_doppler", vars()) |
---|
[710] | 1021 | |
---|
[1862] | 1022 | @asaplog_post_dec |
---|
[226] | 1023 | def set_freqframe(self, frame=None): |
---|
[1846] | 1024 | """\ |
---|
[113] | 1025 | Set the frame type of the Spectral Axis. |
---|
[1846] | 1026 | |
---|
[113] | 1027 | Parameters: |
---|
[1846] | 1028 | |
---|
[591] | 1029 | frame: an optional frame type, default 'LSRK'. Valid frames are: |
---|
[1819] | 1030 | 'TOPO', 'LSRD', 'LSRK', 'BARY', |
---|
[1118] | 1031 | 'GEO', 'GALACTO', 'LGROUP', 'CMB' |
---|
[1846] | 1032 | |
---|
| 1033 | Example:: |
---|
| 1034 | |
---|
[113] | 1035 | scan.set_freqframe('BARY') |
---|
[1846] | 1036 | |
---|
[113] | 1037 | """ |
---|
[1593] | 1038 | frame = frame or rcParams['scantable.freqframe'] |
---|
[484] | 1039 | varlist = vars() |
---|
[1819] | 1040 | # "REST" is not implemented in casacore |
---|
| 1041 | #valid = ['REST', 'TOPO', 'LSRD', 'LSRK', 'BARY', \ |
---|
| 1042 | # 'GEO', 'GALACTO', 'LGROUP', 'CMB'] |
---|
| 1043 | valid = ['TOPO', 'LSRD', 'LSRK', 'BARY', \ |
---|
[1118] | 1044 | 'GEO', 'GALACTO', 'LGROUP', 'CMB'] |
---|
[591] | 1045 | |
---|
[989] | 1046 | if frame in valid: |
---|
[113] | 1047 | inf = list(self._getcoordinfo()) |
---|
| 1048 | inf[1] = frame |
---|
| 1049 | self._setcoordinfo(inf) |
---|
[1118] | 1050 | self._add_history("set_freqframe", varlist) |
---|
[102] | 1051 | else: |
---|
[1118] | 1052 | msg = "Please specify a valid freq type. Valid types are:\n", valid |
---|
[1859] | 1053 | raise TypeError(msg) |
---|
[710] | 1054 | |
---|
[1862] | 1055 | @asaplog_post_dec |
---|
[989] | 1056 | def set_dirframe(self, frame=""): |
---|
[1846] | 1057 | """\ |
---|
[989] | 1058 | Set the frame type of the Direction on the sky. |
---|
[1846] | 1059 | |
---|
[989] | 1060 | Parameters: |
---|
[1846] | 1061 | |
---|
[989] | 1062 | frame: an optional frame type, default ''. Valid frames are: |
---|
| 1063 | 'J2000', 'B1950', 'GALACTIC' |
---|
[1846] | 1064 | |
---|
| 1065 | Example: |
---|
| 1066 | |
---|
[989] | 1067 | scan.set_dirframe('GALACTIC') |
---|
[1846] | 1068 | |
---|
[989] | 1069 | """ |
---|
| 1070 | varlist = vars() |
---|
[1859] | 1071 | Scantable.set_dirframe(self, frame) |
---|
[1118] | 1072 | self._add_history("set_dirframe", varlist) |
---|
[989] | 1073 | |
---|
[113] | 1074 | def get_unit(self): |
---|
[1846] | 1075 | """\ |
---|
[113] | 1076 | Get the default unit set in this scantable |
---|
[1846] | 1077 | |
---|
[113] | 1078 | Returns: |
---|
[1846] | 1079 | |
---|
[113] | 1080 | A unit string |
---|
[1846] | 1081 | |
---|
[113] | 1082 | """ |
---|
| 1083 | inf = self._getcoordinfo() |
---|
| 1084 | unit = inf[0] |
---|
| 1085 | if unit == '': unit = 'channel' |
---|
| 1086 | return unit |
---|
[102] | 1087 | |
---|
[1862] | 1088 | @asaplog_post_dec |
---|
[158] | 1089 | def get_abcissa(self, rowno=0): |
---|
[1846] | 1090 | """\ |
---|
[158] | 1091 | Get the abcissa in the current coordinate setup for the currently |
---|
[113] | 1092 | selected Beam/IF/Pol |
---|
[1846] | 1093 | |
---|
[113] | 1094 | Parameters: |
---|
[1846] | 1095 | |
---|
[226] | 1096 | rowno: an optional row number in the scantable. Default is the |
---|
| 1097 | first row, i.e. rowno=0 |
---|
[1846] | 1098 | |
---|
[113] | 1099 | Returns: |
---|
[1846] | 1100 | |
---|
[1348] | 1101 | The abcissa values and the format string (as a dictionary) |
---|
[1846] | 1102 | |
---|
[113] | 1103 | """ |
---|
[256] | 1104 | abc = self._getabcissa(rowno) |
---|
[710] | 1105 | lbl = self._getabcissalabel(rowno) |
---|
[158] | 1106 | return abc, lbl |
---|
[113] | 1107 | |
---|
[1862] | 1108 | @asaplog_post_dec |
---|
[2322] | 1109 | def flag(self, mask=None, unflag=False, row=-1): |
---|
[1846] | 1110 | """\ |
---|
[1001] | 1111 | Flag the selected data using an optional channel mask. |
---|
[1846] | 1112 | |
---|
[1001] | 1113 | Parameters: |
---|
[1846] | 1114 | |
---|
[1001] | 1115 | mask: an optional channel mask, created with create_mask. Default |
---|
| 1116 | (no mask) is all channels. |
---|
[1855] | 1117 | |
---|
[1819] | 1118 | unflag: if True, unflag the data |
---|
[1846] | 1119 | |
---|
[2322] | 1120 | row: an optional row number in the scantable. |
---|
| 1121 | Default -1 flags all rows |
---|
| 1122 | |
---|
[1001] | 1123 | """ |
---|
| 1124 | varlist = vars() |
---|
[1593] | 1125 | mask = mask or [] |
---|
[1994] | 1126 | self._flag(row, mask, unflag) |
---|
[1001] | 1127 | self._add_history("flag", varlist) |
---|
| 1128 | |
---|
[1862] | 1129 | @asaplog_post_dec |
---|
[2322] | 1130 | def flag_row(self, rows=None, unflag=False): |
---|
[1846] | 1131 | """\ |
---|
[1819] | 1132 | Flag the selected data in row-based manner. |
---|
[1846] | 1133 | |
---|
[1819] | 1134 | Parameters: |
---|
[1846] | 1135 | |
---|
[1843] | 1136 | rows: list of row numbers to be flagged. Default is no row |
---|
[2322] | 1137 | (must be explicitly specified to execute row-based |
---|
| 1138 | flagging). |
---|
[1855] | 1139 | |
---|
[1819] | 1140 | unflag: if True, unflag the data. |
---|
[1846] | 1141 | |
---|
[1819] | 1142 | """ |
---|
| 1143 | varlist = vars() |
---|
[2322] | 1144 | if rows is None: |
---|
| 1145 | rows = [] |
---|
[1859] | 1146 | self._flag_row(rows, unflag) |
---|
[1819] | 1147 | self._add_history("flag_row", varlist) |
---|
| 1148 | |
---|
[1862] | 1149 | @asaplog_post_dec |
---|
[1819] | 1150 | def clip(self, uthres=None, dthres=None, clipoutside=True, unflag=False): |
---|
[1846] | 1151 | """\ |
---|
[1819] | 1152 | Flag the selected data outside a specified range (in channel-base) |
---|
[1846] | 1153 | |
---|
[1819] | 1154 | Parameters: |
---|
[1846] | 1155 | |
---|
[1819] | 1156 | uthres: upper threshold. |
---|
[1855] | 1157 | |
---|
[1819] | 1158 | dthres: lower threshold |
---|
[1846] | 1159 | |
---|
[2322] | 1160 | clipoutside: True for flagging data outside the range |
---|
| 1161 | [dthres:uthres]. |
---|
[1928] | 1162 | False for flagging data inside the range. |
---|
[1855] | 1163 | |
---|
[1846] | 1164 | unflag: if True, unflag the data. |
---|
| 1165 | |
---|
[1819] | 1166 | """ |
---|
| 1167 | varlist = vars() |
---|
[1859] | 1168 | self._clip(uthres, dthres, clipoutside, unflag) |
---|
[1819] | 1169 | self._add_history("clip", varlist) |
---|
| 1170 | |
---|
[1862] | 1171 | @asaplog_post_dec |
---|
[1584] | 1172 | def lag_flag(self, start, end, unit="MHz", insitu=None): |
---|
[1846] | 1173 | """\ |
---|
[1192] | 1174 | Flag the data in 'lag' space by providing a frequency to remove. |
---|
[2177] | 1175 | Flagged data in the scantable get interpolated over the region. |
---|
[1192] | 1176 | No taper is applied. |
---|
[1846] | 1177 | |
---|
[1192] | 1178 | Parameters: |
---|
[1846] | 1179 | |
---|
[1579] | 1180 | start: the start frequency (really a period within the |
---|
| 1181 | bandwidth) or period to remove |
---|
[1855] | 1182 | |
---|
[1579] | 1183 | end: the end frequency or period to remove |
---|
[1855] | 1184 | |
---|
[2431] | 1185 | unit: the frequency unit (default 'MHz') or '' for |
---|
[1579] | 1186 | explicit lag channels |
---|
[1846] | 1187 | |
---|
| 1188 | *Notes*: |
---|
| 1189 | |
---|
[1579] | 1190 | It is recommended to flag edges of the band or strong |
---|
[1348] | 1191 | signals beforehand. |
---|
[1846] | 1192 | |
---|
[1192] | 1193 | """ |
---|
| 1194 | if insitu is None: insitu = rcParams['insitu'] |
---|
| 1195 | self._math._setinsitu(insitu) |
---|
| 1196 | varlist = vars() |
---|
[1579] | 1197 | base = { "GHz": 1000000000., "MHz": 1000000., "kHz": 1000., "Hz": 1.} |
---|
| 1198 | if not (unit == "" or base.has_key(unit)): |
---|
[1192] | 1199 | raise ValueError("%s is not a valid unit." % unit) |
---|
[1859] | 1200 | if unit == "": |
---|
| 1201 | s = scantable(self._math._lag_flag(self, start, end, "lags")) |
---|
| 1202 | else: |
---|
| 1203 | s = scantable(self._math._lag_flag(self, start*base[unit], |
---|
| 1204 | end*base[unit], "frequency")) |
---|
[1192] | 1205 | s._add_history("lag_flag", varlist) |
---|
| 1206 | if insitu: |
---|
| 1207 | self._assign(s) |
---|
| 1208 | else: |
---|
| 1209 | return s |
---|
[1001] | 1210 | |
---|
[1862] | 1211 | @asaplog_post_dec |
---|
[2349] | 1212 | def fft(self, rowno=None, mask=None, getrealimag=False): |
---|
[2177] | 1213 | """\ |
---|
| 1214 | Apply FFT to the spectra. |
---|
| 1215 | Flagged data in the scantable get interpolated over the region. |
---|
| 1216 | |
---|
| 1217 | Parameters: |
---|
[2186] | 1218 | |
---|
| 1219 | rowno: The row number(s) to be processed. int, list |
---|
[2349] | 1220 | and tuple are accepted. By default (None), FFT |
---|
[2186] | 1221 | is applied to the whole data. |
---|
| 1222 | |
---|
| 1223 | mask: Auxiliary channel mask(s). Given as a boolean |
---|
| 1224 | list, it is applied to all specified rows. |
---|
| 1225 | A list of boolean lists can also be used to |
---|
| 1226 | apply different masks. In the latter case, the |
---|
| 1227 | length of 'mask' must be the same as that of |
---|
[2349] | 1228 | 'rowno'. The default is None. |
---|
[2177] | 1229 | |
---|
| 1230 | getrealimag: If True, returns the real and imaginary part |
---|
| 1231 | values of the complex results. |
---|
| 1232 | If False (the default), returns the amplitude |
---|
| 1233 | (absolute value) normalised with Ndata/2 and |
---|
| 1234 | phase (argument, in unit of radian). |
---|
| 1235 | |
---|
| 1236 | Returns: |
---|
| 1237 | |
---|
[2186] | 1238 | A list of dictionaries containing the results for each spectrum. |
---|
| 1239 | Each dictionary contains two values, the real and the imaginary |
---|
| 1240 | parts when getrealimag = True, or the amplitude(absolute value) |
---|
| 1241 | and the phase(argument) when getrealimag = False. The key for |
---|
| 1242 | these values are 'real' and 'imag', or 'ampl' and 'phase', |
---|
[2177] | 1243 | respectively. |
---|
| 1244 | """ |
---|
[2349] | 1245 | if rowno is None: |
---|
| 1246 | rowno = [] |
---|
[2177] | 1247 | if isinstance(rowno, int): |
---|
| 1248 | rowno = [rowno] |
---|
| 1249 | elif not (isinstance(rowno, list) or isinstance(rowno, tuple)): |
---|
[2186] | 1250 | raise TypeError("The row number(s) must be int, list or tuple.") |
---|
| 1251 | if len(rowno) == 0: rowno = [i for i in xrange(self.nrow())] |
---|
| 1252 | |
---|
[2411] | 1253 | usecommonmask = True |
---|
| 1254 | |
---|
| 1255 | if mask is None: |
---|
| 1256 | mask = [] |
---|
| 1257 | if isinstance(mask, list) or isinstance(mask, tuple): |
---|
| 1258 | if len(mask) == 0: |
---|
| 1259 | mask = [[]] |
---|
| 1260 | else: |
---|
| 1261 | if isinstance(mask[0], bool): |
---|
| 1262 | if len(mask) != self.nchan(self.getif(rowno[0])): |
---|
| 1263 | raise ValueError("The spectra and the mask have " |
---|
| 1264 | "different length.") |
---|
| 1265 | mask = [mask] |
---|
| 1266 | elif isinstance(mask[0], list) or isinstance(mask[0], tuple): |
---|
| 1267 | usecommonmask = False |
---|
| 1268 | if len(mask) != len(rowno): |
---|
| 1269 | raise ValueError("When specifying masks for each " |
---|
| 1270 | "spectrum, the numbers of them " |
---|
| 1271 | "must be identical.") |
---|
| 1272 | for i in xrange(mask): |
---|
| 1273 | if len(mask[i]) != self.nchan(self.getif(rowno[i])): |
---|
| 1274 | raise ValueError("The spectra and the mask have " |
---|
| 1275 | "different length.") |
---|
| 1276 | else: |
---|
| 1277 | raise TypeError("The mask must be a boolean list or " |
---|
| 1278 | "a list of boolean list.") |
---|
| 1279 | else: |
---|
[2349] | 1280 | raise TypeError("The mask must be a boolean list or a list of " |
---|
| 1281 | "boolean list.") |
---|
[2186] | 1282 | |
---|
| 1283 | res = [] |
---|
| 1284 | |
---|
| 1285 | imask = 0 |
---|
| 1286 | for whichrow in rowno: |
---|
| 1287 | fspec = self._fft(whichrow, mask[imask], getrealimag) |
---|
| 1288 | nspec = len(fspec) |
---|
[2177] | 1289 | |
---|
[2349] | 1290 | i = 0 |
---|
| 1291 | v1 = [] |
---|
| 1292 | v2 = [] |
---|
| 1293 | reselem = {"real":[],"imag":[]} if getrealimag \ |
---|
| 1294 | else {"ampl":[],"phase":[]} |
---|
[2177] | 1295 | |
---|
[2186] | 1296 | while (i < nspec): |
---|
| 1297 | v1.append(fspec[i]) |
---|
| 1298 | v2.append(fspec[i+1]) |
---|
[2349] | 1299 | i += 2 |
---|
[2186] | 1300 | |
---|
[2177] | 1301 | if getrealimag: |
---|
[2186] | 1302 | reselem["real"] += v1 |
---|
| 1303 | reselem["imag"] += v2 |
---|
[2177] | 1304 | else: |
---|
[2186] | 1305 | reselem["ampl"] += v1 |
---|
| 1306 | reselem["phase"] += v2 |
---|
[2177] | 1307 | |
---|
[2186] | 1308 | res.append(reselem) |
---|
| 1309 | |
---|
[2349] | 1310 | if not usecommonmask: |
---|
| 1311 | imask += 1 |
---|
[2186] | 1312 | |
---|
[2177] | 1313 | return res |
---|
| 1314 | |
---|
| 1315 | @asaplog_post_dec |
---|
[113] | 1316 | def create_mask(self, *args, **kwargs): |
---|
[1846] | 1317 | """\ |
---|
[1118] | 1318 | Compute and return a mask based on [min, max] windows. |
---|
[189] | 1319 | The specified windows are to be INCLUDED, when the mask is |
---|
[113] | 1320 | applied. |
---|
[1846] | 1321 | |
---|
[102] | 1322 | Parameters: |
---|
[1846] | 1323 | |
---|
[1118] | 1324 | [min, max], [min2, max2], ... |
---|
[1024] | 1325 | Pairs of start/end points (inclusive)specifying the regions |
---|
[102] | 1326 | to be masked |
---|
[1855] | 1327 | |
---|
[189] | 1328 | invert: optional argument. If specified as True, |
---|
| 1329 | return an inverted mask, i.e. the regions |
---|
| 1330 | specified are EXCLUDED |
---|
[1855] | 1331 | |
---|
[513] | 1332 | row: create the mask using the specified row for |
---|
| 1333 | unit conversions, default is row=0 |
---|
| 1334 | only necessary if frequency varies over rows. |
---|
[1846] | 1335 | |
---|
| 1336 | Examples:: |
---|
| 1337 | |
---|
[113] | 1338 | scan.set_unit('channel') |
---|
[1846] | 1339 | # a) |
---|
[1118] | 1340 | msk = scan.create_mask([400, 500], [800, 900]) |
---|
[189] | 1341 | # masks everything outside 400 and 500 |
---|
[113] | 1342 | # and 800 and 900 in the unit 'channel' |
---|
| 1343 | |
---|
[1846] | 1344 | # b) |
---|
[1118] | 1345 | msk = scan.create_mask([400, 500], [800, 900], invert=True) |
---|
[189] | 1346 | # masks the regions between 400 and 500 |
---|
[113] | 1347 | # and 800 and 900 in the unit 'channel' |
---|
[1846] | 1348 | |
---|
| 1349 | # c) |
---|
| 1350 | #mask only channel 400 |
---|
[1554] | 1351 | msk = scan.create_mask([400]) |
---|
[1846] | 1352 | |
---|
[102] | 1353 | """ |
---|
[1554] | 1354 | row = kwargs.get("row", 0) |
---|
[513] | 1355 | data = self._getabcissa(row) |
---|
[113] | 1356 | u = self._getcoordinfo()[0] |
---|
[1859] | 1357 | if u == "": |
---|
| 1358 | u = "channel" |
---|
| 1359 | msg = "The current mask window unit is %s" % u |
---|
| 1360 | i = self._check_ifs() |
---|
| 1361 | if not i: |
---|
| 1362 | msg += "\nThis mask is only valid for IF=%d" % (self.getif(i)) |
---|
| 1363 | asaplog.push(msg) |
---|
[2348] | 1364 | n = len(data) |
---|
[1295] | 1365 | msk = _n_bools(n, False) |
---|
[710] | 1366 | # test if args is a 'list' or a 'normal *args - UGLY!!! |
---|
| 1367 | |
---|
[2349] | 1368 | ws = (isinstance(args[-1][-1], int) |
---|
| 1369 | or isinstance(args[-1][-1], float)) and args or args[0] |
---|
[710] | 1370 | for window in ws: |
---|
[1554] | 1371 | if len(window) == 1: |
---|
| 1372 | window = [window[0], window[0]] |
---|
| 1373 | if len(window) == 0 or len(window) > 2: |
---|
[2349] | 1374 | raise ValueError("A window needs to be defined as " |
---|
| 1375 | "[start(, end)]") |
---|
[1545] | 1376 | if window[0] > window[1]: |
---|
| 1377 | tmp = window[0] |
---|
| 1378 | window[0] = window[1] |
---|
| 1379 | window[1] = tmp |
---|
[102] | 1380 | for i in range(n): |
---|
[1024] | 1381 | if data[i] >= window[0] and data[i] <= window[1]: |
---|
[1295] | 1382 | msk[i] = True |
---|
[113] | 1383 | if kwargs.has_key('invert'): |
---|
| 1384 | if kwargs.get('invert'): |
---|
[1295] | 1385 | msk = mask_not(msk) |
---|
[102] | 1386 | return msk |
---|
[710] | 1387 | |
---|
[1931] | 1388 | def get_masklist(self, mask=None, row=0, silent=False): |
---|
[1846] | 1389 | """\ |
---|
[1819] | 1390 | Compute and return a list of mask windows, [min, max]. |
---|
[1846] | 1391 | |
---|
[1819] | 1392 | Parameters: |
---|
[1846] | 1393 | |
---|
[1819] | 1394 | mask: channel mask, created with create_mask. |
---|
[1855] | 1395 | |
---|
[1819] | 1396 | row: calcutate the masklist using the specified row |
---|
| 1397 | for unit conversions, default is row=0 |
---|
| 1398 | only necessary if frequency varies over rows. |
---|
[1846] | 1399 | |
---|
[1819] | 1400 | Returns: |
---|
[1846] | 1401 | |
---|
[1819] | 1402 | [min, max], [min2, max2], ... |
---|
| 1403 | Pairs of start/end points (inclusive)specifying |
---|
| 1404 | the masked regions |
---|
[1846] | 1405 | |
---|
[1819] | 1406 | """ |
---|
| 1407 | if not (isinstance(mask,list) or isinstance(mask, tuple)): |
---|
| 1408 | raise TypeError("The mask should be list or tuple.") |
---|
[2427] | 1409 | if len(mask) <= 0: |
---|
| 1410 | raise TypeError("The mask elements should be > 0") |
---|
[2348] | 1411 | data = self._getabcissa(row) |
---|
| 1412 | if len(data) != len(mask): |
---|
[1819] | 1413 | msg = "Number of channels in scantable != number of mask elements" |
---|
| 1414 | raise TypeError(msg) |
---|
| 1415 | u = self._getcoordinfo()[0] |
---|
[1859] | 1416 | if u == "": |
---|
| 1417 | u = "channel" |
---|
| 1418 | msg = "The current mask window unit is %s" % u |
---|
| 1419 | i = self._check_ifs() |
---|
| 1420 | if not i: |
---|
| 1421 | msg += "\nThis mask is only valid for IF=%d" % (self.getif(i)) |
---|
[1931] | 1422 | if not silent: |
---|
| 1423 | asaplog.push(msg) |
---|
[2349] | 1424 | masklist = [] |
---|
[1819] | 1425 | ist, ien = None, None |
---|
| 1426 | ist, ien=self.get_mask_indices(mask) |
---|
| 1427 | if ist is not None and ien is not None: |
---|
| 1428 | for i in xrange(len(ist)): |
---|
| 1429 | range=[data[ist[i]],data[ien[i]]] |
---|
| 1430 | range.sort() |
---|
| 1431 | masklist.append([range[0],range[1]]) |
---|
| 1432 | return masklist |
---|
| 1433 | |
---|
| 1434 | def get_mask_indices(self, mask=None): |
---|
[1846] | 1435 | """\ |
---|
[1819] | 1436 | Compute and Return lists of mask start indices and mask end indices. |
---|
[1855] | 1437 | |
---|
| 1438 | Parameters: |
---|
| 1439 | |
---|
[1819] | 1440 | mask: channel mask, created with create_mask. |
---|
[1846] | 1441 | |
---|
[1819] | 1442 | Returns: |
---|
[1846] | 1443 | |
---|
[1819] | 1444 | List of mask start indices and that of mask end indices, |
---|
| 1445 | i.e., [istart1,istart2,....], [iend1,iend2,....]. |
---|
[1846] | 1446 | |
---|
[1819] | 1447 | """ |
---|
| 1448 | if not (isinstance(mask,list) or isinstance(mask, tuple)): |
---|
| 1449 | raise TypeError("The mask should be list or tuple.") |
---|
[2427] | 1450 | if len(mask) <= 0: |
---|
| 1451 | raise TypeError("The mask elements should be > 0") |
---|
[2349] | 1452 | istart = [] |
---|
| 1453 | iend = [] |
---|
| 1454 | if mask[0]: |
---|
| 1455 | istart.append(0) |
---|
[1819] | 1456 | for i in range(len(mask)-1): |
---|
| 1457 | if not mask[i] and mask[i+1]: |
---|
| 1458 | istart.append(i+1) |
---|
| 1459 | elif mask[i] and not mask[i+1]: |
---|
| 1460 | iend.append(i) |
---|
[2349] | 1461 | if mask[len(mask)-1]: |
---|
| 1462 | iend.append(len(mask)-1) |
---|
[1819] | 1463 | if len(istart) != len(iend): |
---|
| 1464 | raise RuntimeError("Numbers of mask start != mask end.") |
---|
| 1465 | for i in range(len(istart)): |
---|
| 1466 | if istart[i] > iend[i]: |
---|
| 1467 | raise RuntimeError("Mask start index > mask end index") |
---|
| 1468 | break |
---|
| 1469 | return istart,iend |
---|
| 1470 | |
---|
[2013] | 1471 | @asaplog_post_dec |
---|
[2349] | 1472 | def parse_maskexpr(self, maskstring): |
---|
[2013] | 1473 | """ |
---|
| 1474 | Parse CASA type mask selection syntax (IF dependent). |
---|
| 1475 | |
---|
| 1476 | Parameters: |
---|
| 1477 | maskstring : A string mask selection expression. |
---|
| 1478 | A comma separated selections mean different IF - |
---|
| 1479 | channel combinations. IFs and channel selections |
---|
| 1480 | are partitioned by a colon, ':'. |
---|
| 1481 | examples: |
---|
[2015] | 1482 | '' = all IFs (all channels) |
---|
[2013] | 1483 | '<2,4~6,9' = IFs 0,1,4,5,6,9 (all channels) |
---|
| 1484 | '3:3~45;60' = channels 3 to 45 and 60 in IF 3 |
---|
| 1485 | '0~1:2~6,8' = channels 2 to 6 in IFs 0,1, and |
---|
| 1486 | all channels in IF8 |
---|
| 1487 | Returns: |
---|
| 1488 | A dictionary of selected (valid) IF and masklist pairs, |
---|
| 1489 | e.g. {'0': [[50,250],[350,462]], '2': [[100,400],[550,974]]} |
---|
| 1490 | """ |
---|
| 1491 | if not isinstance(maskstring,str): |
---|
| 1492 | asaplog.post() |
---|
[2611] | 1493 | asaplog.push("Mask expression should be a string.") |
---|
[2013] | 1494 | asaplog.post("ERROR") |
---|
| 1495 | |
---|
| 1496 | valid_ifs = self.getifnos() |
---|
| 1497 | frequnit = self.get_unit() |
---|
| 1498 | seldict = {} |
---|
[2015] | 1499 | if maskstring == "": |
---|
| 1500 | maskstring = str(valid_ifs)[1:-1] |
---|
[2611] | 1501 | ## split each selection "IF range[:CHAN range]" |
---|
[2013] | 1502 | sellist = maskstring.split(',') |
---|
| 1503 | for currselstr in sellist: |
---|
| 1504 | selset = currselstr.split(':') |
---|
| 1505 | # spw and mask string (may include ~, < or >) |
---|
[2349] | 1506 | spwmasklist = self._parse_selection(selset[0], typestr='integer', |
---|
[2611] | 1507 | minval=min(valid_ifs), |
---|
[2349] | 1508 | maxval=max(valid_ifs)) |
---|
[2013] | 1509 | for spwlist in spwmasklist: |
---|
| 1510 | selspws = [] |
---|
| 1511 | for ispw in range(spwlist[0],spwlist[1]+1): |
---|
| 1512 | # Put into the list only if ispw exists |
---|
| 1513 | if valid_ifs.count(ispw): |
---|
| 1514 | selspws.append(ispw) |
---|
| 1515 | del spwmasklist, spwlist |
---|
| 1516 | |
---|
| 1517 | # parse frequency mask list |
---|
| 1518 | if len(selset) > 1: |
---|
[2349] | 1519 | freqmasklist = self._parse_selection(selset[1], typestr='float', |
---|
| 1520 | offset=0.) |
---|
[2013] | 1521 | else: |
---|
| 1522 | # want to select the whole spectrum |
---|
| 1523 | freqmasklist = [None] |
---|
| 1524 | |
---|
| 1525 | ## define a dictionary of spw - masklist combination |
---|
| 1526 | for ispw in selspws: |
---|
| 1527 | #print "working on", ispw |
---|
| 1528 | spwstr = str(ispw) |
---|
| 1529 | if len(selspws) == 0: |
---|
| 1530 | # empty spw |
---|
| 1531 | continue |
---|
| 1532 | else: |
---|
| 1533 | ## want to get min and max of the spw and |
---|
| 1534 | ## offset to set for '<' and '>' |
---|
| 1535 | if frequnit == 'channel': |
---|
| 1536 | minfreq = 0 |
---|
| 1537 | maxfreq = self.nchan(ifno=ispw) |
---|
| 1538 | offset = 0.5 |
---|
| 1539 | else: |
---|
| 1540 | ## This is ugly part. need improvement |
---|
| 1541 | for ifrow in xrange(self.nrow()): |
---|
| 1542 | if self.getif(ifrow) == ispw: |
---|
| 1543 | #print "IF",ispw,"found in row =",ifrow |
---|
| 1544 | break |
---|
| 1545 | freqcoord = self.get_coordinate(ifrow) |
---|
| 1546 | freqs = self._getabcissa(ifrow) |
---|
| 1547 | minfreq = min(freqs) |
---|
| 1548 | maxfreq = max(freqs) |
---|
| 1549 | if len(freqs) == 1: |
---|
| 1550 | offset = 0.5 |
---|
| 1551 | elif frequnit.find('Hz') > 0: |
---|
[2349] | 1552 | offset = abs(freqcoord.to_frequency(1, |
---|
| 1553 | unit=frequnit) |
---|
| 1554 | -freqcoord.to_frequency(0, |
---|
| 1555 | unit=frequnit) |
---|
| 1556 | )*0.5 |
---|
[2013] | 1557 | elif frequnit.find('m/s') > 0: |
---|
[2349] | 1558 | offset = abs(freqcoord.to_velocity(1, |
---|
| 1559 | unit=frequnit) |
---|
| 1560 | -freqcoord.to_velocity(0, |
---|
| 1561 | unit=frequnit) |
---|
| 1562 | )*0.5 |
---|
[2013] | 1563 | else: |
---|
| 1564 | asaplog.post() |
---|
| 1565 | asaplog.push("Invalid frequency unit") |
---|
| 1566 | asaplog.post("ERROR") |
---|
| 1567 | del freqs, freqcoord, ifrow |
---|
| 1568 | for freq in freqmasklist: |
---|
| 1569 | selmask = freq or [minfreq, maxfreq] |
---|
| 1570 | if selmask[0] == None: |
---|
| 1571 | ## selection was "<freq[1]". |
---|
| 1572 | if selmask[1] < minfreq: |
---|
| 1573 | ## avoid adding region selection |
---|
| 1574 | selmask = None |
---|
| 1575 | else: |
---|
| 1576 | selmask = [minfreq,selmask[1]-offset] |
---|
| 1577 | elif selmask[1] == None: |
---|
| 1578 | ## selection was ">freq[0]" |
---|
| 1579 | if selmask[0] > maxfreq: |
---|
| 1580 | ## avoid adding region selection |
---|
| 1581 | selmask = None |
---|
| 1582 | else: |
---|
| 1583 | selmask = [selmask[0]+offset,maxfreq] |
---|
| 1584 | if selmask: |
---|
| 1585 | if not seldict.has_key(spwstr): |
---|
| 1586 | # new spw selection |
---|
| 1587 | seldict[spwstr] = [] |
---|
| 1588 | seldict[spwstr] += [selmask] |
---|
| 1589 | del minfreq,maxfreq,offset,freq,selmask |
---|
| 1590 | del spwstr |
---|
| 1591 | del freqmasklist |
---|
| 1592 | del valid_ifs |
---|
| 1593 | if len(seldict) == 0: |
---|
| 1594 | asaplog.post() |
---|
[2349] | 1595 | asaplog.push("No valid selection in the mask expression: " |
---|
| 1596 | +maskstring) |
---|
[2013] | 1597 | asaplog.post("WARN") |
---|
| 1598 | return None |
---|
| 1599 | msg = "Selected masklist:\n" |
---|
| 1600 | for sif, lmask in seldict.iteritems(): |
---|
| 1601 | msg += " IF"+sif+" - "+str(lmask)+"\n" |
---|
| 1602 | asaplog.push(msg) |
---|
| 1603 | return seldict |
---|
| 1604 | |
---|
[2611] | 1605 | @asaplog_post_dec |
---|
| 1606 | def parse_idx_selection(self, mode, selexpr): |
---|
| 1607 | """ |
---|
| 1608 | Parse CASA type mask selection syntax of SCANNO, IFNO, POLNO, |
---|
| 1609 | BEAMNO, and row number |
---|
| 1610 | |
---|
| 1611 | Parameters: |
---|
| 1612 | mode : which column to select. |
---|
| 1613 | ['scan',|'if'|'pol'|'beam'|'row'] |
---|
| 1614 | selexpr : A comma separated selection expression. |
---|
| 1615 | examples: |
---|
| 1616 | '' = all (returns []) |
---|
| 1617 | '<2,4~6,9' = indices less than 2, 4 to 6 and 9 |
---|
| 1618 | (returns [0,1,4,5,6,9]) |
---|
| 1619 | Returns: |
---|
| 1620 | A List of selected indices |
---|
| 1621 | """ |
---|
| 1622 | if selexpr == "": |
---|
| 1623 | return [] |
---|
| 1624 | valid_modes = {'s': 'scan', 'i': 'if', 'p': 'pol', |
---|
| 1625 | 'b': 'beam', 'r': 'row'} |
---|
| 1626 | smode = mode.lower()[0] |
---|
| 1627 | if not (smode in valid_modes.keys()): |
---|
| 1628 | msg = "Invalid mode '%s'. Valid modes are %s" %\ |
---|
| 1629 | (mode, str(valid_modes.values())) |
---|
| 1630 | asaplog.post() |
---|
| 1631 | asaplog.push(msg) |
---|
| 1632 | asaplog.post("ERROR") |
---|
| 1633 | mode = valid_modes[smode] |
---|
| 1634 | minidx = None |
---|
| 1635 | maxidx = None |
---|
| 1636 | if smode == 'r': |
---|
| 1637 | minidx = 0 |
---|
| 1638 | maxidx = self.nrow() |
---|
| 1639 | else: |
---|
| 1640 | idx = getattr(self,"get"+mode+"nos")() |
---|
| 1641 | minidx = min(idx) |
---|
| 1642 | maxidx = max(idx) |
---|
| 1643 | del idx |
---|
| 1644 | sellist = selexpr.split(',') |
---|
| 1645 | idxlist = [] |
---|
| 1646 | for currselstr in sellist: |
---|
| 1647 | # single range (may include ~, < or >) |
---|
| 1648 | currlist = self._parse_selection(currselstr, typestr='integer', |
---|
| 1649 | minval=minidx,maxval=maxidx) |
---|
| 1650 | for thelist in currlist: |
---|
| 1651 | idxlist += range(thelist[0],thelist[1]+1) |
---|
| 1652 | msg = "Selected %s: %s" % (mode.upper()+"NO", str(idxlist)) |
---|
| 1653 | asaplog.push(msg) |
---|
| 1654 | return idxlist |
---|
| 1655 | |
---|
[2349] | 1656 | def _parse_selection(self, selstr, typestr='float', offset=0., |
---|
[2351] | 1657 | minval=None, maxval=None): |
---|
[2013] | 1658 | """ |
---|
| 1659 | Parameters: |
---|
| 1660 | selstr : The Selection string, e.g., '<3;5~7;100~103;9' |
---|
| 1661 | typestr : The type of the values in returned list |
---|
| 1662 | ('integer' or 'float') |
---|
| 1663 | offset : The offset value to subtract from or add to |
---|
| 1664 | the boundary value if the selection string |
---|
[2611] | 1665 | includes '<' or '>' [Valid only for typestr='float'] |
---|
[2013] | 1666 | minval, maxval : The minimum/maximum values to set if the |
---|
| 1667 | selection string includes '<' or '>'. |
---|
| 1668 | The list element is filled with None by default. |
---|
| 1669 | Returns: |
---|
| 1670 | A list of min/max pair of selections. |
---|
| 1671 | Example: |
---|
[2611] | 1672 | _parse_selection('<3;5~7;9',typestr='int',minval=0) |
---|
| 1673 | --> returns [[0,2],[5,7],[9,9]] |
---|
| 1674 | _parse_selection('<3;5~7;9',typestr='float',offset=0.5,minval=0) |
---|
| 1675 | --> returns [[0.,2.5],[5.0,7.0],[9.,9.]] |
---|
[2013] | 1676 | """ |
---|
| 1677 | selgroups = selstr.split(';') |
---|
| 1678 | sellists = [] |
---|
| 1679 | if typestr.lower().startswith('int'): |
---|
| 1680 | formatfunc = int |
---|
[2611] | 1681 | offset = 1 |
---|
[2013] | 1682 | else: |
---|
| 1683 | formatfunc = float |
---|
| 1684 | |
---|
| 1685 | for currsel in selgroups: |
---|
| 1686 | if currsel.find('~') > 0: |
---|
[2611] | 1687 | # val0 <= x <= val1 |
---|
[2013] | 1688 | minsel = formatfunc(currsel.split('~')[0].strip()) |
---|
| 1689 | maxsel = formatfunc(currsel.split('~')[1].strip()) |
---|
[2611] | 1690 | elif currsel.strip().find('<=') > -1: |
---|
| 1691 | bound = currsel.split('<=') |
---|
| 1692 | try: # try "x <= val" |
---|
| 1693 | minsel = minval |
---|
| 1694 | maxsel = formatfunc(bound[1].strip()) |
---|
| 1695 | except ValueError: # now "val <= x" |
---|
| 1696 | minsel = formatfunc(bound[0].strip()) |
---|
| 1697 | maxsel = maxval |
---|
| 1698 | elif currsel.strip().find('>=') > -1: |
---|
| 1699 | bound = currsel.split('>=') |
---|
| 1700 | try: # try "x >= val" |
---|
| 1701 | minsel = formatfunc(bound[1].strip()) |
---|
| 1702 | maxsel = maxval |
---|
| 1703 | except ValueError: # now "val >= x" |
---|
| 1704 | minsel = minval |
---|
| 1705 | maxsel = formatfunc(bound[0].strip()) |
---|
| 1706 | elif currsel.strip().find('<') > -1: |
---|
| 1707 | bound = currsel.split('<') |
---|
| 1708 | try: # try "x < val" |
---|
| 1709 | minsel = minval |
---|
| 1710 | maxsel = formatfunc(bound[1].strip()) \ |
---|
| 1711 | - formatfunc(offset) |
---|
| 1712 | except ValueError: # now "val < x" |
---|
| 1713 | minsel = formatfunc(bound[0].strip()) \ |
---|
[2013] | 1714 | + formatfunc(offset) |
---|
[2611] | 1715 | maxsel = maxval |
---|
| 1716 | elif currsel.strip().find('>') > -1: |
---|
| 1717 | bound = currsel.split('>') |
---|
| 1718 | try: # try "x > val" |
---|
| 1719 | minsel = formatfunc(bound[1].strip()) \ |
---|
| 1720 | + formatfunc(offset) |
---|
| 1721 | maxsel = maxval |
---|
| 1722 | except ValueError: # now "val > x" |
---|
| 1723 | minsel = minval |
---|
| 1724 | maxsel = formatfunc(bound[0].strip()) \ |
---|
| 1725 | - formatfunc(offset) |
---|
[2013] | 1726 | else: |
---|
| 1727 | minsel = formatfunc(currsel) |
---|
| 1728 | maxsel = formatfunc(currsel) |
---|
| 1729 | sellists.append([minsel,maxsel]) |
---|
| 1730 | return sellists |
---|
| 1731 | |
---|
[1819] | 1732 | # def get_restfreqs(self): |
---|
| 1733 | # """ |
---|
| 1734 | # Get the restfrequency(s) stored in this scantable. |
---|
| 1735 | # The return value(s) are always of unit 'Hz' |
---|
| 1736 | # Parameters: |
---|
| 1737 | # none |
---|
| 1738 | # Returns: |
---|
| 1739 | # a list of doubles |
---|
| 1740 | # """ |
---|
| 1741 | # return list(self._getrestfreqs()) |
---|
| 1742 | |
---|
| 1743 | def get_restfreqs(self, ids=None): |
---|
[1846] | 1744 | """\ |
---|
[256] | 1745 | Get the restfrequency(s) stored in this scantable. |
---|
| 1746 | The return value(s) are always of unit 'Hz' |
---|
[1846] | 1747 | |
---|
[256] | 1748 | Parameters: |
---|
[1846] | 1749 | |
---|
[1819] | 1750 | ids: (optional) a list of MOLECULE_ID for that restfrequency(s) to |
---|
| 1751 | be retrieved |
---|
[1846] | 1752 | |
---|
[256] | 1753 | Returns: |
---|
[1846] | 1754 | |
---|
[1819] | 1755 | dictionary containing ids and a list of doubles for each id |
---|
[1846] | 1756 | |
---|
[256] | 1757 | """ |
---|
[1819] | 1758 | if ids is None: |
---|
[2349] | 1759 | rfreqs = {} |
---|
[1819] | 1760 | idlist = self.getmolnos() |
---|
| 1761 | for i in idlist: |
---|
[2349] | 1762 | rfreqs[i] = list(self._getrestfreqs(i)) |
---|
[1819] | 1763 | return rfreqs |
---|
| 1764 | else: |
---|
[2349] | 1765 | if type(ids) == list or type(ids) == tuple: |
---|
| 1766 | rfreqs = {} |
---|
[1819] | 1767 | for i in ids: |
---|
[2349] | 1768 | rfreqs[i] = list(self._getrestfreqs(i)) |
---|
[1819] | 1769 | return rfreqs |
---|
| 1770 | else: |
---|
| 1771 | return list(self._getrestfreqs(ids)) |
---|
[102] | 1772 | |
---|
[2349] | 1773 | @asaplog_post_dec |
---|
[931] | 1774 | def set_restfreqs(self, freqs=None, unit='Hz'): |
---|
[1846] | 1775 | """\ |
---|
[931] | 1776 | Set or replace the restfrequency specified and |
---|
[1938] | 1777 | if the 'freqs' argument holds a scalar, |
---|
[931] | 1778 | then that rest frequency will be applied to all the selected |
---|
| 1779 | data. If the 'freqs' argument holds |
---|
| 1780 | a vector, then it MUST be of equal or smaller length than |
---|
| 1781 | the number of IFs (and the available restfrequencies will be |
---|
| 1782 | replaced by this vector). In this case, *all* data have |
---|
| 1783 | the restfrequency set per IF according |
---|
| 1784 | to the corresponding value you give in the 'freqs' vector. |
---|
[1118] | 1785 | E.g. 'freqs=[1e9, 2e9]' would mean IF 0 gets restfreq 1e9 and |
---|
[931] | 1786 | IF 1 gets restfreq 2e9. |
---|
[1846] | 1787 | |
---|
[1395] | 1788 | You can also specify the frequencies via a linecatalog. |
---|
[1153] | 1789 | |
---|
[931] | 1790 | Parameters: |
---|
[1846] | 1791 | |
---|
[931] | 1792 | freqs: list of rest frequency values or string idenitfiers |
---|
[1855] | 1793 | |
---|
[931] | 1794 | unit: unit for rest frequency (default 'Hz') |
---|
[402] | 1795 | |
---|
[1846] | 1796 | |
---|
| 1797 | Example:: |
---|
| 1798 | |
---|
[1819] | 1799 | # set the given restfrequency for the all currently selected IFs |
---|
[931] | 1800 | scan.set_restfreqs(freqs=1.4e9) |
---|
[1845] | 1801 | # set restfrequencies for the n IFs (n > 1) in the order of the |
---|
| 1802 | # list, i.e |
---|
| 1803 | # IF0 -> 1.4e9, IF1 -> 1.41e9, IF3 -> 1.42e9 |
---|
| 1804 | # len(list_of_restfreqs) == nIF |
---|
| 1805 | # for nIF == 1 the following will set multiple restfrequency for |
---|
| 1806 | # that IF |
---|
[1819] | 1807 | scan.set_restfreqs(freqs=[1.4e9, 1.41e9, 1.42e9]) |
---|
[1845] | 1808 | # set multiple restfrequencies per IF. as a list of lists where |
---|
| 1809 | # the outer list has nIF elements, the inner s arbitrary |
---|
| 1810 | scan.set_restfreqs(freqs=[[1.4e9, 1.41e9], [1.67e9]]) |
---|
[391] | 1811 | |
---|
[1846] | 1812 | *Note*: |
---|
[1845] | 1813 | |
---|
[931] | 1814 | To do more sophisticate Restfrequency setting, e.g. on a |
---|
| 1815 | source and IF basis, use scantable.set_selection() before using |
---|
[1846] | 1816 | this function:: |
---|
[931] | 1817 | |
---|
[1846] | 1818 | # provided your scantable is called scan |
---|
| 1819 | selection = selector() |
---|
[2431] | 1820 | selection.set_name('ORION*') |
---|
[1846] | 1821 | selection.set_ifs([1]) |
---|
| 1822 | scan.set_selection(selection) |
---|
| 1823 | scan.set_restfreqs(freqs=86.6e9) |
---|
| 1824 | |
---|
[931] | 1825 | """ |
---|
| 1826 | varlist = vars() |
---|
[1157] | 1827 | from asap import linecatalog |
---|
| 1828 | # simple value |
---|
[1118] | 1829 | if isinstance(freqs, int) or isinstance(freqs, float): |
---|
[1845] | 1830 | self._setrestfreqs([freqs], [""], unit) |
---|
[1157] | 1831 | # list of values |
---|
[1118] | 1832 | elif isinstance(freqs, list) or isinstance(freqs, tuple): |
---|
[1157] | 1833 | # list values are scalars |
---|
[1118] | 1834 | if isinstance(freqs[-1], int) or isinstance(freqs[-1], float): |
---|
[1845] | 1835 | if len(freqs) == 1: |
---|
| 1836 | self._setrestfreqs(freqs, [""], unit) |
---|
| 1837 | else: |
---|
| 1838 | # allow the 'old' mode of setting mulitple IFs |
---|
| 1839 | savesel = self._getselection() |
---|
[2599] | 1840 | sel = self.get_selection() |
---|
[1845] | 1841 | iflist = self.getifnos() |
---|
| 1842 | if len(freqs)>len(iflist): |
---|
| 1843 | raise ValueError("number of elements in list of list " |
---|
| 1844 | "exeeds the current IF selections") |
---|
| 1845 | iflist = self.getifnos() |
---|
| 1846 | for i, fval in enumerate(freqs): |
---|
| 1847 | sel.set_ifs(iflist[i]) |
---|
| 1848 | self._setselection(sel) |
---|
| 1849 | self._setrestfreqs([fval], [""], unit) |
---|
| 1850 | self._setselection(savesel) |
---|
| 1851 | |
---|
| 1852 | # list values are dict, {'value'=, 'name'=) |
---|
[1157] | 1853 | elif isinstance(freqs[-1], dict): |
---|
[1845] | 1854 | values = [] |
---|
| 1855 | names = [] |
---|
| 1856 | for d in freqs: |
---|
| 1857 | values.append(d["value"]) |
---|
| 1858 | names.append(d["name"]) |
---|
| 1859 | self._setrestfreqs(values, names, unit) |
---|
[1819] | 1860 | elif isinstance(freqs[-1], list) or isinstance(freqs[-1], tuple): |
---|
[1157] | 1861 | savesel = self._getselection() |
---|
[2599] | 1862 | sel = self.get_selection() |
---|
[1322] | 1863 | iflist = self.getifnos() |
---|
[1819] | 1864 | if len(freqs)>len(iflist): |
---|
[1845] | 1865 | raise ValueError("number of elements in list of list exeeds" |
---|
| 1866 | " the current IF selections") |
---|
| 1867 | for i, fval in enumerate(freqs): |
---|
[1322] | 1868 | sel.set_ifs(iflist[i]) |
---|
[1259] | 1869 | self._setselection(sel) |
---|
[1845] | 1870 | self._setrestfreqs(fval, [""], unit) |
---|
[1157] | 1871 | self._setselection(savesel) |
---|
| 1872 | # freqs are to be taken from a linecatalog |
---|
[1153] | 1873 | elif isinstance(freqs, linecatalog): |
---|
| 1874 | savesel = self._getselection() |
---|
[2599] | 1875 | sel = self.get_selection() |
---|
[1153] | 1876 | for i in xrange(freqs.nrow()): |
---|
[1322] | 1877 | sel.set_ifs(iflist[i]) |
---|
[1153] | 1878 | self._setselection(sel) |
---|
[1845] | 1879 | self._setrestfreqs([freqs.get_frequency(i)], |
---|
| 1880 | [freqs.get_name(i)], "MHz") |
---|
[1153] | 1881 | # ensure that we are not iterating past nIF |
---|
| 1882 | if i == self.nif()-1: break |
---|
| 1883 | self._setselection(savesel) |
---|
[931] | 1884 | else: |
---|
| 1885 | return |
---|
| 1886 | self._add_history("set_restfreqs", varlist) |
---|
| 1887 | |
---|
[2349] | 1888 | @asaplog_post_dec |
---|
[1360] | 1889 | def shift_refpix(self, delta): |
---|
[1846] | 1890 | """\ |
---|
[1589] | 1891 | Shift the reference pixel of the Spectra Coordinate by an |
---|
| 1892 | integer amount. |
---|
[1846] | 1893 | |
---|
[1589] | 1894 | Parameters: |
---|
[1846] | 1895 | |
---|
[1589] | 1896 | delta: the amount to shift by |
---|
[1846] | 1897 | |
---|
| 1898 | *Note*: |
---|
| 1899 | |
---|
[1589] | 1900 | Be careful using this with broadband data. |
---|
[1846] | 1901 | |
---|
[1360] | 1902 | """ |
---|
[2349] | 1903 | varlist = vars() |
---|
[1731] | 1904 | Scantable.shift_refpix(self, delta) |
---|
[2349] | 1905 | s._add_history("shift_refpix", varlist) |
---|
[931] | 1906 | |
---|
[1862] | 1907 | @asaplog_post_dec |
---|
[1259] | 1908 | def history(self, filename=None): |
---|
[1846] | 1909 | """\ |
---|
[1259] | 1910 | Print the history. Optionally to a file. |
---|
[1846] | 1911 | |
---|
[1348] | 1912 | Parameters: |
---|
[1846] | 1913 | |
---|
[1928] | 1914 | filename: The name of the file to save the history to. |
---|
[1846] | 1915 | |
---|
[1259] | 1916 | """ |
---|
[484] | 1917 | hist = list(self._gethistory()) |
---|
[794] | 1918 | out = "-"*80 |
---|
[484] | 1919 | for h in hist: |
---|
[489] | 1920 | if h.startswith("---"): |
---|
[1857] | 1921 | out = "\n".join([out, h]) |
---|
[489] | 1922 | else: |
---|
| 1923 | items = h.split("##") |
---|
| 1924 | date = items[0] |
---|
| 1925 | func = items[1] |
---|
| 1926 | items = items[2:] |
---|
[794] | 1927 | out += "\n"+date+"\n" |
---|
| 1928 | out += "Function: %s\n Parameters:" % (func) |
---|
[489] | 1929 | for i in items: |
---|
[1938] | 1930 | if i == '': |
---|
| 1931 | continue |
---|
[489] | 1932 | s = i.split("=") |
---|
[1118] | 1933 | out += "\n %s = %s" % (s[0], s[1]) |
---|
[1857] | 1934 | out = "\n".join([out, "-"*80]) |
---|
[1259] | 1935 | if filename is not None: |
---|
| 1936 | if filename is "": |
---|
| 1937 | filename = 'scantable_history.txt' |
---|
| 1938 | import os |
---|
| 1939 | filename = os.path.expandvars(os.path.expanduser(filename)) |
---|
| 1940 | if not os.path.isdir(filename): |
---|
| 1941 | data = open(filename, 'w') |
---|
| 1942 | data.write(out) |
---|
| 1943 | data.close() |
---|
| 1944 | else: |
---|
| 1945 | msg = "Illegal file name '%s'." % (filename) |
---|
[1859] | 1946 | raise IOError(msg) |
---|
| 1947 | return page(out) |
---|
[2349] | 1948 | |
---|
[513] | 1949 | # |
---|
| 1950 | # Maths business |
---|
| 1951 | # |
---|
[1862] | 1952 | @asaplog_post_dec |
---|
[931] | 1953 | def average_time(self, mask=None, scanav=False, weight='tint', align=False): |
---|
[1846] | 1954 | """\ |
---|
[2349] | 1955 | Return the (time) weighted average of a scan. Scans will be averaged |
---|
| 1956 | only if the source direction (RA/DEC) is within 1' otherwise |
---|
[1846] | 1957 | |
---|
| 1958 | *Note*: |
---|
| 1959 | |
---|
[1070] | 1960 | in channels only - align if necessary |
---|
[1846] | 1961 | |
---|
[513] | 1962 | Parameters: |
---|
[1846] | 1963 | |
---|
[513] | 1964 | mask: an optional mask (only used for 'var' and 'tsys' |
---|
| 1965 | weighting) |
---|
[1855] | 1966 | |
---|
[558] | 1967 | scanav: True averages each scan separately |
---|
| 1968 | False (default) averages all scans together, |
---|
[1855] | 1969 | |
---|
[1099] | 1970 | weight: Weighting scheme. |
---|
| 1971 | 'none' (mean no weight) |
---|
| 1972 | 'var' (1/var(spec) weighted) |
---|
| 1973 | 'tsys' (1/Tsys**2 weighted) |
---|
| 1974 | 'tint' (integration time weighted) |
---|
| 1975 | 'tintsys' (Tint/Tsys**2) |
---|
| 1976 | 'median' ( median averaging) |
---|
[535] | 1977 | The default is 'tint' |
---|
[1855] | 1978 | |
---|
[931] | 1979 | align: align the spectra in velocity before averaging. It takes |
---|
| 1980 | the time of the first spectrum as reference time. |
---|
[1846] | 1981 | |
---|
| 1982 | Example:: |
---|
| 1983 | |
---|
[513] | 1984 | # time average the scantable without using a mask |
---|
[710] | 1985 | newscan = scan.average_time() |
---|
[1846] | 1986 | |
---|
[513] | 1987 | """ |
---|
| 1988 | varlist = vars() |
---|
[1593] | 1989 | weight = weight or 'TINT' |
---|
| 1990 | mask = mask or () |
---|
| 1991 | scanav = (scanav and 'SCAN') or 'NONE' |
---|
[1118] | 1992 | scan = (self, ) |
---|
[1859] | 1993 | |
---|
| 1994 | if align: |
---|
| 1995 | scan = (self.freq_align(insitu=False), ) |
---|
| 1996 | s = None |
---|
| 1997 | if weight.upper() == 'MEDIAN': |
---|
| 1998 | s = scantable(self._math._averagechannel(scan[0], 'MEDIAN', |
---|
| 1999 | scanav)) |
---|
| 2000 | else: |
---|
| 2001 | s = scantable(self._math._average(scan, mask, weight.upper(), |
---|
| 2002 | scanav)) |
---|
[1099] | 2003 | s._add_history("average_time", varlist) |
---|
[513] | 2004 | return s |
---|
[710] | 2005 | |
---|
[1862] | 2006 | @asaplog_post_dec |
---|
[876] | 2007 | def convert_flux(self, jyperk=None, eta=None, d=None, insitu=None): |
---|
[1846] | 2008 | """\ |
---|
[513] | 2009 | Return a scan where all spectra are converted to either |
---|
| 2010 | Jansky or Kelvin depending upon the flux units of the scan table. |
---|
| 2011 | By default the function tries to look the values up internally. |
---|
| 2012 | If it can't find them (or if you want to over-ride), you must |
---|
| 2013 | specify EITHER jyperk OR eta (and D which it will try to look up |
---|
| 2014 | also if you don't set it). jyperk takes precedence if you set both. |
---|
[1846] | 2015 | |
---|
[513] | 2016 | Parameters: |
---|
[1846] | 2017 | |
---|
[513] | 2018 | jyperk: the Jy / K conversion factor |
---|
[1855] | 2019 | |
---|
[513] | 2020 | eta: the aperture efficiency |
---|
[1855] | 2021 | |
---|
[1928] | 2022 | d: the geometric diameter (metres) |
---|
[1855] | 2023 | |
---|
[513] | 2024 | insitu: if False a new scantable is returned. |
---|
| 2025 | Otherwise, the scaling is done in-situ |
---|
| 2026 | The default is taken from .asaprc (False) |
---|
[1846] | 2027 | |
---|
[513] | 2028 | """ |
---|
| 2029 | if insitu is None: insitu = rcParams['insitu'] |
---|
[876] | 2030 | self._math._setinsitu(insitu) |
---|
[513] | 2031 | varlist = vars() |
---|
[1593] | 2032 | jyperk = jyperk or -1.0 |
---|
| 2033 | d = d or -1.0 |
---|
| 2034 | eta = eta or -1.0 |
---|
[876] | 2035 | s = scantable(self._math._convertflux(self, d, eta, jyperk)) |
---|
| 2036 | s._add_history("convert_flux", varlist) |
---|
| 2037 | if insitu: self._assign(s) |
---|
| 2038 | else: return s |
---|
[513] | 2039 | |
---|
[1862] | 2040 | @asaplog_post_dec |
---|
[876] | 2041 | def gain_el(self, poly=None, filename="", method="linear", insitu=None): |
---|
[1846] | 2042 | """\ |
---|
[513] | 2043 | Return a scan after applying a gain-elevation correction. |
---|
| 2044 | The correction can be made via either a polynomial or a |
---|
| 2045 | table-based interpolation (and extrapolation if necessary). |
---|
| 2046 | You specify polynomial coefficients, an ascii table or neither. |
---|
| 2047 | If you specify neither, then a polynomial correction will be made |
---|
| 2048 | with built in coefficients known for certain telescopes (an error |
---|
| 2049 | will occur if the instrument is not known). |
---|
| 2050 | The data and Tsys are *divided* by the scaling factors. |
---|
[1846] | 2051 | |
---|
[513] | 2052 | Parameters: |
---|
[1846] | 2053 | |
---|
[513] | 2054 | poly: Polynomial coefficients (default None) to compute a |
---|
| 2055 | gain-elevation correction as a function of |
---|
| 2056 | elevation (in degrees). |
---|
[1855] | 2057 | |
---|
[513] | 2058 | filename: The name of an ascii file holding correction factors. |
---|
| 2059 | The first row of the ascii file must give the column |
---|
| 2060 | names and these MUST include columns |
---|
[2431] | 2061 | 'ELEVATION' (degrees) and 'FACTOR' (multiply data |
---|
[513] | 2062 | by this) somewhere. |
---|
| 2063 | The second row must give the data type of the |
---|
| 2064 | column. Use 'R' for Real and 'I' for Integer. |
---|
| 2065 | An example file would be |
---|
| 2066 | (actual factors are arbitrary) : |
---|
| 2067 | |
---|
| 2068 | TIME ELEVATION FACTOR |
---|
| 2069 | R R R |
---|
| 2070 | 0.1 0 0.8 |
---|
| 2071 | 0.2 20 0.85 |
---|
| 2072 | 0.3 40 0.9 |
---|
| 2073 | 0.4 60 0.85 |
---|
| 2074 | 0.5 80 0.8 |
---|
| 2075 | 0.6 90 0.75 |
---|
[1855] | 2076 | |
---|
[513] | 2077 | method: Interpolation method when correcting from a table. |
---|
[2431] | 2078 | Values are 'nearest', 'linear' (default), 'cubic' |
---|
| 2079 | and 'spline' |
---|
[1855] | 2080 | |
---|
[513] | 2081 | insitu: if False a new scantable is returned. |
---|
| 2082 | Otherwise, the scaling is done in-situ |
---|
| 2083 | The default is taken from .asaprc (False) |
---|
[1846] | 2084 | |
---|
[513] | 2085 | """ |
---|
| 2086 | |
---|
| 2087 | if insitu is None: insitu = rcParams['insitu'] |
---|
[876] | 2088 | self._math._setinsitu(insitu) |
---|
[513] | 2089 | varlist = vars() |
---|
[1593] | 2090 | poly = poly or () |
---|
[513] | 2091 | from os.path import expandvars |
---|
| 2092 | filename = expandvars(filename) |
---|
[876] | 2093 | s = scantable(self._math._gainel(self, poly, filename, method)) |
---|
| 2094 | s._add_history("gain_el", varlist) |
---|
[1593] | 2095 | if insitu: |
---|
| 2096 | self._assign(s) |
---|
| 2097 | else: |
---|
| 2098 | return s |
---|
[710] | 2099 | |
---|
[1862] | 2100 | @asaplog_post_dec |
---|
[931] | 2101 | def freq_align(self, reftime=None, method='cubic', insitu=None): |
---|
[1846] | 2102 | """\ |
---|
[513] | 2103 | Return a scan where all rows have been aligned in frequency/velocity. |
---|
| 2104 | The alignment frequency frame (e.g. LSRK) is that set by function |
---|
| 2105 | set_freqframe. |
---|
[1846] | 2106 | |
---|
[513] | 2107 | Parameters: |
---|
[1855] | 2108 | |
---|
[513] | 2109 | reftime: reference time to align at. By default, the time of |
---|
| 2110 | the first row of data is used. |
---|
[1855] | 2111 | |
---|
[513] | 2112 | method: Interpolation method for regridding the spectra. |
---|
[2431] | 2113 | Choose from 'nearest', 'linear', 'cubic' (default) |
---|
| 2114 | and 'spline' |
---|
[1855] | 2115 | |
---|
[513] | 2116 | insitu: if False a new scantable is returned. |
---|
| 2117 | Otherwise, the scaling is done in-situ |
---|
| 2118 | The default is taken from .asaprc (False) |
---|
[1846] | 2119 | |
---|
[513] | 2120 | """ |
---|
[931] | 2121 | if insitu is None: insitu = rcParams["insitu"] |
---|
[2429] | 2122 | oldInsitu = self._math._insitu() |
---|
[876] | 2123 | self._math._setinsitu(insitu) |
---|
[513] | 2124 | varlist = vars() |
---|
[1593] | 2125 | reftime = reftime or "" |
---|
[931] | 2126 | s = scantable(self._math._freq_align(self, reftime, method)) |
---|
[876] | 2127 | s._add_history("freq_align", varlist) |
---|
[2429] | 2128 | self._math._setinsitu(oldInsitu) |
---|
[2349] | 2129 | if insitu: |
---|
| 2130 | self._assign(s) |
---|
| 2131 | else: |
---|
| 2132 | return s |
---|
[513] | 2133 | |
---|
[1862] | 2134 | @asaplog_post_dec |
---|
[1725] | 2135 | def opacity(self, tau=None, insitu=None): |
---|
[1846] | 2136 | """\ |
---|
[513] | 2137 | Apply an opacity correction. The data |
---|
| 2138 | and Tsys are multiplied by the correction factor. |
---|
[1846] | 2139 | |
---|
[513] | 2140 | Parameters: |
---|
[1855] | 2141 | |
---|
[1689] | 2142 | tau: (list of) opacity from which the correction factor is |
---|
[513] | 2143 | exp(tau*ZD) |
---|
[1689] | 2144 | where ZD is the zenith-distance. |
---|
| 2145 | If a list is provided, it has to be of length nIF, |
---|
| 2146 | nIF*nPol or 1 and in order of IF/POL, e.g. |
---|
| 2147 | [opif0pol0, opif0pol1, opif1pol0 ...] |
---|
[1725] | 2148 | if tau is `None` the opacities are determined from a |
---|
| 2149 | model. |
---|
[1855] | 2150 | |
---|
[513] | 2151 | insitu: if False a new scantable is returned. |
---|
| 2152 | Otherwise, the scaling is done in-situ |
---|
| 2153 | The default is taken from .asaprc (False) |
---|
[1846] | 2154 | |
---|
[513] | 2155 | """ |
---|
[2349] | 2156 | if insitu is None: |
---|
| 2157 | insitu = rcParams['insitu'] |
---|
[876] | 2158 | self._math._setinsitu(insitu) |
---|
[513] | 2159 | varlist = vars() |
---|
[1689] | 2160 | if not hasattr(tau, "__len__"): |
---|
| 2161 | tau = [tau] |
---|
[876] | 2162 | s = scantable(self._math._opacity(self, tau)) |
---|
| 2163 | s._add_history("opacity", varlist) |
---|
[2349] | 2164 | if insitu: |
---|
| 2165 | self._assign(s) |
---|
| 2166 | else: |
---|
| 2167 | return s |
---|
[513] | 2168 | |
---|
[1862] | 2169 | @asaplog_post_dec |
---|
[513] | 2170 | def bin(self, width=5, insitu=None): |
---|
[1846] | 2171 | """\ |
---|
[513] | 2172 | Return a scan where all spectra have been binned up. |
---|
[1846] | 2173 | |
---|
[1348] | 2174 | Parameters: |
---|
[1846] | 2175 | |
---|
[513] | 2176 | width: The bin width (default=5) in pixels |
---|
[1855] | 2177 | |
---|
[513] | 2178 | insitu: if False a new scantable is returned. |
---|
| 2179 | Otherwise, the scaling is done in-situ |
---|
| 2180 | The default is taken from .asaprc (False) |
---|
[1846] | 2181 | |
---|
[513] | 2182 | """ |
---|
[2349] | 2183 | if insitu is None: |
---|
| 2184 | insitu = rcParams['insitu'] |
---|
[876] | 2185 | self._math._setinsitu(insitu) |
---|
[513] | 2186 | varlist = vars() |
---|
[876] | 2187 | s = scantable(self._math._bin(self, width)) |
---|
[1118] | 2188 | s._add_history("bin", varlist) |
---|
[1589] | 2189 | if insitu: |
---|
| 2190 | self._assign(s) |
---|
| 2191 | else: |
---|
| 2192 | return s |
---|
[513] | 2193 | |
---|
[1862] | 2194 | @asaplog_post_dec |
---|
[2672] | 2195 | def reshape(self, first, last, insitu=None): |
---|
| 2196 | """Resize the band by providing first and last channel. |
---|
| 2197 | This will cut off all channels outside [first, last]. |
---|
| 2198 | """ |
---|
| 2199 | if insitu is None: |
---|
| 2200 | insitu = rcParams['insitu'] |
---|
| 2201 | varlist = vars() |
---|
| 2202 | if last < 0: |
---|
| 2203 | last = self.nchan()-1 + last |
---|
| 2204 | s = None |
---|
| 2205 | if insitu: |
---|
| 2206 | s = self |
---|
| 2207 | else: |
---|
| 2208 | s = self.copy() |
---|
| 2209 | s._reshape(first,last) |
---|
| 2210 | s._add_history("reshape", varlist) |
---|
| 2211 | if not insitu: |
---|
| 2212 | return s |
---|
| 2213 | |
---|
| 2214 | @asaplog_post_dec |
---|
[513] | 2215 | def resample(self, width=5, method='cubic', insitu=None): |
---|
[1846] | 2216 | """\ |
---|
[1348] | 2217 | Return a scan where all spectra have been binned up. |
---|
[1573] | 2218 | |
---|
[1348] | 2219 | Parameters: |
---|
[1846] | 2220 | |
---|
[513] | 2221 | width: The bin width (default=5) in pixels |
---|
[1855] | 2222 | |
---|
[513] | 2223 | method: Interpolation method when correcting from a table. |
---|
[2431] | 2224 | Values are 'nearest', 'linear', 'cubic' (default) |
---|
| 2225 | and 'spline' |
---|
[1855] | 2226 | |
---|
[513] | 2227 | insitu: if False a new scantable is returned. |
---|
| 2228 | Otherwise, the scaling is done in-situ |
---|
| 2229 | The default is taken from .asaprc (False) |
---|
[1846] | 2230 | |
---|
[513] | 2231 | """ |
---|
[2349] | 2232 | if insitu is None: |
---|
| 2233 | insitu = rcParams['insitu'] |
---|
[876] | 2234 | self._math._setinsitu(insitu) |
---|
[513] | 2235 | varlist = vars() |
---|
[876] | 2236 | s = scantable(self._math._resample(self, method, width)) |
---|
[1118] | 2237 | s._add_history("resample", varlist) |
---|
[2349] | 2238 | if insitu: |
---|
| 2239 | self._assign(s) |
---|
| 2240 | else: |
---|
| 2241 | return s |
---|
[513] | 2242 | |
---|
[1862] | 2243 | @asaplog_post_dec |
---|
[946] | 2244 | def average_pol(self, mask=None, weight='none'): |
---|
[1846] | 2245 | """\ |
---|
[946] | 2246 | Average the Polarisations together. |
---|
[1846] | 2247 | |
---|
[946] | 2248 | Parameters: |
---|
[1846] | 2249 | |
---|
[946] | 2250 | mask: An optional mask defining the region, where the |
---|
| 2251 | averaging will be applied. The output will have all |
---|
| 2252 | specified points masked. |
---|
[1855] | 2253 | |
---|
[946] | 2254 | weight: Weighting scheme. 'none' (default), 'var' (1/var(spec) |
---|
| 2255 | weighted), or 'tsys' (1/Tsys**2 weighted) |
---|
[1846] | 2256 | |
---|
[946] | 2257 | """ |
---|
| 2258 | varlist = vars() |
---|
[1593] | 2259 | mask = mask or () |
---|
[1010] | 2260 | s = scantable(self._math._averagepol(self, mask, weight.upper())) |
---|
[1118] | 2261 | s._add_history("average_pol", varlist) |
---|
[992] | 2262 | return s |
---|
[513] | 2263 | |
---|
[1862] | 2264 | @asaplog_post_dec |
---|
[1145] | 2265 | def average_beam(self, mask=None, weight='none'): |
---|
[1846] | 2266 | """\ |
---|
[1145] | 2267 | Average the Beams together. |
---|
[1846] | 2268 | |
---|
[1145] | 2269 | Parameters: |
---|
| 2270 | mask: An optional mask defining the region, where the |
---|
| 2271 | averaging will be applied. The output will have all |
---|
| 2272 | specified points masked. |
---|
[1855] | 2273 | |
---|
[1145] | 2274 | weight: Weighting scheme. 'none' (default), 'var' (1/var(spec) |
---|
| 2275 | weighted), or 'tsys' (1/Tsys**2 weighted) |
---|
[1846] | 2276 | |
---|
[1145] | 2277 | """ |
---|
| 2278 | varlist = vars() |
---|
[1593] | 2279 | mask = mask or () |
---|
[1145] | 2280 | s = scantable(self._math._averagebeams(self, mask, weight.upper())) |
---|
| 2281 | s._add_history("average_beam", varlist) |
---|
| 2282 | return s |
---|
| 2283 | |
---|
[1586] | 2284 | def parallactify(self, pflag): |
---|
[1846] | 2285 | """\ |
---|
[1843] | 2286 | Set a flag to indicate whether this data should be treated as having |
---|
[1617] | 2287 | been 'parallactified' (total phase == 0.0) |
---|
[1846] | 2288 | |
---|
[1617] | 2289 | Parameters: |
---|
[1855] | 2290 | |
---|
[1843] | 2291 | pflag: Bool indicating whether to turn this on (True) or |
---|
[1617] | 2292 | off (False) |
---|
[1846] | 2293 | |
---|
[1617] | 2294 | """ |
---|
[1586] | 2295 | varlist = vars() |
---|
| 2296 | self._parallactify(pflag) |
---|
| 2297 | self._add_history("parallactify", varlist) |
---|
| 2298 | |
---|
[1862] | 2299 | @asaplog_post_dec |
---|
[992] | 2300 | def convert_pol(self, poltype=None): |
---|
[1846] | 2301 | """\ |
---|
[992] | 2302 | Convert the data to a different polarisation type. |
---|
[1565] | 2303 | Note that you will need cross-polarisation terms for most conversions. |
---|
[1846] | 2304 | |
---|
[992] | 2305 | Parameters: |
---|
[1855] | 2306 | |
---|
[992] | 2307 | poltype: The new polarisation type. Valid types are: |
---|
[2431] | 2308 | 'linear', 'circular', 'stokes' and 'linpol' |
---|
[1846] | 2309 | |
---|
[992] | 2310 | """ |
---|
| 2311 | varlist = vars() |
---|
[1859] | 2312 | s = scantable(self._math._convertpol(self, poltype)) |
---|
[1118] | 2313 | s._add_history("convert_pol", varlist) |
---|
[992] | 2314 | return s |
---|
| 2315 | |
---|
[1862] | 2316 | @asaplog_post_dec |
---|
[2269] | 2317 | def smooth(self, kernel="hanning", width=5.0, order=2, plot=False, |
---|
| 2318 | insitu=None): |
---|
[1846] | 2319 | """\ |
---|
[513] | 2320 | Smooth the spectrum by the specified kernel (conserving flux). |
---|
[1846] | 2321 | |
---|
[513] | 2322 | Parameters: |
---|
[1846] | 2323 | |
---|
[513] | 2324 | kernel: The type of smoothing kernel. Select from |
---|
[1574] | 2325 | 'hanning' (default), 'gaussian', 'boxcar', 'rmedian' |
---|
| 2326 | or 'poly' |
---|
[1855] | 2327 | |
---|
[513] | 2328 | width: The width of the kernel in pixels. For hanning this is |
---|
| 2329 | ignored otherwise it defauls to 5 pixels. |
---|
| 2330 | For 'gaussian' it is the Full Width Half |
---|
| 2331 | Maximum. For 'boxcar' it is the full width. |
---|
[1574] | 2332 | For 'rmedian' and 'poly' it is the half width. |
---|
[1855] | 2333 | |
---|
[1574] | 2334 | order: Optional parameter for 'poly' kernel (default is 2), to |
---|
| 2335 | specify the order of the polnomial. Ignored by all other |
---|
| 2336 | kernels. |
---|
[1855] | 2337 | |
---|
[1819] | 2338 | plot: plot the original and the smoothed spectra. |
---|
| 2339 | In this each indivual fit has to be approved, by |
---|
| 2340 | typing 'y' or 'n' |
---|
[1855] | 2341 | |
---|
[513] | 2342 | insitu: if False a new scantable is returned. |
---|
| 2343 | Otherwise, the scaling is done in-situ |
---|
| 2344 | The default is taken from .asaprc (False) |
---|
[1846] | 2345 | |
---|
[513] | 2346 | """ |
---|
| 2347 | if insitu is None: insitu = rcParams['insitu'] |
---|
[876] | 2348 | self._math._setinsitu(insitu) |
---|
[513] | 2349 | varlist = vars() |
---|
[1819] | 2350 | |
---|
| 2351 | if plot: orgscan = self.copy() |
---|
| 2352 | |
---|
[1574] | 2353 | s = scantable(self._math._smooth(self, kernel.lower(), width, order)) |
---|
[876] | 2354 | s._add_history("smooth", varlist) |
---|
[1819] | 2355 | |
---|
[2610] | 2356 | action = 'H' |
---|
[1819] | 2357 | if plot: |
---|
[2150] | 2358 | from asap.asapplotter import new_asaplot |
---|
| 2359 | theplot = new_asaplot(rcParams['plotter.gui']) |
---|
[2535] | 2360 | from matplotlib import rc as rcp |
---|
| 2361 | rcp('lines', linewidth=1) |
---|
[2150] | 2362 | theplot.set_panels() |
---|
[1819] | 2363 | ylab=s._get_ordinate_label() |
---|
[2150] | 2364 | #theplot.palette(0,["#777777","red"]) |
---|
[1819] | 2365 | for r in xrange(s.nrow()): |
---|
| 2366 | xsm=s._getabcissa(r) |
---|
| 2367 | ysm=s._getspectrum(r) |
---|
| 2368 | xorg=orgscan._getabcissa(r) |
---|
| 2369 | yorg=orgscan._getspectrum(r) |
---|
[2610] | 2370 | if action != "N": #skip plotting if rejecting all |
---|
| 2371 | theplot.clear() |
---|
| 2372 | theplot.hold() |
---|
| 2373 | theplot.set_axes('ylabel',ylab) |
---|
| 2374 | theplot.set_axes('xlabel',s._getabcissalabel(r)) |
---|
| 2375 | theplot.set_axes('title',s._getsourcename(r)) |
---|
| 2376 | theplot.set_line(label='Original',color="#777777") |
---|
| 2377 | theplot.plot(xorg,yorg) |
---|
| 2378 | theplot.set_line(label='Smoothed',color="red") |
---|
| 2379 | theplot.plot(xsm,ysm) |
---|
| 2380 | ### Ugly part for legend |
---|
| 2381 | for i in [0,1]: |
---|
| 2382 | theplot.subplots[0]['lines'].append( |
---|
| 2383 | [theplot.subplots[0]['axes'].lines[i]] |
---|
| 2384 | ) |
---|
| 2385 | theplot.release() |
---|
| 2386 | ### Ugly part for legend |
---|
| 2387 | theplot.subplots[0]['lines']=[] |
---|
| 2388 | res = self._get_verify_action("Accept smoothing?",action) |
---|
| 2389 | #print "IF%d, POL%d: got result = %s" %(s.getif(r),s.getpol(r),res) |
---|
| 2390 | if r == 0: action = None |
---|
| 2391 | #res = raw_input("Accept smoothing ([y]/n): ") |
---|
[1819] | 2392 | if res.upper() == 'N': |
---|
[2610] | 2393 | # reject for the current rows |
---|
[1819] | 2394 | s._setspectrum(yorg, r) |
---|
[2610] | 2395 | elif res.upper() == 'R': |
---|
| 2396 | # reject all the following rows |
---|
| 2397 | action = "N" |
---|
| 2398 | s._setspectrum(yorg, r) |
---|
| 2399 | elif res.upper() == 'A': |
---|
| 2400 | # accept all the following rows |
---|
| 2401 | break |
---|
[2150] | 2402 | theplot.quit() |
---|
| 2403 | del theplot |
---|
[1819] | 2404 | del orgscan |
---|
| 2405 | |
---|
[876] | 2406 | if insitu: self._assign(s) |
---|
| 2407 | else: return s |
---|
[513] | 2408 | |
---|
[2186] | 2409 | @asaplog_post_dec |
---|
[2435] | 2410 | def regrid_channel(self, width=5, plot=False, insitu=None): |
---|
| 2411 | """\ |
---|
| 2412 | Regrid the spectra by the specified channel width |
---|
| 2413 | |
---|
| 2414 | Parameters: |
---|
| 2415 | |
---|
| 2416 | width: The channel width (float) of regridded spectra |
---|
| 2417 | in the current spectral unit. |
---|
| 2418 | |
---|
| 2419 | plot: [NOT IMPLEMENTED YET] |
---|
| 2420 | plot the original and the regridded spectra. |
---|
| 2421 | In this each indivual fit has to be approved, by |
---|
| 2422 | typing 'y' or 'n' |
---|
| 2423 | |
---|
| 2424 | insitu: if False a new scantable is returned. |
---|
| 2425 | Otherwise, the scaling is done in-situ |
---|
| 2426 | The default is taken from .asaprc (False) |
---|
| 2427 | |
---|
| 2428 | """ |
---|
| 2429 | if insitu is None: insitu = rcParams['insitu'] |
---|
| 2430 | varlist = vars() |
---|
| 2431 | |
---|
| 2432 | if plot: |
---|
| 2433 | asaplog.post() |
---|
| 2434 | asaplog.push("Verification plot is not implemtnetd yet.") |
---|
| 2435 | asaplog.post("WARN") |
---|
| 2436 | |
---|
| 2437 | s = self.copy() |
---|
| 2438 | s._regrid_specchan(width) |
---|
| 2439 | |
---|
| 2440 | s._add_history("regrid_channel", varlist) |
---|
| 2441 | |
---|
| 2442 | # if plot: |
---|
| 2443 | # from asap.asapplotter import new_asaplot |
---|
| 2444 | # theplot = new_asaplot(rcParams['plotter.gui']) |
---|
[2535] | 2445 | # from matplotlib import rc as rcp |
---|
| 2446 | # rcp('lines', linewidth=1) |
---|
[2435] | 2447 | # theplot.set_panels() |
---|
| 2448 | # ylab=s._get_ordinate_label() |
---|
| 2449 | # #theplot.palette(0,["#777777","red"]) |
---|
| 2450 | # for r in xrange(s.nrow()): |
---|
| 2451 | # xsm=s._getabcissa(r) |
---|
| 2452 | # ysm=s._getspectrum(r) |
---|
| 2453 | # xorg=orgscan._getabcissa(r) |
---|
| 2454 | # yorg=orgscan._getspectrum(r) |
---|
| 2455 | # theplot.clear() |
---|
| 2456 | # theplot.hold() |
---|
| 2457 | # theplot.set_axes('ylabel',ylab) |
---|
| 2458 | # theplot.set_axes('xlabel',s._getabcissalabel(r)) |
---|
| 2459 | # theplot.set_axes('title',s._getsourcename(r)) |
---|
| 2460 | # theplot.set_line(label='Original',color="#777777") |
---|
| 2461 | # theplot.plot(xorg,yorg) |
---|
| 2462 | # theplot.set_line(label='Smoothed',color="red") |
---|
| 2463 | # theplot.plot(xsm,ysm) |
---|
| 2464 | # ### Ugly part for legend |
---|
| 2465 | # for i in [0,1]: |
---|
| 2466 | # theplot.subplots[0]['lines'].append( |
---|
| 2467 | # [theplot.subplots[0]['axes'].lines[i]] |
---|
| 2468 | # ) |
---|
| 2469 | # theplot.release() |
---|
| 2470 | # ### Ugly part for legend |
---|
| 2471 | # theplot.subplots[0]['lines']=[] |
---|
| 2472 | # res = raw_input("Accept smoothing ([y]/n): ") |
---|
| 2473 | # if res.upper() == 'N': |
---|
| 2474 | # s._setspectrum(yorg, r) |
---|
| 2475 | # theplot.quit() |
---|
| 2476 | # del theplot |
---|
| 2477 | # del orgscan |
---|
| 2478 | |
---|
| 2479 | if insitu: self._assign(s) |
---|
| 2480 | else: return s |
---|
| 2481 | |
---|
| 2482 | @asaplog_post_dec |
---|
[2186] | 2483 | def _parse_wn(self, wn): |
---|
| 2484 | if isinstance(wn, list) or isinstance(wn, tuple): |
---|
| 2485 | return wn |
---|
| 2486 | elif isinstance(wn, int): |
---|
| 2487 | return [ wn ] |
---|
| 2488 | elif isinstance(wn, str): |
---|
[2277] | 2489 | if '-' in wn: # case 'a-b' : return [a,a+1,...,b-1,b] |
---|
[2186] | 2490 | val = wn.split('-') |
---|
| 2491 | val = [int(val[0]), int(val[1])] |
---|
| 2492 | val.sort() |
---|
| 2493 | res = [i for i in xrange(val[0], val[1]+1)] |
---|
[2277] | 2494 | elif wn[:2] == '<=' or wn[:2] == '=<': # cases '<=a','=<a' : return [0,1,...,a-1,a] |
---|
[2186] | 2495 | val = int(wn[2:])+1 |
---|
| 2496 | res = [i for i in xrange(val)] |
---|
[2277] | 2497 | elif wn[-2:] == '>=' or wn[-2:] == '=>': # cases 'a>=','a=>' : return [0,1,...,a-1,a] |
---|
[2186] | 2498 | val = int(wn[:-2])+1 |
---|
| 2499 | res = [i for i in xrange(val)] |
---|
[2277] | 2500 | elif wn[0] == '<': # case '<a' : return [0,1,...,a-2,a-1] |
---|
[2186] | 2501 | val = int(wn[1:]) |
---|
| 2502 | res = [i for i in xrange(val)] |
---|
[2277] | 2503 | elif wn[-1] == '>': # case 'a>' : return [0,1,...,a-2,a-1] |
---|
[2186] | 2504 | val = int(wn[:-1]) |
---|
| 2505 | res = [i for i in xrange(val)] |
---|
[2411] | 2506 | elif wn[:2] == '>=' or wn[:2] == '=>': # cases '>=a','=>a' : return [a,-999], which is |
---|
| 2507 | # then interpreted in C++ |
---|
| 2508 | # side as [a,a+1,...,a_nyq] |
---|
| 2509 | # (CAS-3759) |
---|
[2186] | 2510 | val = int(wn[2:]) |
---|
[2411] | 2511 | res = [val, -999] |
---|
| 2512 | #res = [i for i in xrange(val, self.nchan()/2+1)] |
---|
| 2513 | elif wn[-2:] == '<=' or wn[-2:] == '=<': # cases 'a<=','a=<' : return [a,-999], which is |
---|
| 2514 | # then interpreted in C++ |
---|
| 2515 | # side as [a,a+1,...,a_nyq] |
---|
| 2516 | # (CAS-3759) |
---|
[2186] | 2517 | val = int(wn[:-2]) |
---|
[2411] | 2518 | res = [val, -999] |
---|
| 2519 | #res = [i for i in xrange(val, self.nchan()/2+1)] |
---|
| 2520 | elif wn[0] == '>': # case '>a' : return [a+1,-999], which is |
---|
| 2521 | # then interpreted in C++ |
---|
| 2522 | # side as [a+1,a+2,...,a_nyq] |
---|
| 2523 | # (CAS-3759) |
---|
[2186] | 2524 | val = int(wn[1:])+1 |
---|
[2411] | 2525 | res = [val, -999] |
---|
| 2526 | #res = [i for i in xrange(val, self.nchan()/2+1)] |
---|
| 2527 | elif wn[-1] == '<': # case 'a<' : return [a+1,-999], which is |
---|
| 2528 | # then interpreted in C++ |
---|
| 2529 | # side as [a+1,a+2,...,a_nyq] |
---|
| 2530 | # (CAS-3759) |
---|
[2186] | 2531 | val = int(wn[:-1])+1 |
---|
[2411] | 2532 | res = [val, -999] |
---|
| 2533 | #res = [i for i in xrange(val, self.nchan()/2+1)] |
---|
[2012] | 2534 | |
---|
[2186] | 2535 | return res |
---|
| 2536 | else: |
---|
| 2537 | msg = 'wrong value given for addwn/rejwn' |
---|
| 2538 | raise RuntimeError(msg) |
---|
| 2539 | |
---|
[2713] | 2540 | @asaplog_post_dec |
---|
| 2541 | def calc_aic(self, value=None, blfunc=None, order=None, mask=None, |
---|
| 2542 | whichrow=None, uselinefinder=None, edge=None, |
---|
| 2543 | threshold=None, chan_avg_limit=None): |
---|
| 2544 | """\ |
---|
| 2545 | Calculates and returns model selection criteria for a specified |
---|
| 2546 | baseline model and a given spectrum data. |
---|
| 2547 | Available values include Akaike Information Criterion (AIC), the |
---|
| 2548 | corrected Akaike Information Criterion (AICc) by Sugiura(1978), |
---|
| 2549 | Bayesian Information Criterion (BIC) and the Generalised Cross |
---|
| 2550 | Validation (GCV). |
---|
[2186] | 2551 | |
---|
[2713] | 2552 | Parameters: |
---|
| 2553 | value: name of model selection criteria to calculate. |
---|
| 2554 | available ones include 'aic', 'aicc', 'bic' and |
---|
| 2555 | 'gcv'. default is 'aicc'. |
---|
| 2556 | blfunc: baseline function name. available ones include |
---|
| 2557 | 'chebyshev', 'cspline' and 'sinusoid'. |
---|
| 2558 | default is 'chebyshev'. |
---|
| 2559 | order: parameter for basline function. actually stands for |
---|
| 2560 | order of polynomial (order) for 'chebyshev', |
---|
| 2561 | number of spline pieces (npiece) for 'cspline' and |
---|
| 2562 | maximum wave number for 'sinusoid', respectively. |
---|
| 2563 | default is 5 (which is also the default order value |
---|
| 2564 | for [auto_]chebyshev_baseline()). |
---|
| 2565 | mask: an optional mask. default is []. |
---|
| 2566 | whichrow: row number. default is 0 (the first row) |
---|
| 2567 | uselinefinder: use sd.linefinder() to flag out line regions |
---|
| 2568 | default is True. |
---|
| 2569 | edge: an optional number of channel to drop at |
---|
| 2570 | the edge of spectrum. If only one value is |
---|
| 2571 | specified, the same number will be dropped |
---|
| 2572 | from both sides of the spectrum. Default |
---|
| 2573 | is to keep all channels. Nested tuples |
---|
| 2574 | represent individual edge selection for |
---|
| 2575 | different IFs (a number of spectral channels |
---|
| 2576 | can be different) |
---|
| 2577 | default is (0, 0). |
---|
| 2578 | threshold: the threshold used by line finder. It is |
---|
| 2579 | better to keep it large as only strong lines |
---|
| 2580 | affect the baseline solution. |
---|
| 2581 | default is 3. |
---|
| 2582 | chan_avg_limit: a maximum number of consequtive spectral |
---|
| 2583 | channels to average during the search of |
---|
| 2584 | weak and broad lines. The default is no |
---|
| 2585 | averaging (and no search for weak lines). |
---|
| 2586 | If such lines can affect the fitted baseline |
---|
| 2587 | (e.g. a high order polynomial is fitted), |
---|
| 2588 | increase this parameter (usually values up |
---|
| 2589 | to 8 are reasonable). Most users of this |
---|
| 2590 | method should find the default value sufficient. |
---|
| 2591 | default is 1. |
---|
| 2592 | |
---|
| 2593 | Example: |
---|
| 2594 | aic = scan.calc_aic(blfunc='chebyshev', order=5, whichrow=0) |
---|
| 2595 | """ |
---|
| 2596 | |
---|
| 2597 | try: |
---|
| 2598 | varlist = vars() |
---|
| 2599 | |
---|
| 2600 | if value is None: value = 'aicc' |
---|
| 2601 | if blfunc is None: blfunc = 'chebyshev' |
---|
| 2602 | if order is None: order = 5 |
---|
| 2603 | if mask is None: mask = [] |
---|
| 2604 | if whichrow is None: whichrow = 0 |
---|
| 2605 | if uselinefinder is None: uselinefinder = True |
---|
| 2606 | if edge is None: edge = (0, 0) |
---|
| 2607 | if threshold is None: threshold = 3 |
---|
| 2608 | if chan_avg_limit is None: chan_avg_limit = 1 |
---|
| 2609 | |
---|
| 2610 | return self._calc_aic(value, blfunc, order, mask, |
---|
| 2611 | whichrow, uselinefinder, edge, |
---|
| 2612 | threshold, chan_avg_limit) |
---|
| 2613 | |
---|
| 2614 | except RuntimeError, e: |
---|
| 2615 | raise_fitting_failure_exception(e) |
---|
| 2616 | |
---|
[1862] | 2617 | @asaplog_post_dec |
---|
[2277] | 2618 | def sinusoid_baseline(self, insitu=None, mask=None, applyfft=None, |
---|
[2269] | 2619 | fftmethod=None, fftthresh=None, |
---|
| 2620 | addwn=None, rejwn=None, clipthresh=None, |
---|
| 2621 | clipniter=None, plot=None, |
---|
| 2622 | getresidual=None, showprogress=None, |
---|
[2641] | 2623 | minnrow=None, outlog=None, blfile=None, csvformat=None): |
---|
[2047] | 2624 | """\ |
---|
[2349] | 2625 | Return a scan which has been baselined (all rows) with sinusoidal |
---|
| 2626 | functions. |
---|
| 2627 | |
---|
[2047] | 2628 | Parameters: |
---|
[2186] | 2629 | insitu: if False a new scantable is returned. |
---|
[2081] | 2630 | Otherwise, the scaling is done in-situ |
---|
| 2631 | The default is taken from .asaprc (False) |
---|
[2186] | 2632 | mask: an optional mask |
---|
| 2633 | applyfft: if True use some method, such as FFT, to find |
---|
| 2634 | strongest sinusoidal components in the wavenumber |
---|
| 2635 | domain to be used for baseline fitting. |
---|
| 2636 | default is True. |
---|
| 2637 | fftmethod: method to find the strong sinusoidal components. |
---|
| 2638 | now only 'fft' is available and it is the default. |
---|
| 2639 | fftthresh: the threshold to select wave numbers to be used for |
---|
| 2640 | fitting from the distribution of amplitudes in the |
---|
| 2641 | wavenumber domain. |
---|
| 2642 | both float and string values accepted. |
---|
| 2643 | given a float value, the unit is set to sigma. |
---|
| 2644 | for string values, allowed formats include: |
---|
[2349] | 2645 | 'xsigma' or 'x' (= x-sigma level. e.g., |
---|
| 2646 | '3sigma'), or |
---|
[2186] | 2647 | 'topx' (= the x strongest ones, e.g. 'top5'). |
---|
| 2648 | default is 3.0 (unit: sigma). |
---|
| 2649 | addwn: the additional wave numbers to be used for fitting. |
---|
| 2650 | list or integer value is accepted to specify every |
---|
| 2651 | wave numbers. also string value can be used in case |
---|
| 2652 | you need to specify wave numbers in a certain range, |
---|
| 2653 | e.g., 'a-b' (= a, a+1, a+2, ..., b-1, b), |
---|
| 2654 | '<a' (= 0,1,...,a-2,a-1), |
---|
| 2655 | '>=a' (= a, a+1, ... up to the maximum wave |
---|
| 2656 | number corresponding to the Nyquist |
---|
| 2657 | frequency for the case of FFT). |
---|
[2411] | 2658 | default is [0]. |
---|
[2186] | 2659 | rejwn: the wave numbers NOT to be used for fitting. |
---|
| 2660 | can be set just as addwn but has higher priority: |
---|
| 2661 | wave numbers which are specified both in addwn |
---|
| 2662 | and rejwn will NOT be used. default is []. |
---|
[2081] | 2663 | clipthresh: Clipping threshold. (default is 3.0, unit: sigma) |
---|
[2349] | 2664 | clipniter: maximum number of iteration of 'clipthresh'-sigma |
---|
| 2665 | clipping (default is 0) |
---|
[2081] | 2666 | plot: *** CURRENTLY UNAVAILABLE, ALWAYS FALSE *** |
---|
| 2667 | plot the fit and the residual. In this each |
---|
| 2668 | indivual fit has to be approved, by typing 'y' |
---|
| 2669 | or 'n' |
---|
| 2670 | getresidual: if False, returns best-fit values instead of |
---|
| 2671 | residual. (default is True) |
---|
[2189] | 2672 | showprogress: show progress status for large data. |
---|
| 2673 | default is True. |
---|
| 2674 | minnrow: minimum number of input spectra to show. |
---|
| 2675 | default is 1000. |
---|
[2081] | 2676 | outlog: Output the coefficients of the best-fit |
---|
| 2677 | function to logger (default is False) |
---|
| 2678 | blfile: Name of a text file in which the best-fit |
---|
| 2679 | parameter values to be written |
---|
[2186] | 2680 | (default is '': no file/logger output) |
---|
[2641] | 2681 | csvformat: if True blfile is csv-formatted, default is False. |
---|
[2047] | 2682 | |
---|
| 2683 | Example: |
---|
[2349] | 2684 | # return a scan baselined by a combination of sinusoidal curves |
---|
| 2685 | # having wave numbers in spectral window up to 10, |
---|
[2047] | 2686 | # also with 3-sigma clipping, iteration up to 4 times |
---|
[2186] | 2687 | bscan = scan.sinusoid_baseline(addwn='<=10',clipthresh=3.0,clipniter=4) |
---|
[2081] | 2688 | |
---|
| 2689 | Note: |
---|
| 2690 | The best-fit parameter values output in logger and/or blfile are now |
---|
| 2691 | based on specunit of 'channel'. |
---|
[2047] | 2692 | """ |
---|
| 2693 | |
---|
[2186] | 2694 | try: |
---|
| 2695 | varlist = vars() |
---|
[2047] | 2696 | |
---|
[2186] | 2697 | if insitu is None: insitu = rcParams['insitu'] |
---|
| 2698 | if insitu: |
---|
| 2699 | workscan = self |
---|
| 2700 | else: |
---|
| 2701 | workscan = self.copy() |
---|
| 2702 | |
---|
[2410] | 2703 | #if mask is None: mask = [True for i in xrange(workscan.nchan())] |
---|
| 2704 | if mask is None: mask = [] |
---|
[2186] | 2705 | if applyfft is None: applyfft = True |
---|
| 2706 | if fftmethod is None: fftmethod = 'fft' |
---|
| 2707 | if fftthresh is None: fftthresh = 3.0 |
---|
[2411] | 2708 | if addwn is None: addwn = [0] |
---|
[2186] | 2709 | if rejwn is None: rejwn = [] |
---|
| 2710 | if clipthresh is None: clipthresh = 3.0 |
---|
| 2711 | if clipniter is None: clipniter = 0 |
---|
| 2712 | if plot is None: plot = False |
---|
| 2713 | if getresidual is None: getresidual = True |
---|
[2189] | 2714 | if showprogress is None: showprogress = True |
---|
| 2715 | if minnrow is None: minnrow = 1000 |
---|
[2186] | 2716 | if outlog is None: outlog = False |
---|
| 2717 | if blfile is None: blfile = '' |
---|
[2641] | 2718 | if csvformat is None: csvformat = False |
---|
[2047] | 2719 | |
---|
[2641] | 2720 | if csvformat: |
---|
| 2721 | scsvformat = "T" |
---|
| 2722 | else: |
---|
| 2723 | scsvformat = "F" |
---|
| 2724 | |
---|
[2081] | 2725 | #CURRENTLY, PLOT=true is UNAVAILABLE UNTIL sinusoidal fitting is implemented as a fitter method. |
---|
[2349] | 2726 | workscan._sinusoid_baseline(mask, applyfft, fftmethod.lower(), |
---|
| 2727 | str(fftthresh).lower(), |
---|
| 2728 | workscan._parse_wn(addwn), |
---|
[2643] | 2729 | workscan._parse_wn(rejwn), |
---|
| 2730 | clipthresh, clipniter, |
---|
| 2731 | getresidual, |
---|
[2349] | 2732 | pack_progress_params(showprogress, |
---|
[2641] | 2733 | minnrow), |
---|
| 2734 | outlog, scsvformat+blfile) |
---|
[2186] | 2735 | workscan._add_history('sinusoid_baseline', varlist) |
---|
[2047] | 2736 | |
---|
| 2737 | if insitu: |
---|
| 2738 | self._assign(workscan) |
---|
| 2739 | else: |
---|
| 2740 | return workscan |
---|
| 2741 | |
---|
| 2742 | except RuntimeError, e: |
---|
[2186] | 2743 | raise_fitting_failure_exception(e) |
---|
[2047] | 2744 | |
---|
| 2745 | |
---|
[2186] | 2746 | @asaplog_post_dec |
---|
[2349] | 2747 | def auto_sinusoid_baseline(self, insitu=None, mask=None, applyfft=None, |
---|
| 2748 | fftmethod=None, fftthresh=None, |
---|
| 2749 | addwn=None, rejwn=None, clipthresh=None, |
---|
| 2750 | clipniter=None, edge=None, threshold=None, |
---|
| 2751 | chan_avg_limit=None, plot=None, |
---|
| 2752 | getresidual=None, showprogress=None, |
---|
[2641] | 2753 | minnrow=None, outlog=None, blfile=None, csvformat=None): |
---|
[2047] | 2754 | """\ |
---|
[2349] | 2755 | Return a scan which has been baselined (all rows) with sinusoidal |
---|
| 2756 | functions. |
---|
[2047] | 2757 | Spectral lines are detected first using linefinder and masked out |
---|
| 2758 | to avoid them affecting the baseline solution. |
---|
| 2759 | |
---|
| 2760 | Parameters: |
---|
[2189] | 2761 | insitu: if False a new scantable is returned. |
---|
| 2762 | Otherwise, the scaling is done in-situ |
---|
| 2763 | The default is taken from .asaprc (False) |
---|
| 2764 | mask: an optional mask retreived from scantable |
---|
| 2765 | applyfft: if True use some method, such as FFT, to find |
---|
| 2766 | strongest sinusoidal components in the wavenumber |
---|
| 2767 | domain to be used for baseline fitting. |
---|
| 2768 | default is True. |
---|
| 2769 | fftmethod: method to find the strong sinusoidal components. |
---|
| 2770 | now only 'fft' is available and it is the default. |
---|
| 2771 | fftthresh: the threshold to select wave numbers to be used for |
---|
| 2772 | fitting from the distribution of amplitudes in the |
---|
| 2773 | wavenumber domain. |
---|
| 2774 | both float and string values accepted. |
---|
| 2775 | given a float value, the unit is set to sigma. |
---|
| 2776 | for string values, allowed formats include: |
---|
[2349] | 2777 | 'xsigma' or 'x' (= x-sigma level. e.g., |
---|
| 2778 | '3sigma'), or |
---|
[2189] | 2779 | 'topx' (= the x strongest ones, e.g. 'top5'). |
---|
| 2780 | default is 3.0 (unit: sigma). |
---|
| 2781 | addwn: the additional wave numbers to be used for fitting. |
---|
| 2782 | list or integer value is accepted to specify every |
---|
| 2783 | wave numbers. also string value can be used in case |
---|
| 2784 | you need to specify wave numbers in a certain range, |
---|
| 2785 | e.g., 'a-b' (= a, a+1, a+2, ..., b-1, b), |
---|
| 2786 | '<a' (= 0,1,...,a-2,a-1), |
---|
| 2787 | '>=a' (= a, a+1, ... up to the maximum wave |
---|
| 2788 | number corresponding to the Nyquist |
---|
| 2789 | frequency for the case of FFT). |
---|
[2411] | 2790 | default is [0]. |
---|
[2189] | 2791 | rejwn: the wave numbers NOT to be used for fitting. |
---|
| 2792 | can be set just as addwn but has higher priority: |
---|
| 2793 | wave numbers which are specified both in addwn |
---|
| 2794 | and rejwn will NOT be used. default is []. |
---|
| 2795 | clipthresh: Clipping threshold. (default is 3.0, unit: sigma) |
---|
[2349] | 2796 | clipniter: maximum number of iteration of 'clipthresh'-sigma |
---|
| 2797 | clipping (default is 0) |
---|
[2189] | 2798 | edge: an optional number of channel to drop at |
---|
| 2799 | the edge of spectrum. If only one value is |
---|
| 2800 | specified, the same number will be dropped |
---|
| 2801 | from both sides of the spectrum. Default |
---|
| 2802 | is to keep all channels. Nested tuples |
---|
| 2803 | represent individual edge selection for |
---|
| 2804 | different IFs (a number of spectral channels |
---|
| 2805 | can be different) |
---|
| 2806 | threshold: the threshold used by line finder. It is |
---|
| 2807 | better to keep it large as only strong lines |
---|
| 2808 | affect the baseline solution. |
---|
| 2809 | chan_avg_limit: a maximum number of consequtive spectral |
---|
| 2810 | channels to average during the search of |
---|
| 2811 | weak and broad lines. The default is no |
---|
| 2812 | averaging (and no search for weak lines). |
---|
| 2813 | If such lines can affect the fitted baseline |
---|
| 2814 | (e.g. a high order polynomial is fitted), |
---|
| 2815 | increase this parameter (usually values up |
---|
| 2816 | to 8 are reasonable). Most users of this |
---|
| 2817 | method should find the default value sufficient. |
---|
| 2818 | plot: *** CURRENTLY UNAVAILABLE, ALWAYS FALSE *** |
---|
| 2819 | plot the fit and the residual. In this each |
---|
| 2820 | indivual fit has to be approved, by typing 'y' |
---|
| 2821 | or 'n' |
---|
| 2822 | getresidual: if False, returns best-fit values instead of |
---|
| 2823 | residual. (default is True) |
---|
| 2824 | showprogress: show progress status for large data. |
---|
| 2825 | default is True. |
---|
| 2826 | minnrow: minimum number of input spectra to show. |
---|
| 2827 | default is 1000. |
---|
| 2828 | outlog: Output the coefficients of the best-fit |
---|
| 2829 | function to logger (default is False) |
---|
| 2830 | blfile: Name of a text file in which the best-fit |
---|
| 2831 | parameter values to be written |
---|
| 2832 | (default is "": no file/logger output) |
---|
[2641] | 2833 | csvformat: if True blfile is csv-formatted, default is False. |
---|
[2047] | 2834 | |
---|
| 2835 | Example: |
---|
[2186] | 2836 | bscan = scan.auto_sinusoid_baseline(addwn='<=10', insitu=False) |
---|
[2081] | 2837 | |
---|
| 2838 | Note: |
---|
| 2839 | The best-fit parameter values output in logger and/or blfile are now |
---|
| 2840 | based on specunit of 'channel'. |
---|
[2047] | 2841 | """ |
---|
| 2842 | |
---|
[2186] | 2843 | try: |
---|
| 2844 | varlist = vars() |
---|
[2047] | 2845 | |
---|
[2186] | 2846 | if insitu is None: insitu = rcParams['insitu'] |
---|
| 2847 | if insitu: |
---|
| 2848 | workscan = self |
---|
[2047] | 2849 | else: |
---|
[2186] | 2850 | workscan = self.copy() |
---|
| 2851 | |
---|
[2410] | 2852 | #if mask is None: mask = [True for i in xrange(workscan.nchan())] |
---|
| 2853 | if mask is None: mask = [] |
---|
[2186] | 2854 | if applyfft is None: applyfft = True |
---|
| 2855 | if fftmethod is None: fftmethod = 'fft' |
---|
| 2856 | if fftthresh is None: fftthresh = 3.0 |
---|
[2411] | 2857 | if addwn is None: addwn = [0] |
---|
[2186] | 2858 | if rejwn is None: rejwn = [] |
---|
| 2859 | if clipthresh is None: clipthresh = 3.0 |
---|
| 2860 | if clipniter is None: clipniter = 0 |
---|
| 2861 | if edge is None: edge = (0,0) |
---|
| 2862 | if threshold is None: threshold = 3 |
---|
| 2863 | if chan_avg_limit is None: chan_avg_limit = 1 |
---|
| 2864 | if plot is None: plot = False |
---|
| 2865 | if getresidual is None: getresidual = True |
---|
[2189] | 2866 | if showprogress is None: showprogress = True |
---|
| 2867 | if minnrow is None: minnrow = 1000 |
---|
[2186] | 2868 | if outlog is None: outlog = False |
---|
| 2869 | if blfile is None: blfile = '' |
---|
[2641] | 2870 | if csvformat is None: csvformat = False |
---|
[2047] | 2871 | |
---|
[2641] | 2872 | if csvformat: |
---|
| 2873 | scsvformat = "T" |
---|
| 2874 | else: |
---|
| 2875 | scsvformat = "F" |
---|
| 2876 | |
---|
[2277] | 2877 | #CURRENTLY, PLOT=true is UNAVAILABLE UNTIL sinusoidal fitting is implemented as a fitter method. |
---|
[2349] | 2878 | workscan._auto_sinusoid_baseline(mask, applyfft, |
---|
| 2879 | fftmethod.lower(), |
---|
| 2880 | str(fftthresh).lower(), |
---|
| 2881 | workscan._parse_wn(addwn), |
---|
| 2882 | workscan._parse_wn(rejwn), |
---|
| 2883 | clipthresh, clipniter, |
---|
| 2884 | normalise_edge_param(edge), |
---|
| 2885 | threshold, chan_avg_limit, |
---|
| 2886 | getresidual, |
---|
| 2887 | pack_progress_params(showprogress, |
---|
| 2888 | minnrow), |
---|
[2641] | 2889 | outlog, scsvformat+blfile) |
---|
[2047] | 2890 | workscan._add_history("auto_sinusoid_baseline", varlist) |
---|
| 2891 | |
---|
| 2892 | if insitu: |
---|
| 2893 | self._assign(workscan) |
---|
| 2894 | else: |
---|
| 2895 | return workscan |
---|
| 2896 | |
---|
| 2897 | except RuntimeError, e: |
---|
[2186] | 2898 | raise_fitting_failure_exception(e) |
---|
[2047] | 2899 | |
---|
| 2900 | @asaplog_post_dec |
---|
[2349] | 2901 | def cspline_baseline(self, insitu=None, mask=None, npiece=None, |
---|
| 2902 | clipthresh=None, clipniter=None, plot=None, |
---|
| 2903 | getresidual=None, showprogress=None, minnrow=None, |
---|
[2641] | 2904 | outlog=None, blfile=None, csvformat=None): |
---|
[1846] | 2905 | """\ |
---|
[2349] | 2906 | Return a scan which has been baselined (all rows) by cubic spline |
---|
| 2907 | function (piecewise cubic polynomial). |
---|
| 2908 | |
---|
[513] | 2909 | Parameters: |
---|
[2189] | 2910 | insitu: If False a new scantable is returned. |
---|
| 2911 | Otherwise, the scaling is done in-situ |
---|
| 2912 | The default is taken from .asaprc (False) |
---|
| 2913 | mask: An optional mask |
---|
| 2914 | npiece: Number of pieces. (default is 2) |
---|
| 2915 | clipthresh: Clipping threshold. (default is 3.0, unit: sigma) |
---|
[2349] | 2916 | clipniter: maximum number of iteration of 'clipthresh'-sigma |
---|
| 2917 | clipping (default is 0) |
---|
[2189] | 2918 | plot: *** CURRENTLY UNAVAILABLE, ALWAYS FALSE *** |
---|
| 2919 | plot the fit and the residual. In this each |
---|
| 2920 | indivual fit has to be approved, by typing 'y' |
---|
| 2921 | or 'n' |
---|
| 2922 | getresidual: if False, returns best-fit values instead of |
---|
| 2923 | residual. (default is True) |
---|
| 2924 | showprogress: show progress status for large data. |
---|
| 2925 | default is True. |
---|
| 2926 | minnrow: minimum number of input spectra to show. |
---|
| 2927 | default is 1000. |
---|
| 2928 | outlog: Output the coefficients of the best-fit |
---|
| 2929 | function to logger (default is False) |
---|
| 2930 | blfile: Name of a text file in which the best-fit |
---|
| 2931 | parameter values to be written |
---|
| 2932 | (default is "": no file/logger output) |
---|
[2641] | 2933 | csvformat: if True blfile is csv-formatted, default is False. |
---|
[1846] | 2934 | |
---|
[2012] | 2935 | Example: |
---|
[2349] | 2936 | # return a scan baselined by a cubic spline consisting of 2 pieces |
---|
| 2937 | # (i.e., 1 internal knot), |
---|
[2012] | 2938 | # also with 3-sigma clipping, iteration up to 4 times |
---|
| 2939 | bscan = scan.cspline_baseline(npiece=2,clipthresh=3.0,clipniter=4) |
---|
[2081] | 2940 | |
---|
| 2941 | Note: |
---|
| 2942 | The best-fit parameter values output in logger and/or blfile are now |
---|
| 2943 | based on specunit of 'channel'. |
---|
[2012] | 2944 | """ |
---|
| 2945 | |
---|
[2186] | 2946 | try: |
---|
| 2947 | varlist = vars() |
---|
| 2948 | |
---|
| 2949 | if insitu is None: insitu = rcParams['insitu'] |
---|
| 2950 | if insitu: |
---|
| 2951 | workscan = self |
---|
| 2952 | else: |
---|
| 2953 | workscan = self.copy() |
---|
[1855] | 2954 | |
---|
[2410] | 2955 | #if mask is None: mask = [True for i in xrange(workscan.nchan())] |
---|
| 2956 | if mask is None: mask = [] |
---|
[2189] | 2957 | if npiece is None: npiece = 2 |
---|
| 2958 | if clipthresh is None: clipthresh = 3.0 |
---|
| 2959 | if clipniter is None: clipniter = 0 |
---|
| 2960 | if plot is None: plot = False |
---|
| 2961 | if getresidual is None: getresidual = True |
---|
| 2962 | if showprogress is None: showprogress = True |
---|
| 2963 | if minnrow is None: minnrow = 1000 |
---|
| 2964 | if outlog is None: outlog = False |
---|
| 2965 | if blfile is None: blfile = '' |
---|
[2641] | 2966 | if csvformat is None: csvformat = False |
---|
[1855] | 2967 | |
---|
[2641] | 2968 | if csvformat: |
---|
| 2969 | scsvformat = "T" |
---|
| 2970 | else: |
---|
| 2971 | scsvformat = "F" |
---|
| 2972 | |
---|
[2012] | 2973 | #CURRENTLY, PLOT=true UNAVAILABLE UNTIL cubic spline fitting is implemented as a fitter method. |
---|
[2349] | 2974 | workscan._cspline_baseline(mask, npiece, clipthresh, clipniter, |
---|
| 2975 | getresidual, |
---|
| 2976 | pack_progress_params(showprogress, |
---|
[2641] | 2977 | minnrow), |
---|
| 2978 | outlog, scsvformat+blfile) |
---|
[2012] | 2979 | workscan._add_history("cspline_baseline", varlist) |
---|
| 2980 | |
---|
| 2981 | if insitu: |
---|
| 2982 | self._assign(workscan) |
---|
| 2983 | else: |
---|
| 2984 | return workscan |
---|
| 2985 | |
---|
| 2986 | except RuntimeError, e: |
---|
[2186] | 2987 | raise_fitting_failure_exception(e) |
---|
[1855] | 2988 | |
---|
[2186] | 2989 | @asaplog_post_dec |
---|
[2349] | 2990 | def auto_cspline_baseline(self, insitu=None, mask=None, npiece=None, |
---|
| 2991 | clipthresh=None, clipniter=None, |
---|
| 2992 | edge=None, threshold=None, chan_avg_limit=None, |
---|
| 2993 | getresidual=None, plot=None, |
---|
| 2994 | showprogress=None, minnrow=None, outlog=None, |
---|
[2641] | 2995 | blfile=None, csvformat=None): |
---|
[2012] | 2996 | """\ |
---|
| 2997 | Return a scan which has been baselined (all rows) by cubic spline |
---|
| 2998 | function (piecewise cubic polynomial). |
---|
| 2999 | Spectral lines are detected first using linefinder and masked out |
---|
| 3000 | to avoid them affecting the baseline solution. |
---|
| 3001 | |
---|
| 3002 | Parameters: |
---|
[2189] | 3003 | insitu: if False a new scantable is returned. |
---|
| 3004 | Otherwise, the scaling is done in-situ |
---|
| 3005 | The default is taken from .asaprc (False) |
---|
| 3006 | mask: an optional mask retreived from scantable |
---|
| 3007 | npiece: Number of pieces. (default is 2) |
---|
| 3008 | clipthresh: Clipping threshold. (default is 3.0, unit: sigma) |
---|
[2349] | 3009 | clipniter: maximum number of iteration of 'clipthresh'-sigma |
---|
| 3010 | clipping (default is 0) |
---|
[2189] | 3011 | edge: an optional number of channel to drop at |
---|
| 3012 | the edge of spectrum. If only one value is |
---|
| 3013 | specified, the same number will be dropped |
---|
| 3014 | from both sides of the spectrum. Default |
---|
| 3015 | is to keep all channels. Nested tuples |
---|
| 3016 | represent individual edge selection for |
---|
| 3017 | different IFs (a number of spectral channels |
---|
| 3018 | can be different) |
---|
| 3019 | threshold: the threshold used by line finder. It is |
---|
| 3020 | better to keep it large as only strong lines |
---|
| 3021 | affect the baseline solution. |
---|
| 3022 | chan_avg_limit: a maximum number of consequtive spectral |
---|
| 3023 | channels to average during the search of |
---|
| 3024 | weak and broad lines. The default is no |
---|
| 3025 | averaging (and no search for weak lines). |
---|
| 3026 | If such lines can affect the fitted baseline |
---|
| 3027 | (e.g. a high order polynomial is fitted), |
---|
| 3028 | increase this parameter (usually values up |
---|
| 3029 | to 8 are reasonable). Most users of this |
---|
| 3030 | method should find the default value sufficient. |
---|
| 3031 | plot: *** CURRENTLY UNAVAILABLE, ALWAYS FALSE *** |
---|
| 3032 | plot the fit and the residual. In this each |
---|
| 3033 | indivual fit has to be approved, by typing 'y' |
---|
| 3034 | or 'n' |
---|
| 3035 | getresidual: if False, returns best-fit values instead of |
---|
| 3036 | residual. (default is True) |
---|
| 3037 | showprogress: show progress status for large data. |
---|
| 3038 | default is True. |
---|
| 3039 | minnrow: minimum number of input spectra to show. |
---|
| 3040 | default is 1000. |
---|
| 3041 | outlog: Output the coefficients of the best-fit |
---|
| 3042 | function to logger (default is False) |
---|
| 3043 | blfile: Name of a text file in which the best-fit |
---|
| 3044 | parameter values to be written |
---|
| 3045 | (default is "": no file/logger output) |
---|
[2641] | 3046 | csvformat: if True blfile is csv-formatted, default is False. |
---|
[1846] | 3047 | |
---|
[1907] | 3048 | Example: |
---|
[2012] | 3049 | bscan = scan.auto_cspline_baseline(npiece=3, insitu=False) |
---|
[2081] | 3050 | |
---|
| 3051 | Note: |
---|
| 3052 | The best-fit parameter values output in logger and/or blfile are now |
---|
| 3053 | based on specunit of 'channel'. |
---|
[2012] | 3054 | """ |
---|
[1846] | 3055 | |
---|
[2186] | 3056 | try: |
---|
| 3057 | varlist = vars() |
---|
[2012] | 3058 | |
---|
[2186] | 3059 | if insitu is None: insitu = rcParams['insitu'] |
---|
| 3060 | if insitu: |
---|
| 3061 | workscan = self |
---|
[1391] | 3062 | else: |
---|
[2186] | 3063 | workscan = self.copy() |
---|
| 3064 | |
---|
[2410] | 3065 | #if mask is None: mask = [True for i in xrange(workscan.nchan())] |
---|
| 3066 | if mask is None: mask = [] |
---|
[2186] | 3067 | if npiece is None: npiece = 2 |
---|
| 3068 | if clipthresh is None: clipthresh = 3.0 |
---|
| 3069 | if clipniter is None: clipniter = 0 |
---|
| 3070 | if edge is None: edge = (0, 0) |
---|
| 3071 | if threshold is None: threshold = 3 |
---|
| 3072 | if chan_avg_limit is None: chan_avg_limit = 1 |
---|
| 3073 | if plot is None: plot = False |
---|
| 3074 | if getresidual is None: getresidual = True |
---|
[2189] | 3075 | if showprogress is None: showprogress = True |
---|
| 3076 | if minnrow is None: minnrow = 1000 |
---|
[2186] | 3077 | if outlog is None: outlog = False |
---|
| 3078 | if blfile is None: blfile = '' |
---|
[2641] | 3079 | if csvformat is None: csvformat = False |
---|
[1819] | 3080 | |
---|
[2641] | 3081 | if csvformat: |
---|
| 3082 | scsvformat = "T" |
---|
| 3083 | else: |
---|
| 3084 | scsvformat = "F" |
---|
| 3085 | |
---|
[2277] | 3086 | #CURRENTLY, PLOT=true UNAVAILABLE UNTIL cubic spline fitting is implemented as a fitter method. |
---|
[2269] | 3087 | workscan._auto_cspline_baseline(mask, npiece, clipthresh, |
---|
| 3088 | clipniter, |
---|
| 3089 | normalise_edge_param(edge), |
---|
| 3090 | threshold, |
---|
| 3091 | chan_avg_limit, getresidual, |
---|
| 3092 | pack_progress_params(showprogress, |
---|
| 3093 | minnrow), |
---|
[2641] | 3094 | outlog, scsvformat+blfile) |
---|
[2012] | 3095 | workscan._add_history("auto_cspline_baseline", varlist) |
---|
[1907] | 3096 | |
---|
[1856] | 3097 | if insitu: |
---|
| 3098 | self._assign(workscan) |
---|
| 3099 | else: |
---|
| 3100 | return workscan |
---|
[2012] | 3101 | |
---|
| 3102 | except RuntimeError, e: |
---|
[2186] | 3103 | raise_fitting_failure_exception(e) |
---|
[513] | 3104 | |
---|
[1931] | 3105 | @asaplog_post_dec |
---|
[2645] | 3106 | def chebyshev_baseline(self, insitu=None, mask=None, order=None, |
---|
| 3107 | clipthresh=None, clipniter=None, plot=None, |
---|
| 3108 | getresidual=None, showprogress=None, minnrow=None, |
---|
| 3109 | outlog=None, blfile=None, csvformat=None): |
---|
| 3110 | """\ |
---|
| 3111 | Return a scan which has been baselined (all rows) by Chebyshev polynomials. |
---|
| 3112 | |
---|
| 3113 | Parameters: |
---|
| 3114 | insitu: If False a new scantable is returned. |
---|
| 3115 | Otherwise, the scaling is done in-situ |
---|
| 3116 | The default is taken from .asaprc (False) |
---|
| 3117 | mask: An optional mask |
---|
| 3118 | order: the maximum order of Chebyshev polynomial (default is 5) |
---|
| 3119 | clipthresh: Clipping threshold. (default is 3.0, unit: sigma) |
---|
| 3120 | clipniter: maximum number of iteration of 'clipthresh'-sigma |
---|
| 3121 | clipping (default is 0) |
---|
| 3122 | plot: *** CURRENTLY UNAVAILABLE, ALWAYS FALSE *** |
---|
| 3123 | plot the fit and the residual. In this each |
---|
| 3124 | indivual fit has to be approved, by typing 'y' |
---|
| 3125 | or 'n' |
---|
| 3126 | getresidual: if False, returns best-fit values instead of |
---|
| 3127 | residual. (default is True) |
---|
| 3128 | showprogress: show progress status for large data. |
---|
| 3129 | default is True. |
---|
| 3130 | minnrow: minimum number of input spectra to show. |
---|
| 3131 | default is 1000. |
---|
| 3132 | outlog: Output the coefficients of the best-fit |
---|
| 3133 | function to logger (default is False) |
---|
| 3134 | blfile: Name of a text file in which the best-fit |
---|
| 3135 | parameter values to be written |
---|
| 3136 | (default is "": no file/logger output) |
---|
| 3137 | csvformat: if True blfile is csv-formatted, default is False. |
---|
| 3138 | |
---|
| 3139 | Example: |
---|
| 3140 | # return a scan baselined by a cubic spline consisting of 2 pieces |
---|
| 3141 | # (i.e., 1 internal knot), |
---|
| 3142 | # also with 3-sigma clipping, iteration up to 4 times |
---|
| 3143 | bscan = scan.cspline_baseline(npiece=2,clipthresh=3.0,clipniter=4) |
---|
| 3144 | |
---|
| 3145 | Note: |
---|
| 3146 | The best-fit parameter values output in logger and/or blfile are now |
---|
| 3147 | based on specunit of 'channel'. |
---|
| 3148 | """ |
---|
| 3149 | |
---|
| 3150 | try: |
---|
| 3151 | varlist = vars() |
---|
| 3152 | |
---|
| 3153 | if insitu is None: insitu = rcParams['insitu'] |
---|
| 3154 | if insitu: |
---|
| 3155 | workscan = self |
---|
| 3156 | else: |
---|
| 3157 | workscan = self.copy() |
---|
| 3158 | |
---|
| 3159 | #if mask is None: mask = [True for i in xrange(workscan.nchan())] |
---|
| 3160 | if mask is None: mask = [] |
---|
| 3161 | if order is None: order = 5 |
---|
| 3162 | if clipthresh is None: clipthresh = 3.0 |
---|
| 3163 | if clipniter is None: clipniter = 0 |
---|
| 3164 | if plot is None: plot = False |
---|
| 3165 | if getresidual is None: getresidual = True |
---|
| 3166 | if showprogress is None: showprogress = True |
---|
| 3167 | if minnrow is None: minnrow = 1000 |
---|
| 3168 | if outlog is None: outlog = False |
---|
| 3169 | if blfile is None: blfile = '' |
---|
| 3170 | if csvformat is None: csvformat = False |
---|
| 3171 | |
---|
| 3172 | if csvformat: |
---|
| 3173 | scsvformat = "T" |
---|
| 3174 | else: |
---|
| 3175 | scsvformat = "F" |
---|
| 3176 | |
---|
| 3177 | #CURRENTLY, PLOT=true UNAVAILABLE UNTIL cubic spline fitting is implemented as a fitter method. |
---|
| 3178 | workscan._chebyshev_baseline(mask, order, clipthresh, clipniter, |
---|
| 3179 | getresidual, |
---|
| 3180 | pack_progress_params(showprogress, |
---|
| 3181 | minnrow), |
---|
| 3182 | outlog, scsvformat+blfile) |
---|
| 3183 | workscan._add_history("chebyshev_baseline", varlist) |
---|
| 3184 | |
---|
| 3185 | if insitu: |
---|
| 3186 | self._assign(workscan) |
---|
| 3187 | else: |
---|
| 3188 | return workscan |
---|
| 3189 | |
---|
| 3190 | except RuntimeError, e: |
---|
| 3191 | raise_fitting_failure_exception(e) |
---|
| 3192 | |
---|
| 3193 | @asaplog_post_dec |
---|
| 3194 | def auto_chebyshev_baseline(self, insitu=None, mask=None, order=None, |
---|
| 3195 | clipthresh=None, clipniter=None, |
---|
| 3196 | edge=None, threshold=None, chan_avg_limit=None, |
---|
| 3197 | getresidual=None, plot=None, |
---|
| 3198 | showprogress=None, minnrow=None, outlog=None, |
---|
| 3199 | blfile=None, csvformat=None): |
---|
| 3200 | """\ |
---|
| 3201 | Return a scan which has been baselined (all rows) by Chebyshev polynomials. |
---|
| 3202 | Spectral lines are detected first using linefinder and masked out |
---|
| 3203 | to avoid them affecting the baseline solution. |
---|
| 3204 | |
---|
| 3205 | Parameters: |
---|
| 3206 | insitu: if False a new scantable is returned. |
---|
| 3207 | Otherwise, the scaling is done in-situ |
---|
| 3208 | The default is taken from .asaprc (False) |
---|
| 3209 | mask: an optional mask retreived from scantable |
---|
| 3210 | order: the maximum order of Chebyshev polynomial (default is 5) |
---|
| 3211 | clipthresh: Clipping threshold. (default is 3.0, unit: sigma) |
---|
| 3212 | clipniter: maximum number of iteration of 'clipthresh'-sigma |
---|
| 3213 | clipping (default is 0) |
---|
| 3214 | edge: an optional number of channel to drop at |
---|
| 3215 | the edge of spectrum. If only one value is |
---|
| 3216 | specified, the same number will be dropped |
---|
| 3217 | from both sides of the spectrum. Default |
---|
| 3218 | is to keep all channels. Nested tuples |
---|
| 3219 | represent individual edge selection for |
---|
| 3220 | different IFs (a number of spectral channels |
---|
| 3221 | can be different) |
---|
| 3222 | threshold: the threshold used by line finder. It is |
---|
| 3223 | better to keep it large as only strong lines |
---|
| 3224 | affect the baseline solution. |
---|
| 3225 | chan_avg_limit: a maximum number of consequtive spectral |
---|
| 3226 | channels to average during the search of |
---|
| 3227 | weak and broad lines. The default is no |
---|
| 3228 | averaging (and no search for weak lines). |
---|
| 3229 | If such lines can affect the fitted baseline |
---|
| 3230 | (e.g. a high order polynomial is fitted), |
---|
| 3231 | increase this parameter (usually values up |
---|
| 3232 | to 8 are reasonable). Most users of this |
---|
| 3233 | method should find the default value sufficient. |
---|
| 3234 | plot: *** CURRENTLY UNAVAILABLE, ALWAYS FALSE *** |
---|
| 3235 | plot the fit and the residual. In this each |
---|
| 3236 | indivual fit has to be approved, by typing 'y' |
---|
| 3237 | or 'n' |
---|
| 3238 | getresidual: if False, returns best-fit values instead of |
---|
| 3239 | residual. (default is True) |
---|
| 3240 | showprogress: show progress status for large data. |
---|
| 3241 | default is True. |
---|
| 3242 | minnrow: minimum number of input spectra to show. |
---|
| 3243 | default is 1000. |
---|
| 3244 | outlog: Output the coefficients of the best-fit |
---|
| 3245 | function to logger (default is False) |
---|
| 3246 | blfile: Name of a text file in which the best-fit |
---|
| 3247 | parameter values to be written |
---|
| 3248 | (default is "": no file/logger output) |
---|
| 3249 | csvformat: if True blfile is csv-formatted, default is False. |
---|
| 3250 | |
---|
| 3251 | Example: |
---|
| 3252 | bscan = scan.auto_cspline_baseline(npiece=3, insitu=False) |
---|
| 3253 | |
---|
| 3254 | Note: |
---|
| 3255 | The best-fit parameter values output in logger and/or blfile are now |
---|
| 3256 | based on specunit of 'channel'. |
---|
| 3257 | """ |
---|
| 3258 | |
---|
| 3259 | try: |
---|
| 3260 | varlist = vars() |
---|
| 3261 | |
---|
| 3262 | if insitu is None: insitu = rcParams['insitu'] |
---|
| 3263 | if insitu: |
---|
| 3264 | workscan = self |
---|
| 3265 | else: |
---|
| 3266 | workscan = self.copy() |
---|
| 3267 | |
---|
| 3268 | #if mask is None: mask = [True for i in xrange(workscan.nchan())] |
---|
| 3269 | if mask is None: mask = [] |
---|
| 3270 | if order is None: order = 5 |
---|
| 3271 | if clipthresh is None: clipthresh = 3.0 |
---|
| 3272 | if clipniter is None: clipniter = 0 |
---|
| 3273 | if edge is None: edge = (0, 0) |
---|
| 3274 | if threshold is None: threshold = 3 |
---|
| 3275 | if chan_avg_limit is None: chan_avg_limit = 1 |
---|
| 3276 | if plot is None: plot = False |
---|
| 3277 | if getresidual is None: getresidual = True |
---|
| 3278 | if showprogress is None: showprogress = True |
---|
| 3279 | if minnrow is None: minnrow = 1000 |
---|
| 3280 | if outlog is None: outlog = False |
---|
| 3281 | if blfile is None: blfile = '' |
---|
| 3282 | if csvformat is None: csvformat = False |
---|
| 3283 | |
---|
| 3284 | if csvformat: |
---|
| 3285 | scsvformat = "T" |
---|
| 3286 | else: |
---|
| 3287 | scsvformat = "F" |
---|
| 3288 | |
---|
| 3289 | #CURRENTLY, PLOT=true UNAVAILABLE UNTIL cubic spline fitting is implemented as a fitter method. |
---|
| 3290 | workscan._auto_chebyshev_baseline(mask, order, clipthresh, |
---|
| 3291 | clipniter, |
---|
| 3292 | normalise_edge_param(edge), |
---|
| 3293 | threshold, |
---|
| 3294 | chan_avg_limit, getresidual, |
---|
| 3295 | pack_progress_params(showprogress, |
---|
| 3296 | minnrow), |
---|
| 3297 | outlog, scsvformat+blfile) |
---|
| 3298 | workscan._add_history("auto_chebyshev_baseline", varlist) |
---|
| 3299 | |
---|
| 3300 | if insitu: |
---|
| 3301 | self._assign(workscan) |
---|
| 3302 | else: |
---|
| 3303 | return workscan |
---|
| 3304 | |
---|
| 3305 | except RuntimeError, e: |
---|
| 3306 | raise_fitting_failure_exception(e) |
---|
| 3307 | |
---|
| 3308 | @asaplog_post_dec |
---|
[2269] | 3309 | def poly_baseline(self, mask=None, order=None, insitu=None, plot=None, |
---|
| 3310 | getresidual=None, showprogress=None, minnrow=None, |
---|
[2641] | 3311 | outlog=None, blfile=None, csvformat=None): |
---|
[1907] | 3312 | """\ |
---|
| 3313 | Return a scan which has been baselined (all rows) by a polynomial. |
---|
| 3314 | Parameters: |
---|
[2189] | 3315 | insitu: if False a new scantable is returned. |
---|
| 3316 | Otherwise, the scaling is done in-situ |
---|
| 3317 | The default is taken from .asaprc (False) |
---|
| 3318 | mask: an optional mask |
---|
| 3319 | order: the order of the polynomial (default is 0) |
---|
| 3320 | plot: plot the fit and the residual. In this each |
---|
| 3321 | indivual fit has to be approved, by typing 'y' |
---|
| 3322 | or 'n' |
---|
| 3323 | getresidual: if False, returns best-fit values instead of |
---|
| 3324 | residual. (default is True) |
---|
| 3325 | showprogress: show progress status for large data. |
---|
| 3326 | default is True. |
---|
| 3327 | minnrow: minimum number of input spectra to show. |
---|
| 3328 | default is 1000. |
---|
| 3329 | outlog: Output the coefficients of the best-fit |
---|
| 3330 | function to logger (default is False) |
---|
| 3331 | blfile: Name of a text file in which the best-fit |
---|
| 3332 | parameter values to be written |
---|
| 3333 | (default is "": no file/logger output) |
---|
[2641] | 3334 | csvformat: if True blfile is csv-formatted, default is False. |
---|
[2012] | 3335 | |
---|
[1907] | 3336 | Example: |
---|
| 3337 | # return a scan baselined by a third order polynomial, |
---|
| 3338 | # not using a mask |
---|
| 3339 | bscan = scan.poly_baseline(order=3) |
---|
| 3340 | """ |
---|
[1931] | 3341 | |
---|
[2186] | 3342 | try: |
---|
| 3343 | varlist = vars() |
---|
[1931] | 3344 | |
---|
[2269] | 3345 | if insitu is None: |
---|
| 3346 | insitu = rcParams["insitu"] |
---|
[2186] | 3347 | if insitu: |
---|
| 3348 | workscan = self |
---|
| 3349 | else: |
---|
| 3350 | workscan = self.copy() |
---|
[1907] | 3351 | |
---|
[2410] | 3352 | #if mask is None: mask = [True for i in \ |
---|
| 3353 | # xrange(workscan.nchan())] |
---|
| 3354 | if mask is None: mask = [] |
---|
[2189] | 3355 | if order is None: order = 0 |
---|
| 3356 | if plot is None: plot = False |
---|
| 3357 | if getresidual is None: getresidual = True |
---|
| 3358 | if showprogress is None: showprogress = True |
---|
| 3359 | if minnrow is None: minnrow = 1000 |
---|
| 3360 | if outlog is None: outlog = False |
---|
| 3361 | if blfile is None: blfile = "" |
---|
[2641] | 3362 | if csvformat is None: csvformat = False |
---|
[1907] | 3363 | |
---|
[2641] | 3364 | if csvformat: |
---|
| 3365 | scsvformat = "T" |
---|
| 3366 | else: |
---|
| 3367 | scsvformat = "F" |
---|
| 3368 | |
---|
[2012] | 3369 | if plot: |
---|
[2269] | 3370 | outblfile = (blfile != "") and \ |
---|
[2349] | 3371 | os.path.exists(os.path.expanduser( |
---|
| 3372 | os.path.expandvars(blfile)) |
---|
| 3373 | ) |
---|
[2269] | 3374 | if outblfile: |
---|
| 3375 | blf = open(blfile, "a") |
---|
[2012] | 3376 | |
---|
[1907] | 3377 | f = fitter() |
---|
| 3378 | f.set_function(lpoly=order) |
---|
[2186] | 3379 | |
---|
| 3380 | rows = xrange(workscan.nrow()) |
---|
| 3381 | #if len(rows) > 0: workscan._init_blinfo() |
---|
[2610] | 3382 | |
---|
| 3383 | action = "H" |
---|
[1907] | 3384 | for r in rows: |
---|
| 3385 | f.x = workscan._getabcissa(r) |
---|
| 3386 | f.y = workscan._getspectrum(r) |
---|
[2541] | 3387 | if mask: |
---|
| 3388 | f.mask = mask_and(mask, workscan._getmask(r)) # (CAS-1434) |
---|
| 3389 | else: # mask=None |
---|
| 3390 | f.mask = workscan._getmask(r) |
---|
| 3391 | |
---|
[1907] | 3392 | f.data = None |
---|
| 3393 | f.fit() |
---|
[2541] | 3394 | |
---|
[2610] | 3395 | if action != "Y": # skip plotting when accepting all |
---|
| 3396 | f.plot(residual=True) |
---|
| 3397 | #accept_fit = raw_input("Accept fit ( [y]/n ): ") |
---|
| 3398 | #if accept_fit.upper() == "N": |
---|
| 3399 | # #workscan._append_blinfo(None, None, None) |
---|
| 3400 | # continue |
---|
| 3401 | accept_fit = self._get_verify_action("Accept fit?",action) |
---|
| 3402 | if r == 0: action = None |
---|
[1907] | 3403 | if accept_fit.upper() == "N": |
---|
| 3404 | continue |
---|
[2610] | 3405 | elif accept_fit.upper() == "R": |
---|
| 3406 | break |
---|
| 3407 | elif accept_fit.upper() == "A": |
---|
| 3408 | action = "Y" |
---|
[2012] | 3409 | |
---|
| 3410 | blpars = f.get_parameters() |
---|
| 3411 | masklist = workscan.get_masklist(f.mask, row=r, silent=True) |
---|
| 3412 | #workscan._append_blinfo(blpars, masklist, f.mask) |
---|
[2269] | 3413 | workscan._setspectrum((f.fitter.getresidual() |
---|
| 3414 | if getresidual else f.fitter.getfit()), r) |
---|
[1907] | 3415 | |
---|
[2012] | 3416 | if outblfile: |
---|
| 3417 | rms = workscan.get_rms(f.mask, r) |
---|
[2269] | 3418 | dataout = \ |
---|
| 3419 | workscan.format_blparams_row(blpars["params"], |
---|
| 3420 | blpars["fixed"], |
---|
| 3421 | rms, str(masklist), |
---|
[2641] | 3422 | r, True, csvformat) |
---|
[2012] | 3423 | blf.write(dataout) |
---|
| 3424 | |
---|
[1907] | 3425 | f._p.unmap() |
---|
| 3426 | f._p = None |
---|
[2012] | 3427 | |
---|
[2349] | 3428 | if outblfile: |
---|
| 3429 | blf.close() |
---|
[1907] | 3430 | else: |
---|
[2269] | 3431 | workscan._poly_baseline(mask, order, getresidual, |
---|
| 3432 | pack_progress_params(showprogress, |
---|
| 3433 | minnrow), |
---|
[2641] | 3434 | outlog, scsvformat+blfile) |
---|
[1907] | 3435 | |
---|
| 3436 | workscan._add_history("poly_baseline", varlist) |
---|
| 3437 | |
---|
| 3438 | if insitu: |
---|
| 3439 | self._assign(workscan) |
---|
| 3440 | else: |
---|
| 3441 | return workscan |
---|
| 3442 | |
---|
[1919] | 3443 | except RuntimeError, e: |
---|
[2186] | 3444 | raise_fitting_failure_exception(e) |
---|
[1907] | 3445 | |
---|
[2186] | 3446 | @asaplog_post_dec |
---|
[2269] | 3447 | def auto_poly_baseline(self, mask=None, order=None, edge=None, |
---|
| 3448 | threshold=None, chan_avg_limit=None, |
---|
| 3449 | plot=None, insitu=None, |
---|
| 3450 | getresidual=None, showprogress=None, |
---|
[2641] | 3451 | minnrow=None, outlog=None, blfile=None, csvformat=None): |
---|
[1846] | 3452 | """\ |
---|
[1931] | 3453 | Return a scan which has been baselined (all rows) by a polynomial. |
---|
[880] | 3454 | Spectral lines are detected first using linefinder and masked out |
---|
| 3455 | to avoid them affecting the baseline solution. |
---|
| 3456 | |
---|
| 3457 | Parameters: |
---|
[2189] | 3458 | insitu: if False a new scantable is returned. |
---|
| 3459 | Otherwise, the scaling is done in-situ |
---|
| 3460 | The default is taken from .asaprc (False) |
---|
| 3461 | mask: an optional mask retreived from scantable |
---|
| 3462 | order: the order of the polynomial (default is 0) |
---|
| 3463 | edge: an optional number of channel to drop at |
---|
| 3464 | the edge of spectrum. If only one value is |
---|
| 3465 | specified, the same number will be dropped |
---|
| 3466 | from both sides of the spectrum. Default |
---|
| 3467 | is to keep all channels. Nested tuples |
---|
| 3468 | represent individual edge selection for |
---|
| 3469 | different IFs (a number of spectral channels |
---|
| 3470 | can be different) |
---|
| 3471 | threshold: the threshold used by line finder. It is |
---|
| 3472 | better to keep it large as only strong lines |
---|
| 3473 | affect the baseline solution. |
---|
| 3474 | chan_avg_limit: a maximum number of consequtive spectral |
---|
| 3475 | channels to average during the search of |
---|
| 3476 | weak and broad lines. The default is no |
---|
| 3477 | averaging (and no search for weak lines). |
---|
| 3478 | If such lines can affect the fitted baseline |
---|
| 3479 | (e.g. a high order polynomial is fitted), |
---|
| 3480 | increase this parameter (usually values up |
---|
| 3481 | to 8 are reasonable). Most users of this |
---|
| 3482 | method should find the default value sufficient. |
---|
| 3483 | plot: plot the fit and the residual. In this each |
---|
| 3484 | indivual fit has to be approved, by typing 'y' |
---|
| 3485 | or 'n' |
---|
| 3486 | getresidual: if False, returns best-fit values instead of |
---|
| 3487 | residual. (default is True) |
---|
| 3488 | showprogress: show progress status for large data. |
---|
| 3489 | default is True. |
---|
| 3490 | minnrow: minimum number of input spectra to show. |
---|
| 3491 | default is 1000. |
---|
| 3492 | outlog: Output the coefficients of the best-fit |
---|
| 3493 | function to logger (default is False) |
---|
| 3494 | blfile: Name of a text file in which the best-fit |
---|
| 3495 | parameter values to be written |
---|
| 3496 | (default is "": no file/logger output) |
---|
[2641] | 3497 | csvformat: if True blfile is csv-formatted, default is False. |
---|
[1846] | 3498 | |
---|
[2012] | 3499 | Example: |
---|
| 3500 | bscan = scan.auto_poly_baseline(order=7, insitu=False) |
---|
| 3501 | """ |
---|
[880] | 3502 | |
---|
[2186] | 3503 | try: |
---|
| 3504 | varlist = vars() |
---|
[1846] | 3505 | |
---|
[2269] | 3506 | if insitu is None: |
---|
| 3507 | insitu = rcParams['insitu'] |
---|
[2186] | 3508 | if insitu: |
---|
| 3509 | workscan = self |
---|
| 3510 | else: |
---|
| 3511 | workscan = self.copy() |
---|
[1846] | 3512 | |
---|
[2410] | 3513 | #if mask is None: mask = [True for i in xrange(workscan.nchan())] |
---|
| 3514 | if mask is None: mask = [] |
---|
[2186] | 3515 | if order is None: order = 0 |
---|
| 3516 | if edge is None: edge = (0, 0) |
---|
| 3517 | if threshold is None: threshold = 3 |
---|
| 3518 | if chan_avg_limit is None: chan_avg_limit = 1 |
---|
| 3519 | if plot is None: plot = False |
---|
| 3520 | if getresidual is None: getresidual = True |
---|
[2189] | 3521 | if showprogress is None: showprogress = True |
---|
| 3522 | if minnrow is None: minnrow = 1000 |
---|
[2186] | 3523 | if outlog is None: outlog = False |
---|
| 3524 | if blfile is None: blfile = '' |
---|
[2641] | 3525 | if csvformat is None: csvformat = False |
---|
[1846] | 3526 | |
---|
[2641] | 3527 | if csvformat: |
---|
| 3528 | scsvformat = "T" |
---|
| 3529 | else: |
---|
| 3530 | scsvformat = "F" |
---|
| 3531 | |
---|
[2186] | 3532 | edge = normalise_edge_param(edge) |
---|
[880] | 3533 | |
---|
[2012] | 3534 | if plot: |
---|
[2269] | 3535 | outblfile = (blfile != "") and \ |
---|
| 3536 | os.path.exists(os.path.expanduser(os.path.expandvars(blfile))) |
---|
[2012] | 3537 | if outblfile: blf = open(blfile, "a") |
---|
| 3538 | |
---|
[2186] | 3539 | from asap.asaplinefind import linefinder |
---|
[2012] | 3540 | fl = linefinder() |
---|
[2269] | 3541 | fl.set_options(threshold=threshold, avg_limit=chan_avg_limit) |
---|
[2012] | 3542 | fl.set_scan(workscan) |
---|
[2186] | 3543 | |
---|
[2012] | 3544 | f = fitter() |
---|
| 3545 | f.set_function(lpoly=order) |
---|
[880] | 3546 | |
---|
[2186] | 3547 | rows = xrange(workscan.nrow()) |
---|
| 3548 | #if len(rows) > 0: workscan._init_blinfo() |
---|
[2610] | 3549 | |
---|
| 3550 | action = "H" |
---|
[2012] | 3551 | for r in rows: |
---|
[2186] | 3552 | idx = 2*workscan.getif(r) |
---|
[2541] | 3553 | if mask: |
---|
| 3554 | msk = mask_and(mask, workscan._getmask(r)) # (CAS-1434) |
---|
| 3555 | else: # mask=None |
---|
| 3556 | msk = workscan._getmask(r) |
---|
| 3557 | fl.find_lines(r, msk, edge[idx:idx+2]) |
---|
[907] | 3558 | |
---|
[2012] | 3559 | f.x = workscan._getabcissa(r) |
---|
| 3560 | f.y = workscan._getspectrum(r) |
---|
| 3561 | f.mask = fl.get_mask() |
---|
| 3562 | f.data = None |
---|
| 3563 | f.fit() |
---|
| 3564 | |
---|
[2610] | 3565 | if action != "Y": # skip plotting when accepting all |
---|
| 3566 | f.plot(residual=True) |
---|
| 3567 | #accept_fit = raw_input("Accept fit ( [y]/n ): ") |
---|
| 3568 | accept_fit = self._get_verify_action("Accept fit?",action) |
---|
| 3569 | if r == 0: action = None |
---|
[2012] | 3570 | if accept_fit.upper() == "N": |
---|
| 3571 | #workscan._append_blinfo(None, None, None) |
---|
| 3572 | continue |
---|
[2610] | 3573 | elif accept_fit.upper() == "R": |
---|
| 3574 | break |
---|
| 3575 | elif accept_fit.upper() == "A": |
---|
| 3576 | action = "Y" |
---|
[2012] | 3577 | |
---|
| 3578 | blpars = f.get_parameters() |
---|
| 3579 | masklist = workscan.get_masklist(f.mask, row=r, silent=True) |
---|
| 3580 | #workscan._append_blinfo(blpars, masklist, f.mask) |
---|
[2349] | 3581 | workscan._setspectrum( |
---|
| 3582 | (f.fitter.getresidual() if getresidual |
---|
| 3583 | else f.fitter.getfit()), r |
---|
| 3584 | ) |
---|
[2012] | 3585 | |
---|
| 3586 | if outblfile: |
---|
| 3587 | rms = workscan.get_rms(f.mask, r) |
---|
[2269] | 3588 | dataout = \ |
---|
| 3589 | workscan.format_blparams_row(blpars["params"], |
---|
| 3590 | blpars["fixed"], |
---|
| 3591 | rms, str(masklist), |
---|
[2641] | 3592 | r, True, csvformat) |
---|
[2012] | 3593 | blf.write(dataout) |
---|
| 3594 | |
---|
| 3595 | f._p.unmap() |
---|
| 3596 | f._p = None |
---|
| 3597 | |
---|
| 3598 | if outblfile: blf.close() |
---|
| 3599 | else: |
---|
[2269] | 3600 | workscan._auto_poly_baseline(mask, order, edge, threshold, |
---|
| 3601 | chan_avg_limit, getresidual, |
---|
| 3602 | pack_progress_params(showprogress, |
---|
| 3603 | minnrow), |
---|
[2641] | 3604 | outlog, scsvformat+blfile) |
---|
[2012] | 3605 | |
---|
| 3606 | workscan._add_history("auto_poly_baseline", varlist) |
---|
| 3607 | |
---|
| 3608 | if insitu: |
---|
| 3609 | self._assign(workscan) |
---|
| 3610 | else: |
---|
| 3611 | return workscan |
---|
| 3612 | |
---|
| 3613 | except RuntimeError, e: |
---|
[2186] | 3614 | raise_fitting_failure_exception(e) |
---|
[2012] | 3615 | |
---|
| 3616 | def _init_blinfo(self): |
---|
| 3617 | """\ |
---|
| 3618 | Initialise the following three auxiliary members: |
---|
| 3619 | blpars : parameters of the best-fit baseline, |
---|
| 3620 | masklists : mask data (edge positions of masked channels) and |
---|
| 3621 | actualmask : mask data (in boolean list), |
---|
| 3622 | to keep for use later (including output to logger/text files). |
---|
| 3623 | Used by poly_baseline() and auto_poly_baseline() in case of |
---|
| 3624 | 'plot=True'. |
---|
| 3625 | """ |
---|
| 3626 | self.blpars = [] |
---|
| 3627 | self.masklists = [] |
---|
| 3628 | self.actualmask = [] |
---|
| 3629 | return |
---|
[880] | 3630 | |
---|
[2012] | 3631 | def _append_blinfo(self, data_blpars, data_masklists, data_actualmask): |
---|
| 3632 | """\ |
---|
| 3633 | Append baseline-fitting related info to blpars, masklist and |
---|
| 3634 | actualmask. |
---|
| 3635 | """ |
---|
| 3636 | self.blpars.append(data_blpars) |
---|
| 3637 | self.masklists.append(data_masklists) |
---|
| 3638 | self.actualmask.append(data_actualmask) |
---|
| 3639 | return |
---|
| 3640 | |
---|
[1862] | 3641 | @asaplog_post_dec |
---|
[914] | 3642 | def rotate_linpolphase(self, angle): |
---|
[1846] | 3643 | """\ |
---|
[914] | 3644 | Rotate the phase of the complex polarization O=Q+iU correlation. |
---|
| 3645 | This is always done in situ in the raw data. So if you call this |
---|
| 3646 | function more than once then each call rotates the phase further. |
---|
[1846] | 3647 | |
---|
[914] | 3648 | Parameters: |
---|
[1846] | 3649 | |
---|
[914] | 3650 | angle: The angle (degrees) to rotate (add) by. |
---|
[1846] | 3651 | |
---|
| 3652 | Example:: |
---|
| 3653 | |
---|
[914] | 3654 | scan.rotate_linpolphase(2.3) |
---|
[1846] | 3655 | |
---|
[914] | 3656 | """ |
---|
| 3657 | varlist = vars() |
---|
[936] | 3658 | self._math._rotate_linpolphase(self, angle) |
---|
[914] | 3659 | self._add_history("rotate_linpolphase", varlist) |
---|
| 3660 | return |
---|
[710] | 3661 | |
---|
[1862] | 3662 | @asaplog_post_dec |
---|
[914] | 3663 | def rotate_xyphase(self, angle): |
---|
[1846] | 3664 | """\ |
---|
[914] | 3665 | Rotate the phase of the XY correlation. This is always done in situ |
---|
| 3666 | in the data. So if you call this function more than once |
---|
| 3667 | then each call rotates the phase further. |
---|
[1846] | 3668 | |
---|
[914] | 3669 | Parameters: |
---|
[1846] | 3670 | |
---|
[914] | 3671 | angle: The angle (degrees) to rotate (add) by. |
---|
[1846] | 3672 | |
---|
| 3673 | Example:: |
---|
| 3674 | |
---|
[914] | 3675 | scan.rotate_xyphase(2.3) |
---|
[1846] | 3676 | |
---|
[914] | 3677 | """ |
---|
| 3678 | varlist = vars() |
---|
[936] | 3679 | self._math._rotate_xyphase(self, angle) |
---|
[914] | 3680 | self._add_history("rotate_xyphase", varlist) |
---|
| 3681 | return |
---|
| 3682 | |
---|
[1862] | 3683 | @asaplog_post_dec |
---|
[914] | 3684 | def swap_linears(self): |
---|
[1846] | 3685 | """\ |
---|
[1573] | 3686 | Swap the linear polarisations XX and YY, or better the first two |
---|
[1348] | 3687 | polarisations as this also works for ciculars. |
---|
[914] | 3688 | """ |
---|
| 3689 | varlist = vars() |
---|
[936] | 3690 | self._math._swap_linears(self) |
---|
[914] | 3691 | self._add_history("swap_linears", varlist) |
---|
| 3692 | return |
---|
| 3693 | |
---|
[1862] | 3694 | @asaplog_post_dec |
---|
[914] | 3695 | def invert_phase(self): |
---|
[1846] | 3696 | """\ |
---|
[914] | 3697 | Invert the phase of the complex polarisation |
---|
| 3698 | """ |
---|
| 3699 | varlist = vars() |
---|
[936] | 3700 | self._math._invert_phase(self) |
---|
[914] | 3701 | self._add_history("invert_phase", varlist) |
---|
| 3702 | return |
---|
| 3703 | |
---|
[1862] | 3704 | @asaplog_post_dec |
---|
[876] | 3705 | def add(self, offset, insitu=None): |
---|
[1846] | 3706 | """\ |
---|
[513] | 3707 | Return a scan where all spectra have the offset added |
---|
[1846] | 3708 | |
---|
[513] | 3709 | Parameters: |
---|
[1846] | 3710 | |
---|
[513] | 3711 | offset: the offset |
---|
[1855] | 3712 | |
---|
[513] | 3713 | insitu: if False a new scantable is returned. |
---|
| 3714 | Otherwise, the scaling is done in-situ |
---|
| 3715 | The default is taken from .asaprc (False) |
---|
[1846] | 3716 | |
---|
[513] | 3717 | """ |
---|
| 3718 | if insitu is None: insitu = rcParams['insitu'] |
---|
[876] | 3719 | self._math._setinsitu(insitu) |
---|
[513] | 3720 | varlist = vars() |
---|
[876] | 3721 | s = scantable(self._math._unaryop(self, offset, "ADD", False)) |
---|
[1118] | 3722 | s._add_history("add", varlist) |
---|
[876] | 3723 | if insitu: |
---|
| 3724 | self._assign(s) |
---|
| 3725 | else: |
---|
[513] | 3726 | return s |
---|
| 3727 | |
---|
[1862] | 3728 | @asaplog_post_dec |
---|
[1308] | 3729 | def scale(self, factor, tsys=True, insitu=None): |
---|
[1846] | 3730 | """\ |
---|
| 3731 | |
---|
[1938] | 3732 | Return a scan where all spectra are scaled by the given 'factor' |
---|
[1846] | 3733 | |
---|
[513] | 3734 | Parameters: |
---|
[1846] | 3735 | |
---|
[1819] | 3736 | factor: the scaling factor (float or 1D float list) |
---|
[1855] | 3737 | |
---|
[513] | 3738 | insitu: if False a new scantable is returned. |
---|
| 3739 | Otherwise, the scaling is done in-situ |
---|
| 3740 | The default is taken from .asaprc (False) |
---|
[1855] | 3741 | |
---|
[513] | 3742 | tsys: if True (default) then apply the operation to Tsys |
---|
| 3743 | as well as the data |
---|
[1846] | 3744 | |
---|
[513] | 3745 | """ |
---|
| 3746 | if insitu is None: insitu = rcParams['insitu'] |
---|
[876] | 3747 | self._math._setinsitu(insitu) |
---|
[513] | 3748 | varlist = vars() |
---|
[1819] | 3749 | s = None |
---|
| 3750 | import numpy |
---|
| 3751 | if isinstance(factor, list) or isinstance(factor, numpy.ndarray): |
---|
[2320] | 3752 | if isinstance(factor[0], list) or isinstance(factor[0], |
---|
| 3753 | numpy.ndarray): |
---|
[1819] | 3754 | from asapmath import _array2dOp |
---|
[2320] | 3755 | s = _array2dOp( self, factor, "MUL", tsys, insitu ) |
---|
[1819] | 3756 | else: |
---|
[2320] | 3757 | s = scantable( self._math._arrayop( self, factor, |
---|
| 3758 | "MUL", tsys ) ) |
---|
[1819] | 3759 | else: |
---|
[2320] | 3760 | s = scantable(self._math._unaryop(self, factor, "MUL", tsys)) |
---|
[1118] | 3761 | s._add_history("scale", varlist) |
---|
[876] | 3762 | if insitu: |
---|
| 3763 | self._assign(s) |
---|
| 3764 | else: |
---|
[513] | 3765 | return s |
---|
| 3766 | |
---|
[2349] | 3767 | @preserve_selection |
---|
| 3768 | def set_sourcetype(self, match, matchtype="pattern", |
---|
[1504] | 3769 | sourcetype="reference"): |
---|
[1846] | 3770 | """\ |
---|
[1502] | 3771 | Set the type of the source to be an source or reference scan |
---|
[1846] | 3772 | using the provided pattern. |
---|
| 3773 | |
---|
[1502] | 3774 | Parameters: |
---|
[1846] | 3775 | |
---|
[1504] | 3776 | match: a Unix style pattern, regular expression or selector |
---|
[1855] | 3777 | |
---|
[1504] | 3778 | matchtype: 'pattern' (default) UNIX style pattern or |
---|
| 3779 | 'regex' regular expression |
---|
[1855] | 3780 | |
---|
[1502] | 3781 | sourcetype: the type of the source to use (source/reference) |
---|
[1846] | 3782 | |
---|
[1502] | 3783 | """ |
---|
| 3784 | varlist = vars() |
---|
| 3785 | stype = -1 |
---|
[2480] | 3786 | if sourcetype.lower().startswith("r") or sourcetype.lower() == "off": |
---|
[1502] | 3787 | stype = 1 |
---|
[2480] | 3788 | elif sourcetype.lower().startswith("s") or sourcetype.lower() == "on": |
---|
[1502] | 3789 | stype = 0 |
---|
[1504] | 3790 | else: |
---|
[2480] | 3791 | raise ValueError("Illegal sourcetype use s(ource)/on or r(eference)/off") |
---|
[1504] | 3792 | if matchtype.lower().startswith("p"): |
---|
| 3793 | matchtype = "pattern" |
---|
| 3794 | elif matchtype.lower().startswith("r"): |
---|
| 3795 | matchtype = "regex" |
---|
| 3796 | else: |
---|
| 3797 | raise ValueError("Illegal matchtype, use p(attern) or r(egex)") |
---|
[1502] | 3798 | sel = selector() |
---|
| 3799 | if isinstance(match, selector): |
---|
| 3800 | sel = match |
---|
| 3801 | else: |
---|
[2480] | 3802 | sel.set_query("SRCNAME=%s('%s')" % (matchtype, match)) |
---|
| 3803 | self.set_selection(sel) |
---|
[1502] | 3804 | self._setsourcetype(stype) |
---|
[1573] | 3805 | self._add_history("set_sourcetype", varlist) |
---|
[1502] | 3806 | |
---|
[1862] | 3807 | @asaplog_post_dec |
---|
[1857] | 3808 | @preserve_selection |
---|
[1819] | 3809 | def auto_quotient(self, preserve=True, mode='paired', verify=False): |
---|
[1846] | 3810 | """\ |
---|
[670] | 3811 | This function allows to build quotients automatically. |
---|
[1819] | 3812 | It assumes the observation to have the same number of |
---|
[670] | 3813 | "ons" and "offs" |
---|
[1846] | 3814 | |
---|
[670] | 3815 | Parameters: |
---|
[1846] | 3816 | |
---|
[710] | 3817 | preserve: you can preserve (default) the continuum or |
---|
| 3818 | remove it. The equations used are |
---|
[1857] | 3819 | |
---|
[670] | 3820 | preserve: Output = Toff * (on/off) - Toff |
---|
[1857] | 3821 | |
---|
[1070] | 3822 | remove: Output = Toff * (on/off) - Ton |
---|
[1855] | 3823 | |
---|
[1573] | 3824 | mode: the on/off detection mode |
---|
[1348] | 3825 | 'paired' (default) |
---|
| 3826 | identifies 'off' scans by the |
---|
| 3827 | trailing '_R' (Mopra/Parkes) or |
---|
| 3828 | '_e'/'_w' (Tid) and matches |
---|
| 3829 | on/off pairs from the observing pattern |
---|
[1502] | 3830 | 'time' |
---|
| 3831 | finds the closest off in time |
---|
[1348] | 3832 | |
---|
[1857] | 3833 | .. todo:: verify argument is not implemented |
---|
| 3834 | |
---|
[670] | 3835 | """ |
---|
[1857] | 3836 | varlist = vars() |
---|
[1348] | 3837 | modes = ["time", "paired"] |
---|
[670] | 3838 | if not mode in modes: |
---|
[876] | 3839 | msg = "please provide valid mode. Valid modes are %s" % (modes) |
---|
| 3840 | raise ValueError(msg) |
---|
[1348] | 3841 | s = None |
---|
| 3842 | if mode.lower() == "paired": |
---|
[1857] | 3843 | sel = self.get_selection() |
---|
[1875] | 3844 | sel.set_query("SRCTYPE==psoff") |
---|
[1356] | 3845 | self.set_selection(sel) |
---|
[1348] | 3846 | offs = self.copy() |
---|
[1875] | 3847 | sel.set_query("SRCTYPE==pson") |
---|
[1356] | 3848 | self.set_selection(sel) |
---|
[1348] | 3849 | ons = self.copy() |
---|
| 3850 | s = scantable(self._math._quotient(ons, offs, preserve)) |
---|
| 3851 | elif mode.lower() == "time": |
---|
| 3852 | s = scantable(self._math._auto_quotient(self, mode, preserve)) |
---|
[1118] | 3853 | s._add_history("auto_quotient", varlist) |
---|
[876] | 3854 | return s |
---|
[710] | 3855 | |
---|
[1862] | 3856 | @asaplog_post_dec |
---|
[1145] | 3857 | def mx_quotient(self, mask = None, weight='median', preserve=True): |
---|
[1846] | 3858 | """\ |
---|
[1143] | 3859 | Form a quotient using "off" beams when observing in "MX" mode. |
---|
[1846] | 3860 | |
---|
[1143] | 3861 | Parameters: |
---|
[1846] | 3862 | |
---|
[1145] | 3863 | mask: an optional mask to be used when weight == 'stddev' |
---|
[1855] | 3864 | |
---|
[1143] | 3865 | weight: How to average the off beams. Default is 'median'. |
---|
[1855] | 3866 | |
---|
[1145] | 3867 | preserve: you can preserve (default) the continuum or |
---|
[1855] | 3868 | remove it. The equations used are: |
---|
[1846] | 3869 | |
---|
[1855] | 3870 | preserve: Output = Toff * (on/off) - Toff |
---|
| 3871 | |
---|
| 3872 | remove: Output = Toff * (on/off) - Ton |
---|
| 3873 | |
---|
[1217] | 3874 | """ |
---|
[1593] | 3875 | mask = mask or () |
---|
[1141] | 3876 | varlist = vars() |
---|
| 3877 | on = scantable(self._math._mx_extract(self, 'on')) |
---|
[1143] | 3878 | preoff = scantable(self._math._mx_extract(self, 'off')) |
---|
| 3879 | off = preoff.average_time(mask=mask, weight=weight, scanav=False) |
---|
[1217] | 3880 | from asapmath import quotient |
---|
[1145] | 3881 | q = quotient(on, off, preserve) |
---|
[1143] | 3882 | q._add_history("mx_quotient", varlist) |
---|
[1217] | 3883 | return q |
---|
[513] | 3884 | |
---|
[1862] | 3885 | @asaplog_post_dec |
---|
[718] | 3886 | def freq_switch(self, insitu=None): |
---|
[1846] | 3887 | """\ |
---|
[718] | 3888 | Apply frequency switching to the data. |
---|
[1846] | 3889 | |
---|
[718] | 3890 | Parameters: |
---|
[1846] | 3891 | |
---|
[718] | 3892 | insitu: if False a new scantable is returned. |
---|
| 3893 | Otherwise, the swictching is done in-situ |
---|
| 3894 | The default is taken from .asaprc (False) |
---|
[1846] | 3895 | |
---|
[718] | 3896 | """ |
---|
| 3897 | if insitu is None: insitu = rcParams['insitu'] |
---|
[876] | 3898 | self._math._setinsitu(insitu) |
---|
[718] | 3899 | varlist = vars() |
---|
[876] | 3900 | s = scantable(self._math._freqswitch(self)) |
---|
[1118] | 3901 | s._add_history("freq_switch", varlist) |
---|
[1856] | 3902 | if insitu: |
---|
| 3903 | self._assign(s) |
---|
| 3904 | else: |
---|
| 3905 | return s |
---|
[718] | 3906 | |
---|
[1862] | 3907 | @asaplog_post_dec |
---|
[780] | 3908 | def recalc_azel(self): |
---|
[1846] | 3909 | """Recalculate the azimuth and elevation for each position.""" |
---|
[780] | 3910 | varlist = vars() |
---|
[876] | 3911 | self._recalcazel() |
---|
[780] | 3912 | self._add_history("recalc_azel", varlist) |
---|
| 3913 | return |
---|
| 3914 | |
---|
[1862] | 3915 | @asaplog_post_dec |
---|
[513] | 3916 | def __add__(self, other): |
---|
[2574] | 3917 | """ |
---|
| 3918 | implicit on all axes and on Tsys |
---|
| 3919 | """ |
---|
[513] | 3920 | varlist = vars() |
---|
[2574] | 3921 | s = self.__op( other, "ADD" ) |
---|
[513] | 3922 | s._add_history("operator +", varlist) |
---|
| 3923 | return s |
---|
| 3924 | |
---|
[1862] | 3925 | @asaplog_post_dec |
---|
[513] | 3926 | def __sub__(self, other): |
---|
| 3927 | """ |
---|
| 3928 | implicit on all axes and on Tsys |
---|
| 3929 | """ |
---|
| 3930 | varlist = vars() |
---|
[2574] | 3931 | s = self.__op( other, "SUB" ) |
---|
[513] | 3932 | s._add_history("operator -", varlist) |
---|
| 3933 | return s |
---|
[710] | 3934 | |
---|
[1862] | 3935 | @asaplog_post_dec |
---|
[513] | 3936 | def __mul__(self, other): |
---|
| 3937 | """ |
---|
| 3938 | implicit on all axes and on Tsys |
---|
| 3939 | """ |
---|
| 3940 | varlist = vars() |
---|
[2574] | 3941 | s = self.__op( other, "MUL" ) ; |
---|
[513] | 3942 | s._add_history("operator *", varlist) |
---|
| 3943 | return s |
---|
| 3944 | |
---|
[710] | 3945 | |
---|
[1862] | 3946 | @asaplog_post_dec |
---|
[513] | 3947 | def __div__(self, other): |
---|
| 3948 | """ |
---|
| 3949 | implicit on all axes and on Tsys |
---|
| 3950 | """ |
---|
| 3951 | varlist = vars() |
---|
[2574] | 3952 | s = self.__op( other, "DIV" ) |
---|
| 3953 | s._add_history("operator /", varlist) |
---|
| 3954 | return s |
---|
| 3955 | |
---|
| 3956 | @asaplog_post_dec |
---|
| 3957 | def __op( self, other, mode ): |
---|
[513] | 3958 | s = None |
---|
| 3959 | if isinstance(other, scantable): |
---|
[2574] | 3960 | s = scantable(self._math._binaryop(self, other, mode)) |
---|
[513] | 3961 | elif isinstance(other, float): |
---|
| 3962 | if other == 0.0: |
---|
[718] | 3963 | raise ZeroDivisionError("Dividing by zero is not recommended") |
---|
[2574] | 3964 | s = scantable(self._math._unaryop(self, other, mode, False)) |
---|
[2144] | 3965 | elif isinstance(other, list) or isinstance(other, numpy.ndarray): |
---|
[2349] | 3966 | if isinstance(other[0], list) \ |
---|
| 3967 | or isinstance(other[0], numpy.ndarray): |
---|
[2144] | 3968 | from asapmath import _array2dOp |
---|
[2574] | 3969 | s = _array2dOp( self, other, mode, False ) |
---|
[2144] | 3970 | else: |
---|
[2574] | 3971 | s = scantable( self._math._arrayop( self, other, |
---|
| 3972 | mode, False ) ) |
---|
[513] | 3973 | else: |
---|
[718] | 3974 | raise TypeError("Other input is not a scantable or float value") |
---|
[513] | 3975 | return s |
---|
| 3976 | |
---|
[1862] | 3977 | @asaplog_post_dec |
---|
[530] | 3978 | def get_fit(self, row=0): |
---|
[1846] | 3979 | """\ |
---|
[530] | 3980 | Print or return the stored fits for a row in the scantable |
---|
[1846] | 3981 | |
---|
[530] | 3982 | Parameters: |
---|
[1846] | 3983 | |
---|
[530] | 3984 | row: the row which the fit has been applied to. |
---|
[1846] | 3985 | |
---|
[530] | 3986 | """ |
---|
| 3987 | if row > self.nrow(): |
---|
| 3988 | return |
---|
[976] | 3989 | from asap.asapfit import asapfit |
---|
[530] | 3990 | fit = asapfit(self._getfit(row)) |
---|
[1859] | 3991 | asaplog.push( '%s' %(fit) ) |
---|
| 3992 | return fit.as_dict() |
---|
[530] | 3993 | |
---|
[2349] | 3994 | @preserve_selection |
---|
[1483] | 3995 | def flag_nans(self): |
---|
[1846] | 3996 | """\ |
---|
[1483] | 3997 | Utility function to flag NaN values in the scantable. |
---|
| 3998 | """ |
---|
| 3999 | import numpy |
---|
| 4000 | basesel = self.get_selection() |
---|
| 4001 | for i in range(self.nrow()): |
---|
[1589] | 4002 | sel = self.get_row_selector(i) |
---|
| 4003 | self.set_selection(basesel+sel) |
---|
[1483] | 4004 | nans = numpy.isnan(self._getspectrum(0)) |
---|
| 4005 | if numpy.any(nans): |
---|
| 4006 | bnans = [ bool(v) for v in nans] |
---|
| 4007 | self.flag(bnans) |
---|
| 4008 | |
---|
[1588] | 4009 | def get_row_selector(self, rowno): |
---|
[1992] | 4010 | return selector(rows=[rowno]) |
---|
[1573] | 4011 | |
---|
[484] | 4012 | def _add_history(self, funcname, parameters): |
---|
[1435] | 4013 | if not rcParams['scantable.history']: |
---|
| 4014 | return |
---|
[484] | 4015 | # create date |
---|
| 4016 | sep = "##" |
---|
| 4017 | from datetime import datetime |
---|
| 4018 | dstr = datetime.now().strftime('%Y/%m/%d %H:%M:%S') |
---|
| 4019 | hist = dstr+sep |
---|
| 4020 | hist += funcname+sep#cdate+sep |
---|
[2349] | 4021 | if parameters.has_key('self'): |
---|
| 4022 | del parameters['self'] |
---|
[1118] | 4023 | for k, v in parameters.iteritems(): |
---|
[484] | 4024 | if type(v) is dict: |
---|
[1118] | 4025 | for k2, v2 in v.iteritems(): |
---|
[484] | 4026 | hist += k2 |
---|
| 4027 | hist += "=" |
---|
[1118] | 4028 | if isinstance(v2, scantable): |
---|
[484] | 4029 | hist += 'scantable' |
---|
| 4030 | elif k2 == 'mask': |
---|
[1118] | 4031 | if isinstance(v2, list) or isinstance(v2, tuple): |
---|
[513] | 4032 | hist += str(self._zip_mask(v2)) |
---|
| 4033 | else: |
---|
| 4034 | hist += str(v2) |
---|
[484] | 4035 | else: |
---|
[513] | 4036 | hist += str(v2) |
---|
[484] | 4037 | else: |
---|
| 4038 | hist += k |
---|
| 4039 | hist += "=" |
---|
[1118] | 4040 | if isinstance(v, scantable): |
---|
[484] | 4041 | hist += 'scantable' |
---|
| 4042 | elif k == 'mask': |
---|
[1118] | 4043 | if isinstance(v, list) or isinstance(v, tuple): |
---|
[513] | 4044 | hist += str(self._zip_mask(v)) |
---|
| 4045 | else: |
---|
| 4046 | hist += str(v) |
---|
[484] | 4047 | else: |
---|
| 4048 | hist += str(v) |
---|
| 4049 | hist += sep |
---|
| 4050 | hist = hist[:-2] # remove trailing '##' |
---|
| 4051 | self._addhistory(hist) |
---|
| 4052 | |
---|
[710] | 4053 | |
---|
[484] | 4054 | def _zip_mask(self, mask): |
---|
| 4055 | mask = list(mask) |
---|
| 4056 | i = 0 |
---|
| 4057 | segments = [] |
---|
| 4058 | while mask[i:].count(1): |
---|
| 4059 | i += mask[i:].index(1) |
---|
| 4060 | if mask[i:].count(0): |
---|
| 4061 | j = i + mask[i:].index(0) |
---|
| 4062 | else: |
---|
[710] | 4063 | j = len(mask) |
---|
[1118] | 4064 | segments.append([i, j]) |
---|
[710] | 4065 | i = j |
---|
[484] | 4066 | return segments |
---|
[714] | 4067 | |
---|
[626] | 4068 | def _get_ordinate_label(self): |
---|
| 4069 | fu = "("+self.get_fluxunit()+")" |
---|
| 4070 | import re |
---|
| 4071 | lbl = "Intensity" |
---|
[1118] | 4072 | if re.match(".K.", fu): |
---|
[626] | 4073 | lbl = "Brightness Temperature "+ fu |
---|
[1118] | 4074 | elif re.match(".Jy.", fu): |
---|
[626] | 4075 | lbl = "Flux density "+ fu |
---|
| 4076 | return lbl |
---|
[710] | 4077 | |
---|
[876] | 4078 | def _check_ifs(self): |
---|
[2349] | 4079 | # return len(set([self.nchan(i) for i in self.getifnos()])) == 1 |
---|
[1986] | 4080 | nchans = [self.nchan(i) for i in self.getifnos()] |
---|
[2004] | 4081 | nchans = filter(lambda t: t > 0, nchans) |
---|
[876] | 4082 | return (sum(nchans)/len(nchans) == nchans[0]) |
---|
[976] | 4083 | |
---|
[1862] | 4084 | @asaplog_post_dec |
---|
[1916] | 4085 | def _fill(self, names, unit, average, opts={}): |
---|
[976] | 4086 | first = True |
---|
| 4087 | fullnames = [] |
---|
| 4088 | for name in names: |
---|
| 4089 | name = os.path.expandvars(name) |
---|
| 4090 | name = os.path.expanduser(name) |
---|
| 4091 | if not os.path.exists(name): |
---|
| 4092 | msg = "File '%s' does not exists" % (name) |
---|
| 4093 | raise IOError(msg) |
---|
| 4094 | fullnames.append(name) |
---|
| 4095 | if average: |
---|
| 4096 | asaplog.push('Auto averaging integrations') |
---|
[1079] | 4097 | stype = int(rcParams['scantable.storage'].lower() == 'disk') |
---|
[976] | 4098 | for name in fullnames: |
---|
[1073] | 4099 | tbl = Scantable(stype) |
---|
[2004] | 4100 | if is_ms( name ): |
---|
| 4101 | r = msfiller( tbl ) |
---|
| 4102 | else: |
---|
| 4103 | r = filler( tbl ) |
---|
[976] | 4104 | msg = "Importing %s..." % (name) |
---|
[1118] | 4105 | asaplog.push(msg, False) |
---|
[2349] | 4106 | r.open(name, opts) |
---|
[2480] | 4107 | rx = rcParams['scantable.reference'] |
---|
| 4108 | r.setreferenceexpr(rx) |
---|
[1843] | 4109 | r.fill() |
---|
[976] | 4110 | if average: |
---|
[1118] | 4111 | tbl = self._math._average((tbl, ), (), 'NONE', 'SCAN') |
---|
[976] | 4112 | if not first: |
---|
| 4113 | tbl = self._math._merge([self, tbl]) |
---|
| 4114 | Scantable.__init__(self, tbl) |
---|
[1843] | 4115 | r.close() |
---|
[1118] | 4116 | del r, tbl |
---|
[976] | 4117 | first = False |
---|
[1861] | 4118 | #flush log |
---|
| 4119 | asaplog.post() |
---|
[976] | 4120 | if unit is not None: |
---|
| 4121 | self.set_fluxunit(unit) |
---|
[1824] | 4122 | if not is_casapy(): |
---|
| 4123 | self.set_freqframe(rcParams['scantable.freqframe']) |
---|
[976] | 4124 | |
---|
[2610] | 4125 | def _get_verify_action( self, msg, action=None ): |
---|
| 4126 | valid_act = ['Y', 'N', 'A', 'R'] |
---|
| 4127 | if not action or not isinstance(action, str): |
---|
| 4128 | action = raw_input("%s [Y/n/a/r] (h for help): " % msg) |
---|
| 4129 | if action == '': |
---|
| 4130 | return "Y" |
---|
| 4131 | elif (action.upper()[0] in valid_act): |
---|
| 4132 | return action.upper()[0] |
---|
| 4133 | elif (action.upper()[0] in ['H','?']): |
---|
| 4134 | print "Available actions of verification [Y|n|a|r]" |
---|
| 4135 | print " Y : Yes for current data (default)" |
---|
| 4136 | print " N : No for current data" |
---|
| 4137 | print " A : Accept all in the following and exit from verification" |
---|
| 4138 | print " R : Reject all in the following and exit from verification" |
---|
| 4139 | print " H or ?: help (show this message)" |
---|
| 4140 | return self._get_verify_action(msg) |
---|
| 4141 | else: |
---|
| 4142 | return 'Y' |
---|
[2012] | 4143 | |
---|
[1402] | 4144 | def __getitem__(self, key): |
---|
| 4145 | if key < 0: |
---|
| 4146 | key += self.nrow() |
---|
| 4147 | if key >= self.nrow(): |
---|
| 4148 | raise IndexError("Row index out of range.") |
---|
| 4149 | return self._getspectrum(key) |
---|
| 4150 | |
---|
| 4151 | def __setitem__(self, key, value): |
---|
| 4152 | if key < 0: |
---|
| 4153 | key += self.nrow() |
---|
| 4154 | if key >= self.nrow(): |
---|
| 4155 | raise IndexError("Row index out of range.") |
---|
| 4156 | if not hasattr(value, "__len__") or \ |
---|
| 4157 | len(value) > self.nchan(self.getif(key)): |
---|
| 4158 | raise ValueError("Spectrum length doesn't match.") |
---|
| 4159 | return self._setspectrum(value, key) |
---|
| 4160 | |
---|
| 4161 | def __len__(self): |
---|
| 4162 | return self.nrow() |
---|
| 4163 | |
---|
| 4164 | def __iter__(self): |
---|
| 4165 | for i in range(len(self)): |
---|
| 4166 | yield self[i] |
---|