source: trunk/src/SDMemTable.cc @ 428

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

getStokesSpectrum can now handle 1,2 or 4 input polarzations

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