source: trunk/src/SDMemTable.cc @ 447

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

remove arg 'useSelection ' from rowAsmAskedArray as it
is never used and doesn't do the right thing and
that wrong thing is avaikable in getSpectrum !

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 45.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{
311
312  std::vector<bool> mask;
313//
314  Array<uChar> arr;
315  flagsCol_.get(whichRow, arr);
316//
317  ArrayAccessor<uChar, Axis<asap::BeamAxis> > aa0(arr);
318  aa0.reset(aa0.begin(uInt(beamSel_)));//go to beam
319  ArrayAccessor<uChar, Axis<asap::IFAxis> > aa1(aa0);
320  aa1.reset(aa1.begin(uInt(IFSel_)));// go to IF
321  ArrayAccessor<uChar, Axis<asap::PolAxis> > aa2(aa1);
322  aa2.reset(aa2.begin(uInt(polSel_)));// go to pol
323
324  Bool useUserMask = ( chanMask_.size() == arr.shape()(3) );
325
326  std::vector<bool> tmp;
327  tmp = chanMask_; // WHY the fxxx do I have to make a copy here
328  std::vector<bool>::iterator miter;
329  miter = tmp.begin();
330
331  for (ArrayAccessor<uChar, Axis<asap::ChanAxis> > i(aa2); i != i.end(); ++i) {
332    bool out =!static_cast<bool>(*i);
333    if (useUserMask) {
334      out = out && (*miter);
335      miter++;
336    }
337    mask.push_back(out);
338  }
339  return mask;
340}
341
342
343
344std::vector<float> SDMemTable::getSpectrum(Int whichRow) const
345{
346
347  Array<Float> arr;
348  specCol_.get(whichRow, arr);
349  return getFloatSpectrum (arr);
350}
351
352std::vector<float> SDMemTable::getStokesSpectrum(Int whichRow, Bool doPol, Float paOffset) const
353//
354// Gets
355//  doPol=False  : I,Q,U,V
356//  doPol=True   : I,P,PA,V   ; P = sqrt(Q**2+U**2), PA = 0.5*atan2(Q,U)
357//
358{
359  AlwaysAssert(asap::nAxes==4,AipsError);
360  if (nPol()!=1 && nPol()!=2 && nPol()!=4) {
361     throw (AipsError("You must have 1,2 or 4 polarizations to get the Stokes parameters"));
362  }
363  Array<Float> arr;
364  stokesCol_.get(whichRow, arr);
365//
366  if (doPol && (polSel_==1 || polSel_==2)) {       //   Q,U --> P, P.A.
367
368// Set current cursor location
369
370     const IPosition& shape = arr.shape();
371     IPosition start, end;
372     setCursorSlice (start, end, shape);
373
374// Get Q and U slices
375
376     Array<Float> Q = SDPolUtil::getStokesSlice (arr,start,end,"Q");
377     Array<Float> U = SDPolUtil::getStokesSlice (arr,start,end,"U");
378
379// Compute output
380
381     Array<Float> out;
382     if (polSel_==1) {                                        // P
383        out = SDPolUtil::polarizedIntensity(Q,U);
384     } else if (polSel_==2) {                                 // P.A.
385        out = SDPolUtil::positionAngle(Q,U) + paOffset;
386     }
387
388// Copy to output
389
390     IPosition vecShape(1,shape(asap::ChanAxis));
391     Vector<Float> outV = out.reform(vecShape);
392     return convertVector(outV);
393  } else {
394
395// Selects at the cursor location
396
397    return getFloatSpectrum (arr);
398  }
399}
400
401std::vector<float> SDMemTable::getCircularSpectrum(Int whichRow, Bool doRR) const
402//
403// Gets
404//  RR = I + V
405//  LL = I - V
406//
407{
408  AlwaysAssert(asap::nAxes==4,AipsError);
409  if (nPol()!=4) {
410     throw (AipsError("You must have 4 polarizations to get RR or LL"));
411  }
412  Array<Float> arr;
413  stokesCol_.get(whichRow, arr);
414
415// Set current cursor location
416
417  const IPosition& shape = arr.shape();
418  IPosition start, end;
419  setCursorSlice (start, end, shape);
420
421// Get I and V slices
422
423  Array<Float> I = SDPolUtil::getStokesSlice (arr,start,end,"I");
424  Array<Float> V = SDPolUtil::getStokesSlice (arr,start,end,"V");
425
426// Compute output
427
428  Array<Float> out = SDPolUtil::circularPolarizationFromStokes (I, V, doRR);
429
430// Copy to output
431
432  IPosition vecShape(1,shape(asap::ChanAxis));
433  Vector<Float> outV = out.reform(vecShape);
434  return convertVector(outV);
435}
436
437
438std::vector<string> SDMemTable::getCoordInfo() const
439{
440  String un;
441  Table t = table_.keywordSet().asTable("FREQUENCIES");
442  String sunit;
443  t.keywordSet().get("UNIT",sunit);
444  String dpl;
445  t.keywordSet().get("DOPPLER",dpl);
446  if (dpl == "") dpl = "RADIO";
447  String rfrm;
448  t.keywordSet().get("REFFRAME",rfrm);
449  std::vector<string> inf;
450  inf.push_back(sunit);
451  inf.push_back(rfrm);
452  inf.push_back(dpl);
453  t.keywordSet().get("BASEREFFRAME",rfrm);
454  inf.push_back(rfrm);
455  return inf;
456}
457
458void SDMemTable::setCoordInfo(std::vector<string> theinfo)
459{
460  std::vector<string>::iterator it;
461  String un,rfrm, brfrm,dpl;
462  un = theinfo[0];              // Abcissa unit
463  rfrm = theinfo[1];            // Active (or conversion) frame
464  dpl = theinfo[2];             // Doppler
465  brfrm = theinfo[3];           // Base frame
466//
467  Table t = table_.rwKeywordSet().asTable("FREQUENCIES");
468//
469  Vector<Double> rstf;
470  t.keywordSet().get("RESTFREQS",rstf);
471//
472  Bool canDo = True;
473  Unit u1("km/s");Unit u2("Hz");
474  if (Unit(un) == u1) {
475    Vector<Double> rstf;
476    t.keywordSet().get("RESTFREQS",rstf);
477    if (rstf.nelements() == 0) {
478        throw(AipsError("Can't set unit to km/s if no restfrequencies are specified"));
479    }
480  } else if (Unit(un) != u2 && un != "") {
481        throw(AipsError("Unit not conformant with Spectral Coordinates"));
482  }
483  t.rwKeywordSet().define("UNIT", un);
484//
485  MFrequency::Types mdr;
486  if (!MFrequency::getType(mdr, rfrm)) {
487   
488    Int a,b;const uInt* c;
489    const String* valid = MFrequency::allMyTypes(a, b, c);
490    String pfix = "Please specify a legal frame type. Types are\n";
491    throw(AipsError(pfix+(*valid)));
492  } else {
493    t.rwKeywordSet().define("REFFRAME",rfrm);
494  }
495//
496  MDoppler::Types dtype;
497  dpl.upcase();
498  if (!MDoppler::getType(dtype, dpl)) {
499    throw(AipsError("Doppler type unknown"));
500  } else {
501    t.rwKeywordSet().define("DOPPLER",dpl);
502  }
503//
504  if (!MFrequency::getType(mdr, brfrm)) {
505     Int a,b;const uInt* c;
506     const String* valid = MFrequency::allMyTypes(a, b, c);
507     String pfix = "Please specify a legal frame type. Types are\n";
508     throw(AipsError(pfix+(*valid)));
509   } else {
510    t.rwKeywordSet().define("BASEREFFRAME",brfrm);
511   }
512}
513
514
515std::vector<double> SDMemTable::getAbcissa(Int whichRow) const
516{
517  std::vector<double> abc(nChan());
518
519// Get header units keyword
520
521  Table t = table_.keywordSet().asTable("FREQUENCIES");
522  String sunit;
523  t.keywordSet().get("UNIT",sunit);
524  if (sunit == "") sunit = "pixel";
525  Unit u(sunit);
526
527// Easy if just wanting pixels
528
529  if (sunit==String("pixel")) {
530    // assume channels/pixels
531    std::vector<double>::iterator it;
532    uInt i=0;
533    for (it = abc.begin(); it != abc.end(); ++it) {
534      (*it) = Double(i++);
535    }
536//
537    return abc;
538  }
539
540// Continue with km/s or Hz.  Get FreqIDs
541
542  Vector<uInt> freqIDs;
543  freqidCol_.get(whichRow, freqIDs);
544  uInt freqID = freqIDs(IFSel_);
545  restfreqidCol_.get(whichRow, freqIDs);
546  uInt restFreqID = freqIDs(IFSel_);
547
548// Get SpectralCoordinate, set reference frame conversion,
549// velocity conversion, and rest freq state
550
551  SpectralCoordinate spc = getSpectralCoordinate(freqID, restFreqID, whichRow);
552  Vector<Double> pixel(nChan());
553  indgen(pixel);
554//
555  if (u == Unit("km/s")) {
556     Vector<Double> world;
557     spc.pixelToVelocity(world,pixel);
558     std::vector<double>::iterator it;
559     uInt i = 0;
560     for (it = abc.begin(); it != abc.end(); ++it) {
561       (*it) = world[i];
562       i++;
563     }
564  } else if (u == Unit("Hz")) {
565
566// Set world axis units
567
568    Vector<String> wau(1); wau = u.getName();
569    spc.setWorldAxisUnits(wau);
570//
571    std::vector<double>::iterator it;
572    Double tmp;
573    uInt i = 0;
574    for (it = abc.begin(); it != abc.end(); ++it) {
575      spc.toWorld(tmp,pixel[i]);
576      (*it) = tmp;
577      i++;
578    }
579  }
580  return abc;
581}
582
583std::string SDMemTable::getAbcissaString(Int whichRow) const
584{
585  Table t = table_.keywordSet().asTable("FREQUENCIES");
586//
587  String sunit;
588  t.keywordSet().get("UNIT",sunit);
589  if (sunit == "") sunit = "pixel";
590  Unit u(sunit);
591//
592  Vector<uInt> freqIDs;
593  freqidCol_.get(whichRow, freqIDs);
594  uInt freqID = freqIDs(IFSel_); 
595  restfreqidCol_.get(whichRow, freqIDs);
596  uInt restFreqID = freqIDs(IFSel_);
597
598// Get SpectralCoordinate, with frame, velocity, rest freq state set
599
600  SpectralCoordinate spc = getSpectralCoordinate(freqID, restFreqID, whichRow);
601//
602  String s = "Channel";
603  if (u == Unit("km/s")) {
604    s = CoordinateUtil::axisLabel(spc,0,True,True,True);
605  } else if (u == Unit("Hz")) {
606    Vector<String> wau(1);wau = u.getName();
607    spc.setWorldAxisUnits(wau);
608//
609    s = CoordinateUtil::axisLabel(spc,0,True,True,False);
610  }
611  return s;
612}
613
614void SDMemTable::setSpectrum(std::vector<float> spectrum, int whichRow)
615{
616  Array<Float> arr;
617  specCol_.get(whichRow, arr);
618  if (spectrum.size() != arr.shape()(3)) {
619    throw(AipsError("Attempting to set spectrum with incorrect length."));
620  }
621
622// Setup accessors
623
624  ArrayAccessor<Float, Axis<asap::BeamAxis> > aa0(arr);
625  aa0.reset(aa0.begin(uInt(beamSel_)));                   // Beam selection
626  ArrayAccessor<Float, Axis<asap::IFAxis> > aa1(aa0);
627  aa1.reset(aa1.begin(uInt(IFSel_)));                     // IF selection
628  ArrayAccessor<Float, Axis<asap::PolAxis> > aa2(aa1);
629  aa2.reset(aa2.begin(uInt(polSel_)));                    // Pol selection
630
631// Iterate
632
633  std::vector<float>::iterator it = spectrum.begin();
634  for (ArrayAccessor<Float, Axis<asap::ChanAxis> > i(aa2); i != i.end(); ++i) {
635    (*i) = Float(*it);
636    it++;
637  }
638  specCol_.put(whichRow, arr);
639}
640
641void SDMemTable::getSpectrum(Vector<Float>& spectrum, Int whichRow) const
642{
643  Array<Float> arr;
644  specCol_.get(whichRow, arr);
645
646// Iterate and extract
647
648  spectrum.resize(arr.shape()(3));
649  ArrayAccessor<Float, Axis<asap::BeamAxis> > aa0(arr);
650  aa0.reset(aa0.begin(uInt(beamSel_)));//go to beam
651  ArrayAccessor<Float, Axis<asap::IFAxis> > aa1(aa0);
652  aa1.reset(aa1.begin(uInt(IFSel_)));// go to IF
653  ArrayAccessor<Float, Axis<asap::PolAxis> > aa2(aa1);
654  aa2.reset(aa2.begin(uInt(polSel_)));// go to pol
655//
656  ArrayAccessor<Float, Axis<asap::BeamAxis> > va(spectrum);
657  for (ArrayAccessor<Float, Axis<asap::ChanAxis> > i(aa2); i != i.end(); ++i) {
658    (*va) = (*i);
659    va++;
660  }
661}
662
663
664/*
665void SDMemTable::getMask(Vector<Bool>& mask, Int whichRow) const {
666  Array<uChar> arr;
667  flagsCol_.get(whichRow, arr);
668  mask.resize(arr.shape()(3));
669
670  ArrayAccessor<uChar, Axis<asap::BeamAxis> > aa0(arr);
671  aa0.reset(aa0.begin(uInt(beamSel_)));//go to beam
672  ArrayAccessor<uChar, Axis<asap::IFAxis> > aa1(aa0);
673  aa1.reset(aa1.begin(uInt(IFSel_)));// go to IF
674  ArrayAccessor<uChar, Axis<asap::PolAxis> > aa2(aa1);
675  aa2.reset(aa2.begin(uInt(polSel_)));// go to pol
676
677  Bool useUserMask = ( chanMask_.size() == arr.shape()(3) );
678
679  ArrayAccessor<Bool, Axis<asap::BeamAxis> > va(mask);
680  std::vector<bool> tmp;
681  tmp = chanMask_; // WHY the fxxx do I have to make a copy here. The
682                   // iterator should work on chanMask_??
683  std::vector<bool>::iterator miter;
684  miter = tmp.begin();
685
686  for (ArrayAccessor<uChar, Axis<asap::ChanAxis> > i(aa2); i != i.end(); ++i) {
687    bool out =!static_cast<bool>(*i);
688    if (useUserMask) {
689      out = out && (*miter);
690      miter++;
691    }
692    (*va) = out;
693    va++;
694  }
695}
696*/
697
698MaskedArray<Float> SDMemTable::rowAsMaskedArray(uInt whichRow, Bool toStokes) const
699{
700
701// Get flags
702
703  Array<uChar> farr;
704  flagsCol_.get(whichRow, farr);
705
706// Get data and convert mask to Bool
707
708  Array<Float> arr;
709  Array<Bool> mask;
710  if (toStokes) {
711     stokesCol_.get(whichRow, arr);
712//
713     Array<Bool> tMask(farr.shape());
714     convertArray(tMask, farr);
715     mask = SDPolUtil::stokesMask (tMask, True);
716  } else {
717     specCol_.get(whichRow, arr);
718     mask.resize(farr.shape());
719     convertArray(mask, farr);
720  }
721//
722  return MaskedArray<Float>(arr,!mask);
723}
724
725Float SDMemTable::getTsys(Int whichRow) const
726{
727  Array<Float> arr;
728  tsCol_.get(whichRow, arr);
729  Float out;
730//
731  IPosition ip(arr.shape());
732  ip(asap::BeamAxis) = beamSel_;
733  ip(asap::IFAxis) = IFSel_;
734  ip(asap::PolAxis) = polSel_;
735  ip(asap::ChanAxis)=0;               // First channel only
736//
737  out = arr(ip);
738  return out;
739}
740
741MDirection SDMemTable::getDirection(Int whichRow, Bool refBeam) const
742{
743  MDirection::Types mdr = getDirectionReference();
744  Array<Double> posit;
745  dirCol_.get(whichRow,posit);
746  Vector<Double> wpos(2);
747  Int rb;
748  rbeamCol_.get(whichRow,rb);
749  wpos[0] = posit(IPosition(2,beamSel_,0));
750  wpos[1] = posit(IPosition(2,beamSel_,1));
751  if (refBeam && rb > -1) {  // use refBeam instead if it exists
752    wpos[0] = posit(IPosition(2,rb,0));
753    wpos[1] = posit(IPosition(2,rb,1));
754  }
755
756  Quantum<Double> lon(wpos[0],Unit(String("rad")));
757  Quantum<Double> lat(wpos[1],Unit(String("rad")));
758  return MDirection(lon, lat, mdr);
759}
760
761MEpoch SDMemTable::getEpoch(Int whichRow) const
762{
763  MEpoch::Types met = getTimeReference();
764//
765  Double obstime;
766  timeCol_.get(whichRow,obstime);
767  MVEpoch tm2(Quantum<Double>(obstime, Unit(String("d"))));
768  return MEpoch(tm2, met);
769}
770
771MPosition SDMemTable::getAntennaPosition () const
772{
773  Vector<Double> antpos;
774  table_.keywordSet().get("AntennaPosition", antpos);
775  MVPosition mvpos(antpos(0),antpos(1),antpos(2));
776  return MPosition(mvpos);
777}
778
779
780SpectralCoordinate SDMemTable::getSpectralCoordinate(uInt freqID) const
781{
782 
783  Table t = table_.keywordSet().asTable("FREQUENCIES");
784  if (freqID> t.nrow() ) {
785    throw(AipsError("SDMemTable::getSpectralCoordinate - freqID out of range"));
786  }
787
788  Double rp,rv,inc;
789  String rf;
790  ROScalarColumn<Double> rpc(t, "REFPIX");
791  ROScalarColumn<Double> rvc(t, "REFVAL");
792  ROScalarColumn<Double> incc(t, "INCREMENT");
793  t.keywordSet().get("BASEREFFRAME",rf);
794
795// Create SpectralCoordinate (units Hz)
796
797  MFrequency::Types mft;
798  if (!MFrequency::getType(mft, rf)) {
799    cerr << "Frequency type unknown assuming TOPO" << endl;
800    mft = MFrequency::TOPO;
801  }
802  rpc.get(freqID, rp);
803  rvc.get(freqID, rv);
804  incc.get(freqID, inc);
805//
806  SpectralCoordinate spec(mft,rv,inc,rp);
807//
808  return spec;
809}
810
811
812SpectralCoordinate SDMemTable::getSpectralCoordinate(uInt freqID, uInt restFreqID,
813                                                     uInt whichRow) const
814{
815
816// Create basic SC
817
818  SpectralCoordinate spec = getSpectralCoordinate (freqID);
819//
820  Table t = table_.keywordSet().asTable("FREQUENCIES");
821
822// Set rest frequency
823
824  Vector<Double> restFreqIDs;
825  t.keywordSet().get("RESTFREQS",restFreqIDs);
826  if (restFreqID < restFreqIDs.nelements()) {                  // SHould always be true
827    spec.setRestFrequency(restFreqIDs(restFreqID),True);
828  }
829
830// Set up frame conversion layer
831
832  String frm;
833  t.keywordSet().get("REFFRAME",frm);
834  if (frm == "") frm = "TOPO";
835  MFrequency::Types mtype;
836  if (!MFrequency::getType(mtype, frm)) {
837    cerr << "Frequency type unknown assuming TOPO" << endl;       // SHould never happen
838    mtype = MFrequency::TOPO;
839  }
840
841// Set reference frame conversion  (requires row)
842
843  MDirection dir = getDirection(whichRow);
844  MEpoch epoch = getEpoch(whichRow);
845  MPosition pos = getAntennaPosition();
846//
847  if (!spec.setReferenceConversion(mtype,epoch,pos,dir)) {
848    throw(AipsError("Couldn't convert frequency frame."));
849  }
850
851// Now velocity conversion if appropriate
852
853  String unitStr;
854  t.keywordSet().get("UNIT",unitStr);
855//
856  String dpl;
857  t.keywordSet().get("DOPPLER",dpl);
858  MDoppler::Types dtype;
859  MDoppler::getType(dtype, dpl);
860
861// Only set velocity unit if non-blank and non-Hz
862
863  if (!unitStr.empty()) {
864     Unit unitU(unitStr);
865     if (unitU==Unit("Hz")) {
866     } else {
867        spec.setVelocity(unitStr, dtype);
868     }
869  }
870//
871  return spec;
872}
873
874
875Bool SDMemTable::setCoordinate(const SpectralCoordinate& speccord,
876                               uInt freqID) {
877  Table t = table_.rwKeywordSet().asTable("FREQUENCIES");
878  if (freqID > t.nrow() ) {
879    throw(AipsError("SDMemTable::setCoordinate - coord no out of range"));
880  }
881  ScalarColumn<Double> rpc(t, "REFPIX");
882  ScalarColumn<Double> rvc(t, "REFVAL");
883  ScalarColumn<Double> incc(t, "INCREMENT");
884
885  rpc.put(freqID, speccord.referencePixel()[0]);
886  rvc.put(freqID, speccord.referenceValue()[0]);
887  incc.put(freqID, speccord.increment()[0]);
888
889  return True;
890}
891
892Int SDMemTable::nCoordinates() const
893{
894  return table_.keywordSet().asTable("FREQUENCIES").nrow();
895}
896
897
898std::vector<double> SDMemTable::getRestFreqs() const
899{
900  Table t = table_.keywordSet().asTable("FREQUENCIES");
901  Vector<Double> tvec;
902  t.keywordSet().get("RESTFREQS",tvec);
903  std::vector<double> stlout;
904  tvec.tovector(stlout);
905  return stlout; 
906}
907
908bool SDMemTable::putSDFreqTable(const SDFrequencyTable& sdft)
909{
910  TableDesc td("", "1", TableDesc::Scratch);
911  td.addColumn(ScalarColumnDesc<Double>("REFPIX"));
912  td.addColumn(ScalarColumnDesc<Double>("REFVAL"));
913  td.addColumn(ScalarColumnDesc<Double>("INCREMENT"));
914  SetupNewTable aNewTab("freqs", td, Table::New);
915  Table aTable (aNewTab, Table::Memory, sdft.length());
916  ScalarColumn<Double> sc0(aTable, "REFPIX");
917  ScalarColumn<Double> sc1(aTable, "REFVAL");
918  ScalarColumn<Double> sc2(aTable, "INCREMENT");
919  for (uInt i=0; i < sdft.length(); ++i) {
920    sc0.put(i,sdft.referencePixel(i));
921    sc1.put(i,sdft.referenceValue(i));
922    sc2.put(i,sdft.increment(i));
923  }
924  String rf = sdft.refFrame();
925  if (rf.contains("TOPO")) rf = "TOPO";
926
927  aTable.rwKeywordSet().define("BASEREFFRAME", rf);
928  aTable.rwKeywordSet().define("REFFRAME", rf);
929  aTable.rwKeywordSet().define("EQUINOX", sdft.equinox());
930  aTable.rwKeywordSet().define("UNIT", String(""));
931  aTable.rwKeywordSet().define("DOPPLER", String("RADIO"));
932  Vector<Double> rfvec;
933  String rfunit;
934  sdft.restFrequencies(rfvec,rfunit);
935  Quantum<Vector<Double> > q(rfvec, rfunit);
936  rfvec.resize();
937  rfvec = q.getValue("Hz");
938  aTable.rwKeywordSet().define("RESTFREQS", rfvec);
939  table_.rwKeywordSet().defineTable ("FREQUENCIES", aTable);
940  return True;
941}
942
943SDFrequencyTable SDMemTable::getSDFreqTable() const
944{
945  const Table& t = table_.keywordSet().asTable("FREQUENCIES");
946  SDFrequencyTable sdft;
947
948// Add refpix/refval/incr.  What are the units ? Hz I suppose
949// but it's nowhere described...
950
951  Vector<Double> refPix, refVal, incr;
952  ScalarColumn<Double> refPixCol(t, "REFPIX");
953  ScalarColumn<Double> refValCol(t, "REFVAL");
954  ScalarColumn<Double> incrCol(t, "INCREMENT");
955  refPix = refPixCol.getColumn();
956  refVal = refValCol.getColumn();
957  incr = incrCol.getColumn();
958//
959  uInt n = refPix.nelements();
960  for (uInt i=0; i<n; i++) {
961     sdft.addFrequency(refPix[i], refVal[i], incr[i]);
962  }
963
964// Frequency reference frame.  I don't know if this
965// is the correct frame.  It might be 'REFFRAME'
966// rather than 'BASEREFFRAME' ?
967
968  String baseFrame;
969  t.keywordSet().get("BASEREFFRAME",baseFrame);
970  sdft.setRefFrame(baseFrame);
971
972// Equinox
973
974  Float equinox;
975  t.keywordSet().get("EQUINOX", equinox);
976  sdft.setEquinox(equinox);
977
978// Rest Frequency
979
980  Vector<Double> restFreqs;
981  t.keywordSet().get("RESTFREQS", restFreqs);
982  for (uInt i=0; i<restFreqs.nelements(); i++) {
983     sdft.addRestFrequency(restFreqs[i]);
984  }
985  sdft.setRestFrequencyUnit(String("Hz"));
986//
987  return sdft;
988}
989
990bool SDMemTable::putSDContainer(const SDContainer& sdc)
991{
992  uInt rno = table_.nrow();
993  table_.addRow();
994//
995  timeCol_.put(rno, sdc.timestamp);
996  srcnCol_.put(rno, sdc.sourcename);
997  fldnCol_.put(rno, sdc.fieldname);
998  specCol_.put(rno, sdc.getSpectrum());
999  flagsCol_.put(rno, sdc.getFlags());
1000  tsCol_.put(rno, sdc.getTsys());
1001  scanCol_.put(rno, sdc.scanid);
1002  integrCol_.put(rno, sdc.interval);
1003  freqidCol_.put(rno, sdc.getFreqMap());
1004  restfreqidCol_.put(rno, sdc.getRestFreqMap());
1005  dirCol_.put(rno, sdc.getDirection());
1006  rbeamCol_.put(rno, sdc.refbeam);
1007  tcalCol_.put(rno, sdc.tcal);
1008  tcaltCol_.put(rno, sdc.tcaltime);
1009  azCol_.put(rno, sdc.azimuth);
1010  elCol_.put(rno, sdc.elevation);
1011  paraCol_.put(rno, sdc.parangle);
1012  histCol_.put(rno, sdc.getHistory());
1013//
1014  return true;
1015}
1016
1017SDContainer SDMemTable::getSDContainer(uInt whichRow) const
1018{
1019  SDContainer sdc(nBeam(),nIF(),nPol(),nChan());
1020  timeCol_.get(whichRow, sdc.timestamp);
1021  srcnCol_.get(whichRow, sdc.sourcename);
1022  integrCol_.get(whichRow, sdc.interval);
1023  scanCol_.get(whichRow, sdc.scanid);
1024  fldnCol_.get(whichRow, sdc.fieldname);
1025  rbeamCol_.get(whichRow, sdc.refbeam);
1026  azCol_.get(whichRow, sdc.azimuth);
1027  elCol_.get(whichRow, sdc.elevation);
1028  paraCol_.get(whichRow, sdc.parangle);
1029  Vector<Float> tc;
1030  tcalCol_.get(whichRow, tc);
1031  sdc.tcal[0] = tc[0];sdc.tcal[1] = tc[1];
1032  tcaltCol_.get(whichRow, sdc.tcaltime);
1033//
1034  Array<Float> spectrum;
1035  Array<Float> tsys;
1036  Array<uChar> flagtrum;
1037  Vector<uInt> fmap;
1038  Array<Double> direction;
1039  Vector<String> histo;
1040//
1041  specCol_.get(whichRow, spectrum);
1042  sdc.putSpectrum(spectrum);
1043  flagsCol_.get(whichRow, flagtrum);
1044  sdc.putFlags(flagtrum);
1045  tsCol_.get(whichRow, tsys);
1046  sdc.putTsys(tsys);
1047  freqidCol_.get(whichRow, fmap);
1048  sdc.putFreqMap(fmap);
1049  restfreqidCol_.get(whichRow, fmap);
1050  sdc.putRestFreqMap(fmap);
1051  dirCol_.get(whichRow, direction);
1052  sdc.putDirection(direction);
1053  histCol_.get(whichRow, histo);
1054  sdc.putHistory(histo);
1055  return sdc;
1056}
1057
1058bool SDMemTable::putSDHeader(const SDHeader& sdh)
1059{
1060  table_.rwKeywordSet().define("nIF", sdh.nif);
1061  table_.rwKeywordSet().define("nBeam", sdh.nbeam);
1062  table_.rwKeywordSet().define("nPol", sdh.npol);
1063  table_.rwKeywordSet().define("nChan", sdh.nchan);
1064  table_.rwKeywordSet().define("Observer", sdh.observer);
1065  table_.rwKeywordSet().define("Project", sdh.project);
1066  table_.rwKeywordSet().define("Obstype", sdh.obstype);
1067  table_.rwKeywordSet().define("AntennaName", sdh.antennaname);
1068  table_.rwKeywordSet().define("AntennaPosition", sdh.antennaposition);
1069  table_.rwKeywordSet().define("Equinox", sdh.equinox);
1070  table_.rwKeywordSet().define("FreqRefFrame", sdh.freqref);
1071  table_.rwKeywordSet().define("FreqRefVal", sdh.reffreq);
1072  table_.rwKeywordSet().define("Bandwidth", sdh.bandwidth);
1073  table_.rwKeywordSet().define("UTC", sdh.utc);
1074  table_.rwKeywordSet().define("FluxUnit", sdh.fluxunit);
1075  table_.rwKeywordSet().define("Epoch", sdh.epoch);
1076  return true;
1077}
1078
1079SDHeader SDMemTable::getSDHeader() const
1080{
1081  SDHeader sdh;
1082  table_.keywordSet().get("nBeam",sdh.nbeam);
1083  table_.keywordSet().get("nIF",sdh.nif);
1084  table_.keywordSet().get("nPol",sdh.npol);
1085  table_.keywordSet().get("nChan",sdh.nchan);
1086  table_.keywordSet().get("Observer", sdh.observer);
1087  table_.keywordSet().get("Project", sdh.project);
1088  table_.keywordSet().get("Obstype", sdh.obstype);
1089  table_.keywordSet().get("AntennaName", sdh.antennaname);
1090  table_.keywordSet().get("AntennaPosition", sdh.antennaposition);
1091  table_.keywordSet().get("Equinox", sdh.equinox);
1092  table_.keywordSet().get("FreqRefFrame", sdh.freqref);
1093  table_.keywordSet().get("FreqRefVal", sdh.reffreq);
1094  table_.keywordSet().get("Bandwidth", sdh.bandwidth);
1095  table_.keywordSet().get("UTC", sdh.utc);
1096  table_.keywordSet().get("FluxUnit", sdh.fluxunit);
1097  table_.keywordSet().get("Epoch", sdh.epoch);
1098  return sdh;
1099}
1100void SDMemTable::makePersistent(const std::string& filename)
1101{
1102  table_.deepCopy(filename,Table::New);
1103}
1104
1105Int SDMemTable::nScan() const {
1106  Int n = 0;
1107  Int previous = -1;Int current=0;
1108  for (uInt i=0; i< scanCol_.nrow();i++) {
1109    scanCol_.getScalar(i,current);
1110    if (previous != current) {
1111      previous = current;
1112      n++;
1113    }
1114  }
1115  return n;
1116}
1117
1118String SDMemTable::formatSec(Double x) const
1119{
1120  Double xcop = x;
1121  MVTime mvt(xcop/24./3600.);  // make days
1122
1123  if (x < 59.95)
1124    return  String("      ") + mvt.string(MVTime::TIME_CLEAN_NO_HM, 7)+"s";
1125  else if (x < 3599.95)
1126    return String("   ") + mvt.string(MVTime::TIME_CLEAN_NO_H,7)+" ";
1127  else {
1128    ostringstream oss;
1129    oss << setw(2) << std::right << setprecision(1) << mvt.hour();
1130    oss << ":" << mvt.string(MVTime::TIME_CLEAN_NO_H,7) << " ";
1131    return String(oss);
1132  }   
1133};
1134
1135String SDMemTable::formatDirection(const MDirection& md) const
1136{
1137  Vector<Double> t = md.getAngle(Unit(String("rad"))).getValue();
1138  Int prec = 7;
1139
1140  MVAngle mvLon(t[0]);
1141  String sLon = mvLon.string(MVAngle::TIME,prec);
1142  MVAngle mvLat(t[1]);
1143  String sLat = mvLat.string(MVAngle::ANGLE+MVAngle::DIG2,prec);
1144  return sLon + String(" ") + sLat;
1145}
1146
1147
1148std::string SDMemTable::getFluxUnit() const
1149{
1150  String tmp;
1151  table_.keywordSet().get("FluxUnit", tmp);
1152  return tmp;
1153}
1154
1155void SDMemTable::setFluxUnit(const std::string& unit)
1156{
1157  String tmp(unit);
1158  Unit tU(tmp);
1159  if (tU==Unit("K") || tU==Unit("Jy")) {
1160     table_.rwKeywordSet().define(String("FluxUnit"), tmp);
1161  } else {
1162     throw AipsError("Illegal unit - must be compatible with Jy or K");
1163  }
1164}
1165
1166
1167void SDMemTable::setInstrument(const std::string& name)
1168{
1169  Bool throwIt = True;
1170  Instrument ins = convertInstrument (name, throwIt);
1171  String nameU(name);
1172  nameU.upcase();
1173  table_.rwKeywordSet().define(String("AntennaName"), nameU);
1174}
1175
1176std::string SDMemTable::summary(bool verbose) const  {
1177
1178// Format header info
1179
1180  ostringstream oss;
1181  oss << endl;
1182  oss << "--------------------------------------------------------------------------------" << endl;
1183  oss << " Scan Table Summary" << endl;
1184  oss << "--------------------------------------------------------------------------------" << endl;
1185  oss.flags(std::ios_base::left);
1186  oss << setw(15) << "Beams:" << setw(4) << nBeam() << endl
1187      << setw(15) << "IFs:" << setw(4) << nIF() << endl
1188      << setw(15) << "Polarisations:" << setw(4) << nPol() << endl
1189      << setw(15) << "Channels:"  << setw(4) << nChan() << endl;
1190  oss << endl;
1191  String tmp;
1192  table_.keywordSet().get("Observer", tmp);
1193  oss << setw(15) << "Observer:" << tmp << endl;
1194  oss << setw(15) << "Obs Date:" << getTime(-1,True) << endl;
1195  table_.keywordSet().get("Project", tmp);
1196  oss << setw(15) << "Project:" << tmp << endl;
1197  table_.keywordSet().get("Obstype", tmp);
1198  oss << setw(15) << "Obs. Type:" << tmp << endl;
1199  table_.keywordSet().get("AntennaName", tmp);
1200  oss << setw(15) << "Antenna Name:" << tmp << endl;
1201  table_.keywordSet().get("FluxUnit", tmp);
1202  oss << setw(15) << "Flux Unit:" << tmp << endl;
1203  Table t = table_.keywordSet().asTable("FREQUENCIES");
1204  Vector<Double> vec;
1205  t.keywordSet().get("RESTFREQS",vec);
1206  oss << setw(15) << "Rest Freqs:";
1207  if (vec.nelements() > 0) {
1208      oss << setprecision(0) << vec << " [Hz]" << endl;
1209  } else {
1210      oss << "None set" << endl;
1211  }
1212  oss << setw(15) << "Abcissa:" << getAbcissaString() << endl;
1213  oss << setw(15) << "Cursor:" << "Beam[" << getBeam() << "] "
1214      << "IF[" << getIF() << "] " << "Pol[" << getPol() << "]" << endl;
1215  oss << endl;
1216//
1217  String dirtype ="Position ("+ MDirection::showType(getDirectionReference()) + ")";
1218  oss << setw(5) << "Scan"
1219      << setw(15) << "Source"
1220      << setw(24) << dirtype
1221      << setw(10) << "Time"
1222      << setw(18) << "Integration"
1223      << setw(7) << "FreqIDs" << endl;
1224  oss << "--------------------------------------------------------------------------------" << endl;
1225 
1226// Generate list of scan start and end integrations
1227
1228  Vector<Int> scanIDs = scanCol_.getColumn();
1229  Vector<uInt> startInt, endInt;
1230  mathutil::scanBoundaries(startInt, endInt, scanIDs);
1231//
1232  const uInt nScans = startInt.nelements();
1233  String name;
1234  Vector<uInt> freqIDs, listFQ;
1235  uInt nInt;
1236//
1237  for (uInt i=0; i<nScans; i++) {
1238
1239// Get things from first integration of scan
1240
1241      String time = getTime(startInt(i),False);
1242      String tInt = formatSec(Double(getInterval(startInt(i))));
1243      String posit = formatDirection(getDirection(startInt(i),True));
1244      srcnCol_.getScalar(startInt(i),name);
1245
1246// Find all the FreqIDs in this scan
1247
1248      listFQ.resize(0);     
1249      for (uInt j=startInt(i); j<endInt(i)+1; j++) {
1250         freqidCol_.get(j, freqIDs);
1251         for (uInt k=0; k<freqIDs.nelements(); k++) {
1252            mathutil::addEntry(listFQ, freqIDs(k));
1253         }
1254      }
1255//
1256      nInt = endInt(i) - startInt(i) + 1;
1257      oss << setw(3) << std::right << i << std::left << setw(2) << "  "
1258          << setw(15) << name
1259          << setw(24) << posit
1260          << setw(10) << time
1261          << setw(3) << std::right << nInt  << setw(3) << " x " << std::left
1262          << setw(6) <<  tInt
1263          << " " << listFQ << endl;
1264  }
1265  oss << endl;
1266  oss << "Table contains " << table_.nrow() << " integration(s) in " << nScans << " scan(s)." << endl;
1267
1268// Frequency Table
1269
1270  if (verbose) {
1271    std::vector<string> info = getCoordInfo();
1272    SDFrequencyTable sdft = getSDFreqTable();
1273    oss << endl << endl;
1274    oss << "FreqID  Frame   RefFreq(Hz)     RefPix   Increment(Hz)" << endl;
1275    oss << "--------------------------------------------------------------------------------" << endl;
1276    for (uInt i=0; i<sdft.length(); i++) {
1277      oss << setw(8) << i << setw(8)
1278          << info[3] << setw(16) << setprecision(8)
1279          << sdft.referenceValue(i) << setw(10)
1280          << sdft.referencePixel(i) << setw(12)
1281          << sdft.increment(i) << endl;
1282    }
1283    oss << "--------------------------------------------------------------------------------" << endl;
1284  }
1285  return String(oss);
1286}
1287
1288Int SDMemTable::nBeam() const
1289{
1290  Int n;
1291  table_.keywordSet().get("nBeam",n);
1292  return n;
1293}
1294Int SDMemTable::nIF() const {
1295  Int n;
1296  table_.keywordSet().get("nIF",n);
1297  return n;
1298}
1299Int SDMemTable::nPol() const {
1300  Int n;
1301  table_.keywordSet().get("nPol",n);
1302  return n;
1303}
1304Int SDMemTable::nChan() const {
1305  Int n;
1306  table_.keywordSet().get("nChan",n);
1307  return n;
1308}
1309bool SDMemTable::appendHistory(const std::string& hist, int whichRow)
1310{
1311  Vector<String> history;
1312  histCol_.get(whichRow, history);
1313  history.resize(history.nelements()+1,True);
1314  history[history.nelements()-1] = hist;
1315  histCol_.put(whichRow, history);
1316}
1317
1318std::vector<std::string> SDMemTable::history(int whichRow) const
1319{
1320  Vector<String> history;
1321  histCol_.get(whichRow, history);
1322  std::vector<std::string> stlout;
1323  // there is no Array<String>.tovector(std::vector<std::string>), so
1324  // do it by hand
1325  for (uInt i=0; i<history.nelements(); ++i) {
1326    stlout.push_back(history[i]);
1327  }
1328  return stlout;
1329}
1330/*
1331void SDMemTable::maskChannels(const std::vector<Int>& whichChans ) {
1332
1333  std::vector<int>::iterator it;
1334  ArrayAccessor<uChar, Axis<asap::PolAxis> > j(flags_);
1335  for (it = whichChans.begin(); it != whichChans.end(); it++) {
1336    j.reset(j.begin(uInt(*it)));
1337    for (ArrayAccessor<uChar, Axis<asap::BeamAxis> > i(j); i != i.end(); ++i) {
1338      for (ArrayAccessor<uChar, Axis<asap::IFAxis> > ii(i); ii != ii.end(); ++ii) {
1339        for (ArrayAccessor<uChar, Axis<asap::ChanAxis> > iii(ii);
1340             iii != iii.end(); ++iii) {
1341          (*iii) =
1342        }
1343      }
1344    }
1345  }
1346
1347}
1348*/
1349void SDMemTable::flag(int whichRow)
1350{
1351  Array<uChar> arr;
1352  flagsCol_.get(whichRow, arr);
1353
1354  ArrayAccessor<uChar, Axis<asap::BeamAxis> > aa0(arr);
1355  aa0.reset(aa0.begin(uInt(beamSel_)));//go to beam
1356  ArrayAccessor<uChar, Axis<asap::IFAxis> > aa1(aa0);
1357  aa1.reset(aa1.begin(uInt(IFSel_)));// go to IF
1358  ArrayAccessor<uChar, Axis<asap::PolAxis> > aa2(aa1);
1359  aa2.reset(aa2.begin(uInt(polSel_)));// go to pol
1360
1361  for (ArrayAccessor<uChar, Axis<asap::ChanAxis> > i(aa2); i != i.end(); ++i) {
1362    (*i) = uChar(True);
1363  }
1364
1365  flagsCol_.put(whichRow, arr);
1366}
1367
1368MDirection::Types SDMemTable::getDirectionReference() const
1369
1370  Float eq;
1371  table_.keywordSet().get("Equinox",eq);
1372  std::map<float,string> mp;
1373  mp[2000.0] = "J2000";
1374  mp[1950.0] = "B1950";
1375  MDirection::Types mdr;
1376  if (!MDirection::getType(mdr, mp[eq])) {   
1377    mdr = MDirection::J2000;
1378    cerr  << "Unknown equinox using J2000" << endl;
1379  }
1380//
1381  return mdr;
1382}
1383
1384MEpoch::Types SDMemTable::getTimeReference() const
1385{
1386  MEpoch::Types met;
1387  String ep;
1388  table_.keywordSet().get("Epoch",ep);
1389  if (!MEpoch::getType(met, ep)) {
1390    cerr << "Epoch type unknown - using UTC" << endl;
1391    met = MEpoch::UTC;
1392  }
1393//
1394  return met;
1395}
1396
1397
1398Instrument SDMemTable::convertInstrument(const String& instrument,
1399                                         Bool throwIt)
1400{
1401   String t(instrument);
1402   t.upcase();
1403
1404// The strings are what SDReader returns, after cunning interrogation
1405// of station names... :-(
1406
1407   Instrument inst = asap::UNKNOWN;
1408   if (t==String("DSS-43")) {               
1409      inst = TIDBINBILLA;
1410   } else if (t==String("ATPKSMB")) {
1411      inst = ATPKSMB;
1412   } else if (t==String("ATPKSHOH")) {
1413      inst = ATPKSHOH;
1414   } else if (t==String("ATMOPRA")) {
1415      inst = ATMOPRA;
1416   } else if (t==String("CEDUNA")) {
1417      inst = CEDUNA;
1418   } else if (t==String("HOBART")) {
1419      inst = HOBART;
1420   } else {
1421     if (throwIt) {
1422       throw AipsError("Unrecognized instrument - use function scan.set_instrument to set");
1423     }
1424   }
1425   return inst;
1426}
1427
1428Bool SDMemTable::setRestFreqs (const Vector<Double>& restFreqsIn,
1429                                     const String& sUnit,
1430                                     const vector<string>& lines,
1431                                     const String& source,
1432                                     Int whichIF)
1433{
1434   const Int nIFs = nIF();
1435   if (whichIF>=nIFs) {
1436      throw(AipsError("Illegal IF index"));
1437   }
1438
1439// FInd vector of restfrequencies
1440// Double takes precedence over String
1441
1442   Unit unit;
1443   Vector<Double> restFreqs;
1444   if (restFreqsIn.nelements()>0) {
1445      restFreqs.resize(restFreqsIn.nelements());
1446      restFreqs = restFreqsIn;
1447      unit = Unit(sUnit);
1448   } else if (lines.size()>0) {
1449      const uInt nLines = lines.size();
1450      unit = Unit("Hz");
1451      restFreqs.resize(nLines);
1452      MFrequency lineFreq;
1453      for (uInt i=0; i<nLines; i++) {
1454         String tS(lines[i]);
1455         tS.upcase();
1456         if (MeasTable::Line(lineFreq, tS)) {
1457            restFreqs[i] = lineFreq.getValue().getValue();          // Hz
1458         } else {
1459            String s = String(lines[i]) + String(" is an unrecognized spectral line");
1460            throw(AipsError(s));
1461         }
1462      }
1463   } else {
1464      throw(AipsError("You have not specified any rest frequencies or lines"));
1465   }
1466
1467// If multiple restfreqs, must be length nIF. In this
1468// case we will just replace the rest frequencies
1469//
1470
1471   const uInt nRestFreqs = restFreqs.nelements();
1472   Int idx = -1;
1473   SDFrequencyTable sdft = getSDFreqTable();
1474
1475   if (nRestFreqs>1) {
1476
1477// Replace restFreqs, one per IF
1478
1479      if (nRestFreqs != nIFs) {
1480         throw (AipsError("Number of rest frequencies must be equal to the number of IFs"));
1481      }
1482      cout << "Replacing rest frequencies with given list, one per IF" << endl;
1483//
1484      sdft.deleteRestFrequencies();
1485      for (uInt i=0; i<nRestFreqs; i++) {
1486         Quantum<Double> rf(restFreqs[i], unit);
1487         sdft.addRestFrequency(rf.getValue("Hz"));
1488      }
1489   } else {
1490
1491// Add new rest freq
1492
1493      Quantum<Double> rf(restFreqs[0], unit);
1494      idx = sdft.addRestFrequency(rf.getValue("Hz"));
1495      cout << "Selecting given rest frequency" << endl;
1496   }
1497
1498// Replace
1499
1500   Bool empty = source.empty();
1501   Bool ok = False;
1502   if (putSDFreqTable(sdft)) {
1503      const uInt nRow = table_.nrow();
1504      String srcName;
1505      Vector<uInt> restFreqIDs;
1506      for (uInt i=0; i<nRow; i++) {
1507         srcnCol_.get(i, srcName);
1508         restfreqidCol_.get(i,restFreqIDs);       
1509//
1510         if (idx==-1) {
1511
1512// Replace vector of restFreqs; one per IF.
1513// No selection possible
1514
1515            for (uInt i=0; i<nIFs; i++) restFreqIDs[i] = i;
1516         } else {
1517
1518// Set RestFreqID for selected data
1519
1520            if (empty || source==srcName) {
1521               if (whichIF<0) {
1522                  restFreqIDs = idx;
1523               } else {             
1524                  restFreqIDs[whichIF] = idx;
1525               }
1526            }
1527         }
1528//
1529         restfreqidCol_.put(i,restFreqIDs);       
1530      }
1531      ok = True;
1532   } else {
1533      ok = False;
1534   }
1535//
1536   return ok;
1537}
1538
1539void SDMemTable::spectralLines() const
1540{
1541   Vector<String> lines = MeasTable::Lines();
1542   MFrequency lineFreq;
1543   Double freq;
1544//
1545   cout.flags(std::ios_base::left);
1546   cout << "Line      Frequency (Hz)" << endl;
1547   cout << "-----------------------" << endl;
1548   for (uInt i=0; i<lines.nelements(); i++) {
1549     MeasTable::Line(lineFreq, lines[i]);
1550     freq = lineFreq.getValue().getValue();          // Hz
1551//
1552     cout << setw(11) << lines[i] << setprecision(10) << freq << endl;
1553   }
1554}
1555
1556void SDMemTable::renumber()
1557{
1558  uInt nRow = scanCol_.nrow();
1559  Int newscanid = 0;
1560  Int cIdx;// the current scanid
1561  // get the first scanid
1562  scanCol_.getScalar(0,cIdx);
1563  Int pIdx = cIdx;// the scanid of the previous row
1564  for (uInt i=0; i<nRow;++i) {
1565    scanCol_.getScalar(i,cIdx);
1566    if (pIdx == cIdx) {
1567      // renumber
1568      scanCol_.put(i,newscanid);
1569    } else {
1570      ++newscanid;
1571      pIdx = cIdx;   // store scanid
1572      --i;           // don't increment next loop
1573    }
1574  }
1575}
1576
1577
1578void SDMemTable::rotateXYPhase (Float value, Bool doAll)
1579//
1580// phase in degrees
1581// Applies to all Beams and IFs
1582// Might want to optionally select on Beam/IF
1583//
1584{
1585   if (nPol() != 4) {
1586      throw(AipsError("You must have 4 polarizations to run this function"));
1587   }
1588//
1589   IPosition start(asap::nAxes,0);
1590   IPosition end(asap::nAxes);
1591//
1592   uInt nRow = specCol_.nrow();
1593   Array<Float> data;
1594   for (uInt i=0; i<nRow;++i) {
1595      specCol_.get(i,data);
1596      IPosition shape = data.shape();
1597
1598// Set slice
1599
1600      if (!doAll) {
1601         setCursorSlice (start, end, shape);
1602      } else {
1603         end = shape-1;
1604      }
1605
1606// Get polarization slice references
1607
1608      start(asap::PolAxis) = 2;
1609      end(asap::PolAxis) = 2;
1610      Array<Float> C3 = data(start,end);
1611//
1612      start(asap::PolAxis) = 3;
1613      end(asap::PolAxis) = 3;
1614      Array<Float> C4 = data(start,end);
1615
1616// Rotate
1617
1618      SDPolUtil::rotateXYPhase(C3, C4, value);
1619
1620// Put
1621
1622      specCol_.put(i,data);
1623   }
1624}
1625
1626
1627void SDMemTable::setCursorSlice (IPosition& start, IPosition& end,
1628                                 const IPosition& shape) const
1629{
1630   const uInt nDim = shape.nelements();
1631   start.resize(nDim);
1632   end.resize(nDim);
1633//
1634   start(asap::BeamAxis) = beamSel_;
1635   end(asap::BeamAxis) = beamSel_;
1636//
1637   start(asap::IFAxis) = IFSel_;
1638   end(asap::IFAxis) = IFSel_;
1639//
1640   start(asap::PolAxis) = polSel_;
1641   end(asap::PolAxis) = polSel_;
1642//
1643   start(asap::ChanAxis) = 0;
1644   end(asap::ChanAxis) = shape(asap::ChanAxis) - 1;
1645}
1646
1647
1648std::vector<float> SDMemTable::convertVector (const Vector<Float>& in) const
1649{
1650   std::vector<float> out(in.nelements());
1651   for (uInt i=0; i<in.nelements(); i++) {
1652      out[i] = in[i];
1653   }
1654   return out;
1655}
1656
1657
1658std::vector<float> SDMemTable::getFloatSpectrum (const Array<Float>& arr) const
1659//
1660// Get spectrum at cursor location
1661//
1662{
1663
1664// Setup accessors
1665
1666  ArrayAccessor<Float, Axis<asap::BeamAxis> > aa0(arr);
1667  aa0.reset(aa0.begin(uInt(beamSel_)));                    // Beam selection
1668
1669  ArrayAccessor<Float, Axis<asap::IFAxis> > aa1(aa0);
1670  aa1.reset(aa1.begin(uInt(IFSel_)));                      // IF selection
1671
1672  ArrayAccessor<Float, Axis<asap::PolAxis> > aa2(aa1);
1673  aa2.reset(aa2.begin(uInt(polSel_)));                     // Pol selection
1674//
1675  std::vector<float> spectrum;
1676  for (ArrayAccessor<Float, Axis<asap::ChanAxis> > i(aa2); i != i.end(); ++i) {
1677    spectrum.push_back(*i);
1678  }
1679  return spectrum;
1680}
1681
Note: See TracBrowser for help on using the repository browser.