source: trunk/src/param.cc @ 1144

Last change on this file since 1144 was 1142, checked in by MatthewWhiting, 11 years ago

Ticket #131: Enabling the writing of the moment-0 mask image, with updated documentation. Also removing the code that wrote the BLANK/BSCALE etc parameters to integer FITS files - the only integer files we write are the mask ones which don't need them.

File size: 57.2 KB
Line 
1// -----------------------------------------------------------------------
2// param.cc: Dealing with the set of parameters for Duchamp.
3// -----------------------------------------------------------------------
4// Copyright (C) 2006, Matthew Whiting, ATNF
5//
6// This program is free software; you can redistribute it and/or modify it
7// under the terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 2 of the License, or (at your
9// option) any later version.
10//
11// Duchamp is distributed in the hope that it will be useful, but WITHOUT
12// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14// for more details.
15//
16// You should have received a copy of the GNU General Public License
17// along with Duchamp; if not, write to the Free Software Foundation,
18// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
19//
20// Correspondence concerning Duchamp may be directed to:
21//    Internet email: Matthew.Whiting [at] atnf.csiro.au
22//    Postal address: Dr. Matthew Whiting
23//                    Australia Telescope National Facility, CSIRO
24//                    PO Box 76
25//                    Epping NSW 1710
26//                    AUSTRALIA
27// -----------------------------------------------------------------------
28#include <iostream>
29#include <iomanip>
30#include <fstream>
31#include <sstream>
32#include <string>
33#include <algorithm>
34#include <stdlib.h>
35#include <ctype.h>
36#include <math.h>
37#include <unistd.h>
38#include <duchamp/param.hh>
39#include <duchamp/fitsHeader.hh>
40#include <duchamp/duchamp.hh>
41#include <duchamp/pgheader.hh>
42#include <duchamp/ATrous/filter.hh>
43#include <duchamp/Utils/utils.hh>
44#include <duchamp/Utils/Section.hh>
45#include <duchamp/Utils/VOParam.hh>
46#include <duchamp/Outputs/columns.hh>
47
48namespace duchamp
49{
50  const std::string defaultSection = "[*,*,*]";
51
52  /****************************************************************/
53  ///////////////////////////////////////////////////
54  //// Accessor Functions for Parameter class:
55  ///////////////////////////////////////////////////
56  Param::~Param()
57  {
58    /// Deletes the offsets array if the sizeOffsets parameter is
59    /// positive.
60    if(this->sizeOffsets>0) delete [] this->offsets;
61  }
62
63  Param::Param()
64  {
65    this->defaultValues();
66  }
67
68  void Param::defaultValues()
69  {
70    /// Provides default intial values for the parameters. Note that
71    /// imageFile has no default value!
72
73    // Input files
74    this->imageFile         = "";
75    this->flagSubsection    = false;
76    this->pixelSec.setSection(defaultSection);
77    this->flagReconExists   = false;
78    this->reconFile         = "";
79    this->flagSmoothExists  = false;
80    this->smoothFile        = "";
81    this->usePrevious       = false;
82    this->objectList        = "";
83    // Output files
84    this->flagLog           = false;
85    this->logFile           = "duchamp-Logfile.txt";
86    this->outFile           = "duchamp-Results.txt";
87    this->flagSeparateHeader= false;
88    this->headerFile        = "duchamp-Results.hdr";
89    this->flagPlotSpectra   = true;
90    this->spectraFile       = "duchamp-Spectra.ps";
91    this->flagTextSpectra   = false;
92    this->spectraTextFile   = "duchamp-Spectra.txt";
93    this->flagOutputBaseline    = false;
94    this->fileOutputBaseline    = "";
95    this->flagOutputMomentMap    = false;
96    this->fileOutputMomentMap    = "";
97    this->flagOutputMomentMask    = false;
98    this->fileOutputMomentMask    = "";
99    this->flagOutputMask    = false;
100    this->fileOutputMask    = "";
101    this->flagMaskWithObjectNum = false;
102    this->flagOutputSmooth  = false;
103    this->fileOutputSmooth  = "";
104    this->flagOutputRecon   = false;
105    this->fileOutputRecon   = "";
106    this->flagOutputResid   = false;
107    this->fileOutputResid   = "";
108    this->flagVOT           = false;
109    this->votFile           = "duchamp-Results.xml";
110    this->flagKarma         = false;
111    this->karmaFile         = "duchamp-Results.ann";
112    this->flagDS9           = false;
113    this->ds9File           = "duchamp-Results.reg";
114    this->flagCasa          = false;
115    this->casaFile          = "duchamp-Results.crf";
116    this->annotationType    = "borders";
117    this->flagMaps          = true;
118    this->detectionMap      = "duchamp-DetectionMap.ps";
119    this->momentMap         = "duchamp-MomentMap.ps";
120    this->flagXOutput       = true;
121    this->precFlux          = Catalogues::prFLUX;
122    this->precVel           = Catalogues::prVEL;
123    this->precSNR           = Catalogues::prSNR;
124    // Cube related parameters
125    this->flagBlankPix      = false;
126    this->blankPixValue     = -8.00061;
127    this->blankKeyword      = 1;
128    this->bscaleKeyword     = -8.00061;
129    this->bzeroKeyword      = 0.;
130    this->newFluxUnits      = "";
131    // Milky-Way parameters
132    this->flagMW            = false;
133    this->maxMW             = 112;
134    this->minMW             = 75;
135    this->areaBeam          = 0.;
136    this->fwhmBeam          = 0.;
137    this->beamAsUsed.empty();
138    this->searchType        = "spatial";
139    // Trim-related         
140    this->flagTrim          = false;
141    this->hasBeenTrimmed    = false;
142    this->borderLeft        = 0;
143    this->borderRight       = 0;
144    this->borderBottom      = 0;
145    this->borderTop         = 0;
146    // Subsection offsets
147    this->sizeOffsets       = 0;
148    this->xSubOffset        = 0;
149    this->ySubOffset        = 0;
150    this->zSubOffset        = 0;
151    // Baseline related
152    this->flagBaseline      = false;
153    // Detection-related   
154    this->flagNegative      = false;
155    // Object growth       
156    this->flagGrowth        = false;
157    this->growthCut         = 3.;
158    this->flagUserGrowthThreshold = false;
159    this->growthThreshold   = 0.;
160    // FDR analysis         
161    this->flagFDR           = false;
162    this->alphaFDR          = 0.01;
163    this->FDRnumCorChan     = 2;
164    // Other detection     
165    this->flagStatSec       = false;
166    this->statSec.setSection(defaultSection);
167    this->flagRobustStats   = true;
168    this->snrCut            = 5.;
169    this->threshold         = 0.;
170    this->flagUserThreshold = false;
171    // Smoothing
172    this->flagSmooth        = false;
173    this->smoothType        = "spectral";
174    this->hanningWidth      = 5;
175    this->kernMaj           = 3.;
176    this->kernMin           = -1.;
177    this->kernPA            = 0.;
178    // A trous reconstruction parameters
179    this->flagATrous        = false;
180    this->reconDim          = 1;
181    this->scaleMin          = 1;
182    this->scaleMax          = 0;
183    this->snrRecon          = 4.;
184    this->reconConvergence  = 0.005;
185    this->filterCode        = 1;
186    this->reconFilter.define(this->filterCode);
187    // Volume-merging parameters
188    this->flagAdjacent      = true;
189    this->threshSpatial     = 3.;
190    this->threshVelocity    = 7.;
191    this->minChannels       = 3;
192    this->minPix            = 2;
193    this->minVoxels         = 4;
194    this->flagRejectBeforeMerge = false;
195    this->flagTwoStageMerging = true;
196    // Input-Output related
197    this->spectralMethod    = "peak";
198    this->spectralType      = "";
199    this->restFrequency     = -1.;
200    this->restFrequencyUsed = false;
201    this->spectralUnits     = "";
202    this->pixelCentre       = "centroid";
203    this->sortingParam      = "vel";
204    this->borders           = true;
205    this->blankEdge         = true;
206    this->verbose           = true;
207    this->commentStr        = "";
208  }
209
210  Param::Param (const Param& p)
211  {
212    operator=(p);
213  }
214
215  Param& Param::operator= (const Param& p)
216  {
217    if(this == &p) return *this;
218    this->imageFile         = p.imageFile;
219    this->flagSubsection    = p.flagSubsection;
220    this->pixelSec          = p.pixelSec;
221    this->flagReconExists   = p.flagReconExists;
222    this->reconFile         = p.reconFile;     
223    this->flagSmoothExists  = p.flagSmoothExists;
224    this->smoothFile        = p.smoothFile;     
225    this->usePrevious       = p.usePrevious;
226    this->objectList        = p.objectList;
227    this->flagLog           = p.flagLog;       
228    this->logFile           = p.logFile;       
229    this->outFile           = p.outFile;       
230    this->flagSeparateHeader= p.flagSeparateHeader;
231    this->headerFile        = p.headerFile;
232    this->flagPlotSpectra   = p.flagPlotSpectra;
233    this->spectraFile       = p.spectraFile;   
234    this->flagTextSpectra   = p.flagTextSpectra;   
235    this->spectraTextFile   = p.spectraTextFile;   
236    this->flagOutputBaseline    = p.flagOutputBaseline;
237    this->fileOutputBaseline    = p.fileOutputBaseline;
238    this->flagOutputMomentMap    = p.flagOutputMomentMap;
239    this->fileOutputMomentMap    = p.fileOutputMomentMap;
240    this->flagOutputMomentMask   = p.flagOutputMomentMask;
241    this->fileOutputMomentMask   = p.fileOutputMomentMask;
242    this->flagOutputMask    = p.flagOutputMask;
243    this->fileOutputMask    = p.fileOutputMask;
244    this->flagMaskWithObjectNum = p.flagMaskWithObjectNum;
245    this->flagOutputSmooth  = p.flagOutputSmooth;
246    this->fileOutputSmooth  = p.fileOutputSmooth;
247    this->flagOutputRecon   = p.flagOutputRecon;
248    this->fileOutputRecon   = p.fileOutputRecon;
249    this->flagOutputResid   = p.flagOutputResid;
250    this->fileOutputResid   = p.fileOutputResid;
251    this->flagVOT           = p.flagVOT;         
252    this->votFile           = p.votFile;       
253    this->flagKarma         = p.flagKarma;     
254    this->karmaFile         = p.karmaFile;     
255    this->flagDS9           = p.flagDS9;     
256    this->ds9File           = p.ds9File;     
257    this->flagCasa          = p.flagCasa;     
258    this->casaFile          = p.casaFile;     
259    this->annotationType    = p.annotationType;
260    this->flagMaps          = p.flagMaps;       
261    this->detectionMap      = p.detectionMap;   
262    this->momentMap         = p.momentMap;     
263    this->flagXOutput       = p.flagXOutput;       
264    this->precFlux          = p.precFlux;
265    this->precVel           = p.precVel;
266    this->precSNR           = p.precSNR;
267    this->flagNegative      = p.flagNegative;
268    this->flagBlankPix      = p.flagBlankPix;   
269    this->blankPixValue     = p.blankPixValue; 
270    this->blankKeyword      = p.blankKeyword;   
271    this->bscaleKeyword     = p.bscaleKeyword; 
272    this->bzeroKeyword      = p.bzeroKeyword;   
273    this->newFluxUnits      = p.newFluxUnits;
274    this->flagMW            = p.flagMW;         
275    this->maxMW             = p.maxMW;         
276    this->minMW             = p.minMW;         
277    this->areaBeam          = p.areaBeam;     
278    this->fwhmBeam          = p.fwhmBeam;     
279    this->beamAsUsed        = p.beamAsUsed;
280    this->searchType        = p.searchType;
281    this->flagTrim          = p.flagTrim;   
282    this->hasBeenTrimmed    = p.hasBeenTrimmed;   
283    this->borderLeft        = p.borderLeft;     
284    this->borderRight       = p.borderRight;   
285    this->borderBottom      = p.borderBottom;   
286    this->borderTop         = p.borderTop;     
287    if(this->sizeOffsets>0) delete [] this->offsets;
288    this->sizeOffsets       = p.sizeOffsets;
289    if(this->sizeOffsets>0){
290      this->offsets           = new long[this->sizeOffsets];
291      for(int i=0;i<this->sizeOffsets;i++) this->offsets[i] = p.offsets[i];
292    }
293    this->xSubOffset        = p.xSubOffset;     
294    this->ySubOffset        = p.ySubOffset;     
295    this->zSubOffset        = p.zSubOffset;
296    this->flagBaseline      = p.flagBaseline;
297    this->flagGrowth        = p.flagGrowth;
298    this->growthCut         = p.growthCut;
299    this->growthThreshold   = p.growthThreshold;
300    this->flagUserGrowthThreshold = p.flagUserGrowthThreshold;
301    this->flagFDR           = p.flagFDR;
302    this->alphaFDR          = p.alphaFDR;
303    this->FDRnumCorChan     = p.FDRnumCorChan;
304    this->flagStatSec       = p.flagStatSec;
305    this->statSec           = p.statSec;
306    this->flagRobustStats   = p.flagRobustStats;
307    this->snrCut            = p.snrCut;
308    this->threshold         = p.threshold;
309    this->flagUserThreshold = p.flagUserThreshold;
310    this->flagSmooth        = p.flagSmooth;
311    this->smoothType        = p.smoothType;
312    this->hanningWidth      = p.hanningWidth;
313    this->kernMaj           = p.kernMaj;
314    this->kernMin           = p.kernMin;
315    this->kernPA            = p.kernPA;
316    this->flagATrous        = p.flagATrous;
317    this->reconDim          = p.reconDim;
318    this->scaleMin          = p.scaleMin;
319    this->scaleMax          = p.scaleMax;
320    this->snrRecon          = p.snrRecon;
321    this->reconConvergence  = p.reconConvergence;
322    this->filterCode        = p.filterCode;
323    this->reconFilter       = p.reconFilter;
324    this->flagAdjacent      = p.flagAdjacent;
325    this->threshSpatial     = p.threshSpatial;
326    this->threshVelocity    = p.threshVelocity;
327    this->minChannels       = p.minChannels;
328    this->minPix            = p.minPix;
329    this->minVoxels         = p.minVoxels;
330    this->flagRejectBeforeMerge = p.flagRejectBeforeMerge;
331    this->flagTwoStageMerging = p.flagTwoStageMerging;
332    this->spectralMethod    = p.spectralMethod;
333    this->spectralType      = p.spectralType;
334    this->restFrequency     = p.restFrequency;
335    this->restFrequencyUsed = p.restFrequencyUsed;
336    this->spectralUnits     = p.spectralUnits;
337    this->pixelCentre       = p.pixelCentre;
338    this->sortingParam      = p.sortingParam;
339    this->borders           = p.borders;
340    this->blankEdge         = p.blankEdge;
341    this->verbose           = p.verbose;
342    this->commentStr        = p.commentStr;
343    return *this;
344  }
345  //--------------------------------------------------------------------
346
347  OUTCOME Param::getopts(int argc, char ** argv, std::string progname)
348  {
349    ///   A function that reads in the command-line options, in a manner
350    ///    tailored for use with the main Duchamp program.
351    ///
352    ///   \param argc The number of command line arguments.
353    ///   \param argv The array of command line arguments.
354
355    OUTCOME returnValue = FAILURE;
356    if(argc==1){
357      if(progname=="Selavy") std::cout << SELAVY_ERR_USAGE_MSG;
358      else if(progname=="Duchamp") std::cout << ERR_USAGE_MSG;
359      else std::cout << ERR_USAGE_MSG;
360      returnValue = FAILURE;
361    }
362    else {
363      std::string file;
364      bool changeX = false;
365      this->defaultValues();
366      char c;
367      while( ( c = getopt(argc,argv,"p:f:hvx") )!=-1){
368        switch(c) {
369        case 'p':
370          file = optarg;
371          if(this->readParams(file)==FAILURE){
372            DUCHAMPERROR(progname,"Could not open parameter file " << file);
373          }
374          else returnValue = SUCCESS;
375          break;
376        case 'f':
377          file = optarg;
378          this->imageFile = file;
379          returnValue = SUCCESS;
380          break;
381        case 'v':
382          std::cout << PROGNAME << " version " << VERSION << std::endl;
383          break;
384        case 'x':
385          changeX = true;
386          break;
387        case 'h':
388        default :
389          if(progname=="Selavy") std::cout << SELAVY_ERR_USAGE_MSG;
390          else if(progname=="Duchamp") std::cout << ERR_USAGE_MSG;
391          else std::cout << ERR_USAGE_MSG;
392          break;
393        }
394      }
395      if(changeX){
396        if(returnValue == SUCCESS) this->setFlagXOutput(false);
397        else {
398          DUCHAMPERROR(progname, "You need to specify either a parameter file or FITS image.\n");
399          std::cout << "\n" << ERR_USAGE_MSG;
400        }
401      }
402    }
403    return returnValue;
404  }
405  //--------------------------------------------------------------------
406
407  bool Param::isBlank(float &value)
408  {
409    ///  Tests whether the value passed as the argument is BLANK or not.
410    ///  \param value Pixel value to be tested.
411    ///  \return False if flagBlankPix is false. Else, compare to the
412    ///  relevant FITS keywords, using integer comparison.
413
414    return this->flagBlankPix &&
415      (this->blankKeyword == int((value-this->bzeroKeyword)/this->bscaleKeyword));
416  }
417
418  bool *Param::makeBlankMask(float *array, size_t size)
419  {
420    ///  This returns an array of bools, saying whether each pixel in the
421    ///  given array is BLANK or not. If the pixel is BLANK, set mask to
422    ///  false, else set to true. The array is allocated by the function.
423
424    bool *mask = new bool[size];
425    for(size_t i=0;i<size;i++) mask[i] = !this->isBlank(array[i]);
426    return mask;
427  }
428
429
430  bool *Param::makeStatMask(float *array, size_t *dim)
431  {
432    ///  This returns an array of bools, saying whether each pixel in
433    ///  the given array is suitable for a stats calculation. It needs
434    ///  to be in the StatSec (if defined), not blank and not a MW
435    ///  channel. The array is allocated by the function with a 'new' call.
436
437    bool *mask = new bool[dim[0]*dim[1]*dim[2]];
438    for(size_t x=0;x<dim[0];x++) {
439      for(size_t y=0;y<dim[1];y++) {
440        for(size_t z=0;z<dim[2];z++) {
441          size_t i = x+y*dim[0]+z*dim[0]*dim[1];
442          mask[i] = !this->isBlank(array[i]) && !this->isInMW(z) && this->isStatOK(x,y,z);
443        }
444      }
445    }
446    return mask;
447  }
448
449
450  bool Param::isInMW(int z)
451  {
452    ///  Tests whether we are flagging Milky Way channels, and if so
453    /// whether the given channel number is in the Milky Way range. The
454    /// channels are assumed to start at number 0. 
455    /// \param z The channel number
456    /// \return True if we are flagging Milky Way channels and z is in
457    ///  the range.
458
459    return ( this->flagMW && (z>=this->getMinMW()) && (z<=this->getMaxMW()) );
460  }
461
462  bool Param::isStatOK(int x, int y, int z)
463  {
464    /// Test whether a given pixel position lies within the subsection
465    /// given by the statSec parameter. Only tested if the flagSubsection
466    /// parameter is true -- if it isn't, we just return true since all
467    /// pixels are therefore available for statstical calculations.
468    /// \param x X-value of pixel being tested.
469    /// \param y Y-value of pixel being tested.
470    /// \param z Z-value of pixel being tested.
471    /// \return True if pixel is able to be used for statistical
472    /// calculations. False otherwise.
473
474    int xval=x,yval=y,zval=z;
475    if(flagSubsection){
476      xval += pixelSec.getStart(0);
477      yval += pixelSec.getStart(1);
478      zval += pixelSec.getStart(2);
479    }
480    return !flagStatSec || statSec.isInside(xval,yval,zval);
481  }
482
483  std::vector<int> Param::getObjectRequest()
484  {
485    ///  Returns a list of the object numbers requested via the objectList parameter.
486    /// \return a vector of integers, one for each number in the objectList set.
487
488    std::stringstream ss1;
489    std::string tmp;
490    std::vector<int> tmplist;
491    ss1.str(this->objectList);
492    while(!ss1.eof()){
493      getline(ss1,tmp,',');
494      for(size_t i=0;i<tmp.size();i++) if(tmp[i]=='-') tmp[i]=' ';
495      int a,b;
496      std::stringstream ss2;
497      ss2.str(tmp);
498      ss2 >>a;
499      if(!ss2.eof()) ss2 >> b;
500      else b=a;
501      for(int n=a;n<=b;n++){
502        tmplist.push_back(n);
503      }     
504    }
505    return tmplist;
506  }
507
508  std::vector<bool> Param::getObjectChoices()
509  {
510    ///  Returns a list of bool values, indicating whether a given
511    ///  object was requested or not. The size of the vector is
512    ///  determined by the maximum value in objectList. For instance,
513    ///  if objectList="2,3,5-8", then the returned vector will be
514    ///  [0,1,1,0,1,1,1,1].
515    ///  \return Vector of bool values.
516
517    std::vector<int> objectChoices = this->getObjectRequest();
518    int maxNum = *std::max_element(objectChoices.begin(), objectChoices.end());
519    std::vector<bool> choices(maxNum,false);
520    for(std::vector<int>::iterator obj = objectChoices.begin();obj!=objectChoices.end();obj++)
521      choices[*obj-1] = true;
522    return choices;
523  }
524
525  std::vector<bool> Param::getObjectChoices(int numObjects)
526  {
527    ///  Returns a list of bool values, indicating whether a given
528    ///  object was requested or not. The size of the vector is given
529    ///  by the numObjects parameter. So, if objectList="2,3,5-8", then
530    ///  the returned vector from a getObjectChoices(10) call will be
531    ///  [0,1,1,0,1,1,1,1,0,0].
532    ///  \param numObjects How many objects there are in total.
533    ///  \return Vector of bool values.
534
535    if(this->objectList==""){
536      std::vector<bool> choices(numObjects,true);
537      return choices;
538    }
539    else{
540      std::vector<int> objectChoices = this->getObjectRequest();
541      std::vector<bool> choices(numObjects,false);
542      for(std::vector<int>::iterator obj = objectChoices.begin();obj!=objectChoices.end();obj++)
543        if(*obj<=numObjects) choices[*obj-1] = true;
544      return choices;
545    }
546  }
547
548  /****************************************************************/
549  /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ///
550  /// / Other Functions using the  Parameter class:
551  /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ///
552
553  OUTCOME Param::readParams(std::string paramfile)
554  {
555    /// The parameters are read in from a disk file, on the assumption that each
556    ///  line of the file has the format "parameter value" (eg. alphafdr 0.1)
557    ///
558    /// The case of the parameter name does not matter, nor does the
559    /// formatting of the spaces (it can be any amount of whitespace or
560    /// tabs).
561    ///
562    /// \param paramfile A std::string containing the parameter filename.
563    ///
564    /// \return FAILURE if the parameter file does not exist. SUCCESS if
565    /// it is able to read it.
566
567    if(!USE_PGPLOT){
568      // Change default values for these parameters when we don't use PGPlot
569      this->flagXOutput = false;
570      this->flagMaps = false;
571      this->flagPlotSpectra = false;
572    }
573
574    std::ifstream fin(paramfile.c_str());
575    if(!fin.is_open()) return FAILURE;
576    std::string line;
577    while( !std::getline(fin,line,'\n').eof()){
578
579      if(line[0]!='#'){
580        std::stringstream ss;
581        ss.str(line);
582        std::string arg;
583        ss >> arg;
584        arg = makelower(arg);
585        if(arg=="imagefile")       this->imageFile = readFilename(ss);
586        if(arg=="flagsubsection")  this->flagSubsection = readFlag(ss);
587        if(arg=="subsection")      this->pixelSec.setSection(readSval(ss));
588        if(arg=="flagreconexists") this->flagReconExists = readFlag(ss);
589        if(arg=="reconfile")       this->reconFile = readSval(ss);
590        if(arg=="flagsmoothexists")this->flagSmoothExists = readFlag(ss);
591        if(arg=="smoothfile")      this->smoothFile = readSval(ss);
592        if(arg=="beamarea")        this->areaBeam = readFval(ss);
593        if(arg=="beamfwhm")        this->fwhmBeam = readFval(ss);
594        if(arg=="useprevious")     this->usePrevious = readFlag(ss);
595        if(arg=="objectlist")      this->objectList = readSval(ss);
596
597        if(arg=="flaglog")         this->flagLog = readFlag(ss);
598        if(arg=="logfile")         this->logFile = readSval(ss);
599        if(arg=="outfile")         this->outFile = readSval(ss);
600        if(arg=="flagseparateheader") this->flagSeparateHeader = readFlag(ss);
601        if(arg=="headerfile")      this->headerFile = readFilename(ss);
602        if(arg=="flagplotspectra") this->flagPlotSpectra = readFlag(ss);
603        if(arg=="spectrafile")     this->spectraFile = readFilename(ss);
604        if(arg=="flagtextspectra") this->flagTextSpectra = readFlag(ss);
605        if(arg=="spectratextfile") this->spectraTextFile = readFilename(ss);
606        if(arg=="flagoutputbaseline")  this->flagOutputBaseline = readFlag(ss);
607        if(arg=="fileoutputbaseline")  this->fileOutputBaseline = readFilename(ss);
608        if(arg=="flagoutputmomentmap")  this->flagOutputMomentMap = readFlag(ss);
609        if(arg=="fileoutputmomentmap")  this->fileOutputMomentMap = readFilename(ss);
610        if(arg=="flagoutputmomentmask")  this->flagOutputMomentMask = readFlag(ss);
611        if(arg=="fileoutputmomentmask")  this->fileOutputMomentMask = readFilename(ss);
612        if(arg=="flagoutputmask")  this->flagOutputMask = readFlag(ss);
613        if(arg=="fileoutputmask")  this->fileOutputMask = readFilename(ss);
614        if(arg=="flagmaskwithobjectnum") this->flagMaskWithObjectNum = readFlag(ss);
615        if(arg=="flagoutputsmooth")this->flagOutputSmooth = readFlag(ss);
616        if(arg=="fileoutputsmooth")this->fileOutputSmooth = readFilename(ss);
617        if(arg=="flagoutputrecon") this->flagOutputRecon = readFlag(ss);
618        if(arg=="fileoutputrecon") this->fileOutputRecon = readFilename(ss);
619        if(arg=="flagoutputresid") this->flagOutputResid = readFlag(ss);
620        if(arg=="fileoutputresid") this->fileOutputResid = readFilename(ss);
621        if(arg=="flagvot")         this->flagVOT = readFlag(ss);
622        if(arg=="votfile")         this->votFile = readFilename(ss);
623        if(arg=="flagkarma")       this->flagKarma = readFlag(ss);
624        if(arg=="karmafile")       this->karmaFile = readFilename(ss);
625        if(arg=="flagds9")         this->flagDS9 = readFlag(ss);
626        if(arg=="ds9file")         this->ds9File = readFilename(ss);
627        if(arg=="flagcasa")        this->flagCasa = readFlag(ss);
628        if(arg=="casafile")        this->casaFile = readFilename(ss);
629        if(arg=="annotationtype")  this->annotationType = readSval(ss);
630        if(arg=="flagmaps")        this->flagMaps = readFlag(ss);
631        if(arg=="detectionmap")    this->detectionMap = readFilename(ss);
632        if(arg=="momentmap")       this->momentMap = readFilename(ss);
633        if(arg=="flagxoutput")     this->flagXOutput = readFlag(ss);
634        if(arg=="newfluxunits")    this->newFluxUnits = readSval(ss);
635        if(arg=="precflux")        this->precFlux = readIval(ss);
636        if(arg=="precvel")         this->precVel = readIval(ss);
637        if(arg=="precsnr")         this->precSNR = readIval(ss);
638
639        if(arg=="flagtrim")        this->flagTrim = readFlag(ss);
640        if(arg=="flagmw")          this->flagMW = readFlag(ss);
641        if(arg=="maxmw")           this->maxMW = readIval(ss);
642        if(arg=="minmw")           this->minMW = readIval(ss);
643        if(arg=="flagbaseline")    this->flagBaseline = readFlag(ss);
644        if(arg=="searchtype")      this->searchType = readSval(ss);
645
646        if(arg=="flagnegative")    this->flagNegative = readFlag(ss);
647        if(arg=="minpix")          this->minPix = readIval(ss);
648        if(arg=="flaggrowth")      this->flagGrowth = readFlag(ss);
649        if(arg=="growthcut")       this->growthCut = readFval(ss);
650        if(arg=="growththreshold"){
651          this->growthThreshold = readFval(ss);
652          this->flagUserGrowthThreshold = true;
653        }
654
655        if(arg=="flagfdr")         this->flagFDR = readFlag(ss);
656        if(arg=="alphafdr")        this->alphaFDR = readFval(ss);
657        if(arg=="fdrnumcorchan")   this->FDRnumCorChan = readIval(ss);
658        if(arg=="flagstatsec")     this->flagStatSec = readFlag(ss);
659        if(arg=="statsec")         this->statSec.setSection(readSval(ss));
660        if(arg=="flagrobuststats") this->flagRobustStats = readFlag(ss);
661        if(arg=="snrcut")          this->snrCut = readFval(ss);
662        if(arg=="threshold"){
663          this->threshold = readFval(ss);
664          this->flagUserThreshold = true;
665        }
666     
667        if(arg=="flagsmooth")      this->flagSmooth = readFlag(ss);
668        if(arg=="smoothtype")      this->smoothType = readSval(ss);
669        if(arg=="hanningwidth")    this->hanningWidth = readIval(ss);
670        if(arg=="kernmaj")         this->kernMaj = readFval(ss);
671        if(arg=="kernmin")         this->kernMin = readFval(ss);
672        if(arg=="kernpa")          this->kernPA = readFval(ss);
673
674        if(arg=="flagatrous")      this->flagATrous = readFlag(ss);
675        if(arg=="recondim")        this->reconDim = readIval(ss);
676        if(arg=="scalemin")        this->scaleMin = readIval(ss);
677        if(arg=="scalemax")        this->scaleMax = readIval(ss);
678        if(arg=="snrrecon")        this->snrRecon = readFval(ss);
679        if(arg=="reconconvergence") this->reconConvergence = readFval(ss);
680        if(arg=="filtercode")      this->filterCode = readIval(ss);
681
682        if(arg=="flagadjacent")    this->flagAdjacent = readFlag(ss);
683        if(arg=="threshspatial")   this->threshSpatial = readFval(ss);
684        if(arg=="threshvelocity")  this->threshVelocity = readFval(ss);
685        if(arg=="minchannels")     this->minChannels = readIval(ss);
686        if(arg=="minvoxels")       this->minVoxels = readIval(ss);
687        if(arg=="flagrejectbeforemerge") this->flagRejectBeforeMerge = readFlag(ss);
688        if(arg=="flagtwostagemerging") this->flagTwoStageMerging = readFlag(ss);
689
690        if(arg=="spectralmethod")  this->spectralMethod=makelower(readSval(ss));
691        if(arg=="spectraltype")    this->spectralType = readSval(ss);
692        if(arg=="restfrequency")   this->restFrequency = readFval(ss);
693        if(arg=="spectralunits")   this->spectralUnits = readSval(ss);
694        if(arg=="pixelcentre")     this->pixelCentre = makelower(readSval(ss));
695        if(arg=="sortingparam")    this->sortingParam = makelower(readSval(ss));
696        if(arg=="drawborders")     this->borders = readFlag(ss);
697        if(arg=="drawblankedges")  this->blankEdge = readFlag(ss);
698        if(arg=="verbose")         this->verbose = readFlag(ss);
699
700        // Dealing with deprecated parameters.
701        if(arg=="flagblankpix"){
702          this->flagTrim = readFlag(ss);
703          DUCHAMPWARN("Reading parameters","The parameter flagBlankPix is deprecated. Please use the flagTrim parameter in future.");
704          DUCHAMPWARN("Reading parameters","Setting flagTrim = " << stringize(this->flagTrim));
705        }
706        if(arg=="blankpixvalue"){
707          DUCHAMPWARN("Reading parameters","The parameter blankPixValue is deprecated. This value is only taken from the FITS header.");
708        }
709        if(arg=="beamsize"){
710          this->areaBeam = readFval(ss);
711          DUCHAMPWARN("Reading parameters","The parameter beamSize is deprecated. You can specify the beam size by beamArea or beamFWHM.");
712          DUCHAMPWARN("Reading parameters","Setting beamArea = " << this->areaBeam);
713        }
714
715      }
716    }
717
718    this->checkPars();
719
720    return SUCCESS;
721
722  }
723 
724  void Param::checkPars()
725  {
726
727    // If flagSubsection is false, but the parset had a subsection string in it, we want to set this back to the default.
728    if(!this->flagSubsection){
729      this->pixelSec.setSection(defaultSection);
730    }
731    if(!this->flagStatSec){
732      this->statSec.setSection(defaultSection);
733    }
734
735    // If we have usePrevious=false, set the objectlist to blank so that we use all of them
736    if(!this->usePrevious) this->objectList = "";
737
738    // If pgplot was not included in the compilation, need to set flagXOutput to false
739    if(!USE_PGPLOT){
740      if(this->flagXOutput || this->flagMaps || this->flagPlotSpectra)
741        DUCHAMPWARN("Reading parameters","PGPlot has not been enabled, so setting flagXOutput, flagMaps and flagPlotSpectra to false.");
742      this->flagXOutput = false;
743      this->flagMaps = false;
744      this->flagPlotSpectra = false;
745    }
746
747    // Correcting bad precision values -- if negative, set to 0
748    if(this->precFlux<0) this->precFlux = 0;
749    if(this->precVel<0)  this->precVel = 0;
750    if(this->precSNR<0)  this->precSNR = 0;
751
752    // Can only have "spatial" or "spectral" as search types
753    if(this->searchType != "spatial" && this->searchType != "spectral"){
754      DUCHAMPWARN("Reading parameters","You have requested a search type of \""<<this->searchType<<"\" -- Only \"spectral\" and \"spatial\" are accepted, so setting to \"spatial\".");
755      this->searchType = "spatial";
756    }
757
758    // The wavelet reconstruction takes precendence over the smoothing.
759    if(this->flagATrous) this->flagSmooth = false;
760
761    // Check validity of recon parameters
762    if(this->flagATrous){
763      if(this->reconConvergence < 0.){
764        DUCHAMPWARN("Reading Parameters","Your reconConvergence value is negative ("<<this->reconConvergence<<") - setting to " << -this->reconConvergence <<".");
765        this->reconConvergence *= -1.;
766      }
767
768      this->reconFilter.define(this->filterCode);
769
770      if((this->scaleMax) > 0 && (this->scaleMax < this->scaleMin)){
771        DUCHAMPWARN("Reading Parameters","Reconstruction scaleMax ("<<this->scaleMax<<") is less than scaleMin ("<<this->scaleMin<<"): setting both to "<<this->scaleMin);
772        this->scaleMax = this->scaleMin;
773      }
774
775      if( (this->reconDim < 1) || (this->reconDim > 3) ){
776        DUCHAMPWARN("Reading Parameters", "You requested a " << this->reconDim << " dimensional reconstruction. Setting reconDim to 1");
777        this->reconDim = 1;
778      }
779
780      if( this->snrRecon < 0.){
781        DUCHAMPWARN("Reading Parameters", "Your snrRecon value is negative (" << this->snrRecon<<"). Turning reconstruction off -- fix your parameter file!");
782        this->flagATrous = false;
783      }
784
785    }
786
787    if(this->flagUserThreshold){
788
789      // If we specify a manual threshold, need to also specify a manual growth threshold
790      // If we haven't done so, turn growing off
791      if(this->flagGrowth && !this->flagUserGrowthThreshold){
792        DUCHAMPWARN("Reading parameters","You have specified a manual search threshold, but not a manual growth threshold. You need to do so using the \"growthThreshold\" parameter.");
793        DUCHAMPWARN("Reading parameters","The growth function is being turned off.");
794        this->flagGrowth = false;
795      }
796
797      // If we specify a manual threshold, we don't need the FDR method, so turn it off if requested.
798      if(this->flagFDR){
799        DUCHAMPWARN("Reading parameters","You have specified a manual search threshold, so we don't need to use the FDR method. Setting \"flagFDR=false\".");
800        this->flagFDR = false;
801      }
802
803    }   
804
805    // Make sure the growth level is less than the detection level. Else turn off growing.
806    if(this->flagGrowth){
807      std::stringstream errmsg;
808      bool doWarn = false;
809      if(this->flagUserThreshold &&
810         ( (this->threshold < this->growthThreshold)
811           || (this->snrCut < this->growthCut) ) ){
812        errmsg << "Your \"growthThreshold\" parameter" << this->growthThreshold <<" is larger than your \"threshold\"" << this->threshold;
813        doWarn = true;
814      }
815     
816      if(!this->flagUserThreshold &&
817         (this->snrCut < this->growthCut)) {
818        errmsg << "Your \"growthCut\" parameter " << this->growthCut << " is larger than your \"snrCut\"" << this->snrCut;
819        doWarn = true;
820      }
821
822      if(doWarn){
823        DUCHAMPWARN("Reading parameters",errmsg);
824        DUCHAMPWARN("Reading parameters","The growth function is being turned off.");
825
826      }
827    }
828
829    // Make sure the annnotationType is an acceptable option -- default is "borders"
830    if((this->annotationType != "borders") && (this->annotationType!="circles") && (this->annotationType!="ellipses")){
831      DUCHAMPWARN("Reading parameters","The requested value of the parameter annotationType, \"" << this->annotationType << "\", is invalid -- changing to \"borders\".");
832      this->annotationType = "borders";
833    }
834     
835    // Make sure smoothType is an acceptable type -- default is "spectral"
836    if((this->smoothType!="spectral")&&
837       (this->smoothType!="spatial")){
838      DUCHAMPWARN("Reading parameters","The requested value of the parameter smoothType, \"" << this->smoothType << "\", is invalid -- changing to \"spectral\".");
839      this->smoothType = "spectral";
840    }
841    // If kernMin has not been given, or is negative, make it equal to kernMaj
842    if(this->kernMin < 0) this->kernMin = this->kernMaj;
843
844    // Make sure spectralMethod is an acceptable type -- default is "peak"
845    if((this->spectralMethod!="peak")&&
846       (this->spectralMethod!="sum")){
847      DUCHAMPWARN("Reading parameters","The requested value of the parameter spectralMethod, \"" << this->spectralMethod << "\", is invalid -- changing to \"peak\".");
848      this->spectralMethod = "peak";
849    }
850
851    // make sure pixelCentre is an acceptable type -- default is "peak"
852    if((this->pixelCentre!="centroid")&&
853       (this->pixelCentre!="average") &&
854       (this->pixelCentre!="peak")       ){
855      DUCHAMPWARN("Reading parameters","The requested value of the parameter pixelCentre, \"" << this->pixelCentre << "\", is invalid -- changing to \"centroid\".");
856      this->pixelCentre = "centroid";
857    }
858
859    // Make sure sortingParam is an acceptable type -- default is "vel"
860    bool OK = false;
861    int loc=(this->sortingParam[0]=='-') ? 1 : 0;
862    for(int i=0;i<numSortingParamOptions;i++)
863      OK = OK || this->sortingParam.substr(loc)==sortingParamOptions[i];
864    if(!OK){
865      DUCHAMPWARN("Reading parameters","The requested value of the parameter sortingParam, \"" << this->sortingParam << "\", is invalid. -- changing to \"vel\".");
866      this->sortingParam = "vel";
867    }
868
869    // Make sure minVoxels is appropriate given minChannels & minPixels
870    if(this->minVoxels < (this->minPix + this->minChannels - 1) ){
871      DUCHAMPWARN("Reading parameters","Changing minVoxels to " << this->minPix + this->minChannels - 1 << " given minPix="<<this->minPix << " and minChannels="<<this->minChannels);
872      this->minVoxels = this->minPix + this->minChannels - 1;
873    }
874     
875  }
876
877  OUTCOME Param::checkImageExists()
878  {
879    /// A simple check to see whether the image actually exists or not, using the cfitsio interface.
880    /// If it does, we return SUCCESS, otherwise we throw an exception.
881
882    int exists,status = 0;  /* MUST initialize status */
883    fits_file_exists(this->imageFile.c_str(),&exists,&status);
884    if(exists<=0){
885      fits_report_error(stderr, status);
886      DUCHAMPTHROW("Cube Reader","Requested image " << this->imageFile << " does not exist!");
887      return FAILURE;
888    }
889    return SUCCESS;
890  }
891
892
893  void recordParameters(std::ostream& theStream, Param &par, std::string paramName, std::string paramDesc, std::string paramValue)
894  {
895   
896    const int width = 60;
897    int widthText = width - paramName.size();
898
899    theStream << par.commentString()
900              << std::setw(widthText) << paramDesc
901              << setiosflags(std::ios::right) << paramName
902              << "  =  " << resetiosflags(std::ios::right) << paramValue
903              <<std::endl;
904  }
905
906  std::string fileOption(bool flag, std::string file)
907  {
908    std::ostringstream ss;
909    ss << stringize(flag);
910    if(flag) ss << " --> " << file;
911    return ss.str();
912   
913  }
914
915  std::ostream& operator<< ( std::ostream& theStream, Param& par)
916  {
917    /// Print out the parameter set in a formatted, easy to read style.
918    /// Lists the parameters, a description of them, and their value.
919
920    // BUG -- can get error: `boolalpha' is not a member of type `ios' -- old compilers: gcc 2.95.3?
921    //   theStream.setf(std::ios::boolalpha);
922    theStream.setf(std::ios::left);
923    theStream  <<par.commentString()<<"\n"<<par.commentString()<<"---- Parameters ----"<<std::endl;
924    theStream  << std::setfill('.');
925    if(par.getFlagSubsection())
926      recordParam(theStream, par, "[imageFile]", "Image to be analysed", par.getImageFile()<<par.getSubsection());
927    else
928      recordParam(theStream, par, "[imageFile]", "Image to be analysed", par.getImageFile());
929    if(par.getFlagRestFrequencyUsed()){
930      recordParam(theStream, par, "[restFrequency]","Rest frequency as used", par.getRestFrequency());
931    }
932    if(par.getFlagReconExists() && par.getFlagATrous()){
933      recordParam(theStream, par, "[reconExists]", "Reconstructed array exists?", stringize(par.getFlagReconExists()));
934      recordParam(theStream, par, "[reconFile]", "FITS file containing reconstruction", par.getReconFile());
935    }
936    if(par.getFlagSmoothExists() && par.getFlagSmooth()){
937      recordParam(theStream, par, "[smoothExists]", "Smoothed array exists?", stringize(par.getFlagSmoothExists()));
938      recordParam(theStream, par, "[smoothFile]", "FITS file containing smoothed array", par.getSmoothFile());
939    }
940    recordParam(theStream, par, "[logFile]", "Intermediate Logfile", par.logFile);
941    recordParam(theStream, par, "[outFile]", "Final Results file", par.getOutFile());
942    if(par.getFlagSeparateHeader()){
943      recordParam(theStream, par, "[headerFile]", "Header for results file", par.getHeaderFile());
944    }
945    if(USE_PGPLOT && par.getFlagPlotSpectra()){
946      recordParam(theStream, par, "[spectraFile]", "Spectrum file", par.getSpectraFile());
947    }
948    if(par.getFlagTextSpectra()){
949      recordParam(theStream, par, "[spectraTextFile]", "Text file with ascii spectral data", par.getSpectraTextFile());
950    }
951    if(par.getFlagVOT()){
952      recordParam(theStream, par, "[votFile]", "VOTable file", par.getVOTFile());
953    }
954    if(par.getFlagKarma()){
955      recordParam(theStream, par, "[karmaFile]", "Karma annotation file" , par.getKarmaFile());
956    }
957    if(par.getFlagDS9()){
958      recordParam(theStream, par, "[ds9File]", "DS9 annotation file" , par.getDS9File());
959    }
960    if(par.getFlagCasa()){
961      recordParam(theStream, par, "[casaFile]", "CASA annotation file" , par.getCasaFile());
962    }
963    if(USE_PGPLOT && par.getFlagMaps()){
964      recordParam(theStream, par, "[momentMap]", "0th Moment Map", par.getMomentMap());
965      recordParam(theStream, par, "[detectionMap]", "Detection Map", par.getDetectionMap());
966    }
967    if(USE_PGPLOT){
968      recordParam(theStream, par, "[flagXOutput]", "Display a map in a pgplot xwindow?", stringize(par.getFlagXOutput()));
969    }
970    if(par.getFlagATrous()){
971      recordParam(theStream, par, "[flagOutputRecon]", "Saving reconstructed cube?", fileOption(par.getFlagOutputRecon(),par.outputReconFile()));
972      recordParam(theStream, par, "[flagOutputResid]", "Saving residuals from reconstruction?", fileOption(par.getFlagOutputResid(),par.outputResidFile()));
973    }                                                 
974    if(par.getFlagSmooth()){   
975      recordParam(theStream, par, "[flagOutputSmooth]", "Saving smoothed cube?", fileOption(par.getFlagOutputSmooth(),par.outputSmoothFile()));
976    }                                                 
977    recordParam(theStream, par, "[flagOutputMask]", "Saving mask cube?", fileOption(par.getFlagOutputMask(),par.outputMaskFile()));
978    recordParam(theStream, par, "[flagOutputMomentMap]", "Saving 0th moment to FITS file?", fileOption(par.getFlagOutputMomentMap(),par.outputMomentMapFile()));
979    recordParam(theStream, par, "[flagOutputMomentMask]", "Saving 0th moment mask to FITS file?", fileOption(par.getFlagOutputMomentMask(),par.outputMomentMaskFile()));
980    recordParam(theStream, par, "[flagOutputBaseline]", "Saving baseline values to FITS file?", fileOption(par.getFlagOutputBaseline(),par.outputBaselineFile()));
981
982    theStream  << par.commentString() <<"------"<<std::endl;
983
984    recordParam(theStream, par, "[searchType]", "Type of searching performed", par.getSearchType());
985    if(par.getFlagBlankPix()){
986      recordParam(theStream, par, "", "Blank Pixel Value", par.getBlankPixVal());
987    }
988    recordParam(theStream, par, "[flagTrim]", "Trimming Blank Pixels?", stringize(par.getFlagTrim()));
989    recordParam(theStream, par, "[flagNegative]", "Searching for Negative features?", stringize(par.getFlagNegative()));
990    recordParam(theStream, par, "[flagMW]", "Removing Milky Way channels?", stringize(par.getFlagMW()));
991    if(par.getFlagMW()){
992      // need to remove the offset correction, as we want to report the parameters actually entered
993      recordParam(theStream, par, "[minMW - maxMW]", "Milky Way Channels", par.getMinMW()+par.getZOffset()<<"-"<<par.getMaxMW()+par.getZOffset());
994    }
995    if(par.beamAsUsed.origin()==EMPTY){  // No beam in FITS file and no information provided
996      recordParam(theStream, par, "", "Area of Beam", "No beam");
997    }
998    else if(par.beamAsUsed.origin()==HEADER){ // Report beam size from FITS file
999      recordParam(theStream, par, "", "Area of Beam (pixels)", par.beamAsUsed.area() << "   (beam: " << par.beamAsUsed.maj() << " x " << par.beamAsUsed.min() <<" pixels)");
1000    }
1001    else if(par.beamAsUsed.origin()==PARAM){ // Report beam size requested in parameter set input
1002      if(par.fwhmBeam>0.) recordParam(theStream, par, "[beamFWHM]", "FWHM of Beam (pixels)", par.beamAsUsed.maj() << "   (beam area = " << par.beamAsUsed.area() <<" pixels)");
1003      else  recordParam(theStream, par, "[beamArea]", "Area of Beam (pixels)", par.beamAsUsed.area());
1004    }
1005    else{
1006      recordParam(theStream, par, "[beam info]", "Size & shape of beam", "No information available!");
1007    }
1008    recordParam(theStream, par, "[flagBaseline]", "Removing baselines before search?", stringize(par.getFlagBaseline()));
1009    recordParam(theStream, par, "[flagSmooth]", "Smoothing data prior to searching?", stringize(par.getFlagSmooth()));
1010    if(par.getFlagSmooth()){           
1011      recordParam(theStream, par, "[smoothType]", "Type of smoothing", par.getSmoothType());
1012      if(par.getSmoothType()=="spectral")
1013        recordParam(theStream, par, "[hanningWidth]", "Width of hanning filter", par.getHanningWidth());
1014      else{
1015        recordParam(theStream, par, "[kernMaj]", "Gaussian kernel semi-major axis [pix]", par.getKernMaj());
1016        recordParam(theStream, par, "[kernMin]", "Gaussian kernel semi-minor axis [pix]", par.getKernMin());
1017        recordParam(theStream, par, "[kernPA]",  "Gaussian kernel position angle [deg]",  par.getKernPA());
1018      }
1019    }
1020    recordParam(theStream, par, "[flagATrous]", "Using A Trous reconstruction?", stringize(par.getFlagATrous()));
1021    if(par.getFlagATrous()){                           
1022      recordParam(theStream, par, "[reconDim]", "Number of dimensions in reconstruction", par.getReconDim());
1023      if(par.getMaxScale()>0){
1024        recordParam(theStream, par, "[scaleMin-scaleMax]", "Scales used in reconstruction", par.getMinScale()<<"-"<<par.getMaxScale());
1025      }
1026      else{
1027        recordParam(theStream, par, "[scaleMin]", "Minimum scale in reconstruction", par.getMinScale());
1028      }
1029      recordParam(theStream, par, "[snrRecon]", "SNR Threshold within reconstruction", par.getAtrousCut());
1030      recordParam(theStream, par, "[reconConvergence]", "Residual convergence criterion", par.getReconConvergence());
1031      recordParam(theStream, par, "[filterCode]", "Filter being used for reconstruction", par.getFilterCode()<<" ("<<par.getFilterName()<<")");
1032    }                                                 
1033    recordParam(theStream, par, "[flagRobustStats]", "Using Robust statistics?", stringize(par.getFlagRobustStats()));
1034    if(par.getFlagStatSec()){
1035      recordParam(theStream, par, "[statSec]", "Section used by statistics calculation", par.statSec.getSection());
1036    }
1037    recordParam(theStream, par, "[flagFDR]", "Using FDR analysis?", stringize(par.getFlagFDR()));
1038    if(par.getFlagFDR()){                                     
1039      recordParam(theStream, par, "[alphaFDR]", "Alpha value for FDR analysis", par.getAlpha());
1040      recordParam(theStream, par, "[FDRnumCorChan]", "Number of correlated channels for FDR", par.getFDRnumCorChan());
1041    }                                                 
1042    else {
1043      if(par.getFlagUserThreshold()){
1044        recordParam(theStream, par, "[threshold]", "Detection Threshold", par.getThreshold());
1045      }
1046      else{
1047        recordParam(theStream, par, "[snrCut]", "SNR Threshold (in sigma)", par.getCut());
1048      }
1049    }
1050    recordParam(theStream, par, "[minPix]", "Minimum # Pixels in a detection", par.getMinPix());
1051    recordParam(theStream, par, "[minChannels]", "Minimum # Channels in a detection", par.getMinChannels());
1052    recordParam(theStream, par, "[minVoxels]", "Minimum # Voxels in a detection", par.getMinVoxels());
1053    recordParam(theStream, par, "[flagGrowth]", "Growing objects after detection?", stringize(par.getFlagGrowth()));
1054    if(par.getFlagGrowth()) {                         
1055      if(par.getFlagUserGrowthThreshold()){
1056        recordParam(theStream, par, "[growthThreshold]", "Threshold for growth", par.getGrowthThreshold());
1057      }
1058      else{
1059        recordParam(theStream, par, "[growthCut]", "SNR Threshold for growth", par.getGrowthCut());
1060      }
1061    }
1062    recordParam(theStream, par, "[flagAdjacent]", "Using Adjacent-pixel criterion?", stringize(par.getFlagAdjacent()));
1063    if(!par.getFlagAdjacent()){
1064      recordParam(theStream, par, "[threshSpatial]", "Max. spatial separation for merging", par.getThreshS());
1065    }
1066    recordParam(theStream, par, "[threshVelocity]", "Max. velocity separation for merging", par.getThreshV());
1067    recordParam(theStream, par, "[flagRejectBeforeMerge]", "Reject objects before merging?", stringize(par.getFlagRejectBeforeMerge()));
1068    recordParam(theStream, par, "[flagTwoStageMerging]", "Merge objects in two stages?", stringize(par.getFlagTwoStageMerging()));
1069    recordParam(theStream, par, "[spectralMethod]", "Method of spectral plotting", par.getSpectralMethod());
1070    recordParam(theStream, par, "[pixelCentre]", "Type of object centre used in results", par.getPixelCentre());
1071
1072    theStream  << par.commentString() <<"--------------------\n";
1073    theStream  << std::setfill(' ');
1074    theStream.unsetf(std::ios::left);
1075    //  theStream.unsetf(std::ios::boolalpha);
1076    return theStream;
1077  }
1078
1079  std::vector<VOParam> Param::getVOParams()
1080  {
1081    std::vector<VOParam> vopars;
1082    vopars.push_back(VOParam("imageFile","meta.file;meta.fits","char",this->imageFile,this->imageFile.size(),""));
1083    vopars.push_back(VOParam("flagSubsection","meta.code","boolean",this->flagSubsection,0,""));
1084    if(this->flagSubsection)
1085      vopars.push_back(VOParam("subsection","","char",this->pixelSec.getSection(),this->pixelSec.getSection().size(),""));
1086    vopars.push_back(VOParam("flagStatSec","meta.code","boolean",this->flagStatSec,0,""));
1087    if(this->flagSubsection)
1088      vopars.push_back(VOParam("StatSec","","char",this->statSec.getSection(),this->statSec.getSection().size(),""));
1089    if(this->flagReconExists)
1090      vopars.push_back(VOParam("reconfile","meta.file;meta.fits","char",this->reconFile, this->reconFile.size(),""));
1091    if(this->flagSmoothExists)
1092      vopars.push_back(VOParam("smoothfile","meta.file;meta.fits","char",this->smoothFile, this->smoothFile.size(),""));
1093    if(this->usePrevious)
1094      vopars.push_back(VOParam("objectlist","","char",this->objectList,this->objectList.size(),""));
1095
1096    vopars.push_back(VOParam("searchType","meta.note","char",this->searchType,this->searchType.size(),""));
1097    vopars.push_back(VOParam("flagNegative","meta.code","boolean",this->flagNegative,0,""));
1098    vopars.push_back(VOParam("flagBaseline","meta.code","boolean",this->flagBaseline,0,""));
1099    vopars.push_back(VOParam("flagRobustStats","meta.code","boolean",this->flagRobustStats,0,""));
1100    vopars.push_back(VOParam("flagFDR","meta.code","boolean",this->flagFDR,0,""));
1101    if(this->flagFDR){
1102      vopars.push_back(VOParam("alphaFDR","stat.param","float",this->alphaFDR,0,""));
1103      vopars.push_back(VOParam("FDRnumCorChan","stat.param","int",this->FDRnumCorChan,0,""));
1104    }
1105    else{
1106      if(this->flagUserThreshold)
1107            vopars.push_back(VOParam("threshold","phot.flux;stat.min","float",this->threshold,0,""));
1108      else
1109        vopars.push_back(VOParam("snrCut","stat.snr;phot;stat.min","float",this->snrCut,0,""));
1110    }
1111    vopars.push_back(VOParam("flagGrowth","meta.code","boolean",this->flagGrowth,0,""));
1112    if(this->flagGrowth){
1113      if(this->flagUserGrowthThreshold)
1114        vopars.push_back(VOParam("growthThreshold","phot.flux;stat.min","float",this->growthThreshold,0,""));
1115      else
1116        vopars.push_back(VOParam("growthCut","stat.snr;phot;stat.min","float",this->growthCut,0,""));
1117    }
1118    vopars.push_back(VOParam("minVoxels","","int",minVoxels,0,""));
1119    vopars.push_back(VOParam("minPix","","int",minPix,0,""));
1120    vopars.push_back(VOParam("minChannels","","int",minChannels,0,""));
1121    vopars.push_back(VOParam("flagAdjacent","meta.code","boolean",this->flagAdjacent,0,""));
1122    if(!this->flagAdjacent)
1123      vopars.push_back(VOParam("threshSpatial","","float",this->threshSpatial,0,""));
1124    vopars.push_back(VOParam("threshVelocity","","float",this->threshSpatial,0,""));
1125    vopars.push_back(VOParam("flagRejectBeforeMerge","","boolean",this->flagRejectBeforeMerge,0,""));
1126    vopars.push_back(VOParam("flagTwoStageMerging","","boolean",this->flagTwoStageMerging,0,""));
1127    vopars.push_back(VOParam("pixelCentre","","char",this->pixelCentre,this->pixelCentre.size(),""));
1128    vopars.push_back(VOParam("flagSmooth","meta.code","boolean",this->flagSmooth,0,""));
1129    if(this->flagSmooth){
1130      vopars.push_back(VOParam("smoothType","","char",this->smoothType,this->smoothType.size(),""));
1131      if(this->smoothType=="spectral")
1132        vopars.push_back(VOParam("hanningWidth","","int",this->hanningWidth,0,""));
1133      else{
1134        vopars.push_back(VOParam("kernMaj","","float",this->kernMaj,0,""));
1135        vopars.push_back(VOParam("kernMin","","float",this->kernMin,0,""));
1136        vopars.push_back(VOParam("kernPA","","float",this->kernPA,0,""));
1137      }
1138    }
1139    vopars.push_back(VOParam("flagATrous","meta.code","boolean",this->flagATrous,0,""));
1140    if(this->flagATrous){
1141      vopars.push_back(VOParam("reconDim","","int",this->reconDim,0,""));
1142      vopars.push_back(VOParam("scaleMin","","int",this->scaleMin,0,""));
1143      if(this->scaleMax>0)
1144        vopars.push_back(VOParam("scaleMax","","int",this->scaleMax,0,""));
1145      vopars.push_back(VOParam("snrRecon","","float",this->snrRecon,0,""));
1146      vopars.push_back(VOParam("reconConvergence","","float",this->reconConvergence,0,""));
1147      vopars.push_back(VOParam("filterCode","","int",this->filterCode,0,""));
1148    }
1149    if(this->beamAsUsed.origin()==PARAM){
1150      if(this->fwhmBeam>0)
1151        vopars.push_back(VOParam("beamFWHM","","float",this->fwhmBeam,0,""));
1152      else
1153        vopars.push_back(VOParam("beamArea","","float",this->areaBeam,0,""));
1154    }
1155    if(this->restFrequencyUsed){
1156      vopars.push_back(VOParam("restFrequency","em.freq","float",this->restFrequency,0,"Hz"));
1157    }
1158
1159    return vopars;
1160
1161  }
1162
1163
1164
1165  void Param::copyHeaderInfo(FitsHeader &head)
1166  {
1167    ///  A function to copy across relevant header keywords from the
1168    ///  FitsHeader class to the Param class, as they are needed by
1169    ///  functions in the Param class.
1170    ///  The parameters are the keywords BLANK, BSCALE, BZERO, and the beam size.
1171
1172    this->blankKeyword  = head.getBlankKeyword();
1173    this->bscaleKeyword = head.getBscaleKeyword();
1174    this->bzeroKeyword  = head.getBzeroKeyword();
1175    this->blankPixValue = this->blankKeyword * this->bscaleKeyword +
1176      this->bzeroKeyword;
1177  }
1178
1179  std::string Param::outputMaskFile()
1180  {
1181    ///  This function produces the required filename in which to save
1182    ///  the mask image, indicating which pixels have been detected as
1183    ///  part of an object. If the input image is image.fits, then the
1184    ///  output will be image.MASK.fits.
1185
1186    if(this->fileOutputMask==""){
1187      std::string inputName = this->imageFile;
1188      std::string outputName = inputName;
1189      if(inputName.substr(inputName.size()-5,5)==".fits")
1190        outputName = inputName.substr(0,inputName.size()-5); 
1191      // remove the ".fits" on the end.
1192      outputName += ".MASK.fits";
1193      return outputName;
1194    }
1195    else return this->fileOutputMask;
1196  }
1197
1198  std::string Param::outputMomentMapFile()
1199  {
1200    ///  This function produces the required filename in which to save
1201    ///  the moment-0 FITS image. If the input image is image.fits, then the
1202    ///  output will be image.MOM0.fits.
1203
1204    if(this->fileOutputMomentMap==""){
1205      std::string inputName = this->imageFile;
1206      std::string outputName = inputName;
1207      if(inputName.substr(inputName.size()-5,5)==".fits")
1208        outputName = inputName.substr(0,inputName.size()-5); 
1209      // remove the ".fits" on the end.
1210      outputName += ".MOM0.fits";
1211      return outputName;
1212    }
1213    else return this->fileOutputMomentMap;
1214  }
1215
1216  std::string Param::outputMomentMaskFile()
1217  {
1218    ///  This function produces the required filename in which to save
1219    ///  the moment-0 FITS image. If the input image is image.fits, then the
1220    ///  output will be image.MOM0.fits.
1221
1222    if(this->fileOutputMomentMask==""){
1223      std::string inputName = this->imageFile;
1224      std::string outputName = inputName;
1225      if(inputName.substr(inputName.size()-5,5)==".fits")
1226        outputName = inputName.substr(0,inputName.size()-5); 
1227      // remove the ".fits" on the end.
1228      outputName += ".MOM0MASK.fits";
1229      return outputName;
1230    }
1231    else return this->fileOutputMomentMask;
1232  }
1233
1234  std::string Param::outputBaselineFile()
1235  {
1236    ///  This function produces the required filename in which to save
1237    ///  the baseline FITS image. If the input image is image.fits, then the
1238    ///  output will be image.BASE.fits.
1239
1240    if(this->fileOutputBaseline==""){
1241      std::string inputName = this->imageFile;
1242      std::string outputName = inputName;
1243      if(inputName.substr(inputName.size()-5,5)==".fits")
1244        outputName = inputName.substr(0,inputName.size()-5); 
1245      // remove the ".fits" on the end.
1246      outputName += ".BASE.fits";
1247      return outputName;
1248    }
1249    else return this->fileOutputBaseline;
1250  }
1251
1252  std::string Param::outputSmoothFile()
1253  {
1254    ///  This function produces the required filename in which to save
1255    ///   the smoothed array. If the input image is image.fits, then
1256    ///   the output will be:
1257    ///    <ul><li> Spectral smoothing: image.SMOOTH-1D-3.fits, where the
1258    ///             width of the Hanning filter was 3 pixels.
1259    ///        <li> Spatial smoothing : image.SMOOTH-2D-3-2-20.fits, where
1260    ///             kernMaj=3, kernMin=2 and kernPA=20 degrees.
1261    ///    </ul>
1262
1263    if(this->fileOutputSmooth==""){
1264      std::string inputName = this->imageFile;
1265      std::stringstream ss;
1266      if(inputName.substr(inputName.size()-5,5)==".fits")
1267        ss << inputName.substr(0,inputName.size()-5); 
1268      else
1269        ss << inputName;
1270      // remove the ".fits" on the end if necessary.
1271      if(this->flagSubsection) ss<<".sub";
1272      if(this->smoothType=="spectral")
1273        ss << ".SMOOTH-1D-" << this->hanningWidth << ".fits";
1274      else if(this->smoothType=="spatial")
1275        ss << ".SMOOTH-2D-"
1276           << this->kernMaj << "-"
1277           << this->kernMin << "-"
1278           << this->kernPA  << ".fits";
1279      return ss.str();
1280    }
1281    else return this->fileOutputSmooth;
1282  }
1283
1284  std::string Param::outputReconFile()
1285  {
1286    /// This function produces the required filename in which to save
1287    ///  the reconstructed array. If the input image is image.fits, then
1288    ///  the output will be eg. image.RECON-3-2-4-1.fits, where the numbers are
1289    ///  3=reconDim, 2=filterCode, 4=snrRecon, 1=minScale
1290
1291    if(this->fileOutputRecon==""){
1292      std::string inputName = this->imageFile;
1293      std::stringstream ss;
1294      // First we remove the ".fits" from the end of the filename.
1295      ss << inputName.substr(0,inputName.size()-5); 
1296      if(this->flagSubsection) ss<<".sub";
1297      ss << ".RECON-" << this->reconDim
1298         << "-"       << this->filterCode
1299         << "-"       << this->snrRecon
1300         << "-"       << this->scaleMin
1301         << "-"       << this->scaleMax
1302         << "-"       << this->reconConvergence
1303         << ".fits";
1304      return ss.str();
1305    }
1306    else return this->fileOutputRecon;
1307  }
1308
1309  std::string Param::outputResidFile()
1310  {
1311    /// This function produces the required filename in which to save
1312    ///  the reconstructed array. If the input image is image.fits, then
1313    ///  the output will be eg. image.RESID-3-2-4-1.fits, where the numbers are
1314    ///  3=reconDim, 2=filterCode, 4=snrRecon, 1=scaleMin
1315
1316    if(this->fileOutputResid==""){
1317      std::string inputName = this->imageFile;
1318      std::stringstream ss;
1319      // First we remove the ".fits" from the end of the filename.
1320      ss << inputName.substr(0,inputName.size()-5);
1321      if(this->flagSubsection) ss<<".sub";
1322      ss << ".RESID-" << this->reconDim
1323         << "-"       << this->filterCode
1324         << "-"       << this->snrRecon
1325         << "-"       << this->scaleMin
1326         << "-"       << this->scaleMax
1327         << "-"       << this->reconConvergence
1328         << ".fits";
1329      return ss.str();
1330    }
1331    else return this->fileOutputResid;
1332  }
1333
1334}
Note: See TracBrowser for help on using the repository browser.