source: trunk/src/SDMemTable.cc @ 476

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

move function convertInstrument to SDAttr

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