source: trunk/src/param.cc @ 1448

Last change on this file since 1448 was 1448, checked in by MatthewWhiting, 4 years ago

AXA-537 - Cleaning up some memory usage.
Ensuring that we free up WCS allocations at the appropriate point.
Also other uses of calloc, in B3SplineFilter & the plotting

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