source: trunk/src/SDMemTable.cc @ 455

Last change on this file since 455 was 455, checked in by mar637, 19 years ago
  • added FITS subtable for fitting and relevant functions to set fits and put/get SDFitContainer
  • cleanup
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 49.3 KB
Line 
1//#---------------------------------------------------------------------------
2//# SDMemTable.cc: A MemoryTable container for single dish integrations
3//#---------------------------------------------------------------------------
4//# Copyright (C) 2004
5//# ATNF
6//#
7//# This program is free software; you can redistribute it and/or modify it
8//# under the terms of the GNU General Public License as published by the Free
9//# Software Foundation; either version 2 of the License, or (at your option)
10//# any later version.
11//#
12//# This program is distributed in the hope that it will be useful, but
13//# WITHOUT ANY WARRANTY; without even the implied warranty of
14//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
15//# Public License for more details.
16//#
17//# You should have received a copy of the GNU General Public License along
18//# with this program; if not, write to the Free Software Foundation, Inc.,
19//# 675 Massachusetts Ave, Cambridge, MA 02139, USA.
20//#
21//# Correspondence concerning this software should be addressed as follows:
22//#        Internet email: Malte.Marquarding@csiro.au
23//#        Postal address: Malte Marquarding,
24//#                        Australia Telescope National Facility,
25//#                        P.O. Box 76,
26//#                        Epping, NSW, 2121,
27//#                        AUSTRALIA
28//#
29//# $Id:
30//#---------------------------------------------------------------------------
31
32#include <map>
33
34#include <casa/aips.h>
35#include <casa/iostream.h>
36#include <casa/iomanip.h>
37#include <casa/Arrays/Array.h>
38#include <casa/Arrays/ArrayMath.h>
39#include <casa/Arrays/MaskArrMath.h>
40#include <casa/Arrays/ArrayLogical.h>
41#include <casa/Arrays/ArrayAccessor.h>
42#include <casa/Arrays/VectorSTLIterator.h>
43#include <casa/Arrays/Vector.h>
44#include <casa/BasicMath/Math.h>
45#include <casa/Quanta/MVAngle.h>
46
47#include <tables/Tables/TableParse.h>
48#include <tables/Tables/TableDesc.h>
49#include <tables/Tables/SetupNewTab.h>
50#include <tables/Tables/ScaColDesc.h>
51#include <tables/Tables/ArrColDesc.h>
52
53#include <tables/Tables/ExprNode.h>
54#include <tables/Tables/TableRecord.h>
55#include <measures/Measures/MFrequency.h>
56#include <measures/Measures/MeasTable.h>
57#include <coordinates/Coordinates/CoordinateUtil.h>
58#include <casa/Quanta/MVTime.h>
59#include <casa/Quanta/MVAngle.h>
60
61#include "SDDefs.h"
62#include "SDMemTable.h"
63#include "SDContainer.h"
64#include "MathUtils.h"
65#include "SDPol.h"
66
67
68using namespace casa;
69using namespace asap;
70
71SDMemTable::SDMemTable() :
72  IFSel_(0),
73  beamSel_(0),
74  polSel_(0)
75{
76  setup();
77  attach();
78}
79
80SDMemTable::SDMemTable(const std::string& name) :
81  IFSel_(0),
82  beamSel_(0),
83  polSel_(0)
84{
85  Table tab(name);
86  table_ = tab.copyToMemoryTable("dummy");
87  //cerr << "hello from C SDMemTable @ " << this << endl;
88  attach();
89}
90
91SDMemTable::SDMemTable(const SDMemTable& other, Bool clear)
92{
93  IFSel_= other.IFSel_;
94  beamSel_= other.beamSel_;
95  polSel_= other.polSel_;
96  chanMask_ = other.chanMask_;
97  table_ = other.table_.copyToMemoryTable(String("dummy"));
98  // clear all rows()
99  if (clear) {
100    table_.removeRow(this->table_.rowNumbers());
101  } else {
102    IFSel_ = other.IFSel_;
103    beamSel_ = other.beamSel_;
104    polSel_ = other.polSel_;
105  }
106//
107  attach();
108  //cerr << "hello from CC SDMemTable @ " << this << endl;
109}
110
111SDMemTable::SDMemTable(const Table& tab, const std::string& exprs) :
112  IFSel_(0),
113  beamSel_(0),
114  polSel_(0)
115{
116  Table t = tableCommand(exprs,tab);
117  if (t.nrow() == 0)
118      throw(AipsError("Query unsuccessful."));
119  table_ = t.copyToMemoryTable("dummy");
120  attach();
121  renumber();
122}
123
124SDMemTable::~SDMemTable()
125{
126  //cerr << "goodbye from SDMemTable @ " << this << endl;
127}
128
129SDMemTable SDMemTable::getScan(Int scanID) const
130{
131  String cond("SELECT * from $1 WHERE SCANID == ");
132  cond += String::toString(scanID);
133  return SDMemTable(table_, cond);
134}
135
136SDMemTable &SDMemTable::operator=(const SDMemTable& other)
137{
138  if (this != &other) {
139     IFSel_= other.IFSel_;
140     beamSel_= other.beamSel_;
141     polSel_= other.polSel_;
142     chanMask_.resize(0);
143     chanMask_ = other.chanMask_;
144     table_ = other.table_.copyToMemoryTable(String("dummy"));
145     attach();
146  }
147  //cerr << "hello from ASS SDMemTable @ " << this << endl;
148  return *this;
149}
150
151SDMemTable SDMemTable::getSource(const std::string& source) const
152{
153  String cond("SELECT * from $1 WHERE SRCNAME == ");
154  cond += source;
155  return SDMemTable(table_, cond);
156}
157
158void SDMemTable::setup()
159{
160  TableDesc td("", "1", TableDesc::Scratch);
161  td.comment() = "A SDMemTable";
162 
163  td.addColumn(ScalarColumnDesc<Double>("TIME"));
164  td.addColumn(ScalarColumnDesc<String>("SRCNAME"));
165  td.addColumn(ArrayColumnDesc<Float>("SPECTRA"));
166  td.addColumn(ArrayColumnDesc<uChar>("FLAGTRA"));
167  td.addColumn(ArrayColumnDesc<Float>("TSYS"));
168  td.addColumn(ArrayColumnDesc<Float>("STOKES"));
169  td.addColumn(ScalarColumnDesc<Int>("SCANID"));
170  td.addColumn(ScalarColumnDesc<Double>("INTERVAL"));
171  td.addColumn(ArrayColumnDesc<uInt>("FREQID"));
172  td.addColumn(ArrayColumnDesc<uInt>("RESTFREQID"));
173  td.addColumn(ArrayColumnDesc<Double>("DIRECTION"));
174  td.addColumn(ScalarColumnDesc<String>("FIELDNAME"));
175  td.addColumn(ScalarColumnDesc<String>("TCALTIME"));
176  td.addColumn(ArrayColumnDesc<Float>("TCAL"));
177  td.addColumn(ScalarColumnDesc<Float>("AZIMUTH"));
178  td.addColumn(ScalarColumnDesc<Float>("ELEVATION"));
179  td.addColumn(ScalarColumnDesc<Float>("PARANGLE"));
180  td.addColumn(ScalarColumnDesc<Int>("REFBEAM"));
181  td.addColumn(ArrayColumnDesc<String>("HISTORY"));
182  td.addColumn(ArrayColumnDesc<Int>("FITID"));
183
184
185  // Now create Table SetUp from the description.
186
187  SetupNewTable aNewTab("dummy", td, Table::New);
188
189  // Bind the Stokes Virtual machine to the STOKES column Because we
190  // don't know how many polarizations will be in the data at this
191  // point, we must bind the Virtual Engine regardless.  The STOKES
192  // column won't be accessed if not appropriate (nPol=4)
193
194   SDStokesEngine stokesEngine(String("STOKES"), String("SPECTRA"));
195   aNewTab.bindColumn ("STOKES", stokesEngine);
196
197   // Create Table
198  table_ = Table(aNewTab, Table::Memory, 0);
199  // add subtable
200  TableDesc tdf("", "1", TableDesc::Scratch);
201  tdf.addColumn(ArrayColumnDesc<String>("FUNCTIONS"));
202  tdf.addColumn(ArrayColumnDesc<Int>("COMPONENTS"));
203  tdf.addColumn(ArrayColumnDesc<Double>("PARAMETERS"));
204  tdf.addColumn(ArrayColumnDesc<Bool>("PARMASK"));
205  SetupNewTable fittab("fits", tdf, Table::New);
206  Table fitTable(fittab, Table::Memory);
207  table_.rwKeywordSet().defineTable("FITS", fitTable);
208
209
210}
211
212void SDMemTable::attach()
213{
214  timeCol_.attach(table_, "TIME");
215  srcnCol_.attach(table_, "SRCNAME");
216  specCol_.attach(table_, "SPECTRA");
217  flagsCol_.attach(table_, "FLAGTRA");
218  tsCol_.attach(table_, "TSYS");
219  stokesCol_.attach(table_, "STOKES");
220  scanCol_.attach(table_, "SCANID");
221  integrCol_.attach(table_, "INTERVAL");
222  freqidCol_.attach(table_, "FREQID");
223  restfreqidCol_.attach(table_, "RESTFREQID");
224  dirCol_.attach(table_, "DIRECTION");
225  fldnCol_.attach(table_, "FIELDNAME");
226  tcaltCol_.attach(table_, "TCALTIME");
227  tcalCol_.attach(table_, "TCAL");
228  azCol_.attach(table_, "AZIMUTH");
229  elCol_.attach(table_, "ELEVATION");
230  paraCol_.attach(table_, "PARANGLE");
231  rbeamCol_.attach(table_, "REFBEAM");
232  histCol_.attach(table_, "HISTORY");
233  fitCol_.attach(table_,"FITID");
234}
235
236
237std::string SDMemTable::getSourceName(Int whichRow) const
238{
239  String name;
240  srcnCol_.get(whichRow, name);
241  return name;
242}
243
244std::string SDMemTable::getTime(Int whichRow, Bool showDate) const
245{
246  Double tm;
247  if (whichRow > -1) {
248    timeCol_.get(whichRow, tm);
249  } else {
250    table_.keywordSet().get("UTC",tm);
251  }
252  MVTime mvt(tm);
253  if (showDate)
254    mvt.setFormat(MVTime::YMD);
255  else
256    mvt.setFormat(MVTime::TIME);
257  ostringstream oss;
258  oss << mvt;
259  return String(oss);
260}
261
262double SDMemTable::getInterval(Int whichRow) const
263{
264  Double intval;
265  integrCol_.get(whichRow, intval);
266  return intval;
267}
268
269bool SDMemTable::setIF(Int whichIF)
270{
271  if ( whichIF >= 0 && whichIF < nIF()) {
272    IFSel_ = whichIF;
273    return true;
274  }
275  return false;
276}
277
278bool SDMemTable::setBeam(Int whichBeam)
279{
280  if ( whichBeam >= 0 && whichBeam < nBeam()) {
281    beamSel_ = whichBeam;
282    return true;
283  }
284  return false;
285}
286
287bool SDMemTable::setPol(Int whichPol)
288{
289  if ( whichPol >= 0 && whichPol < nPol()) {
290    polSel_ = whichPol;
291    return true;
292  }
293  return false;
294}
295
296void SDMemTable::resetCursor()
297{
298   polSel_ = 0;
299   IFSel_ = 0;
300   beamSel_ = 0;
301}
302
303bool SDMemTable::setMask(std::vector<int> whichChans)
304{
305  std::vector<int>::iterator it;
306  uInt n = flagsCol_.shape(0)(3);
307  if (whichChans.empty()) {
308    chanMask_ = std::vector<bool>(n,true);
309    return true;     
310  }
311  chanMask_.resize(n,true);
312  for (it = whichChans.begin(); it != whichChans.end(); ++it) {
313    if (*it < n) {
314      chanMask_[*it] = false;
315    }
316  }
317  return true;
318}
319
320std::vector<bool> SDMemTable::getMask(Int whichRow) const
321{
322
323  std::vector<bool> mask;
324
325  Array<uChar> arr;
326  flagsCol_.get(whichRow, arr);
327
328  ArrayAccessor<uChar, Axis<asap::BeamAxis> > aa0(arr);
329  aa0.reset(aa0.begin(uInt(beamSel_)));//go to beam
330  ArrayAccessor<uChar, Axis<asap::IFAxis> > aa1(aa0);
331  aa1.reset(aa1.begin(uInt(IFSel_)));// go to IF
332  ArrayAccessor<uChar, Axis<asap::PolAxis> > aa2(aa1);
333  aa2.reset(aa2.begin(uInt(polSel_)));// go to pol
334
335  Bool useUserMask = ( chanMask_.size() == arr.shape()(3) );
336
337  std::vector<bool> tmp;
338  tmp = chanMask_; // WHY the fxxx do I have to make a copy here
339  std::vector<bool>::iterator miter;
340  miter = tmp.begin();
341
342  for (ArrayAccessor<uChar, Axis<asap::ChanAxis> > i(aa2); i != i.end(); ++i) {
343    bool out =!static_cast<bool>(*i);
344    if (useUserMask) {
345      out = out && (*miter);
346      miter++;
347    }
348    mask.push_back(out);
349  }
350  return mask;
351}
352
353
354
355std::vector<float> SDMemTable::getSpectrum(Int whichRow) const
356{
357
358  Array<Float> arr;
359  specCol_.get(whichRow, arr);
360  return getFloatSpectrum(arr);
361}
362
363std::vector<float> SDMemTable::getStokesSpectrum(Int whichRow, Bool doPol,
364                                                 Float paOffset) const
365  // Gets
366  //  doPol=False  : I,Q,U,V
367  //  doPol=True   : I,P,PA,V   ; P = sqrt(Q**2+U**2), PA = 0.5*atan2(Q,U)
368  //
369{
370  AlwaysAssert(asap::nAxes==4,AipsError);
371  if (nPol()!=1 && nPol()!=2 && nPol()!=4) {
372     throw (AipsError("You must have 1,2 or 4 polarizations to get the Stokes parameters"));
373  }
374  Array<Float> arr;
375  stokesCol_.get(whichRow, arr);
376
377  if (doPol && (polSel_==1 || polSel_==2)) {       //   Q,U --> P, P.A.
378
379    // Set current cursor location
380     const IPosition& shape = arr.shape();
381     IPosition start, end;
382     setCursorSlice (start, end, shape);
383
384     // Get Q and U slices
385
386     Array<Float> Q = SDPolUtil::getStokesSlice(arr,start,end,"Q");
387     Array<Float> U = SDPolUtil::getStokesSlice(arr,start,end,"U");
388
389     // Compute output
390
391     Array<Float> out;
392     if (polSel_==1) {                                        // P
393        out = SDPolUtil::polarizedIntensity(Q,U);
394     } else if (polSel_==2) {                                 // P.A.
395        out = SDPolUtil::positionAngle(Q,U) + paOffset;
396     }
397
398     // Copy to output
399
400     IPosition vecShape(1,shape(asap::ChanAxis));
401     Vector<Float> outV = out.reform(vecShape);
402     std::vector<float> stlout;
403     outV.tovector(stlout);
404     return stlout;
405
406  } else {
407
408    // Selects at the cursor location
409    return getFloatSpectrum(arr);
410  }
411}
412
413std::vector<float> SDMemTable::getCircularSpectrum(Int whichRow,
414                                                   Bool doRR) const
415  // Gets
416  //  RR = I + V
417  //  LL = I - V
418{
419  AlwaysAssert(asap::nAxes==4,AipsError);
420  if (nPol()!=4) {
421     throw (AipsError("You must have 4 polarizations to get RR or LL"));
422  }
423  Array<Float> arr;
424  stokesCol_.get(whichRow, arr);
425
426  // Set current cursor location
427
428  const IPosition& shape = arr.shape();
429  IPosition start, end;
430  setCursorSlice(start, end, shape);
431
432  // Get I and V slices
433
434  Array<Float> I = SDPolUtil::getStokesSlice(arr,start,end,"I");
435  Array<Float> V = SDPolUtil::getStokesSlice(arr,start,end,"V");
436
437  // Compute output
438
439  Array<Float> out = SDPolUtil::circularPolarizationFromStokes(I, V, doRR);
440
441  // Copy to output
442
443  IPosition vecShape(1,shape(asap::ChanAxis));
444  Vector<Float> outV = out.reform(vecShape);
445  std::vector<float> stlout;
446  outV.tovector(stlout);
447
448  return stlout;
449}
450
451
452std::vector<string> SDMemTable::getCoordInfo() const
453{
454  String un;
455  Table t = table_.keywordSet().asTable("FREQUENCIES");
456  String sunit;
457  t.keywordSet().get("UNIT",sunit);
458  String dpl;
459  t.keywordSet().get("DOPPLER",dpl);
460  if (dpl == "") dpl = "RADIO";
461  String rfrm;
462  t.keywordSet().get("REFFRAME",rfrm);
463  std::vector<string> inf;
464  inf.push_back(sunit);
465  inf.push_back(rfrm);
466  inf.push_back(dpl);
467  t.keywordSet().get("BASEREFFRAME",rfrm);
468  inf.push_back(rfrm);
469  return inf;
470}
471
472void SDMemTable::setCoordInfo(std::vector<string> theinfo)
473{
474  std::vector<string>::iterator it;
475  String un,rfrm, brfrm,dpl;
476  un = theinfo[0];              // Abcissa unit
477  rfrm = theinfo[1];            // Active (or conversion) frame
478  dpl = theinfo[2];             // Doppler
479  brfrm = theinfo[3];           // Base frame
480
481  Table t = table_.rwKeywordSet().asTable("FREQUENCIES");
482
483  Vector<Double> rstf;
484  t.keywordSet().get("RESTFREQS",rstf);
485
486  Bool canDo = True;
487  Unit u1("km/s");Unit u2("Hz");
488  if (Unit(un) == u1) {
489    Vector<Double> rstf;
490    t.keywordSet().get("RESTFREQS",rstf);
491    if (rstf.nelements() == 0) {
492        throw(AipsError("Can't set unit to km/s if no restfrequencies are specified"));
493    }
494  } else if (Unit(un) != u2 && un != "") {
495        throw(AipsError("Unit not conformant with Spectral Coordinates"));
496  }
497  t.rwKeywordSet().define("UNIT", un);
498
499  MFrequency::Types mdr;
500  if (!MFrequency::getType(mdr, rfrm)) {
501   
502    Int a,b;const uInt* c;
503    const String* valid = MFrequency::allMyTypes(a, b, c);
504    String pfix = "Please specify a legal frame type. Types are\n";
505    throw(AipsError(pfix+(*valid)));
506  } else {
507    t.rwKeywordSet().define("REFFRAME",rfrm);
508  }
509
510  MDoppler::Types dtype;
511  dpl.upcase();
512  if (!MDoppler::getType(dtype, dpl)) {
513    throw(AipsError("Doppler type unknown"));
514  } else {
515    t.rwKeywordSet().define("DOPPLER",dpl);
516  }
517
518  if (!MFrequency::getType(mdr, brfrm)) {
519     Int a,b;const uInt* c;
520     const String* valid = MFrequency::allMyTypes(a, b, c);
521     String pfix = "Please specify a legal frame type. Types are\n";
522     throw(AipsError(pfix+(*valid)));
523   } else {
524    t.rwKeywordSet().define("BASEREFFRAME",brfrm);
525   }
526}
527
528
529std::vector<double> SDMemTable::getAbcissa(Int whichRow) const
530{
531  std::vector<double> abc(nChan());
532
533  // Get header units keyword
534  Table t = table_.keywordSet().asTable("FREQUENCIES");
535  String sunit;
536  t.keywordSet().get("UNIT",sunit);
537  if (sunit == "") sunit = "pixel";
538  Unit u(sunit);
539
540  // Easy if just wanting pixels
541  if (sunit==String("pixel")) {
542    // assume channels/pixels
543    std::vector<double>::iterator it;
544    uInt i=0;
545    for (it = abc.begin(); it != abc.end(); ++it) {
546      (*it) = Double(i++);
547    }
548    return abc;
549  }
550
551  // Continue with km/s or Hz.  Get FreqIDs
552  Vector<uInt> freqIDs;
553  freqidCol_.get(whichRow, freqIDs);
554  uInt freqID = freqIDs(IFSel_);
555  restfreqidCol_.get(whichRow, freqIDs);
556  uInt restFreqID = freqIDs(IFSel_);
557
558  // Get SpectralCoordinate, set reference frame conversion,
559  // velocity conversion, and rest freq state
560
561  SpectralCoordinate spc = getSpectralCoordinate(freqID, restFreqID, whichRow);
562  Vector<Double> pixel(nChan());
563  indgen(pixel);
564
565  if (u == Unit("km/s")) {
566     Vector<Double> world;
567     spc.pixelToVelocity(world,pixel);
568     std::vector<double>::iterator it;
569     uInt i = 0;
570     for (it = abc.begin(); it != abc.end(); ++it) {
571       (*it) = world[i];
572       i++;
573     }
574  } else if (u == Unit("Hz")) {
575
576    // Set world axis units   
577    Vector<String> wau(1); wau = u.getName();
578    spc.setWorldAxisUnits(wau);
579
580    std::vector<double>::iterator it;
581    Double tmp;
582    uInt i = 0;
583    for (it = abc.begin(); it != abc.end(); ++it) {
584      spc.toWorld(tmp,pixel[i]);
585      (*it) = tmp;
586      i++;
587    }
588  }
589  return abc;
590}
591
592std::string SDMemTable::getAbcissaString(Int whichRow) const
593{
594  Table t = table_.keywordSet().asTable("FREQUENCIES");
595
596  String sunit;
597  t.keywordSet().get("UNIT",sunit);
598  if (sunit == "") sunit = "pixel";
599  Unit u(sunit);
600
601  Vector<uInt> freqIDs;
602  freqidCol_.get(whichRow, freqIDs);
603  uInt freqID = freqIDs(IFSel_); 
604  restfreqidCol_.get(whichRow, freqIDs);
605  uInt restFreqID = freqIDs(IFSel_);
606
607  // Get SpectralCoordinate, with frame, velocity, rest freq state set
608  SpectralCoordinate spc = getSpectralCoordinate(freqID, restFreqID, whichRow);
609
610  String s = "Channel";
611  if (u == Unit("km/s")) {
612    s = CoordinateUtil::axisLabel(spc,0,True,True,True);
613  } else if (u == Unit("Hz")) {
614    Vector<String> wau(1);wau = u.getName();
615    spc.setWorldAxisUnits(wau);
616
617    s = CoordinateUtil::axisLabel(spc,0,True,True,False);
618  }
619  return s;
620}
621
622void SDMemTable::setSpectrum(std::vector<float> spectrum, int whichRow)
623{
624  Array<Float> arr;
625  specCol_.get(whichRow, arr);
626  if (spectrum.size() != arr.shape()(asap::ChanAxis)) {
627    throw(AipsError("Attempting to set spectrum with incorrect length."));
628  }
629
630  // Setup accessors
631  ArrayAccessor<Float, Axis<asap::BeamAxis> > aa0(arr);
632  aa0.reset(aa0.begin(uInt(beamSel_)));                   // Beam selection
633  ArrayAccessor<Float, Axis<asap::IFAxis> > aa1(aa0);
634  aa1.reset(aa1.begin(uInt(IFSel_)));                     // IF selection
635  ArrayAccessor<Float, Axis<asap::PolAxis> > aa2(aa1);
636  aa2.reset(aa2.begin(uInt(polSel_)));                    // Pol selection
637
638  // Iterate
639  std::vector<float>::iterator it = spectrum.begin();
640  for (ArrayAccessor<Float, Axis<asap::ChanAxis> > i(aa2); i != i.end(); ++i) {
641    (*i) = Float(*it);
642    it++;
643  }
644  specCol_.put(whichRow, arr);
645}
646
647void SDMemTable::getSpectrum(Vector<Float>& spectrum, Int whichRow) const
648{
649  Array<Float> arr;
650  specCol_.get(whichRow, arr);
651
652  // Iterate and extract
653  spectrum.resize(arr.shape()(3));
654  ArrayAccessor<Float, Axis<asap::BeamAxis> > aa0(arr);
655  aa0.reset(aa0.begin(uInt(beamSel_)));//go to beam
656  ArrayAccessor<Float, Axis<asap::IFAxis> > aa1(aa0);
657  aa1.reset(aa1.begin(uInt(IFSel_)));// go to IF
658  ArrayAccessor<Float, Axis<asap::PolAxis> > aa2(aa1);
659  aa2.reset(aa2.begin(uInt(polSel_)));// go to pol
660
661  ArrayAccessor<Float, Axis<asap::BeamAxis> > va(spectrum);
662  for (ArrayAccessor<Float, Axis<asap::ChanAxis> > i(aa2); i != i.end(); ++i) {
663    (*va) = (*i);
664    va++;
665  }
666}
667
668
669/*
670void SDMemTable::getMask(Vector<Bool>& mask, Int whichRow) const {
671  Array<uChar> arr;
672  flagsCol_.get(whichRow, arr);
673  mask.resize(arr.shape()(3));
674
675  ArrayAccessor<uChar, Axis<asap::BeamAxis> > aa0(arr);
676  aa0.reset(aa0.begin(uInt(beamSel_)));//go to beam
677  ArrayAccessor<uChar, Axis<asap::IFAxis> > aa1(aa0);
678  aa1.reset(aa1.begin(uInt(IFSel_)));// go to IF
679  ArrayAccessor<uChar, Axis<asap::PolAxis> > aa2(aa1);
680  aa2.reset(aa2.begin(uInt(polSel_)));// go to pol
681
682  Bool useUserMask = ( chanMask_.size() == arr.shape()(3) );
683
684  ArrayAccessor<Bool, Axis<asap::BeamAxis> > va(mask);
685  std::vector<bool> tmp;
686  tmp = chanMask_; // WHY the fxxx do I have to make a copy here. The
687                   // iterator should work on chanMask_??
688  std::vector<bool>::iterator miter;
689  miter = tmp.begin();
690
691  for (ArrayAccessor<uChar, Axis<asap::ChanAxis> > i(aa2); i != i.end(); ++i) {
692    bool out =!static_cast<bool>(*i);
693    if (useUserMask) {
694      out = out && (*miter);
695      miter++;
696    }
697    (*va) = out;
698    va++;
699  }
700}
701*/
702
703MaskedArray<Float> SDMemTable::rowAsMaskedArray(uInt whichRow,
704                                                Bool toStokes) const
705{
706  // Get flags
707  Array<uChar> farr;
708  flagsCol_.get(whichRow, farr);
709
710  // Get data and convert mask to Bool
711  Array<Float> arr;
712  Array<Bool> mask;
713  if (toStokes) {
714     stokesCol_.get(whichRow, arr);
715
716     Array<Bool> tMask(farr.shape());
717     convertArray(tMask, farr);
718     mask = SDPolUtil::stokesMask (tMask, True);
719  } else {
720     specCol_.get(whichRow, arr);
721     mask.resize(farr.shape());
722     convertArray(mask, farr);
723  }
724
725  return MaskedArray<Float>(arr,!mask);
726}
727
728Float SDMemTable::getTsys(Int whichRow) const
729{
730  Array<Float> arr;
731  tsCol_.get(whichRow, arr);
732  Float out;
733
734  IPosition ip(arr.shape());
735  ip(asap::BeamAxis) = beamSel_;
736  ip(asap::IFAxis) = IFSel_;
737  ip(asap::PolAxis) = polSel_;
738  ip(asap::ChanAxis)=0;               // First channel only
739
740  out = arr(ip);
741  return out;
742}
743
744MDirection SDMemTable::getDirection(Int whichRow, Bool refBeam) const
745{
746  MDirection::Types mdr = getDirectionReference();
747  Array<Double> posit;
748  dirCol_.get(whichRow,posit);
749  Vector<Double> wpos(2);
750  Int rb;
751  rbeamCol_.get(whichRow,rb);
752  wpos[0] = posit(IPosition(2,beamSel_,0));
753  wpos[1] = posit(IPosition(2,beamSel_,1));
754  if (refBeam && rb > -1) {  // use refBeam instead if it exists
755    wpos[0] = posit(IPosition(2,rb,0));
756    wpos[1] = posit(IPosition(2,rb,1));
757  }
758
759  Quantum<Double> lon(wpos[0],Unit(String("rad")));
760  Quantum<Double> lat(wpos[1],Unit(String("rad")));
761  return MDirection(lon, lat, mdr);
762}
763
764MEpoch SDMemTable::getEpoch(Int whichRow) const
765{
766  MEpoch::Types met = getTimeReference();
767
768  Double obstime;
769  timeCol_.get(whichRow,obstime);
770  MVEpoch tm2(Quantum<Double>(obstime, Unit(String("d"))));
771  return MEpoch(tm2, met);
772}
773
774MPosition SDMemTable::getAntennaPosition () const
775{
776  Vector<Double> antpos;
777  table_.keywordSet().get("AntennaPosition", antpos);
778  MVPosition mvpos(antpos(0),antpos(1),antpos(2));
779  return MPosition(mvpos);
780}
781
782
783SpectralCoordinate SDMemTable::getSpectralCoordinate(uInt freqID) const
784{
785 
786  Table t = table_.keywordSet().asTable("FREQUENCIES");
787  if (freqID> t.nrow() ) {
788    throw(AipsError("SDMemTable::getSpectralCoordinate - freqID out of range"));
789  }
790
791  Double rp,rv,inc;
792  String rf;
793  ROScalarColumn<Double> rpc(t, "REFPIX");
794  ROScalarColumn<Double> rvc(t, "REFVAL");
795  ROScalarColumn<Double> incc(t, "INCREMENT");
796  t.keywordSet().get("BASEREFFRAME",rf);
797
798  // Create SpectralCoordinate (units Hz)
799  MFrequency::Types mft;
800  if (!MFrequency::getType(mft, rf)) {
801    cerr << "Frequency type unknown assuming TOPO" << endl;
802    mft = MFrequency::TOPO;
803  }
804  rpc.get(freqID, rp);
805  rvc.get(freqID, rv);
806  incc.get(freqID, inc);
807
808  SpectralCoordinate spec(mft,rv,inc,rp);
809  return spec;
810}
811
812
813SpectralCoordinate SDMemTable::getSpectralCoordinate(uInt freqID,
814                                                     uInt restFreqID,
815                                                     uInt whichRow) const
816{
817 
818  // Create basic SC
819  SpectralCoordinate spec = getSpectralCoordinate (freqID);
820
821  Table t = table_.keywordSet().asTable("FREQUENCIES");
822
823  // Set rest frequency
824  Vector<Double> restFreqIDs;
825  t.keywordSet().get("RESTFREQS",restFreqIDs);
826  if (restFreqID < restFreqIDs.nelements()) {    // Should always be true
827    spec.setRestFrequency(restFreqIDs(restFreqID),True);
828  }
829
830  // Set up frame conversion layer
831  String frm;
832  t.keywordSet().get("REFFRAME",frm);
833  if (frm == "") frm = "TOPO";
834  MFrequency::Types mtype;
835  if (!MFrequency::getType(mtype, frm)) {
836    // Should never happen
837    cerr << "Frequency type unknown assuming TOPO" << endl;
838    mtype = MFrequency::TOPO;
839  }
840
841  // Set reference frame conversion  (requires row)
842  MDirection dir = getDirection(whichRow);
843  MEpoch epoch = getEpoch(whichRow);
844  MPosition pos = getAntennaPosition();
845
846  if (!spec.setReferenceConversion(mtype,epoch,pos,dir)) {
847    throw(AipsError("Couldn't convert frequency frame."));
848  }
849
850  // Now velocity conversion if appropriate
851  String unitStr;
852  t.keywordSet().get("UNIT",unitStr);
853
854  String dpl;
855  t.keywordSet().get("DOPPLER",dpl);
856  MDoppler::Types dtype;
857  MDoppler::getType(dtype, dpl);
858
859  // Only set velocity unit if non-blank and non-Hz
860  if (!unitStr.empty()) {
861     Unit unitU(unitStr);
862     if (unitU==Unit("Hz")) {
863     } else {
864        spec.setVelocity(unitStr, dtype);
865     }
866  }
867
868  return spec;
869}
870
871
872Bool SDMemTable::setCoordinate(const SpectralCoordinate& speccord,
873                               uInt freqID) {
874  Table t = table_.rwKeywordSet().asTable("FREQUENCIES");
875  if (freqID > t.nrow() ) {
876    throw(AipsError("SDMemTable::setCoordinate - coord no out of range"));
877  }
878  ScalarColumn<Double> rpc(t, "REFPIX");
879  ScalarColumn<Double> rvc(t, "REFVAL");
880  ScalarColumn<Double> incc(t, "INCREMENT");
881
882  rpc.put(freqID, speccord.referencePixel()[0]);
883  rvc.put(freqID, speccord.referenceValue()[0]);
884  incc.put(freqID, speccord.increment()[0]);
885
886  return True;
887}
888
889Int SDMemTable::nCoordinates() const
890{
891  return table_.keywordSet().asTable("FREQUENCIES").nrow();
892}
893
894
895std::vector<double> SDMemTable::getRestFreqs() const
896{
897  Table t = table_.keywordSet().asTable("FREQUENCIES");
898  Vector<Double> tvec;
899  t.keywordSet().get("RESTFREQS",tvec);
900  std::vector<double> stlout;
901  tvec.tovector(stlout);
902  return stlout; 
903}
904
905bool SDMemTable::putSDFreqTable(const SDFrequencyTable& sdft)
906{
907  TableDesc td("", "1", TableDesc::Scratch);
908  td.addColumn(ScalarColumnDesc<Double>("REFPIX"));
909  td.addColumn(ScalarColumnDesc<Double>("REFVAL"));
910  td.addColumn(ScalarColumnDesc<Double>("INCREMENT"));
911  SetupNewTable aNewTab("freqs", td, Table::New);
912  Table aTable (aNewTab, Table::Memory, sdft.length());
913  ScalarColumn<Double> sc0(aTable, "REFPIX");
914  ScalarColumn<Double> sc1(aTable, "REFVAL");
915  ScalarColumn<Double> sc2(aTable, "INCREMENT");
916  for (uInt i=0; i < sdft.length(); ++i) {
917    sc0.put(i,sdft.referencePixel(i));
918    sc1.put(i,sdft.referenceValue(i));
919    sc2.put(i,sdft.increment(i));
920  }
921  String rf = sdft.refFrame();
922  if (rf.contains("TOPO")) rf = "TOPO";
923
924  aTable.rwKeywordSet().define("BASEREFFRAME", rf);
925  aTable.rwKeywordSet().define("REFFRAME", rf);
926  aTable.rwKeywordSet().define("EQUINOX", sdft.equinox());
927  aTable.rwKeywordSet().define("UNIT", String(""));
928  aTable.rwKeywordSet().define("DOPPLER", String("RADIO"));
929  Vector<Double> rfvec;
930  String rfunit;
931  sdft.restFrequencies(rfvec,rfunit);
932  Quantum<Vector<Double> > q(rfvec, rfunit);
933  rfvec.resize();
934  rfvec = q.getValue("Hz");
935  aTable.rwKeywordSet().define("RESTFREQS", rfvec);
936  table_.rwKeywordSet().defineTable("FREQUENCIES", aTable);
937  return true;
938}
939
940bool SDMemTable::putSDFitTable(const SDFitTable& sdft)
941{
942  TableDesc td("", "1", TableDesc::Scratch);
943  td.addColumn(ArrayColumnDesc<String>("FUNCTIONS"));
944  td.addColumn(ArrayColumnDesc<Int>("COMPONENTS"));
945  td.addColumn(ArrayColumnDesc<Double>("PARAMETERS"));
946  td.addColumn(ArrayColumnDesc<Bool>("PARMASK"));
947  SetupNewTable aNewTab("fits", td, Table::New);
948  Table aTable(aNewTab, Table::Memory);
949  ArrayColumn<String> sc0(aTable, "FUNCTIONS");
950  ArrayColumn<Int> sc1(aTable, "COMPONENTS");
951  ArrayColumn<Double> sc2(aTable, "PARAMETERS");
952  ArrayColumn<Bool> sc3(aTable, "PARMASK");
953  for (uInt i; i<sdft.length(); ++i) {
954    const Vector<Double>& parms = sdft.getFitParameters(i);
955    const Vector<Bool>& parmask = sdft.getFitParameterMask(i);
956    const Vector<String>& funcs = sdft.getFitFunctions(i);
957    const Vector<Int>& comps = sdft.getFitComponents(i);
958    sc0.put(i,funcs);
959    sc1.put(i,comps);
960    sc3.put(i,parmask);
961    sc2.put(i,parms);
962  }
963  table_.rwKeywordSet().defineTable("FITS", aTable);
964  return true;
965}
966
967SDFitTable SDMemTable::getSDFitTable() const
968{
969  const Table& t = table_.keywordSet().asTable("FITS");
970  Vector<Double> parms;
971  Vector<Bool> parmask;
972  Vector<String> funcs;
973  Vector<Int> comps; 
974  ROArrayColumn<Double> parmsCol(t, "PARAMETERS");
975  ROArrayColumn<Bool> parmaskCol(t, "PARMASK");
976  ROArrayColumn<Int> compsCol(t, "COMPONENTS");
977  ROArrayColumn<String> funcsCol(t, "FUNCTIONS");
978  uInt n = t.nrow();
979  SDFitTable sdft(n);
980  for (uInt i=0; i<n; ++i) {
981    parmaskCol.get(i, parmask);
982    sdft.putFitParameterMask(i, parmask);
983    parmsCol.get(i, parms);
984    sdft.putFitParameters(i, parms);
985    funcsCol.get(i, funcs);
986    sdft.putFitFunctions(i, funcs);
987    compsCol.get(i, comps);
988    sdft.putFitComponents(i, comps);
989  }
990  return sdft;
991}
992
993
994void SDMemTable::addFit(uInt whichRow,
995                        const Vector<Double>& p, const Vector<Bool>& m,
996                        const Vector<String>& f, const Vector<Int>& c)
997{
998  if (whichRow >= nRow()) {
999    throw(AipsError("Specified row out of range"));
1000  }
1001  Table t = table_.keywordSet().asTable("FITS");
1002  uInt nrow = t.nrow(); 
1003  t.addRow();
1004  ArrayColumn<Double> parmsCol(t, "PARAMETERS");
1005  ArrayColumn<Bool> parmaskCol(t, "PARMASK");
1006  ArrayColumn<Int> compsCol(t, "COMPONENTS");
1007  ArrayColumn<String> funcsCol(t, "FUNCTIONS");
1008  parmsCol.put(nrow, p);
1009  parmaskCol.put(nrow, m);
1010  compsCol.put(nrow, c);
1011  funcsCol.put(nrow, f);
1012
1013  Array<Int> fitarr;
1014  fitCol_.get(whichRow, fitarr);
1015
1016  Array<Int> newarr;               // The new Array containing the fitid
1017  Int pos =-1;                     // The fitid position in the array
1018  if ( fitarr.nelements() == 0 ) { // no fits at all in this row
1019    Array<Int> arr(IPosition(4,nBeam(),nIF(),nPol(),1));
1020    arr = -1;
1021    newarr.reference(arr);
1022    pos = 0;     
1023  } else {
1024    IPosition shp = fitarr.shape();
1025    IPosition start(4, beamSel_, IFSel_, polSel_,0);
1026    IPosition end(4, beamSel_, IFSel_, polSel_, shp[3]-1);
1027    // reform the output array slice to be of dim=1
1028    Array<Int> tmp = (fitarr(start, end)).reform(IPosition(1,shp[3]));
1029    const Vector<Int>& fits = tmp;
1030    VectorSTLIterator<Int> it(fits);
1031    Int i = 0;
1032    while (it != fits.end()) {
1033      if (*it == -1) {
1034        pos = i;
1035        break;
1036      }
1037      ++i;
1038      ++it;
1039    };
1040  }
1041  if (pos == -1) {
1042      mathutil::extendLastArrayAxis(newarr,fitarr, -1);
1043      pos = fitarr.shape()[3];     // the new element position
1044  } else {
1045    if (fitarr.nelements() > 0)
1046      newarr = fitarr;
1047  }
1048  newarr(IPosition(4, beamSel_, IFSel_, polSel_, pos)) = Int(nrow);
1049  fitCol_.put(whichRow, newarr);
1050
1051}
1052
1053SDFrequencyTable SDMemTable::getSDFreqTable() const
1054{
1055  const Table& t = table_.keywordSet().asTable("FREQUENCIES");
1056  SDFrequencyTable sdft;
1057
1058  // Add refpix/refval/incr.  What are the units ? Hz I suppose
1059  // but it's nowhere described...
1060  Vector<Double> refPix, refVal, incr;
1061  ScalarColumn<Double> refPixCol(t, "REFPIX");
1062  ScalarColumn<Double> refValCol(t, "REFVAL");
1063  ScalarColumn<Double> incrCol(t, "INCREMENT");
1064  refPix = refPixCol.getColumn();
1065  refVal = refValCol.getColumn();
1066  incr = incrCol.getColumn();
1067
1068  uInt n = refPix.nelements();
1069  for (uInt i=0; i<n; i++) {
1070     sdft.addFrequency(refPix[i], refVal[i], incr[i]);
1071  }
1072
1073  // Frequency reference frame.  I don't know if this
1074  // is the correct frame.  It might be 'REFFRAME'
1075  // rather than 'BASEREFFRAME' ?
1076  String baseFrame;
1077  t.keywordSet().get("BASEREFFRAME",baseFrame);
1078  sdft.setRefFrame(baseFrame);
1079
1080  // Equinox 
1081  Float equinox;
1082  t.keywordSet().get("EQUINOX", equinox);
1083  sdft.setEquinox(equinox);
1084
1085  // Rest Frequency
1086  Vector<Double> restFreqs;
1087  t.keywordSet().get("RESTFREQS", restFreqs);
1088  for (uInt i=0; i<restFreqs.nelements(); i++) {
1089     sdft.addRestFrequency(restFreqs[i]);
1090  }
1091  sdft.setRestFrequencyUnit(String("Hz"));
1092
1093  return sdft;
1094}
1095
1096bool SDMemTable::putSDContainer(const SDContainer& sdc)
1097{
1098  uInt rno = table_.nrow();
1099  table_.addRow();
1100
1101  timeCol_.put(rno, sdc.timestamp);
1102  srcnCol_.put(rno, sdc.sourcename);
1103  fldnCol_.put(rno, sdc.fieldname);
1104  specCol_.put(rno, sdc.getSpectrum());
1105  flagsCol_.put(rno, sdc.getFlags());
1106  tsCol_.put(rno, sdc.getTsys());
1107  scanCol_.put(rno, sdc.scanid);
1108  integrCol_.put(rno, sdc.interval);
1109  freqidCol_.put(rno, sdc.getFreqMap());
1110  restfreqidCol_.put(rno, sdc.getRestFreqMap());
1111  dirCol_.put(rno, sdc.getDirection());
1112  rbeamCol_.put(rno, sdc.refbeam);
1113  tcalCol_.put(rno, sdc.tcal);
1114  tcaltCol_.put(rno, sdc.tcaltime);
1115  azCol_.put(rno, sdc.azimuth);
1116  elCol_.put(rno, sdc.elevation);
1117  paraCol_.put(rno, sdc.parangle);
1118  histCol_.put(rno, sdc.getHistory());
1119  fitCol_.put(rno, sdc.getFitMap());
1120
1121  return true;
1122}
1123
1124SDContainer SDMemTable::getSDContainer(uInt whichRow) const
1125{
1126  SDContainer sdc(nBeam(),nIF(),nPol(),nChan());
1127  timeCol_.get(whichRow, sdc.timestamp);
1128  srcnCol_.get(whichRow, sdc.sourcename);
1129  integrCol_.get(whichRow, sdc.interval);
1130  scanCol_.get(whichRow, sdc.scanid);
1131  fldnCol_.get(whichRow, sdc.fieldname);
1132  rbeamCol_.get(whichRow, sdc.refbeam);
1133  azCol_.get(whichRow, sdc.azimuth);
1134  elCol_.get(whichRow, sdc.elevation);
1135  paraCol_.get(whichRow, sdc.parangle);
1136  Vector<Float> tc;
1137  tcalCol_.get(whichRow, tc);
1138  sdc.tcal[0] = tc[0];sdc.tcal[1] = tc[1];
1139  tcaltCol_.get(whichRow, sdc.tcaltime);
1140
1141  Array<Float> spectrum;
1142  Array<Float> tsys;
1143  Array<uChar> flagtrum;
1144  Vector<uInt> fmap;
1145  Array<Double> direction;
1146  Vector<String> histo;
1147  Array<Int> fits;
1148 
1149  specCol_.get(whichRow, spectrum);
1150  sdc.putSpectrum(spectrum);
1151  flagsCol_.get(whichRow, flagtrum);
1152  sdc.putFlags(flagtrum);
1153  tsCol_.get(whichRow, tsys);
1154  sdc.putTsys(tsys);
1155  freqidCol_.get(whichRow, fmap);
1156  sdc.putFreqMap(fmap);
1157  restfreqidCol_.get(whichRow, fmap);
1158  sdc.putRestFreqMap(fmap);
1159  dirCol_.get(whichRow, direction);
1160  sdc.putDirection(direction);
1161  histCol_.get(whichRow, histo);
1162  sdc.putHistory(histo);
1163  fitCol_.get(whichRow, fits);
1164  sdc.putFitMap(fits);
1165  return sdc;
1166}
1167
1168bool SDMemTable::putSDHeader(const SDHeader& sdh)
1169{
1170  table_.rwKeywordSet().define("nIF", sdh.nif);
1171  table_.rwKeywordSet().define("nBeam", sdh.nbeam);
1172  table_.rwKeywordSet().define("nPol", sdh.npol);
1173  table_.rwKeywordSet().define("nChan", sdh.nchan);
1174  table_.rwKeywordSet().define("Observer", sdh.observer);
1175  table_.rwKeywordSet().define("Project", sdh.project);
1176  table_.rwKeywordSet().define("Obstype", sdh.obstype);
1177  table_.rwKeywordSet().define("AntennaName", sdh.antennaname);
1178  table_.rwKeywordSet().define("AntennaPosition", sdh.antennaposition);
1179  table_.rwKeywordSet().define("Equinox", sdh.equinox);
1180  table_.rwKeywordSet().define("FreqRefFrame", sdh.freqref);
1181  table_.rwKeywordSet().define("FreqRefVal", sdh.reffreq);
1182  table_.rwKeywordSet().define("Bandwidth", sdh.bandwidth);
1183  table_.rwKeywordSet().define("UTC", sdh.utc);
1184  table_.rwKeywordSet().define("FluxUnit", sdh.fluxunit);
1185  table_.rwKeywordSet().define("Epoch", sdh.epoch);
1186  return true;
1187}
1188
1189SDHeader SDMemTable::getSDHeader() const
1190{
1191  SDHeader sdh;
1192  table_.keywordSet().get("nBeam",sdh.nbeam);
1193  table_.keywordSet().get("nIF",sdh.nif);
1194  table_.keywordSet().get("nPol",sdh.npol);
1195  table_.keywordSet().get("nChan",sdh.nchan);
1196  table_.keywordSet().get("Observer", sdh.observer);
1197  table_.keywordSet().get("Project", sdh.project);
1198  table_.keywordSet().get("Obstype", sdh.obstype);
1199  table_.keywordSet().get("AntennaName", sdh.antennaname);
1200  table_.keywordSet().get("AntennaPosition", sdh.antennaposition);
1201  table_.keywordSet().get("Equinox", sdh.equinox);
1202  table_.keywordSet().get("FreqRefFrame", sdh.freqref);
1203  table_.keywordSet().get("FreqRefVal", sdh.reffreq);
1204  table_.keywordSet().get("Bandwidth", sdh.bandwidth);
1205  table_.keywordSet().get("UTC", sdh.utc);
1206  table_.keywordSet().get("FluxUnit", sdh.fluxunit);
1207  table_.keywordSet().get("Epoch", sdh.epoch);
1208  return sdh;
1209}
1210void SDMemTable::makePersistent(const std::string& filename)
1211{
1212  table_.deepCopy(filename,Table::New);
1213}
1214
1215Int SDMemTable::nScan() const {
1216  Int n = 0;
1217  Int previous = -1;Int current=0;
1218  for (uInt i=0; i< scanCol_.nrow();i++) {
1219    scanCol_.getScalar(i,current);
1220    if (previous != current) {
1221      previous = current;
1222      n++;
1223    }
1224  }
1225  return n;
1226}
1227
1228String SDMemTable::formatSec(Double x) const
1229{
1230  Double xcop = x;
1231  MVTime mvt(xcop/24./3600.);  // make days
1232
1233  if (x < 59.95)
1234    return  String("      ") + mvt.string(MVTime::TIME_CLEAN_NO_HM, 7)+"s";
1235  else if (x < 3599.95)
1236    return String("   ") + mvt.string(MVTime::TIME_CLEAN_NO_H,7)+" ";
1237  else {
1238    ostringstream oss;
1239    oss << setw(2) << std::right << setprecision(1) << mvt.hour();
1240    oss << ":" << mvt.string(MVTime::TIME_CLEAN_NO_H,7) << " ";
1241    return String(oss);
1242  }   
1243};
1244
1245String SDMemTable::formatDirection(const MDirection& md) const
1246{
1247  Vector<Double> t = md.getAngle(Unit(String("rad"))).getValue();
1248  Int prec = 7;
1249
1250  MVAngle mvLon(t[0]);
1251  String sLon = mvLon.string(MVAngle::TIME,prec);
1252  MVAngle mvLat(t[1]);
1253  String sLat = mvLat.string(MVAngle::ANGLE+MVAngle::DIG2,prec);
1254  return sLon + String(" ") + sLat;
1255}
1256
1257
1258std::string SDMemTable::getFluxUnit() const
1259{
1260  String tmp;
1261  table_.keywordSet().get("FluxUnit", tmp);
1262  return tmp;
1263}
1264
1265void SDMemTable::setFluxUnit(const std::string& unit)
1266{
1267  String tmp(unit);
1268  Unit tU(tmp);
1269  if (tU==Unit("K") || tU==Unit("Jy")) {
1270     table_.rwKeywordSet().define(String("FluxUnit"), tmp);
1271  } else {
1272     throw AipsError("Illegal unit - must be compatible with Jy or K");
1273  }
1274}
1275
1276
1277void SDMemTable::setInstrument(const std::string& name)
1278{
1279  Bool throwIt = True;
1280  Instrument ins = convertInstrument(name, throwIt);
1281  String nameU(name);
1282  nameU.upcase();
1283  table_.rwKeywordSet().define(String("AntennaName"), nameU);
1284}
1285
1286std::string SDMemTable::summary(bool verbose) const  {
1287
1288  // Format header info
1289  ostringstream oss;
1290  oss << endl;
1291  oss << "--------------------------------------------------------------------------------" << endl;
1292  oss << " Scan Table Summary" << endl;
1293  oss << "--------------------------------------------------------------------------------" << endl;
1294  oss.flags(std::ios_base::left);
1295  oss << setw(15) << "Beams:" << setw(4) << nBeam() << endl
1296      << setw(15) << "IFs:" << setw(4) << nIF() << endl
1297      << setw(15) << "Polarisations:" << setw(4) << nPol() << endl
1298      << setw(15) << "Channels:"  << setw(4) << nChan() << endl;
1299  oss << endl;
1300  String tmp;
1301  table_.keywordSet().get("Observer", tmp);
1302  oss << setw(15) << "Observer:" << tmp << endl;
1303  oss << setw(15) << "Obs Date:" << getTime(-1,True) << endl;
1304  table_.keywordSet().get("Project", tmp);
1305  oss << setw(15) << "Project:" << tmp << endl;
1306  table_.keywordSet().get("Obstype", tmp);
1307  oss << setw(15) << "Obs. Type:" << tmp << endl;
1308  table_.keywordSet().get("AntennaName", tmp);
1309  oss << setw(15) << "Antenna Name:" << tmp << endl;
1310  table_.keywordSet().get("FluxUnit", tmp);
1311  oss << setw(15) << "Flux Unit:" << tmp << endl;
1312  Table t = table_.keywordSet().asTable("FREQUENCIES");
1313  Vector<Double> vec;
1314  t.keywordSet().get("RESTFREQS",vec);
1315  oss << setw(15) << "Rest Freqs:";
1316  if (vec.nelements() > 0) {
1317      oss << setprecision(0) << vec << " [Hz]" << endl;
1318  } else {
1319      oss << "None set" << endl;
1320  }
1321  oss << setw(15) << "Abcissa:" << getAbcissaString() << endl;
1322  oss << setw(15) << "Cursor:" << "Beam[" << getBeam() << "] "
1323      << "IF[" << getIF() << "] " << "Pol[" << getPol() << "]" << endl;
1324  oss << endl;
1325
1326  String dirtype ="Position ("+ MDirection::showType(getDirectionReference()) + ")";
1327  oss << setw(5) << "Scan"
1328      << setw(15) << "Source"
1329      << setw(24) << dirtype
1330      << setw(10) << "Time"
1331      << setw(18) << "Integration"
1332      << setw(7) << "FreqIDs" << endl;
1333  oss << "--------------------------------------------------------------------------------" << endl;
1334 
1335  // Generate list of scan start and end integrations
1336  Vector<Int> scanIDs = scanCol_.getColumn();
1337  Vector<uInt> startInt, endInt;
1338  mathutil::scanBoundaries(startInt, endInt, scanIDs);
1339
1340  const uInt nScans = startInt.nelements();
1341  String name;
1342  Vector<uInt> freqIDs, listFQ;
1343  uInt nInt;
1344
1345  for (uInt i=0; i<nScans; i++) {
1346    // Get things from first integration of scan
1347    String time = getTime(startInt(i),False);
1348    String tInt = formatSec(Double(getInterval(startInt(i))));
1349    String posit = formatDirection(getDirection(startInt(i),True));
1350    srcnCol_.getScalar(startInt(i),name);
1351
1352    // Find all the FreqIDs in this scan
1353    listFQ.resize(0);     
1354    for (uInt j=startInt(i); j<endInt(i)+1; j++) {
1355      freqidCol_.get(j, freqIDs);
1356      for (uInt k=0; k<freqIDs.nelements(); k++) {
1357        mathutil::addEntry(listFQ, freqIDs(k));
1358      }
1359    }
1360
1361    nInt = endInt(i) - startInt(i) + 1;
1362    oss << setw(3) << std::right << i << std::left << setw(2) << "  "
1363        << setw(15) << name
1364        << setw(24) << posit
1365        << setw(10) << time
1366        << setw(3) << std::right << nInt  << setw(3) << " x " << std::left
1367        << setw(6) <<  tInt
1368        << " " << listFQ << endl;
1369  }
1370  oss << endl;
1371  oss << "Table contains " << table_.nrow() << " integration(s) in "
1372      << nScans << " scan(s)." << endl;
1373
1374  // Frequency Table
1375  if (verbose) {
1376    std::vector<string> info = getCoordInfo();
1377    SDFrequencyTable sdft = getSDFreqTable();
1378    oss << endl << endl;
1379    oss << "FreqID  Frame   RefFreq(Hz)     RefPix   Increment(Hz)" << endl;
1380    oss << "--------------------------------------------------------------------------------" << endl;
1381    for (uInt i=0; i<sdft.length(); i++) {
1382      oss << setw(8) << i << setw(8)
1383          << info[3] << setw(16) << setprecision(8)
1384          << sdft.referenceValue(i) << setw(10)
1385          << sdft.referencePixel(i) << setw(12)
1386          << sdft.increment(i) << endl;
1387    }
1388    oss << "--------------------------------------------------------------------------------" << endl;
1389  }
1390  return String(oss);
1391}
1392
1393Int SDMemTable::nBeam() const
1394{
1395  Int n;
1396  table_.keywordSet().get("nBeam",n);
1397  return n;
1398}
1399
1400Int SDMemTable::nIF() const {
1401  Int n;
1402  table_.keywordSet().get("nIF",n);
1403  return n;
1404}
1405
1406Int SDMemTable::nPol() const {
1407  Int n;
1408  table_.keywordSet().get("nPol",n);
1409  return n;
1410}
1411
1412Int SDMemTable::nChan() const {
1413  Int n;
1414  table_.keywordSet().get("nChan",n);
1415  return n;
1416}
1417
1418bool SDMemTable::appendHistory(const std::string& hist, int whichRow)
1419{
1420  Vector<String> history;
1421  histCol_.get(whichRow, history);
1422  history.resize(history.nelements()+1,True);
1423  history[history.nelements()-1] = hist;
1424  histCol_.put(whichRow, history);
1425}
1426
1427std::vector<std::string> SDMemTable::history(int whichRow) const
1428{
1429  Vector<String> history;
1430  histCol_.get(whichRow, history);
1431  std::vector<std::string> stlout;
1432  // there is no Array<String>.tovector(std::vector<std::string>), so
1433  // do it by hand
1434  for (uInt i=0; i<history.nelements(); ++i) {
1435    stlout.push_back(history[i]);
1436  }
1437  return stlout;
1438}
1439/*
1440void SDMemTable::maskChannels(const std::vector<Int>& whichChans ) {
1441
1442  std::vector<int>::iterator it;
1443  ArrayAccessor<uChar, Axis<asap::PolAxis> > j(flags_);
1444  for (it = whichChans.begin(); it != whichChans.end(); it++) {
1445    j.reset(j.begin(uInt(*it)));
1446    for (ArrayAccessor<uChar, Axis<asap::BeamAxis> > i(j); i != i.end(); ++i) {
1447      for (ArrayAccessor<uChar, Axis<asap::IFAxis> > ii(i); ii != ii.end(); ++ii) {
1448        for (ArrayAccessor<uChar, Axis<asap::ChanAxis> > iii(ii);
1449             iii != iii.end(); ++iii) {
1450          (*iii) =
1451        }
1452      }
1453    }
1454  }
1455
1456}
1457*/
1458void SDMemTable::flag(int whichRow)
1459{
1460  Array<uChar> arr;
1461  flagsCol_.get(whichRow, arr);
1462
1463  ArrayAccessor<uChar, Axis<asap::BeamAxis> > aa0(arr);
1464  aa0.reset(aa0.begin(uInt(beamSel_)));//go to beam
1465  ArrayAccessor<uChar, Axis<asap::IFAxis> > aa1(aa0);
1466  aa1.reset(aa1.begin(uInt(IFSel_)));// go to IF
1467  ArrayAccessor<uChar, Axis<asap::PolAxis> > aa2(aa1);
1468  aa2.reset(aa2.begin(uInt(polSel_)));// go to pol
1469
1470  for (ArrayAccessor<uChar, Axis<asap::ChanAxis> > i(aa2); i != i.end(); ++i) {
1471    (*i) = uChar(True);
1472  }
1473
1474  flagsCol_.put(whichRow, arr);
1475}
1476
1477MDirection::Types SDMemTable::getDirectionReference() const
1478
1479  Float eq;
1480  table_.keywordSet().get("Equinox",eq);
1481  std::map<float,string> mp;
1482  mp[2000.0] = "J2000";
1483  mp[1950.0] = "B1950";
1484  MDirection::Types mdr;
1485  if (!MDirection::getType(mdr, mp[eq])) {   
1486    mdr = MDirection::J2000;
1487    cerr  << "Unknown equinox using J2000" << endl;
1488  }
1489
1490  return mdr;
1491}
1492
1493MEpoch::Types SDMemTable::getTimeReference() const
1494{
1495  MEpoch::Types met;
1496  String ep;
1497  table_.keywordSet().get("Epoch",ep);
1498  if (!MEpoch::getType(met, ep)) {
1499    cerr << "Epoch type unknown - using UTC" << endl;
1500    met = MEpoch::UTC;
1501  }
1502
1503  return met;
1504}
1505
1506
1507Instrument SDMemTable::convertInstrument(const String& instrument,
1508                                         Bool throwIt)
1509{
1510   String t(instrument);
1511   t.upcase();
1512
1513   // The strings are what SDReader returns, after cunning interrogation
1514   // of station names... :-(
1515   Instrument inst = asap::UNKNOWN;
1516   if (t==String("DSS-43")) {               
1517      inst = TIDBINBILLA;
1518   } else if (t==String("ATPKSMB")) {
1519      inst = ATPKSMB;
1520   } else if (t==String("ATPKSHOH")) {
1521      inst = ATPKSHOH;
1522   } else if (t==String("ATMOPRA")) {
1523      inst = ATMOPRA;
1524   } else if (t==String("CEDUNA")) {
1525      inst = CEDUNA;
1526   } else if (t==String("HOBART")) {
1527      inst = HOBART;
1528   } else {
1529     if (throwIt) {
1530       throw AipsError("Unrecognized instrument - use function scan.set_instrument to set");
1531     }
1532   }
1533   return inst;
1534}
1535
1536Bool SDMemTable::setRestFreqs(const Vector<Double>& restFreqsIn,
1537                              const String& sUnit,
1538                              const vector<string>& lines,
1539                              const String& source,
1540                              Int whichIF)
1541{
1542   const Int nIFs = nIF();
1543   if (whichIF>=nIFs) {
1544      throw(AipsError("Illegal IF index"));
1545   }
1546
1547   // Find vector of restfrequencies
1548   // Double takes precedence over String
1549   Unit unit;
1550   Vector<Double> restFreqs;
1551   if (restFreqsIn.nelements()>0) {
1552      restFreqs.resize(restFreqsIn.nelements());
1553      restFreqs = restFreqsIn;
1554      unit = Unit(sUnit);
1555   } else if (lines.size()>0) {
1556      const uInt nLines = lines.size();
1557      unit = Unit("Hz");
1558      restFreqs.resize(nLines);
1559      MFrequency lineFreq;
1560      for (uInt i=0; i<nLines; i++) {
1561         String tS(lines[i]);
1562         tS.upcase();
1563         if (MeasTable::Line(lineFreq, tS)) {
1564            restFreqs[i] = lineFreq.getValue().getValue();          // Hz
1565         } else {
1566            String s = String(lines[i]) +
1567              String(" is an unrecognized spectral line");
1568            throw(AipsError(s));
1569         }
1570      }
1571   } else {
1572      throw(AipsError("You have not specified any rest frequencies or lines"));
1573   }
1574
1575   // If multiple restfreqs, must be length nIF. In this
1576   // case we will just replace the rest frequencies
1577   const uInt nRestFreqs = restFreqs.nelements();
1578   Int idx = -1;
1579   SDFrequencyTable sdft = getSDFreqTable();
1580
1581   if (nRestFreqs>1) {
1582     // Replace restFreqs, one per IF
1583      if (nRestFreqs != nIFs) {
1584         throw (AipsError("Number of rest frequencies must be equal to the number of IFs"));
1585      }
1586      cout << "Replacing rest frequencies with given list, one per IF" << endl;
1587      sdft.deleteRestFrequencies();
1588      for (uInt i=0; i<nRestFreqs; i++) {
1589         Quantum<Double> rf(restFreqs[i], unit);
1590         sdft.addRestFrequency(rf.getValue("Hz"));
1591      }
1592   } else {
1593
1594     // Add new rest freq
1595      Quantum<Double> rf(restFreqs[0], unit);
1596      idx = sdft.addRestFrequency(rf.getValue("Hz"));
1597      cout << "Selecting given rest frequency" << endl;
1598   }
1599   
1600   // Replace
1601   Bool empty = source.empty();
1602   Bool ok = False;
1603   if (putSDFreqTable(sdft)) {
1604      const uInt nRow = table_.nrow();
1605      String srcName;
1606      Vector<uInt> restFreqIDs;
1607      for (uInt i=0; i<nRow; i++) {
1608         srcnCol_.get(i, srcName);
1609         restfreqidCol_.get(i,restFreqIDs);       
1610
1611         if (idx==-1) {
1612           // Replace vector of restFreqs; one per IF.
1613           // No selection possible
1614            for (uInt i=0; i<nIFs; i++) restFreqIDs[i] = i;
1615         } else {
1616           // Set RestFreqID for selected data
1617            if (empty || source==srcName) {
1618               if (whichIF<0) {
1619                  restFreqIDs = idx;
1620               } else {             
1621                  restFreqIDs[whichIF] = idx;
1622               }
1623            }
1624         }
1625         restfreqidCol_.put(i,restFreqIDs);       
1626      }
1627      ok = True;
1628   } else {
1629     ok = False;
1630   }
1631
1632   return ok;
1633}
1634
1635void SDMemTable::spectralLines() const
1636{
1637   Vector<String> lines = MeasTable::Lines();
1638   MFrequency lineFreq;
1639   Double freq;
1640
1641   cout.flags(std::ios_base::left);
1642   cout << "Line      Frequency (Hz)" << endl;
1643   cout << "-----------------------" << endl;
1644   for (uInt i=0; i<lines.nelements(); i++) {
1645     MeasTable::Line(lineFreq, lines[i]);
1646     freq = lineFreq.getValue().getValue();          // Hz
1647     cout << setw(11) << lines[i] << setprecision(10) << freq << endl;
1648   }
1649}
1650
1651void SDMemTable::renumber()
1652{
1653  uInt nRow = scanCol_.nrow();
1654  Int newscanid = 0;
1655  Int cIdx;// the current scanid
1656  // get the first scanid
1657  scanCol_.getScalar(0,cIdx);
1658  Int pIdx = cIdx;// the scanid of the previous row
1659  for (uInt i=0; i<nRow;++i) {
1660    scanCol_.getScalar(i,cIdx);
1661    if (pIdx == cIdx) {
1662      // renumber
1663      scanCol_.put(i,newscanid);
1664    } else {
1665      ++newscanid;
1666      pIdx = cIdx;   // store scanid
1667      --i;           // don't increment next loop
1668    }
1669  }
1670}
1671
1672
1673void SDMemTable::rotateXYPhase (Float value, Bool doAll)
1674  // phase in degrees
1675  // Applies to all Beams and IFs
1676  // Might want to optionally select on Beam/IF
1677{
1678  if (nPol() != 4) {
1679    throw(AipsError("You must have 4 polarizations to run this function"));
1680  }
1681 
1682  IPosition start(asap::nAxes,0);
1683  IPosition end(asap::nAxes);
1684 
1685  uInt nRow = specCol_.nrow();
1686  Array<Float> data;
1687  for (uInt i=0; i<nRow;++i) {
1688    specCol_.get(i,data);
1689    IPosition shape = data.shape();
1690   
1691    // Set slice
1692    if (!doAll) {
1693      setCursorSlice (start, end, shape);
1694    } else {
1695      end = shape-1;
1696    }
1697
1698    // Get polarization slice references
1699    start(asap::PolAxis) = 2;
1700    end(asap::PolAxis) = 2;
1701    Array<Float> C3 = data(start,end);
1702   
1703    start(asap::PolAxis) = 3;
1704    end(asap::PolAxis) = 3;
1705    Array<Float> C4 = data(start,end);
1706   
1707    // Rotate
1708    SDPolUtil::rotateXYPhase(C3, C4, value);
1709   
1710    // Put
1711    specCol_.put(i,data);
1712  }
1713}
1714
1715void SDMemTable::setCursorSlice(IPosition& start, IPosition& end,
1716                                const IPosition& shape) const
1717{
1718  const uInt nDim = shape.nelements();
1719  start.resize(nDim);
1720  end.resize(nDim);
1721 
1722  start(asap::BeamAxis) = beamSel_;
1723  end(asap::BeamAxis) = beamSel_;
1724  start(asap::IFAxis) = IFSel_;
1725  end(asap::IFAxis) = IFSel_;
1726
1727  start(asap::PolAxis) = polSel_;
1728  end(asap::PolAxis) = polSel_;
1729
1730  start(asap::ChanAxis) = 0;
1731  end(asap::ChanAxis) = shape(asap::ChanAxis) - 1;
1732}
1733
1734
1735std::vector<float> SDMemTable::getFloatSpectrum(const Array<Float>& arr) const
1736  // Get spectrum at cursor location
1737{
1738
1739  // Setup accessors
1740  ArrayAccessor<Float, Axis<asap::BeamAxis> > aa0(arr);
1741  aa0.reset(aa0.begin(uInt(beamSel_)));                    // Beam selection
1742
1743  ArrayAccessor<Float, Axis<asap::IFAxis> > aa1(aa0);
1744  aa1.reset(aa1.begin(uInt(IFSel_)));                      // IF selection
1745
1746  ArrayAccessor<Float, Axis<asap::PolAxis> > aa2(aa1);
1747  aa2.reset(aa2.begin(uInt(polSel_)));                     // Pol selection
1748 
1749  std::vector<float> spectrum;
1750  for (ArrayAccessor<Float, Axis<asap::ChanAxis> > i(aa2); i != i.end(); ++i) {
1751    spectrum.push_back(*i);
1752  }
1753  return spectrum;
1754}
1755
Note: See TracBrowser for help on using the repository browser.