source: trunk/src/ATrous/atrous_3d_reconstruct.cc @ 913

Last change on this file since 913 was 913, checked in by MatthewWhiting, 12 years ago

A large swathe of changes aimed at improving warning/error/exception handling. Now make use of macros and streams. Also, there is now a distinction between DUCHAMPERROR and DUCHAMPTHROW.

File size: 11.4 KB
Line 
1// -----------------------------------------------------------------------
2// atrous_3d_reconstruct.cc: 3-dimensional wavelet reconstruction.
3// -----------------------------------------------------------------------
4// Copyright (C) 2006, Matthew Whiting, ATNF
5//
6// This program is free software; you can redistribute it and/or modify it
7// under the terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 2 of the License, or (at your
9// option) any later version.
10//
11// Duchamp is distributed in the hope that it will be useful, but WITHOUT
12// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14// for more details.
15//
16// You should have received a copy of the GNU General Public License
17// along with Duchamp; if not, write to the Free Software Foundation,
18// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
19//
20// Correspondence concerning Duchamp may be directed to:
21//    Internet email: Matthew.Whiting [at] atnf.csiro.au
22//    Postal address: Dr. Matthew Whiting
23//                    Australia Telescope National Facility, CSIRO
24//                    PO Box 76
25//                    Epping NSW 1710
26//                    AUSTRALIA
27// -----------------------------------------------------------------------
28#include <iostream>
29#include <iomanip>
30#include <math.h>
31#include <duchamp/duchamp.hh>
32#include <duchamp/param.hh>
33#include <duchamp/ATrous/atrous.hh>
34#include <duchamp/ATrous/filter.hh>
35#include <duchamp/Utils/utils.hh>
36#include <duchamp/Utils/feedback.hh>
37#include <duchamp/Utils/Statistics.hh>
38using Statistics::madfmToSigma;
39
40using std::endl;
41using std::setw;
42
43namespace duchamp
44{
45
46  void atrous3DReconstruct(size_t &xdim, size_t &ydim, size_t &zdim, float *&input,
47                           float *&output, Param &par)
48  {
49    ///  A routine that uses the a trous wavelet method to reconstruct a
50    ///   3-dimensional image cube.
51    ///  The Param object "par" contains all necessary info about the filter and
52    ///   reconstruction parameters.
53    ///
54    ///  If there are no non-BLANK pixels (and we are testing for
55    ///  BLANKs), the reconstruction cannot be done, so we return the
56    ///  input array as the output array and give a warning message.
57    ///
58    ///  \param xdim The length of the x-axis.
59    ///  \param ydim The length of the y-axis.
60    ///  \param zdim The length of the z-axis.
61    ///  \param input The input spectrum.
62    ///  \param output The returned reconstructed spectrum. This array needs to be declared beforehand.
63    ///  \param par The Param set.
64
65    size_t size = xdim * ydim * zdim;
66    size_t spatialSize = xdim * ydim;
67    unsigned long mindim = xdim;
68    if (ydim<mindim) mindim = ydim;
69    if (zdim<mindim) mindim = zdim;
70    unsigned int numScales = par.filter().getNumScales(mindim);
71
72    double *sigmaFactors = new double[numScales+1];
73    for(size_t i=0;i<=numScales;i++){
74      if(i<=size_t(par.filter().maxFactor(3)) )
75        sigmaFactors[i] = par.filter().sigmaFactor(3,i);
76      else sigmaFactors[i] = sigmaFactors[i-1] / sqrt(8.);
77    }
78
79    float mean,originalSigma,oldsigma,newsigma;
80    bool *isGood = new bool[size];
81    size_t goodSize=0;
82    for(size_t pos=0;pos<size;pos++){
83      isGood[pos] = !par.isBlank(input[pos]);
84      if(isGood[pos]) goodSize++;
85    }
86
87    if(goodSize == 0){
88      // There are no good pixels -- everything is BLANK for some reason.
89      // Return the input array as the output, and give a warning message.
90
91      for(size_t pos=0;pos<xdim; pos++) output[pos] = input[pos];
92
93      DUCHAMPWARN("3D Reconstruction", "There are no good pixels to be reconstructed -- all are BLANK. Returning input array.\n");
94    }
95    else{
96      // Otherwise, all is good, and we continue.
97
98
99      // findMedianStats(input,goodSize,isGood,originalMean,originalSigma);
100      if(par.getFlagRobustStats())
101        originalSigma = madfmToSigma(findMADFM(input,isGood,size));
102      else
103        originalSigma = findStddev<float>(input,isGood,size);
104
105      float *coeffs = new float[size];
106      float *wavelet = new float[size];
107      // float *residual = new float[size];
108
109      for(size_t pos=0;pos<size;pos++) output[pos]=0.;
110
111      // Define the 3-D (separable) filter, using info from par.filter()
112      size_t filterwidth = par.filter().width();
113      int filterHW = filterwidth/2;
114      size_t fsize = filterwidth*filterwidth*filterwidth;
115      double *filter = new double[fsize];
116      for(size_t i=0;i<filterwidth;i++){
117        for(size_t j=0;j<filterwidth;j++){
118          for(size_t k=0;k<filterwidth;k++){
119            filter[i +j*filterwidth + k*filterwidth*filterwidth] =
120              par.filter().coeff(i) * par.filter().coeff(j) * par.filter().coeff(k);
121          }
122        }
123      }
124
125      // // Locating the borders of the image -- ignoring BLANK pixels
126      // //  Only do this if flagBlankPix is true.
127      // //  Otherwise use the full range of x and y.
128      // //  No trimming is done in the z-direction at this point.
129      // long *xLim1 = new long[ydim];
130      // for(size_t i=0;i<ydim;i++) xLim1[i] = 0;
131      // long *xLim2 = new long[ydim];
132      // for(size_t i=0;i<ydim;i++) xLim2[i] = xdim-1;
133      // long *yLim1 = new long[xdim];
134      // for(size_t i=0;i<xdim;i++) yLim1[i] = 0;
135      // long *yLim2 = new long[xdim];
136      // for(size_t i=0;i<xdim;i++) yLim2[i] = ydim-1;
137
138      // if(par.getFlagBlankPix()){
139      //        float avGapX = 0, avGapY = 0;
140      //        for(size_t row=0;row<ydim;row++){
141      //          size_t ct1 = 0;
142      //          size_t ct2 = xdim - 1;
143      //          while((ct1<ct2)&&(par.isBlank(input[row*xdim+ct1]))) ct1++;
144      //          while((ct2>ct1)&&(par.isBlank(input[row*xdim+ct2]))) ct2--;
145      //          xLim1[row] = ct1;
146      //          xLim2[row] = ct2;
147      //          avGapX += ct2 - ct1 + 1;
148      //        }
149      //        avGapX /= float(ydim);
150
151      //        for(size_t col=0;col<xdim;col++){
152      //          size_t ct1=0;
153      //          size_t ct2=ydim-1;
154      //          while((ct1<ct2)&&(par.isBlank(input[col+xdim*ct1]))) ct1++;
155      //          while((ct2>ct1)&&(par.isBlank(input[col+xdim*ct2]))) ct2--;
156      //          yLim1[col] = ct1;
157      //          yLim2[col] = ct2;
158      //          avGapY += ct2 - ct1 + 1;
159      //        }
160      //        avGapY /= float(xdim);
161 
162      //        // if(avGapX < mindim) mindim = int(avGapX);
163      //        // if(avGapY < mindim) mindim = int(avGapY);
164      //        // numScales = par.filter().getNumScales(mindim);
165      // }
166
167      float threshold;
168      int iteration=0;
169      newsigma = 1.e9;
170      for(size_t i=0;i<size;i++) output[i] = 0;
171      do{
172        if(par.isVerbose()) std::cout << "Iteration #"<<setw(2)<<++iteration<<": ";
173        // first, get the value of oldsigma, set it to the previous newsigma value
174        oldsigma = newsigma;
175        // we are transforming the residual array (input array first time around)
176        for(size_t i=0;i<size;i++)  coeffs[i] = input[i] - output[i];
177
178        int spacing = 1;
179        for(unsigned int scale = 1; scale<=numScales; scale++){
180
181          if(par.isVerbose()){
182            std::cout << "Scale ";
183            std::cout << setw(2)<<scale<<" / "<<setw(2)<<numScales;
184            printBackSpace(13);
185            std::cout << std::flush;
186          }
187
188          size_t pos = 0;
189          for(unsigned long zpos = 0; zpos<zdim; zpos++){
190            for(unsigned long ypos = 0; ypos<ydim; ypos++){
191              for(unsigned long xpos = 0; xpos<xdim; xpos++){
192                // loops over each pixel in the image
193
194                wavelet[pos] = coeffs[pos];
195           
196                if(!isGood[pos] )  wavelet[pos] = 0.;
197                else{
198
199                  unsigned int filterpos = 0;
200                  for(int zoffset=-filterHW; zoffset<=filterHW; zoffset++){
201                    long z = zpos + spacing*zoffset;
202                    while((z<0)||(z>=long(zdim))){
203                      if(z<0) z = -z;                 // boundary conditions are
204                      if(z>=long(zdim)) z = 2*(zdim-1) - z; //    reflection.
205                    }
206                    size_t oldchan = z * spatialSize;
207               
208                    for(int yoffset=-filterHW; yoffset<=filterHW; yoffset++){
209                      long y = long(ypos) + spacing*yoffset;
210                      while((y<0)||(y>=long(ydim))){
211                        // boundary conditions are reflection.
212                        if(y<0) y = 0 - y;
213                        else if(y>=long(ydim)) y = 2*(ydim-1) - y;
214                      }
215
216                      // // Boundary conditions -- assume reflection at boundaries.
217                      // // Use limits as calculated above
218                      // if(yLim1[xpos]!=yLim2[xpos]){
219                      //        // if these are equal we will get into an infinite loop
220                      //        while((y<yLim1[xpos])||(y>yLim2[xpos])){
221                      //        // std::cerr << y << " " <<spacing << " " << yoffset << " " << ypos << " " << xpos << " " << yLim1[xpos] << " " << yLim2[xpos] << "\n";
222                      //          if(y<yLim1[xpos]) y = 2*yLim1[xpos] - y;     
223                      //          else if(y>yLim2[xpos]) y = 2*yLim2[xpos] - y;     
224                      //        }
225                      // }
226                      size_t oldrow = y * xdim;
227         
228                      for(int xoffset=-filterHW; xoffset<=filterHW; xoffset++){
229                        long x = long(xpos) + spacing*xoffset;
230                        while((x<0)||(x>=long(xdim))){
231                          // boundary conditions are reflection.
232                          if(x<0) x = 0 - x;
233                          else if(x>=long(xdim)) x = 2*(xdim-1) - x;
234                        }
235
236                        // // Boundary conditions -- assume reflection at boundaries.
237                        // // Use limits as calculated above
238                        // if(xLim1[ypos]!=xLim2[ypos]){
239                        //   // if these are equal we will get into an infinite loop
240                        //   while((x<xLim1[ypos])||(x>xLim2[ypos])){
241                        //     if(x<xLim1[ypos]) x = 2*xLim1[ypos] - x;     
242                        //     else if(x>xLim2[ypos]) x = 2*xLim2[ypos] - x;     
243                        //   }
244                        // }
245
246                        size_t oldpos = oldchan + oldrow + x;
247
248                        if(isGood[oldpos])
249                          wavelet[pos] -= filter[filterpos]*coeffs[oldpos];
250                     
251                        filterpos++;
252                   
253                      } //-> end of xoffset loop
254                    } //-> end of yoffset loop
255                  } //-> end of zoffset loop
256                } //-> end of else{ ( from if(!isGood[pos])  )
257           
258                pos++;
259              } //-> end of xpos loop
260            } //-> end of ypos loop
261          } //-> end of zpos loop
262
263          // Need to do this after we've done *all* the convolving
264          for(size_t pos=0;pos<size;pos++) coeffs[pos] = coeffs[pos] - wavelet[pos];
265
266          // Have found wavelet coeffs for this scale -- now threshold
267          if(scale>=par.getMinScale()){
268            if(par.getFlagRobustStats())
269              // findMedianStats(wavelet,size,isGood,mean,sigma);
270              mean = findMedian<float>(wavelet,isGood,size);
271            else
272              //findNormalStats(wavelet,size,isGood,mean,sigma);
273              mean = findMean<float>(wavelet,isGood,size);
274             
275            threshold = mean +
276              par.getAtrousCut()*originalSigma*sigmaFactors[scale];
277            for(size_t pos=0;pos<size;pos++){
278              if(!isGood[pos]){
279                output[pos] = input[pos];
280                // this preserves the Blank pixel values in the output.
281              }
282              else if( fabs(wavelet[pos]) > threshold ){
283                output[pos] += wavelet[pos];
284                // only add to the output if the wavelet coefficient is significant
285              }
286            }
287          }
288 
289          spacing *= 2;  // double the scale of the filter.
290
291        } //-> end of scale loop
292
293        for(size_t pos=0;pos<size;pos++) if(isGood[pos]) output[pos] += coeffs[pos];
294
295        // for(size_t i=0;i<size;i++) residual[i] = input[i] - output[i];
296        // findMedianStats(residual,goodSize,isGood,mean,newsigma);
297        // findMedianStatsDiff(input,output,goodSize,isGood,mean,newsigma);
298        // newsigma = madfmToSigma(newsigma);
299        if(par.getFlagRobustStats())
300          newsigma = madfmToSigma(findMADFMDiff(input,output,isGood,size));
301        else
302          newsigma = findStddevDiff<float>(input,output,isGood,size);
303
304        if(par.isVerbose()) printBackSpace(15);
305
306      } while( (iteration==1) ||
307               (fabs(oldsigma-newsigma)/newsigma > reconTolerance) );
308
309      if(par.isVerbose()) std::cout << "Completed "<<iteration<<" iterations. ";
310
311      // delete [] xLim1;
312      // delete [] xLim2;
313      // delete [] yLim1;
314      // delete [] yLim2;
315      delete [] filter;
316      // delete [] residual;
317      delete [] coeffs;
318      delete [] wavelet;
319
320    }
321
322    delete [] isGood;
323    delete [] sigmaFactors;
324  }
325
326}
Note: See TracBrowser for help on using the repository browser.