source: trunk/src/SDMemTable.cc @ 504

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

remiove pa offset from getStokesSpectrum

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