source: trunk/src/SDMemTable.cc @ 483

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