r186: *** empty log message ***
[ctsim.git] / tools / pjrec.cpp
1 /*****************************************************************************
2 ** FILE IDENTIFICATION
3 **
4 **   Name:          pjrec.cpp
5 **   Purpose:       Reconstruct an image from projections
6 **   Programmer:    Kevin Rosenberg
7 **   Date Started:  Aug 1984
8 **
9 **  This is part of the CTSim program
10 **  Copyright (C) 1983-2000 Kevin Rosenberg
11 **
12 **  $Id: pjrec.cpp,v 1.16 2000/08/31 08:38:58 kevin Exp $
13 **
14 **  This program is free software; you can redistribute it and/or modify
15 **  it under the terms of the GNU General Public License (version 2) as
16 **  published by the Free Software Foundation.
17 **
18 **  This program is distributed in the hope that it will be useful,
19 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
20 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 **  GNU General Public License for more details.
22 **
23 **  You should have received a copy of the GNU General Public License
24 **  along with this program; if not, write to the Free Software
25 **  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26 ******************************************************************************/
27
28 #include "ct.h"
29 #include "timer.h"
30
31
32 enum {O_INTERP, O_FILTER, O_FILTER_METHOD, O_ZEROPAD, O_FILTER_PARAM, O_FILTER_GENERATION, O_BACKPROJ, O_PREINTERPOLATION_FACTOR, O_VERBOSE, O_TRACE, O_HELP, O_DEBUG, O_VERSION};
33
34 static struct option my_options[] =
35 {
36   {"interp", 1, 0, O_INTERP},
37   {"preinterpolation-factor", 1, 0, O_PREINTERPOLATION_FACTOR},
38   {"filter", 1, 0, O_FILTER},
39   {"filter-method", 1, 0, O_FILTER_METHOD},
40   {"zeropad", 1, 0, O_ZEROPAD},
41   {"filter-generation", 1, 0, O_FILTER_GENERATION},
42   {"filter-param", 1, 0, O_FILTER_PARAM},
43   {"backproj", 1, 0, O_BACKPROJ},
44   {"trace", 1, 0, O_TRACE},
45   {"debug", 0, 0, O_DEBUG},
46   {"verbose", 0, 0, O_VERBOSE},
47   {"help", 0, 0, O_HELP},
48   {"version", 0, 0, O_VERSION},
49   {0, 0, 0, 0}
50 };
51
52 static const char* g_szIdStr = "$Id: pjrec.cpp,v 1.16 2000/08/31 08:38:58 kevin Exp $";
53
54 void 
55 pjrec_usage (const char *program)
56 {
57   cout << "usage: " << fileBasename(program) << " raysum-file image-file nx-image ny-image [OPTIONS]" << endl;
58   cout << "Image reconstruction from raysum projections" << endl;
59   cout << endl;
60   cout << "  raysum-file     Input raysum file" << endl;
61   cout << "  image-file      Output image file in SDF2D format" << endl;
62   cout << "  nx-image        Number of columns in output image" << endl;
63   cout << "  ny-image        Number of rows in output image" << endl;
64   cout << "  --interp        Interpolation method during backprojection" << endl;
65   cout << "    nearest     Nearest neighbor interpolation" << endl;
66   cout << "    linear      Linear interpolation" << endl;
67 #if HAVE_BSPLINE_INTERP
68   cout << "    bspline     B-spline interpolation" << endl;
69 #endif
70   cout << "  --preinterpolate  Preinterpolation factor (default = 1)\n";
71   cout << "                    Used only with frequency-based filtering\n";
72   cout << "  --filter       Filter name" << endl;
73   cout << "    abs_bandlimit Abs * Bandlimiting (default)" << endl;
74   cout << "    abs_sinc      Abs * Sinc" << endl;
75   cout << "    abs_cosine    Abs * Cosine" << endl;
76   cout << "    abs_hamming   Abs * Hamming" << endl;
77   cout << "    shepp         Shepp-Logan" << endl;
78   cout << "    bandlimit     Bandlimiting" << endl;
79   cout << "    sinc          Sinc" << endl;
80   cout << "    cosine        Cosine" << endl;
81   cout << "    triangle      Triangle" << endl;
82   cout << "    hamming       Hamming" << endl;
83   cout << "  --filter-method  Filter method before backprojections\n";;
84   cout << "    convolution      Spatial filtering (default)\n";
85   cout << "    fourier          Frequency filtering with discete fourier\n";
86   cout << "    fourier_table    Frequency filtering with table lookup fourier\n";
87   cout << "    fft              Fast Fourier Transform\n";
88 #if HAVE_FFTW
89   cout << "    fftw             Fast Fourier Transform West library\n";
90   cout << "    rfftw            Fast Fourier Transform West (real-mode) library\n";
91 #endif
92   cout << "  --zeropad n   Set zeropad level (default = 0)\n";
93   cout << "                set n to number of powers to two to pad\n";
94   cout << "  --filter-generation  Filter Generation mode\n";
95   cout << "    direct       Use direct filter in spatial or frequency domain (default)\n";
96   cout << "    inverse_fourier  Use inverse fourier transform of inverse filter\n";
97   cout << "  --backproj    Backprojection Method" << endl;
98   cout << "    trig        Trigometric functions at every point" << endl;
99   cout << "    table       Trigometric functions with precalculated table" << endl;
100   cout << "    diff        Difference method" << endl;
101   cout << "    diff2       Optimized difference method (default)" << endl;
102   cout << "    idiff2      Optimized difference method with integer math" << endl;
103   cout << "    idiff3      Highly-optimized difference method with integer math" << endl;
104   cout << "  --filter-param Alpha level for Hamming filter" << endl;
105   cout << "  --trace        Set tracing to level" << endl;
106   cout << "     none        No tracing (default)" << endl;
107   cout << "     console     Text level tracing" << endl;
108   cout << "     phantom     Trace phantom" << endl;
109   cout << "     proj        Trace allrays" << endl;
110   cout << "     plot        Trace plotting" << endl;
111   cout << "     clipping    Trace clipping" << endl;
112   cout << "  --verbose      Turn on verbose mode" << endl;
113   cout << "  --debug        Turn on debug mode" << endl;
114   cout << "  --version      Print version" << endl;
115   cout << "  --help         Print this help message" << endl;
116 }
117
118
119 #ifdef HAVE_MPI
120 static void ScatterProjectionsMPI (MPIWorld& mpiWorld, Projections& projGlobal, Projections& projLocal, const bool bDebug);
121 static void ReduceImageMPI (MPIWorld& mpiWorld, ImageFile* imLocal, ImageFile* imGlobal);
122 #endif
123
124
125 int 
126 pjrec_main (int argc, char * argv[])
127 {
128   Projections projGlobal;
129   ImageFile* imGlobal = NULL;
130   char* pszFilenameProj = NULL;
131   char* pszFilenameImage = NULL;
132   string sRemark;
133   bool bOptVerbose = false;
134   bool bOptDebug = 1;
135   int iOptZeropad = 1;
136   int optTrace = Trace::TRACE_NONE;
137   double dOptFilterParam = -1;
138   string sOptFilterName (SignalFilter::convertFilterIDToName (SignalFilter::FILTER_ABS_BANDLIMIT));
139   string sOptFilterMethodName (ProcessSignal::convertFilterMethodIDToName (ProcessSignal::FILTER_METHOD_CONVOLUTION));
140   string sOptFilterGenerationName (ProcessSignal::convertFilterGenerationIDToName (ProcessSignal::FILTER_GENERATION_DIRECT));
141   string sOptInterpName (Backprojector::convertInterpIDToName (Backprojector::INTERP_LINEAR));
142   string sOptBackprojectName (Backprojector::convertBackprojectIDToName (Backprojector::BPROJ_IDIFF3));
143   int iOptPreinterpolationFactor = 1;
144   int nx, ny;
145   char *endptr;
146 #ifdef HAVE_MPI
147   ImageFile* imLocal;
148   int mpi_nview, mpi_ndet;
149   double mpi_detinc, mpi_rotinc, mpi_phmlen;
150   MPIWorld mpiWorld (argc, argv);
151 #endif
152
153   Timer timerProgram;
154
155 #ifdef HAVE_MPI
156   if (mpiWorld.getRank() == 0) {
157 #endif
158     while (1) {
159       int c = getopt_long(argc, argv, "", my_options, NULL);
160       char *endptr = NULL;
161       
162       if (c == -1)
163         break;
164       
165       switch (c)
166         {
167         case O_INTERP:
168           sOptInterpName = optarg;
169           break;
170         case O_PREINTERPOLATION_FACTOR:
171           iOptPreinterpolationFactor = strtol(optarg, &endptr, 10);
172           if (endptr != optarg + strlen(optarg)) {
173             pjrec_usage(argv[0]);
174             return(1);
175           }
176           break;
177         case O_FILTER:
178           sOptFilterName = optarg;
179           break;
180         case O_FILTER_METHOD:
181           sOptFilterMethodName = optarg;
182           break;
183         case O_FILTER_GENERATION:
184           sOptFilterGenerationName = optarg;
185           break;
186         case O_FILTER_PARAM:
187           dOptFilterParam = strtod(optarg, &endptr);
188           if (endptr != optarg + strlen(optarg)) {
189             pjrec_usage(argv[0]);
190             return(1);
191           }
192           break;
193         case O_ZEROPAD:
194           iOptZeropad = strtol(optarg, &endptr, 10);
195           if (endptr != optarg + strlen(optarg)) {
196             pjrec_usage(argv[0]);
197             return(1);
198           }
199           break;
200         case O_BACKPROJ:
201           sOptBackprojectName = optarg;
202           break;
203         case O_VERBOSE:
204           bOptVerbose = true;
205           break;
206         case O_DEBUG:
207           bOptDebug = true;
208           break;
209         case O_TRACE:
210           if ((optTrace = Trace::convertTraceNameToID(optarg)) == Trace::TRACE_INVALID) {
211             pjrec_usage(argv[0]);
212             return (1);
213           }
214           break;
215         case O_VERSION:
216 #ifdef VERSION
217           cout <<  "Version " <<  VERSION << endl << g_szIdStr << endl;
218 #else
219           cout << "Unknown version number" << endl;
220 #endif
221           return (0);
222         case O_HELP:
223         case '?':
224           pjrec_usage(argv[0]);
225           return (0);
226         default:
227           pjrec_usage(argv[0]);
228           return (1);
229         }
230     }
231   
232     if (optind + 4 != argc) {
233       pjrec_usage(argv[0]);
234       return (1);
235     }
236
237     pszFilenameProj = argv[optind];
238   
239     pszFilenameImage = argv[optind + 1];
240   
241     nx = strtol(argv[optind + 2], &endptr, 10);
242     ny = strtol(argv[optind + 3], &endptr, 10);
243   
244     ostringstream filterDesc;
245     if (dOptFilterParam >= 0)
246       filterDesc << sOptFilterName << ": alpha=" << dOptFilterParam; 
247     else
248       filterDesc << sOptFilterName;
249
250     ostringstream label;
251     label << "pjrec: " << nx << "x" << ny << ", " << filterDesc.str() << ", " << sOptInterpName << ", preinterpolationFactor=" << iOptPreinterpolationFactor << ", " << sOptBackprojectName;
252     sRemark = label.str();
253   
254     if (bOptVerbose)
255       cout << "SRemark: " << sRemark << endl;
256 #ifdef HAVE_MPI
257   }
258 #endif
259
260 #ifdef HAVE_MPI
261   if (mpiWorld.getRank() == 0) {
262     projGlobal.read (pszFilenameProj);
263     if (bOptVerbose) {
264       ostringstream os;
265       projGlobal.printScanInfo (os);
266       cout << os.str();
267     }
268
269     mpi_ndet = projGlobal.nDet();
270     mpi_nview = projGlobal.nView();
271     mpi_detinc = projGlobal.detInc();
272     mpi_phmlen = projGlobal.phmLen();
273     mpi_rotinc = projGlobal.rotInc();
274   }
275
276   TimerCollectiveMPI timerBcast (mpiWorld.getComm());
277   mpiWorld.BcastString (sOptBackprojectName);
278   mpiWorld.BcastString (sOptFilterName);
279   mpiWorld.BcastString (sOptFilterMethodName);
280   mpiWorld.BcastString (sOptInterpName);
281   mpiWorld.getComm().Bcast (&bOptVerbose, 1, MPI::INT, 0);
282   mpiWorld.getComm().Bcast (&bOptDebug, 1, MPI::INT, 0);
283   mpiWorld.getComm().Bcast (&optTrace, 1, MPI::INT, 0);
284   mpiWorld.getComm().Bcast (&dOptFilterParam, 1, MPI::DOUBLE, 0);
285   mpiWorld.getComm().Bcast (&iOptZeropad, 1, MPI::INT, 0);
286   mpiWorld.getComm().Bcast (&iOptPreinterpolationFactor, 1, MPI::INT, 0);
287   mpiWorld.getComm().Bcast (&mpi_ndet, 1, MPI::INT, 0);
288   mpiWorld.getComm().Bcast (&mpi_nview, 1, MPI::INT, 0);
289   mpiWorld.getComm().Bcast (&mpi_detinc, 1, MPI::DOUBLE, 0);
290   mpiWorld.getComm().Bcast (&mpi_phmlen, 1, MPI::DOUBLE, 0);
291   mpiWorld.getComm().Bcast (&mpi_rotinc, 1, MPI::DOUBLE, 0);
292   mpiWorld.getComm().Bcast (&nx, 1, MPI::INT, 0);
293   mpiWorld.getComm().Bcast (&ny, 1, MPI::INT, 0);
294   if (bOptVerbose)
295       timerBcast.timerEndAndReport ("Time to broadcast variables");
296
297   mpiWorld.setTotalWorkUnits (mpi_nview);
298
299   Projections projLocal (mpiWorld.getMyLocalWorkUnits(), mpi_ndet);
300   projLocal.setDetInc (mpi_detinc);
301   projLocal.setPhmLen (mpi_phmlen);
302   projLocal.setRotInc (mpi_rotinc);
303
304   TimerCollectiveMPI timerScatter (mpiWorld.getComm());
305   ScatterProjectionsMPI (mpiWorld, projGlobal, projLocal, bOptDebug);
306   if (bOptVerbose)
307       timerScatter.timerEndAndReport ("Time to scatter projections");
308
309   if (mpiWorld.getRank() == 0) {
310     imGlobal = new ImageFile (nx, ny);
311   }
312
313   imLocal = new ImageFile (nx, ny);
314 #else
315   projGlobal.read (pszFilenameProj);
316   if (bOptVerbose) {
317     ostringstream os;
318     projGlobal.printScanInfo(os);
319     cout << os.str();
320   }
321
322   imGlobal = new ImageFile (nx, ny);
323 #endif
324
325 #ifdef HAVE_MPI
326   TimerCollectiveMPI timerReconstruct (mpiWorld.getComm());
327   projLocal.reconstruct (*imLocal, sOptFilterName.c_str(), dOptFilterParam, sOptFilterMethodName.c_str(), iOptZeropad, sOptFilterGenerationName.c_str(), sOptInterpName.c_str(), iOptPreinterpolationFactor, sOptBackprojectName.c_str(), optTrace);
328   if (bOptVerbose)
329       timerReconstruct.timerEndAndReport ("Time to reconstruct");
330
331   TimerCollectiveMPI timerReduce (mpiWorld.getComm());
332   ReduceImageMPI (mpiWorld, imLocal, imGlobal);
333   if (bOptVerbose)
334       timerReduce.timerEndAndReport ("Time to reduce image");
335 #else
336   projGlobal.reconstruct (*imGlobal, sOptFilterName.c_str(), dOptFilterParam, sOptFilterMethodName.c_str(), iOptZeropad, sOptFilterGenerationName.c_str(), sOptInterpName.c_str(), iOptPreinterpolationFactor, sOptBackprojectName.c_str(), optTrace);
337 #endif
338
339 #ifdef HAVE_MPI
340   if (mpiWorld.getRank() == 0)
341 #endif
342     {
343       double dCalcTime = timerProgram.timerEnd();
344       imGlobal->labelAdd (projGlobal.getLabel());
345       imGlobal->labelAdd (Array2dFileLabel::L_HISTORY, sRemark.c_str(), dCalcTime);
346       imGlobal->fileWrite (pszFilenameImage);
347       if (bOptVerbose)
348         cout << "Run time: " << dCalcTime << " seconds" << endl;
349     }
350 #ifdef HAVE_MPI
351   MPI::Finalize();
352 #endif
353
354   return (0);
355 }
356
357
358 //////////////////////////////////////////////////////////////////////////////////////
359 // MPI Support Routines
360 //
361 //////////////////////////////////////////////////////////////////////////////////////
362
363 #ifdef HAVE_MPI
364 static void ScatterProjectionsMPI (MPIWorld& mpiWorld, Projections& projGlobal, Projections& projLocal, const bool bOptDebug)
365 {
366   if (mpiWorld.getRank() == 0) {
367     for (int iProc = 0; iProc < mpiWorld.getNumProcessors(); iProc++) {
368       for (int iw = mpiWorld.getStartWorkUnit(iProc); iw <= mpiWorld.getEndWorkUnit(iProc); iw++) {
369         DetectorArray& detarray = projGlobal.getDetectorArray( iw );
370         int nDet = detarray.nDet();
371         DetectorValue* detval = detarray.detValues();
372
373         double viewAngle = detarray.viewAngle();
374         mpiWorld.getComm().Send(&nDet, 1, MPI::INT, iProc, 0);
375         mpiWorld.getComm().Send(&viewAngle, 1, MPI::DOUBLE, iProc, 0);
376         mpiWorld.getComm().Send(detval, nDet, MPI::FLOAT, iProc, 0);
377       }
378     }
379   }
380
381   for (int iw = 0; iw < mpiWorld.getMyLocalWorkUnits(); iw++) {
382     MPI::Status status;
383     int nDet;
384     double viewAngle;
385     DetectorValue* detval = projLocal.getDetectorArray(iw).detValues();
386
387     mpiWorld.getComm().Recv(&nDet, 1, MPI::INT, 0, 0, status);
388     mpiWorld.getComm().Recv(&viewAngle, 1, MPI::DOUBLE, 0, 0, status);
389     mpiWorld.getComm().Recv(detval, nDet, MPI::FLOAT, 0, 0, status);
390     projLocal.getDetectorArray(iw).setViewAngle( viewAngle );
391   }
392 }
393
394 static void
395 ReduceImageMPI (MPIWorld& mpiWorld, ImageFile* imLocal, ImageFile* imGlobal)
396 {
397   ImageFileArray vLocal = imLocal->getArray();
398
399   for (unsigned int ix = 0; ix < imLocal->nx(); ix++) {
400     void *recvbuf = NULL;
401     if (mpiWorld.getRank() == 0) {
402       ImageFileArray vGlobal = imGlobal->getArray();
403       recvbuf = vGlobal[ix];
404     }
405     mpiWorld.getComm().Reduce (vLocal[ix], recvbuf, imLocal->ny(), imLocal->getMPIDataType(), MPI::SUM, 0);
406   }
407 }
408
409 #endif
410
411
412 #ifndef NO_MAIN
413 int 
414 main (int argc, char* argv[])
415 {
416   int retval = 1;
417
418   try {
419     retval = pjrec_main(argc, argv);
420   } catch (exception e) {
421     cerr << "Exception: " << e.what() << endl;
422   } catch (...) {
423     cerr << "Unknown exception" << endl;
424   }
425
426   return (retval);
427 }
428 #endif
429