source: trunk/src/param.cc

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

AXA-537 - Adding a bit more care in the pointer handling, particularly for the reconFilter in the copy constructor

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