source: trunk/src/SDMemTable.cc @ 462

Last change on this file since 462 was 462, checked in by kil064, 19 years ago

track change to SDPolUtil

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