source: trunk/src/SDMemTable.cc @ 395

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

bit more info to user for restFreq selection

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