source: trunk/src/SDMemTable.cc @ 439

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

make stokesCOl_ read only
add toStokes arg. to function rowAsMaskedArry

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