source: branches/OptimisedGrowerTesting/src/param.cc @ 1441

Last change on this file since 1441 was 1342, checked in by MatthewWhiting, 10 years ago

Initial commit of the code for #204. Porting the OptimisedGrower? from the ASKAP/Selavy code, getting it to build, and implementing as a separate growing step in Merger.cc. Still to test.

File size: 75.6 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/ATrous/FilterFactory.hh>
44#include <duchamp/Utils/utils.hh>
45#include <duchamp/Utils/Section.hh>
46#include <duchamp/Utils/VOParam.hh>
47#include <duchamp/Outputs/columns.hh>
48
49namespace duchamp
50{
51  const std::string defaultSection = "[*,*,*]";
52
53  /****************************************************************/
54  ///////////////////////////////////////////////////
55  //// Accessor Functions for Parameter class:
56  ///////////////////////////////////////////////////
57  Param::~Param()
58  {
59    /// Deletes the offsets array if the sizeOffsets parameter is
60    /// positive.
61    if(this->sizeOffsets>0) delete [] this->offsets;
62  }
63
64  Param::Param()
65  {
66    this->defaultValues();
67  }
68
69  void Param::defaultValues()
70  {
71    /// Provides default intial values for the parameters. Note that
72    /// imageFile has no default value!
73
74    // Input files
75    this->imageFile         = "";
76    this->flagSubsection    = false;
77    this->pixelSec          = Section();
78    this->flagReconExists   = false;
79    this->reconFile         = "";
80    this->flagSmoothExists  = false;
81    this->smoothFile        = "";
82    this->usePrevious       = false;
83    this->objectList        = "";
84    // Output files
85    this->flagLog           = false;
86    this->logFile           = "duchamp-Logfile.txt";
87    this->outFile           = "duchamp-Results.txt";
88    this->flagSeparateHeader= false;
89    this->headerFile        = "duchamp-Results.hdr";
90    this->flagWriteBinaryCatalogue = true;
91    this->binaryCatalogue   = "duchamp-Catalogue.dpc";
92    this->flagPlotSpectra   = true;
93    this->spectraFile       = "duchamp-Spectra.ps";
94    this->flagPlotIndividualSpectra = false;
95    this->flagTextSpectra   = false;
96    this->spectraTextFile   = "duchamp-Spectra.txt";
97    this->flagOutputBaseline    = false;
98    this->fileOutputBaseline    = "";
99    this->flagOutputMomentMap    = false;
100    this->fileOutputMomentMap    = "";
101    this->flagOutputMomentMask    = false;
102    this->fileOutputMomentMask    = "";
103    this->flagOutputMask    = false;
104    this->fileOutputMask    = "";
105    this->flagMaskWithObjectNum = false;
106    this->flagOutputSmooth  = false;
107    this->fileOutputSmooth  = "";
108    this->flagOutputRecon   = false;
109    this->fileOutputRecon   = "";
110    this->flagOutputResid   = false;
111    this->fileOutputResid   = "";
112    this->flagVOT           = false;
113    this->votFile           = "duchamp-Results.xml";
114    this->flagKarma         = false;
115    this->karmaFile         = "duchamp-Results.ann";
116    this->flagDS9           = false;
117    this->ds9File           = "duchamp-Results.reg";
118    this->flagCasa          = false;
119    this->casaFile          = "duchamp-Results.crf";
120    this->annotationType    = "borders";
121    this->flagMaps          = true;
122    this->detectionMap      = "duchamp-DetectionMap.ps";
123    this->momentMap         = "duchamp-MomentMap.ps";
124    this->flagXOutput       = true;
125    this->precFlux          = Catalogues::prFLUX;
126    this->precVel           = Catalogues::prVEL;
127    this->precSNR           = Catalogues::prSNR;
128    // Cube related parameters
129    this->flagBlankPix      = false;
130    this->blankPixValue     = -8.00061;
131    this->blankKeyword      = 1;
132    this->bscaleKeyword     = -8.00061;
133    this->bzeroKeyword      = 0.;
134    this->newFluxUnits      = "";
135    // Flagged channel parameters
136    this->flaggedChannelList = "";
137    this->flaggedChannels   = std::vector<int>();
138    this->flaggedChannelMask= std::vector<bool>();
139    // Beam
140    this->areaBeam          = 0.;
141    this->fwhmBeam          = 0.;
142    this->beamAsUsed.empty();
143    this->searchType        = "spatial";
144    // Trim-related         
145    this->flagTrim          = false;
146    this->hasBeenTrimmed    = false;
147    this->borderLeft        = 0;
148    this->borderRight       = 0;
149    this->borderBottom      = 0;
150    this->borderTop         = 0;
151    // Subsection offsets
152    this->sizeOffsets       = 0;
153    this->xSubOffset        = 0;
154    this->ySubOffset        = 0;
155    this->zSubOffset        = 0;
156    // Baseline related
157    this->flagBaseline      = false;
158    this->baselineType      = "atrous";
159    this->baselineBoxWidth  = 51;
160    // Detection-related   
161    this->flagNegative      = false;
162    // Object growth       
163    this->flagGrowth        = false;
164    this->growthCut         = 3.;
165    this->flagUserGrowthThreshold = false;
166    this->growthThreshold   = 0.;
167    this->flagOptimisedGrower = false;
168    this->flagClobberPrevious = true;
169    this->maxGrowingIter    = 10;
170    // FDR analysis         
171    this->flagFDR           = false;
172    this->alphaFDR          = 0.01;
173    this->FDRnumCorChan     = 2;
174    // Other detection     
175    this->flagStatSec       = false;
176    this->statSec           = Section();
177    this->flagRobustStats   = true;
178    this->snrCut            = 5.;
179    this->threshold         = 0.;
180    this->flagUserThreshold = false;
181    // Smoothing
182    this->flagSmooth        = false;
183    this->smoothType        = "spectral";
184    this->hanningWidth      = 5;
185    this->kernMaj           = 3.;
186    this->kernMin           = -1.;
187    this->kernPA            = 0.;
188    this->smoothEdgeMethod  = "equal";
189    this->spatialSmoothCutoff = 1.e-10;
190    // A trous reconstruction parameters
191    this->flagATrous        = false;
192    this->reconDim          = 1;
193    this->scaleMin          = 1;
194    this->scaleMax          = 0;
195    this->snrRecon          = 4.;
196    this->reconConvergence  = 0.005;
197    this->filterCode        = 1;
198//    this->reconFilter.define(this->filterCode);
199    this->reconFilter = 0;
200    // Volume-merging parameters
201    this->flagAdjacent      = true;
202    this->threshSpatial     = 3.;
203    this->threshVelocity    = 7.;
204    this->minChannels       = 3;
205    this->minPix            = 2;
206    this->minVoxels         = 4;
207    this->maxChannels       = -1;
208    this->maxPix            = -1;
209    this->maxVoxels         = -1;
210    this->flagRejectBeforeMerge = false;
211    this->flagTwoStageMerging = true;
212    // Input-Output related
213    this->spectralMethod    = "peak";
214    this->spectralType      = "";
215    this->restFrequency     = -1.;
216    this->restFrequencyUsed = false;
217    this->spectralUnits     = "";
218    this->pixelCentre       = "centroid";
219    this->sortingParam      = "vel";
220    this->borders           = true;
221    this->blankEdge         = true;
222    this->verbose           = true;
223    this->commentStr        = "";
224  }
225
226  Param::Param (const Param& p)
227  {
228    operator=(p);
229  }
230
231  Param& Param::operator= (const Param& p)
232  {
233    if(this == &p) return *this;
234    this->imageFile         = p.imageFile;
235    this->flagSubsection    = p.flagSubsection;
236    this->pixelSec          = p.pixelSec;
237    this->flagReconExists   = p.flagReconExists;
238    this->reconFile         = p.reconFile;     
239    this->flagSmoothExists  = p.flagSmoothExists;
240    this->smoothFile        = p.smoothFile;     
241    this->usePrevious       = p.usePrevious;
242    this->objectList        = p.objectList;
243    this->flagLog           = p.flagLog;       
244    this->logFile           = p.logFile;       
245    this->outFile           = p.outFile;       
246    this->flagSeparateHeader= p.flagSeparateHeader;
247    this->headerFile        = p.headerFile;
248    this->flagWriteBinaryCatalogue = p.flagWriteBinaryCatalogue;
249    this->binaryCatalogue   = p.binaryCatalogue;
250    this->flagPlotSpectra   = p.flagPlotSpectra;
251    this->spectraFile       = p.spectraFile;   
252    this->flagPlotIndividualSpectra = p.flagPlotIndividualSpectra;
253    this->flagTextSpectra   = p.flagTextSpectra;   
254    this->spectraTextFile   = p.spectraTextFile;   
255    this->flagOutputBaseline    = p.flagOutputBaseline;
256    this->fileOutputBaseline    = p.fileOutputBaseline;
257    this->flagOutputMomentMap    = p.flagOutputMomentMap;
258    this->fileOutputMomentMap    = p.fileOutputMomentMap;
259    this->flagOutputMomentMask   = p.flagOutputMomentMask;
260    this->fileOutputMomentMask   = p.fileOutputMomentMask;
261    this->flagOutputMask    = p.flagOutputMask;
262    this->fileOutputMask    = p.fileOutputMask;
263    this->flagMaskWithObjectNum = p.flagMaskWithObjectNum;
264    this->flagOutputSmooth  = p.flagOutputSmooth;
265    this->fileOutputSmooth  = p.fileOutputSmooth;
266    this->flagOutputRecon   = p.flagOutputRecon;
267    this->fileOutputRecon   = p.fileOutputRecon;
268    this->flagOutputResid   = p.flagOutputResid;
269    this->fileOutputResid   = p.fileOutputResid;
270    this->flagVOT           = p.flagVOT;         
271    this->votFile           = p.votFile;       
272    this->flagKarma         = p.flagKarma;     
273    this->karmaFile         = p.karmaFile;     
274    this->flagDS9           = p.flagDS9;     
275    this->ds9File           = p.ds9File;     
276    this->flagCasa          = p.flagCasa;     
277    this->casaFile          = p.casaFile;     
278    this->annotationType    = p.annotationType;
279    this->flagMaps          = p.flagMaps;       
280    this->detectionMap      = p.detectionMap;   
281    this->momentMap         = p.momentMap;     
282    this->flagXOutput       = p.flagXOutput;       
283    this->precFlux          = p.precFlux;
284    this->precVel           = p.precVel;
285    this->precSNR           = p.precSNR;
286    this->flagNegative      = p.flagNegative;
287    this->flagBlankPix      = p.flagBlankPix;   
288    this->blankPixValue     = p.blankPixValue; 
289    this->blankKeyword      = p.blankKeyword;   
290    this->bscaleKeyword     = p.bscaleKeyword; 
291    this->bzeroKeyword      = p.bzeroKeyword;   
292    this->newFluxUnits      = p.newFluxUnits;
293    this->flaggedChannelList = p.flaggedChannelList;
294    this->flaggedChannels   = p.flaggedChannels;
295    this->flaggedChannelMask= p.flaggedChannelMask;
296    this->areaBeam          = p.areaBeam;     
297    this->fwhmBeam          = p.fwhmBeam;     
298    this->beamAsUsed        = p.beamAsUsed;
299    this->searchType        = p.searchType;
300    this->flagTrim          = p.flagTrim;   
301    this->hasBeenTrimmed    = p.hasBeenTrimmed;   
302    this->borderLeft        = p.borderLeft;     
303    this->borderRight       = p.borderRight;   
304    this->borderBottom      = p.borderBottom;   
305    this->borderTop         = p.borderTop;     
306    if(this->sizeOffsets>0) delete [] this->offsets;
307    this->sizeOffsets       = p.sizeOffsets;
308    if(this->sizeOffsets>0){
309      this->offsets           = new long[this->sizeOffsets];
310      for(int i=0;i<this->sizeOffsets;i++) this->offsets[i] = p.offsets[i];
311    }
312    this->xSubOffset        = p.xSubOffset;     
313    this->ySubOffset        = p.ySubOffset;     
314    this->zSubOffset        = p.zSubOffset;
315    this->flagBaseline      = p.flagBaseline;
316    this->baselineType      = p.baselineType;
317    this->baselineBoxWidth  = p.baselineBoxWidth;
318    this->flagGrowth        = p.flagGrowth;
319    this->growthCut         = p.growthCut;
320    this->growthThreshold   = p.growthThreshold;
321    this->flagUserGrowthThreshold = p.flagUserGrowthThreshold;
322    this->flagOptimisedGrower = p.flagOptimisedGrower;
323    this->flagClobberPrevious = p.flagClobberPrevious;
324    this->maxGrowingIter    = p.maxGrowingIter;
325    this->flagFDR           = p.flagFDR;
326    this->alphaFDR          = p.alphaFDR;
327    this->FDRnumCorChan     = p.FDRnumCorChan;
328    this->flagStatSec       = p.flagStatSec;
329    this->statSec           = p.statSec;
330    this->flagRobustStats   = p.flagRobustStats;
331    this->snrCut            = p.snrCut;
332    this->threshold         = p.threshold;
333    this->flagUserThreshold = p.flagUserThreshold;
334    this->flagSmooth        = p.flagSmooth;
335    this->smoothType        = p.smoothType;
336    this->hanningWidth      = p.hanningWidth;
337    this->kernMaj           = p.kernMaj;
338    this->kernMin           = p.kernMin;
339    this->kernPA            = p.kernPA;
340    this->smoothEdgeMethod  = p.smoothEdgeMethod;
341    this->spatialSmoothCutoff = p.spatialSmoothCutoff;
342    this->flagATrous        = p.flagATrous;
343    this->reconDim          = p.reconDim;
344    this->scaleMin          = p.scaleMin;
345    this->scaleMax          = p.scaleMax;
346    this->snrRecon          = p.snrRecon;
347    this->reconConvergence  = p.reconConvergence;
348    this->filterCode        = p.filterCode;
349    this->reconFilter       = p.reconFilter;
350    this->flagAdjacent      = p.flagAdjacent;
351    this->threshSpatial     = p.threshSpatial;
352    this->threshVelocity    = p.threshVelocity;
353    this->minChannels       = p.minChannels;
354    this->minPix            = p.minPix;
355    this->minVoxels         = p.minVoxels;
356    this->maxChannels       = p.maxChannels;
357    this->maxPix            = p.maxPix;
358    this->maxVoxels         = p.maxVoxels;
359    this->flagRejectBeforeMerge = p.flagRejectBeforeMerge;
360    this->flagTwoStageMerging = p.flagTwoStageMerging;
361    this->spectralMethod    = p.spectralMethod;
362    this->spectralType      = p.spectralType;
363    this->restFrequency     = p.restFrequency;
364    this->restFrequencyUsed = p.restFrequencyUsed;
365    this->spectralUnits     = p.spectralUnits;
366    this->pixelCentre       = p.pixelCentre;
367    this->sortingParam      = p.sortingParam;
368    this->borders           = p.borders;
369    this->blankEdge         = p.blankEdge;
370    this->verbose           = p.verbose;
371    this->commentStr        = p.commentStr;
372    return *this;
373  }
374  //--------------------------------------------------------------------
375
376  OUTCOME Param::getopts(int argc, char ** argv, std::string progname)
377  {
378    ///   A function that reads in the command-line options, in a manner
379    ///    tailored for use with the main Duchamp program.
380    ///
381    ///   \param argc The number of command line arguments.
382    ///   \param argv The array of command line arguments.
383
384    OUTCOME returnValue = FAILURE;
385    if(argc==1){
386      std::cout << ERR_USAGE_MSG;
387      returnValue = FAILURE;
388    }
389    else {
390      std::string file;
391      float thresh;
392      bool changeX = false, changeThresh=false;
393      this->defaultValues();
394      char c;
395      while( ( c = getopt(argc,argv,"p:f:t:hvx") )!=-1){
396        switch(c) {
397        case 'p':
398          file = optarg;
399          if(this->readParams(file)==FAILURE){
400            DUCHAMPERROR(progname,"Could not open parameter file " << file);
401          }
402          else returnValue = SUCCESS;
403          break;
404        case 'f':
405          file = optarg;
406          this->imageFile = file;
407          returnValue = SUCCESS;
408          break;
409        case 'v':
410          std::cout << PROGNAME << " version " << VERSION << std::endl;
411          break;
412        case 'x':
413          changeX = true;
414          break;
415        case 't':
416          thresh = atof(optarg);
417          changeThresh = true;
418          break;
419        case 'h':
420        default :
421          std::cout << ERR_USAGE_MSG;
422          break;
423        }
424      }
425      if(changeX){
426        if(returnValue == SUCCESS) this->setFlagXOutput(false);
427        else {
428          DUCHAMPERROR(progname, "You need to specify either a parameter file or FITS image.\n");
429          std::cout << "\n" << ERR_USAGE_MSG;
430        }
431      }
432      if(changeThresh){
433        this->threshold = thresh;
434        this->flagUserThreshold = true;
435        this->checkPars();
436      }
437    }
438    return returnValue;
439  }
440  //--------------------------------------------------------------------
441
442  bool Param::isBlank(float &value)
443  {
444    ///  Tests whether the value passed as the argument is BLANK or not.
445    ///  \param value Pixel value to be tested.
446    ///  \return False if flagBlankPix is false. Else, compare to the
447    ///  relevant FITS keywords, using integer comparison.
448
449    return this->flagBlankPix &&
450      (this->blankKeyword == int((value-this->bzeroKeyword)/this->bscaleKeyword));
451  }
452
453  bool *Param::makeBlankMask(float *array, size_t size)
454  {
455    ///  This returns an array of bools, saying whether each pixel in the
456    ///  given array is BLANK or not. If the pixel is BLANK, set mask to
457    ///  false, else set to true. The array is allocated by the function.
458
459    bool *mask = new bool[size];
460    for(size_t i=0;i<size;i++) mask[i] = !this->isBlank(array[i]);
461    return mask;
462  }
463
464
465  bool *Param::makeStatMask(float *array, size_t *dim)
466  {
467    ///  This returns an array of bools, saying whether each pixel in
468    ///  the given array is suitable for a stats calculation. It needs
469    ///  to be in the StatSec (if defined), not blank and not a flagged
470    ///  channel. The array is allocated by the function with a 'new' call.
471
472    bool *mask = new bool[dim[0]*dim[1]*dim[2]];
473    std::vector<bool> flaggedChans = this->getChannelFlags(dim[2]);
474    for(size_t x=0;x<dim[0];x++) {
475      for(size_t y=0;y<dim[1];y++) {
476        for(size_t z=0;z<dim[2];z++) {
477          size_t i = x+y*dim[0]+z*dim[0]*dim[1];
478          mask[i] = !this->isBlank(array[i]) && !flaggedChans[z] && this->isStatOK(x,y,z);
479        }
480      }
481    }
482    return mask;
483  }
484
485    bool Param::isFlaggedChannel(int z)
486    {
487        /// Tests whether a given channel has been flagged by the user
488
489        // bool isFlagged=false;
490        // for(size_t i=0;i<this->flaggedChannels.size()&&!isFlagged;i++)
491        //     isFlagged=(z==this->flaggedChannels[i]);
492        // return isFlagged;
493
494        if(this->flaggedChannelMask.size()==0) return false;
495        else if(z>int(this->flaggedChannelMask.size()) || z<0) return false;
496        else return this->flaggedChannelMask[z];
497
498    }
499
500    std::vector<bool> Param::getChannelFlags(int numChannels)
501    {
502
503        std::vector<bool> flags(numChannels,false);
504        for(std::vector<int>::iterator chan = this->flaggedChannels.begin(); chan!=this->flaggedChannels.end(); chan++){
505            // channels are zero-based, but channel-specification is 1-based
506            if(*chan<=numChannels && *chan>-1) flags[*chan-1] = true;
507        }
508        return flags;
509    }
510
511
512  bool Param::isStatOK(int x, int y, int z)
513  {
514    /// Test whether a given pixel position lies within the subsection
515    /// given by the statSec parameter. Only tested if the flagSubsection
516    /// parameter is true -- if it isn't, we just return true since all
517    /// pixels are therefore available for statstical calculations.
518    /// \param x X-value of pixel being tested.
519    /// \param y Y-value of pixel being tested.
520    /// \param z Z-value of pixel being tested.
521    /// \return True if pixel is able to be used for statistical
522    /// calculations. False otherwise.
523
524    int xval=x,yval=y,zval=z;
525    if(flagSubsection){
526      xval += pixelSec.getStart(0);
527      yval += pixelSec.getStart(1);
528      zval += pixelSec.getStart(2);
529    }
530    return !flagStatSec || statSec.isInside(xval,yval,zval);
531  }
532
533  std::vector<bool> Param::getObjectChoices()
534  {
535    ///  Returns a list of bool values, indicating whether a given
536    ///  object was requested or not. The size of the vector is
537    ///  determined by the maximum value in objectList. For instance,
538    ///  if objectList="2,3,5-8", then the returned vector will be
539    ///  [0,1,1,0,1,1,1,1].
540    ///  \return Vector of bool values.
541
542      if(this->objectListVector.size()==0) return std::vector<bool>(0);
543      else {
544          int maxNum = *std::max_element(this->objectListVector.begin(), this->objectListVector.end());
545          std::vector<bool> choices(maxNum,false);
546          for(std::vector<int>::iterator obj = objectListVector.begin();obj!=objectListVector.end();obj++)
547              choices[*obj-1] = true;
548          return choices;
549      }
550  }
551
552  std::vector<bool> Param::getObjectChoices(int numObjects)
553  {
554    ///  Returns a list of bool values, indicating whether a given
555    ///  object was requested or not. The size of the vector is given
556    ///  by the numObjects parameter. So, if objectList="2,3,5-8", then
557    ///  the returned vector from a getObjectChoices(10) call will be
558    ///  [0,1,1,0,1,1,1,1,0,0].
559    ///  \param numObjects How many objects there are in total.
560    ///  \return Vector of bool values.
561
562    if(this->objectList==""){
563      std::vector<bool> choices(numObjects,true);
564      return choices;
565    }
566    else{
567      std::vector<bool> choices(numObjects,false);
568      std::vector<int> duds,goodlist;
569      for(std::vector<int>::iterator obj = this->objectListVector.begin();obj!=this->objectListVector.end();obj++){
570          if(*obj<=numObjects) {
571              choices[*obj-1] = true;
572              goodlist.push_back(*obj);
573          }
574          else duds.push_back(*obj);
575      }
576      if(duds.size()>0){
577          this->objectListVector = goodlist;
578          std::stringstream dudlist;
579          dudlist << duds[0];
580          for(size_t i=1;i<duds.size();i++) dudlist << ","<<duds[i];
581          std::string obj="object";
582          if(duds.size()>1) obj+= "s";
583          DUCHAMPWARN("Object Selection", "You have only detected " << numObjects << " objects, so the requested "
584                      << obj << " '" << dudlist.str() << "' cannot be returned. Please check your request, as it doesn't match the results.");
585      }
586      return choices;
587    }
588
589  }
590
591  /****************************************************************/
592  /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ///
593  /// / Other Functions using the  Parameter class:
594  /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ///
595
596  OUTCOME Param::readParams(std::string paramfile)
597  {
598    /// The parameters are read in from a disk file, on the assumption that each
599    ///  line of the file has the format "parameter value" (eg. alphafdr 0.1)
600    ///
601    /// The case of the parameter name does not matter, nor does the
602    /// formatting of the spaces (it can be any amount of whitespace or
603    /// tabs).
604    ///
605    /// \param paramfile A std::string containing the parameter filename.
606    ///
607    /// \return FAILURE if the parameter file does not exist. SUCCESS if
608    /// it is able to read it.
609
610    if(!USE_PGPLOT){
611      // Change default values for these parameters when we don't use PGPlot
612      this->flagXOutput = false;
613      this->flagMaps = false;
614      this->flagPlotSpectra = false;
615    }
616
617    std::ifstream fin(paramfile.c_str());
618    if(!fin.is_open()) return FAILURE;
619    std::string line;
620    while( !std::getline(fin,line,'\n').eof()){
621
622      if(line[0]!='#'){
623        std::stringstream ss;
624        ss.str(line);
625        std::string arg;
626        ss >> arg;
627        arg = makelower(arg);
628        if(arg=="imagefile")       this->imageFile = readFilename(ss);
629        if(arg=="flagsubsection")  this->flagSubsection = readFlag(ss);
630        if(arg=="subsection")      this->pixelSec.setSection(readSval(ss));
631        if(arg=="flagreconexists") this->flagReconExists = readFlag(ss);
632        if(arg=="reconfile")       this->reconFile = readSval(ss);
633        if(arg=="flagsmoothexists")this->flagSmoothExists = readFlag(ss);
634        if(arg=="smoothfile")      this->smoothFile = readSval(ss);
635        if(arg=="beamarea")        this->areaBeam = readFval(ss);
636        if(arg=="beamfwhm")        this->fwhmBeam = readFval(ss);
637        if(arg=="useprevious")     this->usePrevious = readFlag(ss);
638        if(arg=="objectlist")      this->objectList = readSval(ss);
639
640        if(arg=="flaglog")         this->flagLog = readFlag(ss);
641        if(arg=="logfile")         this->logFile = readSval(ss);
642        if(arg=="outfile")         this->outFile = readSval(ss);
643        if(arg=="flagseparateheader") this->flagSeparateHeader = readFlag(ss);
644        if(arg=="headerfile")      this->headerFile = readFilename(ss);
645        if(arg=="flagwritebinarycatalogue") this->flagWriteBinaryCatalogue = readFlag(ss);
646        if(arg=="binarycatalogue") this->binaryCatalogue = readFilename(ss);
647        if(arg=="flagplotspectra") this->flagPlotSpectra = readFlag(ss);
648        if(arg=="spectrafile")     this->spectraFile = readFilename(ss);
649        if(arg=="flagplotindividualspectra") this->flagPlotIndividualSpectra = readFlag(ss);
650        if(arg=="flagtextspectra") this->flagTextSpectra = readFlag(ss);
651        if(arg=="spectratextfile") this->spectraTextFile = readFilename(ss);
652        if(arg=="flagoutputbaseline")  this->flagOutputBaseline = readFlag(ss);
653        if(arg=="fileoutputbaseline")  this->fileOutputBaseline = readFilename(ss);
654        if(arg=="flagoutputmomentmap")  this->flagOutputMomentMap = readFlag(ss);
655        if(arg=="fileoutputmomentmap")  this->fileOutputMomentMap = readFilename(ss);
656        if(arg=="flagoutputmomentmask")  this->flagOutputMomentMask = readFlag(ss);
657        if(arg=="fileoutputmomentmask")  this->fileOutputMomentMask = readFilename(ss);
658        if(arg=="flagoutputmask")  this->flagOutputMask = readFlag(ss);
659        if(arg=="fileoutputmask")  this->fileOutputMask = readFilename(ss);
660        if(arg=="flagmaskwithobjectnum") this->flagMaskWithObjectNum = readFlag(ss);
661        if(arg=="flagoutputsmooth")this->flagOutputSmooth = readFlag(ss);
662        if(arg=="fileoutputsmooth")this->fileOutputSmooth = readFilename(ss);
663        if(arg=="flagoutputrecon") this->flagOutputRecon = readFlag(ss);
664        if(arg=="fileoutputrecon") this->fileOutputRecon = readFilename(ss);
665        if(arg=="flagoutputresid") this->flagOutputResid = readFlag(ss);
666        if(arg=="fileoutputresid") this->fileOutputResid = readFilename(ss);
667        if(arg=="flagvot")         this->flagVOT = readFlag(ss);
668        if(arg=="votfile")         this->votFile = readFilename(ss);
669        if(arg=="flagkarma")       this->flagKarma = readFlag(ss);
670        if(arg=="karmafile")       this->karmaFile = readFilename(ss);
671        if(arg=="flagds9")         this->flagDS9 = readFlag(ss);
672        if(arg=="ds9file")         this->ds9File = readFilename(ss);
673        if(arg=="flagcasa")        this->flagCasa = readFlag(ss);
674        if(arg=="casafile")        this->casaFile = readFilename(ss);
675        if(arg=="annotationtype")  this->annotationType = readSval(ss);
676        if(arg=="flagmaps")        this->flagMaps = readFlag(ss);
677        if(arg=="detectionmap")    this->detectionMap = readFilename(ss);
678        if(arg=="momentmap")       this->momentMap = readFilename(ss);
679        if(arg=="flagxoutput")     this->flagXOutput = readFlag(ss);
680        if(arg=="newfluxunits")    this->newFluxUnits = readSval(ss);
681        if(arg=="precflux")        this->precFlux = readIval(ss);
682        if(arg=="precvel")         this->precVel = readIval(ss);
683        if(arg=="precsnr")         this->precSNR = readIval(ss);
684
685        if(arg=="flagtrim")        this->flagTrim = readFlag(ss);
686        if(arg=="flaggedchannels") this->flaggedChannelList = readSval(ss);
687        if(arg=="flagbaseline")    this->flagBaseline = readFlag(ss);
688        if(arg=="baselinetype")    this->baselineType = readSval(ss);
689        if(arg=="baselineboxwidth") this->baselineBoxWidth = readIval(ss);
690        if(arg=="searchtype")      this->searchType = readSval(ss);
691
692        if(arg=="flagnegative")    this->flagNegative = readFlag(ss);
693        if(arg=="flaggrowth")      this->flagGrowth = readFlag(ss);
694        if(arg=="growthcut")       this->growthCut = readFval(ss);
695        if(arg=="growththreshold"){
696          this->growthThreshold = readFval(ss);
697          this->flagUserGrowthThreshold = true;
698        }
699        if(arg=="flagoptimisedgrower") this->flagOptimisedGrower = readFlag(ss);
700        if(arg=="flagclobberprevious") this->flagClobberPrevious = readFlag(ss);
701        if(arg=="maxgrowingiter")  this->maxGrowingIter = readIval(ss);
702
703        if(arg=="flagfdr")         this->flagFDR = readFlag(ss);
704        if(arg=="alphafdr")        this->alphaFDR = readFval(ss);
705        if(arg=="fdrnumcorchan")   this->FDRnumCorChan = readIval(ss);
706        if(arg=="flagstatsec")     this->flagStatSec = readFlag(ss);
707        if(arg=="statsec")         this->statSec.setSection(readSval(ss));
708        if(arg=="flagrobuststats") this->flagRobustStats = readFlag(ss);
709        if(arg=="snrcut")          this->snrCut = readFval(ss);
710        if(arg=="threshold"){
711          this->threshold = readFval(ss);
712          this->flagUserThreshold = true;
713        }
714     
715        if(arg=="flagsmooth")      this->flagSmooth = readFlag(ss);
716        if(arg=="smoothtype")      this->smoothType = readSval(ss);
717        if(arg=="hanningwidth")    this->hanningWidth = readIval(ss);
718        if(arg=="kernmaj")         this->kernMaj = readFval(ss);
719        if(arg=="kernmin")         this->kernMin = readFval(ss);
720        if(arg=="kernpa")          this->kernPA = readFval(ss);
721        if(arg=="smoothedgemethod") this->smoothEdgeMethod = readSval(ss);
722        if(arg=="spatialsmoothcutoff") this->spatialSmoothCutoff = readFval(ss);
723
724        if(arg=="flagatrous")      this->flagATrous = readFlag(ss);
725        if(arg=="recondim")        this->reconDim = readIval(ss);
726        if(arg=="scalemin")        this->scaleMin = readIval(ss);
727        if(arg=="scalemax")        this->scaleMax = readIval(ss);
728        if(arg=="snrrecon")        this->snrRecon = readFval(ss);
729        if(arg=="reconconvergence") this->reconConvergence = readFval(ss);
730        if(arg=="filtercode")      this->filterCode = readIval(ss);
731
732        if(arg=="flagadjacent")    this->flagAdjacent = readFlag(ss);
733        if(arg=="threshspatial")   this->threshSpatial = readFval(ss);
734        if(arg=="threshvelocity")  this->threshVelocity = readFval(ss);
735        if(arg=="minpix")          this->minPix = readIval(ss);
736        if(arg=="minchannels")     this->minChannels = readIval(ss);
737        if(arg=="minvoxels")       this->minVoxels = readIval(ss);
738        if(arg=="maxpix")          this->maxPix = readIval(ss);
739        if(arg=="maxchannels")     this->maxChannels = readIval(ss);
740        if(arg=="maxvoxels")       this->maxVoxels = readIval(ss);
741        if(arg=="flagrejectbeforemerge") this->flagRejectBeforeMerge = readFlag(ss);
742        if(arg=="flagtwostagemerging") this->flagTwoStageMerging = readFlag(ss);
743
744        if(arg=="spectralmethod")  this->spectralMethod=makelower(readSval(ss));
745        if(arg=="spectraltype")    this->spectralType = readSval(ss);
746        if(arg=="restfrequency")   this->restFrequency = readFval(ss);
747        if(arg=="spectralunits")   this->spectralUnits = readSval(ss);
748        if(arg=="pixelcentre")     this->pixelCentre = makelower(readSval(ss));
749        if(arg=="sortingparam")    this->sortingParam = makelower(readSval(ss));
750        if(arg=="drawborders")     this->borders = readFlag(ss);
751        if(arg=="drawblankedges")  this->blankEdge = readFlag(ss);
752        if(arg=="verbose")         this->verbose = readFlag(ss);
753
754        // Dealing with deprecated parameters.
755        if(arg=="flagblankpix"){
756          this->flagTrim = readFlag(ss);
757          DUCHAMPWARN("Reading parameters","The parameter flagBlankPix is deprecated. Please use the flagTrim parameter in future.");
758          DUCHAMPWARN("Reading parameters","   Setting flagTrim = " << stringize(this->flagTrim));
759        }
760        if(arg=="blankpixvalue"){
761          DUCHAMPWARN("Reading parameters","The parameter blankPixValue is deprecated. This value is only taken from the FITS header.");
762        }
763        if(arg=="beamsize"){
764          this->areaBeam = readFval(ss);
765          DUCHAMPWARN("Reading parameters","The parameter beamSize is deprecated. You can specify the beam size by beamArea or beamFWHM.");
766          DUCHAMPWARN("Reading parameters","   Setting beamArea = " << this->areaBeam);
767        }
768        if(arg=="flagmw"){
769            DUCHAMPWARN("Reading parameters", "The parameters flagMW, minMW and maxMW have been deprecated.");
770            DUCHAMPWARN("Reading parameters", "   Instead, use the parameter flaggedChannels to indicate channels & channel ranges to be excluded from detection.");
771        }
772      }
773    }
774
775    this->checkPars();
776
777    return SUCCESS;
778
779  }
780 
781  void Param::checkPars()
782  {
783
784    // If flagSubsection is false, but the parset had a subsection string in it, we want to set this back to the default.
785    if(!this->flagSubsection){
786      this->pixelSec.setSection(defaultSection);
787    }
788    if(!this->flagStatSec){
789      this->statSec.setSection(defaultSection);
790    }
791
792    // If we have usePrevious=false, set the objectlist to blank so that we use all of them. Otherwise, define the vector list of choices.
793    if(!this->usePrevious) this->objectList = "";
794    else this->objectListVector = selectionToIntVec(this->objectList);
795
796    // Defining the vector list of flagged channels
797    if(this->flaggedChannelList.size()>0){
798        this->flaggedChannels = selectionToIntVec(this->flaggedChannelList);
799        this->flaggedChannelMask = std::vector<bool>(*std::max_element(this->flaggedChannels.begin(),this->flaggedChannels.end()),false);
800        for(size_t i=0;i<this->flaggedChannels.size();i++) this->flaggedChannelMask[ this->flaggedChannels[i] ] = true;
801    }
802
803    // If pgplot was not included in the compilation, need to set flagXOutput to false
804    if(!USE_PGPLOT){
805      if(this->flagXOutput || this->flagMaps || this->flagPlotSpectra || this->flagPlotIndividualSpectra)
806        DUCHAMPWARN("Reading parameters","PGPlot has not been enabled, so setting flagXOutput, flagMaps, flagPlotSpectra and flagPlotIndividualSpectra to false.");
807      this->flagXOutput = false;
808      this->flagMaps = false;
809      this->flagPlotSpectra = false;
810      this->flagPlotIndividualSpectra = false;
811    }
812
813    if(!this->flagPlotSpectra && this->flagPlotIndividualSpectra){
814      DUCHAMPWARN("Reading parameters","flagPlotSpectra is false, so setting flagPlotIndividualSpectra to false as well.");
815      this->flagPlotIndividualSpectra = false;
816    }
817
818    // Correcting bad precision values -- if negative, set to 0
819    if(this->precFlux<0) this->precFlux = 0;
820    if(this->precVel<0)  this->precVel = 0;
821    if(this->precSNR<0)  this->precSNR = 0;
822
823    // Can only have "spatial" or "spectral" as search types
824    if(this->searchType != "spatial" && this->searchType != "spectral"){
825      DUCHAMPWARN("Reading parameters","You have requested a search type of \""<<this->searchType<<"\" -- Only \"spectral\" and \"spatial\" are accepted, so setting to \"spatial\".");
826      this->searchType = "spatial";
827    }
828
829    // The wavelet reconstruction takes precendence over the smoothing.
830    if(this->flagATrous) this->flagSmooth = false;
831
832    // Check validity of recon parameters
833    if(this->flagATrous){
834      if(this->reconConvergence < 0.){
835        DUCHAMPWARN("Reading Parameters","Your reconConvergence value is negative ("<<this->reconConvergence<<") - setting to " << -this->reconConvergence <<".");
836        this->reconConvergence *= -1.;
837      }
838
839//      this->reconFilter.define(this->filterCode);
840      FilterFactory filtFac;
841      this->reconFilter = filtFac.getFilter(this->filterCode);
842
843      if((this->scaleMax) > 0 && (this->scaleMax < this->scaleMin)){
844        DUCHAMPWARN("Reading Parameters","Reconstruction scaleMax ("<<this->scaleMax<<") is less than scaleMin ("<<this->scaleMin<<"): setting both to "<<this->scaleMin);
845        this->scaleMax = this->scaleMin;
846      }
847
848      if( (this->reconDim < 1) || (this->reconDim > 3) ){
849        DUCHAMPWARN("Reading Parameters", "You requested a " << this->reconDim << " dimensional reconstruction. Setting reconDim to 1");
850        this->reconDim = 1;
851      }
852
853      if( this->snrRecon < 0.){
854        DUCHAMPWARN("Reading Parameters", "Your snrRecon value is negative (" << this->snrRecon<<"). Turning reconstruction off -- fix your parameter file!");
855        this->flagATrous = false;
856      }
857
858    }
859
860    // Check validity of smoothing parameters
861    if(this->flagSmooth){
862       
863        // Make sure smoothType is an acceptable type -- default is "spectral"
864        if((this->smoothType!="spectral")&&
865           (this->smoothType!="spatial")){
866            DUCHAMPWARN("Reading parameters","The requested value of the parameter smoothType, \"" << this->smoothType << "\", is invalid -- changing to \"spectral\".");
867            this->smoothType = "spectral";
868        }
869
870        // If kernMin has not been given, or is negative, make it equal to kernMaj
871        if(this->kernMin < 0) this->kernMin = this->kernMaj;
872       
873        // Check the smoothEdgeMethod and spatialSmoothCutoff parameters.
874        if(this->smoothType=="spatial"){
875            if((this->smoothEdgeMethod != "equal") && (this->smoothEdgeMethod!="truncate") && (this->smoothEdgeMethod!="scale")){
876                DUCHAMPWARN("Reading parameters","The requested value of the parameter smoothEdgeMethod, \""<< this->smoothEdgeMethod << "\", is invalid - changing to \"equal\".");
877                this->smoothEdgeMethod = "equal";
878            }
879            if(this->spatialSmoothCutoff<0.){
880                this->spatialSmoothCutoff *= -1.;
881                DUCHAMPWARN("Reading parameters","The value of spatialSmoothCutoff is negative. Changing to "<<this->spatialSmoothCutoff);
882            }
883        }
884
885    }
886
887    if(this->flagUserThreshold){
888
889      // If we specify a manual threshold, need to also specify a manual growth threshold
890      // If we haven't done so, turn growing off
891      if(this->flagGrowth && !this->flagUserGrowthThreshold){
892        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.");
893        DUCHAMPWARN("Reading parameters","The growth function is being turned off.");
894        this->flagGrowth = false;
895      }
896
897      // If we specify a manual threshold, we don't need the FDR method, so turn it off if requested.
898      if(this->flagFDR){
899        DUCHAMPWARN("Reading parameters","You have specified a manual search threshold, so we don't need to use the FDR method. Setting \"flagFDR=false\".");
900        this->flagFDR = false;
901      }
902
903    }   
904
905    // Make sure the growth level is less than the detection level. Else turn off growing.
906    if(this->flagGrowth){
907      std::stringstream errmsg;
908      bool doWarn = false;
909      if(this->flagUserThreshold &&
910         ( (this->threshold < this->growthThreshold)
911           || (this->snrCut < this->growthCut) ) ){
912        errmsg << "Your \"growthThreshold\" parameter" << this->growthThreshold <<" is larger than your \"threshold\"" << this->threshold;
913        doWarn = true;
914      }
915     
916      if(!this->flagUserThreshold &&
917         (this->snrCut < this->growthCut)) {
918        errmsg << "Your \"growthCut\" parameter " << this->growthCut << " is larger than your \"snrCut\"" << this->snrCut;
919        doWarn = true;
920      }
921
922      if(doWarn){
923        DUCHAMPWARN("Reading parameters",errmsg);
924        DUCHAMPWARN("Reading parameters","The growth function is being turned off.");
925
926      }
927    }
928
929    // Make sure the annnotationType is an acceptable option -- default is "borders"
930    if((this->annotationType != "borders") && (this->annotationType!="circles") && (this->annotationType!="ellipses")){
931      DUCHAMPWARN("Reading parameters","The requested value of the parameter annotationType, \"" << this->annotationType << "\", is invalid -- changing to \"borders\".");
932      this->annotationType = "borders";
933    }
934     
935
936    // Make sure spectralMethod is an acceptable type -- default is "peak"
937    if((this->spectralMethod!="peak")&&
938       (this->spectralMethod!="sum")){
939      DUCHAMPWARN("Reading parameters","The requested value of the parameter spectralMethod, \"" << this->spectralMethod << "\", is invalid -- changing to \"peak\".");
940      this->spectralMethod = "peak";
941    }
942
943    // make sure pixelCentre is an acceptable type -- default is "peak"
944    if((this->pixelCentre!="centroid")&&
945       (this->pixelCentre!="average") &&
946       (this->pixelCentre!="peak")       ){
947      DUCHAMPWARN("Reading parameters","The requested value of the parameter pixelCentre, \"" << this->pixelCentre << "\", is invalid -- changing to \"centroid\".");
948      this->pixelCentre = "centroid";
949    }
950
951    // Make sure sortingParam is an acceptable type -- default is "vel"
952    bool OK = false;
953    int loc=(this->sortingParam[0]=='-') ? 1 : 0;
954    for(int i=0;i<numSortingParamOptions;i++)
955      OK = OK || this->sortingParam.substr(loc)==sortingParamOptions[i];
956    if(!OK){
957      DUCHAMPWARN("Reading parameters","The requested value of the parameter sortingParam, \"" << this->sortingParam << "\", is invalid. -- changing to \"vel\".");
958      this->sortingParam = "vel";
959    }
960
961    // Make sure minVoxels is appropriate given minChannels & minPixels
962    if(this->minVoxels < (this->minPix + this->minChannels - 1) ){
963      DUCHAMPWARN("Reading parameters","Changing minVoxels to " << this->minPix + this->minChannels - 1 << " given minPix="<<this->minPix << " and minChannels="<<this->minChannels);
964      this->minVoxels = this->minPix + this->minChannels - 1;
965    }
966   
967    // check that baselines are being calculated if we want to save them to a FITS file
968    if(this->flagOutputBaseline && !this->flagBaseline){
969      DUCHAMPWARN("Reading parameters","Saving of baseline values to a FITS file has been requested, but baselines are not being calculated. Turning off saving of baseline values.");
970      this->flagOutputBaseline = false;
971    }
972
973    // check that the baseline option is valid
974    if(this->flagBaseline){
975        if (this->baselineType != "atrous" && this->baselineType != "median"){
976            DUCHAMPWARN("Reading parameters", "The only types of baseline subtraction available are 'atrous' or 'median' - you provided '"<<this->baselineType <<"'. Setting to 'atrous'.");
977            this->baselineType = "atrous";
978        }
979        if(this->baselineType == "median" && this->baselineBoxWidth%2 == 0){
980            DUCHAMPWARN("Reading parameters", "The baseline box width needs to be odd. Changing from " << this->baselineBoxWidth << " to " << this->baselineBoxWidth+1 <<".");
981            this->baselineBoxWidth++;
982        }
983    }
984     
985  }
986
987  OUTCOME Param::checkImageExists()
988  {
989    /// A simple check to see whether the image actually exists or not, using the cfitsio interface.
990    /// If it does, we return SUCCESS, otherwise we throw an exception.
991
992    int exists,status = 0;  /* MUST initialize status */
993    fits_file_exists(this->imageFile.c_str(),&exists,&status);
994    if(exists<=0){
995      fits_report_error(stderr, status);
996      DUCHAMPTHROW("Cube Reader","Requested image " << this->imageFile << " does not exist!");
997      return FAILURE;
998    }
999    return SUCCESS;
1000  }
1001
1002
1003  void recordParameters(std::ostream& theStream, Param &par, std::string paramName, std::string paramDesc, std::string paramValue)
1004  {
1005   
1006    const int width = 60;
1007    int widthText = width - paramName.size();
1008
1009    theStream << par.commentString()
1010              << std::setw(widthText) << paramDesc
1011              << setiosflags(std::ios::right) << paramName
1012              << "  =  " << resetiosflags(std::ios::right) << paramValue
1013              <<std::endl;
1014  }
1015
1016  std::string fileOption(bool flag, std::string file)
1017  {
1018    std::ostringstream ss;
1019    ss << stringize(flag);
1020    if(flag) ss << " --> " << file;
1021    return ss.str();
1022   
1023  }
1024
1025  std::ostream& operator<< ( std::ostream& theStream, Param& par)
1026  {
1027    /// Print out the parameter set in a formatted, easy to read style.
1028    /// Lists the parameters, a description of them, and their value.
1029
1030    // BUG -- can get error: `boolalpha' is not a member of type `ios' -- old compilers: gcc 2.95.3?
1031    //   theStream.setf(std::ios::boolalpha);
1032    theStream.setf(std::ios::left);
1033    theStream  <<par.commentString()<<"\n"<<par.commentString()<<"---- Parameters ----"<<std::endl;
1034    theStream  << std::setfill('.');
1035    if(par.getFlagSubsection())
1036      recordParam(theStream, par, "[imageFile]", "Image to be analysed", par.getImageFile()<<par.getSubsection());
1037    else
1038      recordParam(theStream, par, "[imageFile]", "Image to be analysed", par.getImageFile());
1039    if(par.getFlagRestFrequencyUsed()){
1040      recordParam(theStream, par, "[restFrequency]","Rest frequency as used", par.getRestFrequency());
1041    }
1042    if(par.getFlagReconExists() && par.getFlagATrous()){
1043      recordParam(theStream, par, "[reconExists]", "Reconstructed array exists?", stringize(par.getFlagReconExists()));
1044      recordParam(theStream, par, "[reconFile]", "FITS file containing reconstruction", par.getReconFile());
1045    }
1046    if(par.getFlagSmoothExists() && par.getFlagSmooth()){
1047      recordParam(theStream, par, "[smoothExists]", "Smoothed array exists?", stringize(par.getFlagSmoothExists()));
1048      recordParam(theStream, par, "[smoothFile]", "FITS file containing smoothed array", par.getSmoothFile());
1049    }
1050    recordParam(theStream, par, "[logFile]", "Intermediate Logfile", par.logFile);
1051    recordParam(theStream, par, "[outFile]", "Final Results file", par.getOutFile());
1052    if(par.getFlagSeparateHeader()){
1053      recordParam(theStream, par, "[headerFile]", "Header for results file", par.getHeaderFile());
1054    }
1055    if(USE_PGPLOT && par.getFlagPlotSpectra()){
1056      std::string label=par.getSpectraFile();
1057      if(par.getFlagPlotIndividualSpectra()) label += ", with individual spectra too";
1058      recordParam(theStream, par, "[spectraFile]", "Spectrum file", label);
1059    }
1060    if(par.getFlagTextSpectra()){
1061      recordParam(theStream, par, "[spectraTextFile]", "Text file with ascii spectral data", par.getSpectraTextFile());
1062    }
1063    if(par.getFlagVOT()){
1064      recordParam(theStream, par, "[votFile]", "VOTable file", par.getVOTFile());
1065    }
1066    if(par.getFlagKarma()){
1067      recordParam(theStream, par, "[karmaFile]", "Karma annotation file" , par.getKarmaFile());
1068    }
1069    if(par.getFlagDS9()){
1070      recordParam(theStream, par, "[ds9File]", "DS9 annotation file" , par.getDS9File());
1071    }
1072    if(par.getFlagCasa()){
1073      recordParam(theStream, par, "[casaFile]", "CASA annotation file" , par.getCasaFile());
1074    }
1075    if(USE_PGPLOT && par.getFlagMaps()){
1076      recordParam(theStream, par, "[momentMap]", "0th Moment Map", par.getMomentMap());
1077      recordParam(theStream, par, "[detectionMap]", "Detection Map", par.getDetectionMap());
1078    }
1079    if(USE_PGPLOT){
1080      recordParam(theStream, par, "[flagXOutput]", "Display a map in a pgplot xwindow?", stringize(par.getFlagXOutput()));
1081    }
1082    if(par.getFlagATrous()){
1083      recordParam(theStream, par, "[flagOutputRecon]", "Saving reconstructed cube?", fileOption(par.getFlagOutputRecon(),par.outputReconFile()));
1084      recordParam(theStream, par, "[flagOutputResid]", "Saving residuals from reconstruction?", fileOption(par.getFlagOutputResid(),par.outputResidFile()));
1085    }                                                 
1086    if(par.getFlagSmooth()){   
1087      recordParam(theStream, par, "[flagOutputSmooth]", "Saving smoothed cube?", fileOption(par.getFlagOutputSmooth(),par.outputSmoothFile()));
1088    }                                                 
1089    recordParam(theStream, par, "[flagOutputMask]", "Saving mask cube?", fileOption(par.getFlagOutputMask(),par.outputMaskFile()));
1090    recordParam(theStream, par, "[flagOutputMomentMap]", "Saving 0th moment to FITS file?", fileOption(par.getFlagOutputMomentMap(),par.outputMomentMapFile()));
1091    recordParam(theStream, par, "[flagOutputMomentMask]", "Saving 0th moment mask to FITS file?", fileOption(par.getFlagOutputMomentMask(),par.outputMomentMaskFile()));
1092    recordParam(theStream, par, "[flagOutputBaseline]", "Saving baseline values to FITS file?", fileOption(par.getFlagOutputBaseline(),par.outputBaselineFile()));
1093
1094    theStream  << par.commentString() <<"------"<<std::endl;
1095
1096    recordParam(theStream, par, "[searchType]", "Type of searching performed", par.getSearchType());
1097    if(par.getFlagBlankPix()){
1098      recordParam(theStream, par, "", "Blank Pixel Value", par.getBlankPixVal());
1099    }
1100    recordParam(theStream, par, "[flagTrim]", "Trimming Blank Pixels?", stringize(par.getFlagTrim()));
1101    recordParam(theStream, par, "[flagNegative]", "Searching for Negative features?", stringize(par.getFlagNegative()));
1102    if(par.getFlaggedChannelList().size()>0){
1103        recordParam(theStream, par, "[flaggedChannels]", "Channels flagged by user", par.getFlaggedChannelList());
1104    }
1105    if(par.beamAsUsed.origin()==EMPTY){  // No beam in FITS file and no information provided
1106      recordParam(theStream, par, "", "Area of Beam", "No beam");
1107    }
1108    else if(par.beamAsUsed.origin()==HEADER){ // Report beam size from FITS file
1109      recordParam(theStream, par, "", "Area of Beam (pixels)", par.beamAsUsed.area() << "   (beam: " << par.beamAsUsed.maj() << " x " << par.beamAsUsed.min() <<" pixels)");
1110    }
1111    else if(par.beamAsUsed.origin()==PARAM){ // Report beam size requested in parameter set input
1112      if(par.fwhmBeam>0.) recordParam(theStream, par, "[beamFWHM]", "FWHM of Beam (pixels)", par.beamAsUsed.maj() << "   (beam area = " << par.beamAsUsed.area() <<" pixels)");
1113      else  recordParam(theStream, par, "[beamArea]", "Area of Beam (pixels)", par.beamAsUsed.area());
1114    }
1115    else{
1116      recordParam(theStream, par, "[beam info]", "Size & shape of beam", "No information available!");
1117    }
1118    recordParam(theStream, par, "[flagBaseline]", "Removing baselines before search?", stringize(par.getFlagBaseline()));
1119    if(par.getFlagBaseline()){
1120        recordParam(theStream, par, "[baselineType]", "Baseline removal algorithm", par.getBaselineType());
1121        if(par.getBaselineType()=="median")
1122            recordParam(theStream, par, "[baselineBoxWidth]", "Box width for median baseline estimation", par.getBaselineBoxWidth());
1123    }
1124    recordParam(theStream, par, "[flagSmooth]", "Smoothing data prior to searching?", stringize(par.getFlagSmooth()));
1125    if(par.getFlagSmooth()){           
1126      recordParam(theStream, par, "[smoothType]", "Type of smoothing", par.getSmoothType());
1127      if(par.getSmoothType()=="spectral")
1128        recordParam(theStream, par, "[hanningWidth]", "Width of hanning filter", par.getHanningWidth());
1129      else{
1130        recordParam(theStream, par, "[kernMaj]", "Gaussian kernel major axis FWHM [pix]", par.getKernMaj());
1131        recordParam(theStream, par, "[kernMin]", "Gaussian kernel minor axis FWHM [pix]", par.getKernMin());
1132        recordParam(theStream, par, "[kernPA]",  "Gaussian kernel position angle [deg]",  par.getKernPA());
1133        recordParam(theStream, par, "[smoothEdgeMethod]","Method for treating edge pixels", par.getSmoothEdgeMethod());
1134        recordParam(theStream, par, "[spatialSmoothCutoff]","Cutoff value for determining kernel", par.getSpatialSmoothCutoff());
1135      }
1136    }
1137    recordParam(theStream, par, "[flagATrous]", "Using A Trous reconstruction?", stringize(par.getFlagATrous()));
1138    if(par.getFlagATrous()){                           
1139      recordParam(theStream, par, "[reconDim]", "Number of dimensions in reconstruction", par.getReconDim());
1140      if(par.getMaxScale()>0){
1141        recordParam(theStream, par, "[scaleMin-scaleMax]", "Scales used in reconstruction", par.getMinScale()<<"-"<<par.getMaxScale());
1142      }
1143      else{
1144        recordParam(theStream, par, "[scaleMin]", "Minimum scale in reconstruction", par.getMinScale());
1145      }
1146      recordParam(theStream, par, "[snrRecon]", "SNR Threshold within reconstruction", par.getAtrousCut());
1147      recordParam(theStream, par, "[reconConvergence]", "Residual convergence criterion", par.getReconConvergence());
1148      recordParam(theStream, par, "[filterCode]", "Filter being used for reconstruction", par.getFilterCode()<<" ("<<par.getFilterName()<<")");
1149    }                                                 
1150    recordParam(theStream, par, "[flagRobustStats]", "Using Robust statistics?", stringize(par.getFlagRobustStats()));
1151    if(par.getFlagStatSec()){
1152      recordParam(theStream, par, "[statSec]", "Section used by statistics calculation", par.statSec.getSection());
1153    }
1154    recordParam(theStream, par, "[flagFDR]", "Using FDR analysis?", stringize(par.getFlagFDR()));
1155    if(par.getFlagFDR()){                                     
1156      recordParam(theStream, par, "[alphaFDR]", "Alpha value for FDR analysis", par.getAlpha());
1157      recordParam(theStream, par, "[FDRnumCorChan]", "Number of correlated channels for FDR", par.getFDRnumCorChan());
1158    }                                                 
1159    else {
1160      if(par.getFlagUserThreshold()){
1161        recordParam(theStream, par, "[threshold]", "Detection Threshold", par.getThreshold());
1162      }
1163      else{
1164        recordParam(theStream, par, "[snrCut]", "SNR Threshold (in sigma)", par.getCut());
1165      }
1166    }
1167    recordParam(theStream, par, "[minPix]", "Minimum # Pixels in a detection", par.getMinPix());
1168    recordParam(theStream, par, "[minChannels]", "Minimum # Channels in a detection", par.getMinChannels());
1169    recordParam(theStream, par, "[minVoxels]", "Minimum # Voxels in a detection", par.getMinVoxels());
1170    if(par.getMaxPix()>0) recordParam(theStream, par, "[maxPix]", "Maximum # Pixels in a detection", par.getMaxPix());
1171    if(par.getMaxChannels()>0) recordParam(theStream, par, "[maxChannels]", "Maximum # Channels in a detection", par.getMaxChannels());
1172    if(par.getMaxVoxels()>0) recordParam(theStream, par, "[maxVoxels]", "Maximum # Voxels in a detection", par.getMaxVoxels());
1173    recordParam(theStream, par, "[flagGrowth]", "Growing objects after detection?", stringize(par.getFlagGrowth()));
1174    if(par.getFlagGrowth()) {                         
1175      if(par.getFlagUserGrowthThreshold()){
1176        recordParam(theStream, par, "[growthThreshold]", "Threshold for growth", par.getGrowthThreshold());
1177      }
1178      else{
1179        recordParam(theStream, par, "[growthCut]", "SNR Threshold for growth", par.getGrowthCut());
1180      }
1181    }
1182    recordParam(theStream, par, "[flagAdjacent]", "Using Adjacent-pixel criterion?", stringize(par.getFlagAdjacent()));
1183    if(!par.getFlagAdjacent()){
1184      recordParam(theStream, par, "[threshSpatial]", "Max. spatial separation for merging", par.getThreshS());
1185    }
1186    recordParam(theStream, par, "[threshVelocity]", "Max. velocity separation for merging", par.getThreshV());
1187    recordParam(theStream, par, "[flagRejectBeforeMerge]", "Reject objects before merging?", stringize(par.getFlagRejectBeforeMerge()));
1188    recordParam(theStream, par, "[flagTwoStageMerging]", "Merge objects in two stages?", stringize(par.getFlagTwoStageMerging()));
1189    recordParam(theStream, par, "[spectralMethod]", "Method of spectral plotting", par.getSpectralMethod());
1190    recordParam(theStream, par, "[pixelCentre]", "Type of object centre used in results", par.getPixelCentre());
1191
1192    theStream  << par.commentString() <<"--------------------\n";
1193    theStream  << std::setfill(' ');
1194    theStream.unsetf(std::ios::left);
1195    //  theStream.unsetf(std::ios::boolalpha);
1196    return theStream;
1197  }
1198
1199  std::vector<VOParam> Param::getVOParams()
1200  {
1201    std::vector<VOParam> vopars;
1202    vopars.push_back(VOParam("imageFile","meta.file;meta.fits","char",this->imageFile,this->imageFile.size(),""));
1203    vopars.push_back(VOParam("flagSubsection","meta.code","boolean",this->flagSubsection,0,""));
1204    if(this->flagSubsection)
1205      vopars.push_back(VOParam("subsection","","char",this->pixelSec.getSection(),this->pixelSec.getSection().size(),""));
1206    vopars.push_back(VOParam("flagStatSec","meta.code","boolean",this->flagStatSec,0,""));
1207    if(this->flagSubsection)
1208      vopars.push_back(VOParam("StatSec","","char",this->statSec.getSection(),this->statSec.getSection().size(),""));
1209    if(this->flagReconExists)
1210      vopars.push_back(VOParam("reconfile","meta.file;meta.fits","char",this->reconFile, this->reconFile.size(),""));
1211    if(this->flagSmoothExists)
1212      vopars.push_back(VOParam("smoothfile","meta.file;meta.fits","char",this->smoothFile, this->smoothFile.size(),""));
1213    if(this->usePrevious)
1214      vopars.push_back(VOParam("objectlist","","char",this->objectList,this->objectList.size(),""));
1215
1216    vopars.push_back(VOParam("searchType","meta.note","char",this->searchType,this->searchType.size(),""));
1217    vopars.push_back(VOParam("flagNegative","meta.code","boolean",this->flagNegative,0,""));
1218    vopars.push_back(VOParam("flagBaseline","meta.code","boolean",this->flagBaseline,0,""));
1219    if(this->flagBaseline){
1220        vopars.push_back(VOParam("baselineType","meta.note","char",this->baselineType,this->baselineType.size(),""));
1221        if(this->baselineType=="median")
1222            vopars.push_back(VOParam("baselineBoxWidth","","int",this->baselineBoxWidth,0,""));
1223    }
1224    vopars.push_back(VOParam("flagRobustStats","meta.code","boolean",this->flagRobustStats,0,""));
1225    vopars.push_back(VOParam("flagFDR","meta.code","boolean",this->flagFDR,0,""));
1226    if(this->flagFDR){
1227      vopars.push_back(VOParam("alphaFDR","stat.param","float",this->alphaFDR,0,""));
1228      vopars.push_back(VOParam("FDRnumCorChan","stat.param","int",this->FDRnumCorChan,0,""));
1229    }
1230    else{
1231      if(this->flagUserThreshold)
1232            vopars.push_back(VOParam("threshold","phot.flux;stat.min","float",this->threshold,0,""));
1233      else
1234        vopars.push_back(VOParam("snrCut","stat.snr;phot;stat.min","float",this->snrCut,0,""));
1235    }
1236    vopars.push_back(VOParam("flagGrowth","meta.code","boolean",this->flagGrowth,0,""));
1237    if(this->flagGrowth){
1238      if(this->flagUserGrowthThreshold)
1239        vopars.push_back(VOParam("growthThreshold","phot.flux;stat.min","float",this->growthThreshold,0,""));
1240      else
1241        vopars.push_back(VOParam("growthCut","stat.snr;phot;stat.min","float",this->growthCut,0,""));
1242    }
1243    vopars.push_back(VOParam("minPix","","int",this->minPix,0,""));
1244    vopars.push_back(VOParam("minChannels","","int",this->minChannels,0,""));
1245    vopars.push_back(VOParam("minVoxels","","int",this->minVoxels,0,""));
1246    if(this->maxPix>0) vopars.push_back(VOParam("maxPix","","int",this->maxPix,0,""));
1247    if(this->maxChannels>0) vopars.push_back(VOParam("maxChannels","","int",this->maxChannels,0,""));
1248    if(this->maxVoxels>0) vopars.push_back(VOParam("maxVoxels","","int",this->maxVoxels,0,""));
1249    vopars.push_back(VOParam("flagAdjacent","meta.code","boolean",this->flagAdjacent,0,""));
1250    if(!this->flagAdjacent)
1251      vopars.push_back(VOParam("threshSpatial","","float",this->threshSpatial,0,""));
1252    vopars.push_back(VOParam("threshVelocity","","float",this->threshVelocity,0,""));
1253    vopars.push_back(VOParam("flagRejectBeforeMerge","","boolean",this->flagRejectBeforeMerge,0,""));
1254    vopars.push_back(VOParam("flagTwoStageMerging","","boolean",this->flagTwoStageMerging,0,""));
1255    vopars.push_back(VOParam("pixelCentre","","char",this->pixelCentre,this->pixelCentre.size(),""));
1256    vopars.push_back(VOParam("flagSmooth","meta.code","boolean",this->flagSmooth,0,""));
1257    if(this->flagSmooth){
1258      vopars.push_back(VOParam("smoothType","","char",this->smoothType,this->smoothType.size(),""));
1259      if(this->smoothType=="spectral")
1260        vopars.push_back(VOParam("hanningWidth","","int",this->hanningWidth,0,""));
1261      else{
1262        vopars.push_back(VOParam("kernMaj","","float",this->kernMaj,0,""));
1263        vopars.push_back(VOParam("kernMin","","float",this->kernMin,0,""));
1264        vopars.push_back(VOParam("kernPA","","float",this->kernPA,0,""));
1265        vopars.push_back(VOParam("smoothEdgeMethod","","char",this->smoothEdgeMethod,this->smoothEdgeMethod.size(),""));
1266        vopars.push_back(VOParam("spatialSmoothCutoff","","float", this->spatialSmoothCutoff,0,""));
1267      }
1268    }
1269    vopars.push_back(VOParam("flagATrous","meta.code","boolean",this->flagATrous,0,""));
1270    if(this->flagATrous){
1271      vopars.push_back(VOParam("reconDim","","int",this->reconDim,0,""));
1272      vopars.push_back(VOParam("scaleMin","","int",this->scaleMin,0,""));
1273      if(this->scaleMax>0)
1274        vopars.push_back(VOParam("scaleMax","","int",this->scaleMax,0,""));
1275      vopars.push_back(VOParam("snrRecon","","float",this->snrRecon,0,""));
1276      vopars.push_back(VOParam("reconConvergence","","float",this->reconConvergence,0,""));
1277      vopars.push_back(VOParam("filterCode","","int",this->filterCode,0,""));
1278    }
1279    if(this->beamAsUsed.origin()==PARAM){
1280      if(this->fwhmBeam>0)
1281        vopars.push_back(VOParam("beamFWHM","","float",this->fwhmBeam,0,""));
1282      else
1283        vopars.push_back(VOParam("beamArea","","float",this->areaBeam,0,""));
1284    }
1285    if(this->restFrequencyUsed){
1286      vopars.push_back(VOParam("restFrequency","em.freq","float",this->restFrequency,0,"Hz"));
1287    }
1288
1289    return vopars;
1290
1291  }
1292
1293  void Param::writeToBinaryFile(std::string &filename)
1294  {
1295    std::ofstream outfile(filename.c_str(), std::ios::out | std::ios::binary | std::ios::app);
1296    writeStringToBinaryFile(outfile,this->imageFile);
1297    outfile.write(reinterpret_cast<const char*>(&this->flagSubsection), sizeof this->flagSubsection);
1298    if(this->flagSubsection) writeStringToBinaryFile(outfile,this->pixelSec.getSection());
1299    outfile.write(reinterpret_cast<const char*>(&this->flagStatSec), sizeof this->flagStatSec);
1300    if(this->flagStatSec) writeStringToBinaryFile(outfile,this->statSec.getSection());
1301    outfile.write(reinterpret_cast<const char*>(&this->flagReconExists), sizeof this->flagReconExists);
1302    if(this->flagReconExists) writeStringToBinaryFile(outfile,this->reconFile);
1303    outfile.write(reinterpret_cast<const char*>(&this->flagSmoothExists), sizeof this->flagSmoothExists);
1304    if(this->flagSmoothExists) writeStringToBinaryFile(outfile,this->smoothFile);
1305    //
1306    writeStringToBinaryFile(outfile,this->searchType);
1307    outfile.write(reinterpret_cast<const char*>(&this->flagNegative), sizeof this->flagNegative);
1308    outfile.write(reinterpret_cast<const char*>(&this->flagBaseline), sizeof this->flagBaseline);
1309    if(this->flagBaseline){
1310        writeStringToBinaryFile(outfile,this->baselineType);
1311        if(this->baselineType=="median")
1312            outfile.write(reinterpret_cast<const char*>(&this->baselineBoxWidth), sizeof this->baselineBoxWidth);
1313    }
1314    outfile.write(reinterpret_cast<const char*>(&this->flagRobustStats), sizeof this->flagRobustStats);
1315    outfile.write(reinterpret_cast<const char*>(&this->flagFDR), sizeof this->flagFDR);
1316    if(this->flagFDR){
1317      outfile.write(reinterpret_cast<const char*>(&this->alphaFDR), sizeof this->alphaFDR);
1318      outfile.write(reinterpret_cast<const char*>(&this->FDRnumCorChan), sizeof this->FDRnumCorChan);
1319      if(this->beamAsUsed.origin()==PARAM){
1320        outfile.write(reinterpret_cast<const char*>(&this->fwhmBeam), sizeof this->fwhmBeam);
1321        outfile.write(reinterpret_cast<const char*>(&this->areaBeam), sizeof this->areaBeam);
1322      }
1323    }
1324    else{
1325      outfile.write(reinterpret_cast<const char*>(&this->flagUserThreshold), sizeof this->flagUserThreshold);
1326      if(this->flagUserThreshold)
1327        outfile.write(reinterpret_cast<const char*>(&this->threshold), sizeof this->threshold);
1328      else
1329        outfile.write(reinterpret_cast<const char*>(&this->snrCut), sizeof this->snrCut);
1330    }
1331    outfile.write(reinterpret_cast<const char*>(&this->flagGrowth), sizeof this->flagGrowth);
1332    if(this->flagGrowth){
1333      if(this->flagUserGrowthThreshold)
1334        outfile.write(reinterpret_cast<const char*>(&this->growthThreshold), sizeof this->growthThreshold);
1335      else
1336        outfile.write(reinterpret_cast<const char*>(&this->growthCut), sizeof this->growthCut);
1337    }
1338    outfile.write(reinterpret_cast<const char*>(&this->minPix), sizeof this->minPix);
1339    outfile.write(reinterpret_cast<const char*>(&this->minChannels), sizeof this->minChannels);
1340    outfile.write(reinterpret_cast<const char*>(&this->minVoxels), sizeof this->minVoxels);
1341    outfile.write(reinterpret_cast<const char*>(&this->maxPix), sizeof this->maxPix);
1342    outfile.write(reinterpret_cast<const char*>(&this->maxChannels), sizeof this->maxChannels);
1343    outfile.write(reinterpret_cast<const char*>(&this->maxVoxels), sizeof this->maxVoxels);
1344    outfile.write(reinterpret_cast<const char*>(&this->flagAdjacent), sizeof this->flagAdjacent);
1345    if(!this->flagAdjacent)
1346      outfile.write(reinterpret_cast<const char*>(&this->threshSpatial), sizeof this->threshSpatial);
1347    outfile.write(reinterpret_cast<const char*>(&this->threshVelocity), sizeof this->threshVelocity);
1348    outfile.write(reinterpret_cast<const char*>(&this->flagRejectBeforeMerge), sizeof this->flagRejectBeforeMerge);
1349    outfile.write(reinterpret_cast<const char*>(&this->flagTwoStageMerging), sizeof this->flagTwoStageMerging);
1350    outfile.write(reinterpret_cast<const char*>(&this->flagSmooth), sizeof this->flagSmooth);
1351    if(this->flagSmooth){
1352      bool type=(this->smoothType=="spectral");
1353      outfile.write(reinterpret_cast<const char*>(&type), sizeof type);
1354      if(type)
1355        outfile.write(reinterpret_cast<const char*>(&this->hanningWidth), sizeof this->hanningWidth);
1356      else{
1357        outfile.write(reinterpret_cast<const char*>(&this->kernMaj), sizeof this->kernMaj);
1358        outfile.write(reinterpret_cast<const char*>(&this->kernMin), sizeof this->kernMin);
1359        outfile.write(reinterpret_cast<const char*>(&this->kernPA), sizeof this->kernPA);
1360        outfile.write(reinterpret_cast<const char*>(&this->smoothEdgeMethod), sizeof this->smoothEdgeMethod);
1361        outfile.write(reinterpret_cast<const char*>(&this->spatialSmoothCutoff), sizeof this->spatialSmoothCutoff);
1362      }
1363    }
1364    outfile.write(reinterpret_cast<const char*>(&this->flagATrous), sizeof this->flagATrous);
1365    if(this->flagATrous){
1366      outfile.write(reinterpret_cast<const char*>(&this->reconDim), sizeof this->reconDim);
1367      outfile.write(reinterpret_cast<const char*>(&this->scaleMin), sizeof this->scaleMin);
1368      outfile.write(reinterpret_cast<const char*>(&this->scaleMax), sizeof this->scaleMax);
1369      outfile.write(reinterpret_cast<const char*>(&this->snrRecon), sizeof this->snrRecon);
1370      outfile.write(reinterpret_cast<const char*>(&this->reconConvergence), sizeof this->reconConvergence);
1371      outfile.write(reinterpret_cast<const char*>(&this->filterCode), sizeof this->filterCode);
1372    }
1373    writeStringToBinaryFile(outfile,this->flaggedChannelList);
1374
1375    outfile.close();
1376  }
1377
1378  std::streampos Param::readFromBinaryFile(std::string &filename, std::streampos loc)
1379  {
1380    std::ifstream infile(filename.c_str(), std::ios::in | std::ios::binary);
1381    if(!infile.is_open()){
1382      DUCHAMPERROR("read binary parameters","Could not open binary catalogue \""<<filename <<"\"");
1383      return -1;
1384    }
1385    infile.seekg(loc);
1386    this->imageFile = readStringFromBinaryFile(infile);
1387    infile.read(reinterpret_cast<char*>(&this->flagSubsection), sizeof this->flagSubsection);
1388    if(this->flagSubsection){
1389      std::string sec=readStringFromBinaryFile(infile);
1390      this->pixelSec.setSection(sec);
1391    }
1392    infile.read(reinterpret_cast<char*>(&this->flagStatSec), sizeof this->flagStatSec);
1393    if(this->flagStatSec){
1394      std::string sec=readStringFromBinaryFile(infile);
1395      this->statSec.setSection(sec);
1396    }
1397    infile.read(reinterpret_cast<char*>(&this->flagReconExists), sizeof this->flagReconExists);
1398    if(this->flagReconExists) this->reconFile=readStringFromBinaryFile(infile);
1399    infile.read(reinterpret_cast<char*>(&this->flagSmoothExists), sizeof this->flagSmoothExists);
1400    if(this->flagSmoothExists) this->smoothFile=readStringFromBinaryFile(infile);
1401    //
1402    this->searchType=readStringFromBinaryFile(infile);
1403    infile.read(reinterpret_cast<char*>(&this->flagNegative), sizeof this->flagNegative);
1404    infile.read(reinterpret_cast<char*>(&this->flagBaseline), sizeof this->flagBaseline);
1405    if(this->flagBaseline){
1406        this->baselineType = readStringFromBinaryFile(infile);
1407        if(this->baselineType == "median")
1408            infile.read(reinterpret_cast<char*>(&this->baselineBoxWidth), sizeof this->baselineBoxWidth);
1409    }
1410    infile.read(reinterpret_cast<char*>(&this->flagRobustStats), sizeof this->flagRobustStats);
1411    infile.read(reinterpret_cast<char*>(&this->flagFDR), sizeof this->flagFDR);
1412    if(this->flagFDR){
1413      infile.read(reinterpret_cast<char*>(&this->alphaFDR), sizeof this->alphaFDR);
1414      infile.read(reinterpret_cast<char*>(&this->FDRnumCorChan), sizeof this->FDRnumCorChan);
1415      if(this->beamAsUsed.origin()==PARAM){
1416        infile.read(reinterpret_cast<char*>(&this->fwhmBeam), sizeof this->fwhmBeam);
1417        infile.read(reinterpret_cast<char*>(&this->areaBeam), sizeof this->areaBeam);
1418      }
1419    }
1420    else{
1421      infile.read(reinterpret_cast<char*>(&this->flagUserThreshold), sizeof this->flagUserThreshold);
1422      if(this->flagUserThreshold)
1423        infile.read(reinterpret_cast<char*>(&this->threshold), sizeof this->threshold);
1424      else
1425        infile.read(reinterpret_cast<char*>(&this->snrCut), sizeof this->snrCut);
1426    }
1427    infile.read(reinterpret_cast<char*>(&this->flagGrowth), sizeof this->flagGrowth);
1428    if(this->flagGrowth){
1429      if(this->flagUserGrowthThreshold)
1430        infile.read(reinterpret_cast<char*>(&this->growthThreshold), sizeof this->growthThreshold);
1431      else
1432        infile.read(reinterpret_cast<char*>(&this->growthCut), sizeof this->growthCut);
1433    }
1434    infile.read(reinterpret_cast<char*>(&this->minPix), sizeof this->minPix);
1435    infile.read(reinterpret_cast<char*>(&this->minChannels), sizeof this->minChannels);
1436    infile.read(reinterpret_cast<char*>(&this->minVoxels), sizeof this->minVoxels);
1437    infile.read(reinterpret_cast<char*>(&this->maxPix), sizeof this->maxPix);
1438    infile.read(reinterpret_cast<char*>(&this->maxChannels), sizeof this->maxChannels);
1439    infile.read(reinterpret_cast<char*>(&this->maxVoxels), sizeof this->maxVoxels);
1440    infile.read(reinterpret_cast<char*>(&this->flagAdjacent), sizeof this->flagAdjacent);
1441    if(!this->flagAdjacent)
1442      infile.read(reinterpret_cast<char*>(&this->threshSpatial), sizeof this->threshSpatial);
1443    infile.read(reinterpret_cast<char*>(&this->threshVelocity), sizeof this->threshVelocity);
1444    infile.read(reinterpret_cast<char*>(&this->flagRejectBeforeMerge), sizeof this->flagRejectBeforeMerge);
1445    infile.read(reinterpret_cast<char*>(&this->flagTwoStageMerging), sizeof this->flagTwoStageMerging);
1446    infile.read(reinterpret_cast<char*>(&this->flagSmooth), sizeof this->flagSmooth);
1447    if(this->flagSmooth){
1448      bool type;
1449      infile.read(reinterpret_cast<char*>(&type), sizeof type);
1450      this->smoothType = type ? "spectral" : "spatial";
1451      if(type)
1452        infile.read(reinterpret_cast<char*>(&this->hanningWidth), sizeof this->hanningWidth);
1453      else{
1454        infile.read(reinterpret_cast<char*>(&this->kernMaj), sizeof this->kernMaj);
1455        infile.read(reinterpret_cast<char*>(&this->kernMin), sizeof this->kernMin);
1456        infile.read(reinterpret_cast<char*>(&this->kernPA), sizeof this->kernPA);
1457        infile.read(reinterpret_cast<char*>(&this->smoothEdgeMethod), sizeof this->smoothEdgeMethod);
1458        infile.read(reinterpret_cast<char*>(&this->spatialSmoothCutoff), sizeof this->spatialSmoothCutoff);
1459      }
1460    }
1461    infile.read(reinterpret_cast<char*>(&this->flagATrous), sizeof this->flagATrous);
1462    if(this->flagATrous){
1463      infile.read(reinterpret_cast<char*>(&this->reconDim), sizeof this->reconDim);
1464      infile.read(reinterpret_cast<char*>(&this->scaleMin), sizeof this->scaleMin);
1465      infile.read(reinterpret_cast<char*>(&this->scaleMax), sizeof this->scaleMax);
1466      infile.read(reinterpret_cast<char*>(&this->snrRecon), sizeof this->snrRecon);
1467      infile.read(reinterpret_cast<char*>(&this->reconConvergence), sizeof this->reconConvergence);
1468      infile.read(reinterpret_cast<char*>(&this->filterCode), sizeof this->filterCode);
1469    }
1470    this->flaggedChannelList=readStringFromBinaryFile(infile);
1471
1472    std::streampos newloc = infile.tellg();
1473    infile.close();
1474    return newloc;
1475
1476  }
1477
1478
1479
1480
1481  void Param::copyHeaderInfo(FitsHeader &head)
1482  {
1483    ///  A function to copy across relevant header keywords from the
1484    ///  FitsHeader class to the Param class, as they are needed by
1485    ///  functions in the Param class.
1486    ///  The parameters are the keywords BLANK, BSCALE, BZERO, and the beam size.
1487
1488    this->blankKeyword  = head.getBlankKeyword();
1489    this->bscaleKeyword = head.getBscaleKeyword();
1490    this->bzeroKeyword  = head.getBzeroKeyword();
1491    this->blankPixValue = this->blankKeyword * this->bscaleKeyword +
1492      this->bzeroKeyword;
1493  }
1494
1495  std::string Param::outputMaskFile()
1496  {
1497    ///  This function produces the required filename in which to save
1498    ///  the mask image, indicating which pixels have been detected as
1499    ///  part of an object. If the input image is image.fits, then the
1500    ///  output will be image.MASK.fits.
1501
1502    if(this->fileOutputMask==""){
1503      std::string inputName = this->imageFile;
1504      std::string outputName = inputName;
1505      if(this->imageFile.size()>5 && inputName.substr(inputName.size()-5,5)==".fits")
1506        outputName = inputName.substr(0,inputName.size()-5); 
1507      // remove the ".fits" on the end.
1508      outputName += ".MASK.fits";
1509      return outputName;
1510    }
1511    else return this->fileOutputMask;
1512  }
1513
1514  std::string Param::outputMomentMapFile()
1515  {
1516    ///  This function produces the required filename in which to save
1517    ///  the moment-0 FITS image. If the input image is image.fits, then the
1518    ///  output will be image.MOM0.fits.
1519
1520    if(this->fileOutputMomentMap==""){
1521      std::string inputName = this->imageFile;
1522      std::string outputName = inputName;
1523      if(this->imageFile.size()>5 && inputName.substr(inputName.size()-5,5)==".fits")
1524        outputName = inputName.substr(0,inputName.size()-5); 
1525      // remove the ".fits" on the end.
1526      outputName += ".MOM0.fits";
1527      return outputName;
1528    }
1529    else return this->fileOutputMomentMap;
1530  }
1531
1532  std::string Param::outputMomentMaskFile()
1533  {
1534    ///  This function produces the required filename in which to save
1535    ///  the moment-0 FITS image. If the input image is image.fits, then the
1536    ///  output will be image.MOM0.fits.
1537
1538    if(this->fileOutputMomentMask==""){
1539      std::string inputName = this->imageFile;
1540      std::string outputName = inputName;
1541      if(this->imageFile.size()>5 && inputName.substr(inputName.size()-5,5)==".fits")
1542        outputName = inputName.substr(0,inputName.size()-5); 
1543      // remove the ".fits" on the end.
1544      outputName += ".MOM0MASK.fits";
1545      return outputName;
1546    }
1547    else return this->fileOutputMomentMask;
1548  }
1549
1550  std::string Param::outputBaselineFile()
1551  {
1552    ///  This function produces the required filename in which to save
1553    ///  the baseline FITS image. If the input image is image.fits, then the
1554    ///  output will be image.BASE.fits.
1555
1556    if(this->fileOutputBaseline==""){
1557      std::string inputName = this->imageFile;
1558      std::string outputName = inputName;
1559      if(this->imageFile.size()>5 && inputName.substr(inputName.size()-5,5)==".fits")
1560        outputName = inputName.substr(0,inputName.size()-5); 
1561      // remove the ".fits" on the end.
1562      outputName += ".BASE.fits";
1563      return outputName;
1564    }
1565    else return this->fileOutputBaseline;
1566  }
1567
1568  std::string Param::outputSmoothFile()
1569  {
1570    ///  This function produces the required filename in which to save
1571    ///   the smoothed array. If the input image is image.fits, then
1572    ///   the output will be:
1573    ///    <ul><li> Spectral smoothing: image.SMOOTH-1D-3.fits, where the
1574    ///             width of the Hanning filter was 3 pixels.
1575    ///        <li> Spatial smoothing : image.SMOOTH-2D-3-2-20-E-10.fits, where
1576    ///             kernMaj=3, kernMin=2 and kernPA=20 degrees, EQUAL edge method, and cutoff of 1.e-10.
1577    ///    </ul>
1578
1579    if(this->fileOutputSmooth==""){
1580      std::string inputName = this->imageFile;
1581      std::stringstream ss;
1582      if(this->imageFile.size()>5 && inputName.substr(inputName.size()-5,5)==".fits")
1583        ss << inputName.substr(0,inputName.size()-5); 
1584      else
1585        ss << inputName;
1586      // remove the ".fits" on the end if necessary.
1587      if(this->flagSubsection) ss<<".sub";
1588      if(this->smoothType=="spectral")
1589        ss << ".SMOOTH-1D-" << this->hanningWidth << ".fits";
1590      else if(this->smoothType=="spatial"){
1591          char method='X';
1592          if(this->smoothEdgeMethod=="equal") method='E';
1593          else if (this->smoothEdgeMethod=="truncate") method='T';
1594          else if (this->smoothEdgeMethod=="scale") method='S';
1595          ss << ".SMOOTH-2D-"
1596             << this->kernMaj << "-"
1597             << this->kernMin << "-"
1598             << this->kernPA  << "-"
1599             << method        << "-"
1600             << -log10(this->spatialSmoothCutoff)
1601             << ".fits";
1602      }
1603      return ss.str();
1604    }
1605    else return this->fileOutputSmooth;
1606  }
1607
1608  std::string Param::outputReconFile()
1609  {
1610    /// This function produces the required filename in which to save
1611    ///  the reconstructed array. If the input image is image.fits, then
1612    ///  the output will be eg. image.RECON-3-2-4-1.fits, where the numbers are
1613    ///  3=reconDim, 2=filterCode, 4=snrRecon, 1=minScale
1614
1615    if(this->fileOutputRecon==""){
1616      std::string inputName = this->imageFile;
1617      std::stringstream ss;
1618      // First we remove the ".fits" from the end of the filename.
1619      if(this->imageFile.size()>5 && inputName.substr(inputName.size()-5,5)==".fits")
1620          ss << inputName.substr(0,inputName.size()-5); 
1621      else
1622          ss << inputName;
1623      if(this->flagSubsection) ss<<".sub";
1624      ss << ".RECON-" << this->reconDim
1625         << "-"       << this->filterCode
1626         << "-"       << this->snrRecon
1627         << "-"       << this->scaleMin
1628         << "-"       << this->scaleMax
1629         << "-"       << this->reconConvergence
1630         << ".fits";
1631      return ss.str();
1632    }
1633    else return this->fileOutputRecon;
1634  }
1635
1636  std::string Param::outputResidFile()
1637  {
1638    /// This function produces the required filename in which to save
1639    ///  the reconstructed array. If the input image is image.fits, then
1640    ///  the output will be eg. image.RESID-3-2-4-1.fits, where the numbers are
1641    ///  3=reconDim, 2=filterCode, 4=snrRecon, 1=scaleMin
1642
1643    if(this->fileOutputResid==""){
1644      std::string inputName = this->imageFile;
1645      std::stringstream ss;
1646      // First we remove the ".fits" from the end of the filename.
1647      if(this->imageFile.size()>5 && inputName.substr(inputName.size()-5,5)==".fits")
1648          ss << inputName.substr(0,inputName.size()-5);
1649      else
1650          ss << inputName;
1651      if(this->flagSubsection) ss<<".sub";
1652      ss << ".RESID-" << this->reconDim
1653         << "-"       << this->filterCode
1654         << "-"       << this->snrRecon
1655         << "-"       << this->scaleMin
1656         << "-"       << this->scaleMax
1657         << "-"       << this->reconConvergence
1658         << ".fits";
1659      return ss.str();
1660    }
1661    else return this->fileOutputResid;
1662  }
1663
1664}
Note: See TracBrowser for help on using the repository browser.