source: trunk/src/Cubes/detectionIO.cc @ 463

Last change on this file since 463 was 461, checked in by MatthewWhiting, 16 years ago

A few fixes:

  • Fixed a bug in setupColumns and the VOTable output when there are no detections
  • Fixed some bugs from the tidy up in the last commit
  • Fixed conflicts between a manual threshold and growth thresholds. Introduced a manual growth threshold that must be used when a manual threshold is used.
  • Also, a manual threshold turns off the FDR flag.
  • Improved the growth threshold reporting in the results header.
File size: 13.5 KB
Line 
1// -----------------------------------------------------------------------
2// detectionIO.cc: Screen and File output of the detected objects.
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 <sstream>
30#include <fstream>
31#include <iomanip>
32#include <string>
33#include <vector>
34#include <time.h>
35#include <duchamp/param.hh>
36#include <duchamp/fitsHeader.hh>
37#include <duchamp/Cubes/cubes.hh>
38#include <duchamp/PixelMap/Object3D.hh>
39#include <duchamp/Detection/detection.hh>
40#include <duchamp/Detection/columns.hh>
41#include <duchamp/Utils/utils.hh>
42#include <duchamp/Utils/Statistics.hh>
43 
44using std::endl;
45using std::setw;
46using std::setprecision;
47using namespace PixelInfo;
48using namespace Statistics;
49
50namespace duchamp
51{
52
53  void Cube::outputDetectionsKarma(std::ostream &stream)
54  {
55    /**
56     *  Prints to a stream (provided) the list of detected objects in the cube
57     *   in the format of an annotation file for the Karma suite of programs.
58     *  Annotation file draws a box enclosing the detection, and writes the
59     *   ID number of the detection to the right of the box.
60     */
61
62    std::string fname = this->par.getImageFile();
63    if(this->par.getFlagSubsection()) fname+=this->par.getSubsection();
64    stream << "# Duchamp Source Finder results for FITS file: " << fname << endl;
65    if(this->par.getFlagFDR())
66      stream<<"# FDR Significance = " << this->par.getAlpha() << endl;
67    else
68      stream<<"# Threshold = " << this->par.getCut() << endl;
69    if(this->par.getFlagATrous()){
70      stream<<"# The a trous reconstruction method was used, with the following parameters." << endl;
71      stream<<"#  ATrous Dimension = " << this->par.getReconDim() << endl;
72      stream<<"#  ATrous Threshold = " << this->par.getAtrousCut() << endl;
73      stream<<"#  ATrous Minimum Scale =" << this->par.getMinScale() << endl;
74      stream<<"#  ATrous Filter = " << this->par.getFilterName() << endl;
75    }
76    else if(this->par.getFlagSmooth()){
77      stream<<"# The data was smoothed prior to searching, with the following parameters." << endl;
78      stream<<"#  Smoothing type = " << this->par.getSmoothType() << endl;
79      if(this->par.getSmoothType()=="spectral"){
80        stream << "#  Hanning width = " << this->par.getHanningWidth() << endl;
81      }
82      else{
83        stream << "#  Kernel Major axis = " << this->par.getKernMaj() << endl;
84        if(this->par.getKernMin()>0)
85          stream << "#  Kernel Minor axis = " << this->par.getKernMin() << endl;
86        else
87          stream << "#  Kernel Minor axis = " << this->par.getKernMaj() << endl;
88        stream << "#  Kernel Major axis = " << this->par.getKernPA() << endl;
89      }
90    }
91    else stream << "# No ATrous reconstruction done." << endl;
92    stream << "#\n";
93    stream << "COLOR RED" << endl;
94    stream << "COORD W" << endl;
95    stream << std::setprecision(6);
96    stream.setf(std::ios::fixed);
97    double *pix = new double[3];
98    double *wld = new double[3];
99    std::vector<Detection>::iterator obj;
100    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
101
102      if(this->par.getAnnotationType()=="borders"){
103        std::vector<int> vertexSet = obj->getVertexSet();
104        for(int i=0;i<vertexSet.size()/4;i++){
105          pix[0] = vertexSet[i*4]-0.5;
106          pix[1] = vertexSet[i*4+1]-0.5;
107          pix[2] = obj->getZcentre();
108          this->head.pixToWCS(pix,wld);
109          stream << "LINE " << wld[0] << " " << wld[1];
110          pix[0] = vertexSet[i*4+2]-0.5;
111          pix[1] = vertexSet[i*4+3]-0.5;
112          this->head.pixToWCS(pix,wld);
113          stream << " " << wld[0] << " " << wld[1] << "\n";
114        }
115      }
116      else if(this->par.getAnnotationType()=="circles"){
117        float radius = obj->getRAWidth()/120.;
118        if(obj->getDecWidth()/120.>radius)
119          radius = obj->getDecWidth()/120.;
120        stream << "CIRCLE "
121               << obj->getRA() << " "
122               << obj->getDec() << " "
123               << radius << "\n";
124      }
125
126      stream << "TEXT "
127             << obj->getRA() << " "
128             << obj->getDec() << " "
129             << obj->getID() << "\n\n";
130    }
131  }
132
133  void Cube::prepareOutputFile()
134  {
135    /**
136     *  A function to write the paramters, time of execution, and
137     *  statistical information to the output file.
138     */
139
140    std::string outfile;
141    if(this->par.getFlagSeparateHeader()) outfile = this->par.getHeaderFile();
142    else outfile = this->par.getOutFile();
143    std::ofstream output(outfile.c_str());
144    output<<"Results of the Duchamp source finder: ";
145    time_t now = time(NULL);
146    output << asctime( localtime(&now) );
147    this->showParam(output);
148    output<<"--------------------\n";
149    output.close();
150    this->outputStats();
151 
152  }
153
154  void Cube::outputStats()
155  {
156    /**
157     *  A function to write the statistical information to the output
158     *  file. This writes the threshold, its equivalent S/N ratio, and
159     *  the noise level and spread.
160     *
161     *  If smoothing has been done, the noise level & spread for the
162     *  original array are calculated and printed as well.
163     */
164
165    std::string outfile;
166    if(this->par.getFlagSeparateHeader()) outfile = this->par.getHeaderFile();
167    else outfile = this->par.getOutFile();
168    std::ofstream output(outfile.c_str(),std::ios::app);
169    output<<"Summary of statistics:\n";
170    output<<"Detection threshold = " << this->Stats.getThreshold()
171          <<" " << this->head.getFluxUnits();
172    if(this->par.getFlagFDR())
173      output<<" (or S/N=" << this->Stats.getThresholdSNR()<<")";
174    if(this->par.getFlagSmooth()){
175      output << " in smoothed cube.";
176      if(!this->par.getFlagUserThreshold())
177        output<<"\nNoise level = " << this->Stats.getMiddle()
178              <<", Noise spread = " << this->Stats.getSpread()
179              <<" in smoothed cube.";
180   
181      // calculate the stats for the original array, so that we can
182      // quote S/N values correctly.
183      this->par.setFlagSmooth(false);
184      bool verb=this->par.isVerbose();
185      bool fdrflag=this->par.getFlagFDR();
186      this->par.setVerbosity(false);
187      this->par.setFlagFDR(false);
188      this->setCubeStats();
189      this->par.setVerbosity(verb);
190      this->par.setFlagFDR(fdrflag);
191      this->par.setFlagSmooth(true);
192     
193      output << "\nNoise properties for the original cube are:";
194    }
195     
196    if(!this->par.getFlagUserThreshold())
197      output<<"\nNoise level = " << this->Stats.getMiddle()
198            <<", Noise spread = " << this->Stats.getSpread();
199
200    if(this->par.getFlagGrowth()){
201      StatsContainer<float> growthStats = this->Stats;
202      if(this->par.getFlagUserGrowthThreshold())
203        growthStats.setThreshold(this->par.getGrowthThreshold());
204      else
205        growthStats.setThresholdSNR(this->par.getGrowthCut());
206      growthStats.setUseFDR(false);
207      output<<"\nDetections grown down to threshold of "
208            << growthStats.getThreshold() << " "
209            << this->head.getFluxUnits();
210    }
211
212    if(!this->par.getFlagUserThreshold())
213      output << "\nFull stats:\n" << this->Stats;
214    else
215      output << "\n\nNot calculating full stats since threshold was provided directly.\n";
216
217    output<<"--------------------\n";
218    output.close();
219  }
220
221  void Cube::outputDetectionList()
222  {
223    /**
224     *  A front-end to writing the full list of detected objects to a results
225     *   file and to cout.
226     *  Leaves the testing of whether the WCS parameters for each object
227     *   have been calculated to the printing function.
228     */
229
230    std::string outfile;
231    if(this->par.getFlagSeparateHeader()) outfile = this->par.getHeaderFile();
232    else outfile = this->par.getOutFile();
233    std::ofstream output(outfile.c_str(),std::ios::app);
234    output<<"Total number of detections = "<<this->objectList->size()<<endl;
235    output<<"--------------------\n";
236    output.close();
237
238    if(this->par.getFlagSeparateHeader())
239      output.open(this->par.getOutFile().c_str());
240    else
241      output.open(this->par.getOutFile().c_str(),std::ios::app);
242
243    if(this->objectList->size()>0){
244      this->setupColumns();
245      outputTableHeader(output,this->fullCols,"file",this->head.isWCS());
246      outputTableHeader(std::cout,this->fullCols,"screen",this->head.isWCS());
247      std::vector<Detection>::iterator obj;
248      for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
249        obj->printTableRow(output,this->fullCols,"file");
250        obj->printTableRow(std::cout,this->fullCols,"screen");
251      }
252    }
253
254    output.close();
255  }
256
257  void Cube::prepareLogFile(int argc, char *argv[])
258  {
259    /**
260     *  Opens the log file so that it can be written to, and writes
261     *  the parameter summary as well as the time of execution to the
262     *  file.
263     *
264     *  It also writes the command-line statement, hence the need for
265     *  argv and argc.
266     */
267    // Open the logfile and write the time on the first line
268    std::ofstream logfile(this->par.getLogFile().c_str());
269    logfile << "New run of the Duchamp sourcefinder: ";
270    time_t now = time(NULL);
271    logfile << asctime( localtime(&now) );
272    // Write out the command-line statement
273    logfile << "Executing statement : ";
274    for(int i=0;i<argc;i++) logfile << argv[i] << " ";
275    logfile << std::endl;
276    logfile << this->par;
277    logfile.close();
278
279  }
280
281
282  void Cube::logDetectionList()
283  {
284    /**
285     *  A front-end to writing a list of detected objects to the log file.
286     *  Does not assume WCS is present.
287     *  Designed to be used by searching routines before returning their
288     *   final list.
289     */
290
291    if(this->objectList->size()>0){
292
293      long left = this->par.getBorderLeft();
294      long bottom = this->par.getBorderBottom();
295
296      std::ofstream fout(this->par.getLogFile().c_str(),std::ios::app);
297      this->calcObjectFluxes();
298      this->setupColumns();
299      outputTableHeader(fout,this->fullCols,"log",this->head.isWCS());
300
301      if(this->par.getFlagBaseline()){
302        for(int i=0;i<this->axisDim[0]*this->axisDim[1]*this->axisDim[2];i++)
303          this->array[i] += this->baseline[i];
304      }
305
306      for(int objCtr=0;objCtr<this->objectList->size();objCtr++){
307        Detection *obj = new Detection;
308        *obj = objectList->at(objCtr);
309        obj->setOffsets(par);
310        if(this->par.getFlagCubeTrimmed()){
311          obj->pixels().addOffsets(left,bottom,0);
312        }
313        obj->calcFluxes(this->array, this->axisDim);
314        obj->setID(objCtr+1);
315        obj->printTableRow(fout,this->fullCols,"log");
316        delete obj;
317      }
318
319      if(this->par.getFlagBaseline()){
320        for(int i=0;i<this->axisDim[0]*this->axisDim[1]*this->axisDim[2];i++)
321          this->array[i] -= this->baseline[i];
322      }
323      fout.close();
324 
325    }
326
327  }
328
329  void Cube::logDetection(Detection obj, int counter)
330  {
331    /**
332     *  A front-end to writing a detected object to the log file.
333     *  Does not assume WCS is present.
334     *  Corrects for changes to positions of pixels and removal of baselines.
335     *  Designed to be used by searching routines before returning their final
336     *   list.
337     *  \param obj Detection object to be written : passed by value, as we want
338     *    to potentially change positions etc, but not for the object in the
339     *    calling function.
340     *  \param counter The number to assign to the object : ideally its number
341     *    in a list of some kind.
342     */
343
344    std::ofstream fout(this->par.getLogFile().c_str(),std::ios::app);
345    // Need to deal with possibility of trimmed array
346    long left = this->par.getBorderLeft();
347    long right = this->par.getBorderRight();
348    long top = this->par.getBorderTop();
349    long bottom = this->par.getBorderBottom();
350    long *tempDim = new long[3];
351    tempDim[0] = (this->axisDim[0] + left + right);
352    tempDim[1] = (this->axisDim[1] + bottom + top);
353    tempDim[2] = this->axisDim[2];
354    long tempsize = tempDim[0] * tempDim[1] * tempDim[2];
355    float *temparray = new float[tempsize];
356    //  for(int i=0;i<this->numPixels;i++){ // loop over this->array
357    for(int z=0;z<tempDim[2];z++){
358      for(int y=0;y<tempDim[1];y++){
359        for(int x=0;x<tempDim[0];x++){
360
361          bool isDud = (x<left) || (x>=this->axisDim[0]+left) ||
362            (y<bottom) || (y>=this->axisDim[1]+bottom);
363       
364          int temppos = x + tempDim[0]*y + tempDim[1]*tempDim[0]*z;
365
366          int pos = (x-left) + (y-bottom)*this->axisDim[0] +
367            z*this->axisDim[0]*this->axisDim[1];
368
369          if(isDud) temparray[temppos] = this->par.getBlankPixVal();
370          else temparray[temppos] = this->array[pos];
371 
372          if(this->par.getFlagBaseline() && !isDud)
373            temparray[temppos] += this->baseline[pos];
374
375        }
376      }
377    }
378
379    if(this->par.getFlagCubeTrimmed()){
380      obj.pixels().addOffsets(left,bottom,0);
381    }
382    obj.calcFluxes(temparray, this->axisDim);
383    obj.printTableRow(fout,this->fullCols,"log");
384    delete [] temparray;
385    delete [] tempDim;
386    fout.close();
387  }
388
389}
Note: See TracBrowser for help on using the repository browser.