source: trunk/src/SDMemTable.cc @ 457

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

move SDMemTable::rotateXYPhase to SDMath

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