source: trunk/src/SDMemTable.cc @ 493

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

function stokesLength() -> nStokes()

getStokesSpectrumLabel and getCircularSpectrumLabel combined into

getPolarizationLabel

getCircularSpectrum -> stokesToPolSpectrum

This is a more consistent set. Move some functionality to SDPolUtil

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