r170: *** 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.7 2000/08/02 18:09:11 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_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-param", 1, 0, O_FILTER_PARAM},
42   {"backproj", 1, 0, O_BACKPROJ},
43   {"trace", 1, 0, O_TRACE},
44   {"debug", 0, 0, O_DEBUG},
45   {"verbose", 0, 0, O_VERBOSE},
46   {"help", 0, 0, O_HELP},
47   {"version", 0, 0, O_VERSION},
48   {0, 0, 0, 0}
49 };
50
51 static const char* g_szIdStr = "$id$";
52
53 void 
54 pjrec_usage (const char *program)
55 {
56   cout << "usage: " << fileBasename(program) << " raysum-file image-file nx-image ny-image [OPTIONS]" << endl;
57   cout << "Image reconstruction from raysum projections" << endl;
58   cout << endl;
59   cout << "  raysum-file     Input raysum file" << endl;
60   cout << "  image-file      Output image file in SDF2D format" << endl;
61   cout << "  nx-image        Number of columns in output image" << endl;
62   cout << "  ny-image        Number of rows in output image" << endl;
63   cout << "  --interp        Interpolation method during backprojection" << endl;
64   cout << "    nearest     Nearest neighbor interpolation" << endl;
65   cout << "    linear      Linear interpolation" << endl;
66 #if HAVE_BSPLINE_INTERP
67   cout << "    bspline     B-spline interpolation" << endl;
68 #endif
69   cout << "  --preinterpolate  Preinterpolation factor (default = 1)\n";
70   cout << "                    Used only with frequency-based filtering\n";
71   cout << "  --filter       Filter name" << endl;
72   cout << "    abs_bandlimit Abs * Bandlimiting (default)" << endl;
73   cout << "    abs_sinc      Abs * Sinc" << endl;
74   cout << "    abs_cos       Abs * Cosine" << endl;
75   cout << "    abs_hamming   Abs * Hamming" << endl;
76   cout << "    shepp         Shepp-Logan" << endl;
77   cout << "    bandlimit     Bandlimiting" << endl;
78   cout << "    sinc          Sinc" << endl;
79   cout << "    cos           Cosine" << endl;
80   cout << "    triangle      Triangle" << endl;
81   cout << "    hamming       Hamming" << endl;
82   cout << "  --filter-method  Filter method before backprojections\n";;
83   cout << "    convolution      Spatial filtering (default)\n";
84   cout << "    fourier          Frequency filtering with discete fourier\n";
85   cout << "    fourier_table    Frequency filtering with table lookup fourier\n";
86   cout << "    fft              Fast Fourier Transform\n";
87 #if HAVE_FFTW
88   cout << "    fftw             Fast Fourier Transform West library\n";
89   cout << "    rfftw            Fast Fourier Transform West (real-mode) library\n";
90 #endif
91   cout << "  --zeropad n   Set zeropad level (default = 0)\n";
92   cout << "                set n to number of powers to two to pad\n";
93   cout << "  --frequency-filter  Set type of frequency filter\n";
94   cout << "    direct      Use direct frequency filter\n";
95   cout << "    ifourier    Use inverse fourier transform of spatial filter\n";
96   cout << "  --backproj    Backprojection Method" << endl;
97   cout << "    trig        Trigometric functions at every point" << endl;
98   cout << "    table       Trigometric functions with precalculated table" << endl;
99   cout << "    diff        Difference method" << endl;
100   cout << "    diff2       Optimized difference method (default)" << endl;
101   cout << "    idiff2      Optimized difference method with integer math" << endl;
102   cout << "    idiff3      Highly-optimized difference method with integer math" << endl;
103   cout << "  --filter-param Alpha level for Hamming filter" << endl;
104   cout << "  --trace        Set tracing to level" << endl;
105   cout << "     none      No tracing (default)" << endl;
106   cout << "     text      Text level tracing" << endl;
107   cout << "     phm       Trace phantom" << endl;
108   cout << "     rays      Trace allrays" << endl;
109   cout << "     plot      Trace plotting" << endl;
110   cout << "     clipping  Trace clipping" << endl;
111   cout << "  --verbose      Turn on verbose mode" << endl;
112   cout << "  --debug        Turn on debug mode" << endl;
113   cout << "  --version      Print version" << endl;
114   cout << "  --help         Print this help message" << endl;
115 }
116
117
118 #ifdef HAVE_MPI
119 static void ScatterProjectionsMPI (MPIWorld& mpiWorld, Projections& projGlobal, Projections& projLocal, const int debug);
120 static void ReduceImageMPI (MPIWorld& mpiWorld, ImageFile* imLocal, ImageFile* imGlobal);
121 #endif
122
123
124 int 
125 pjrec_main (int argc, char * argv[])
126 {
127   Projections projGlobal;
128   ImageFile* imGlobal = NULL;
129   char* filenameProj = NULL;
130   char* filenameImage = NULL;
131   string remark;
132   char *endptr;
133   int optVerbose = 0;
134   int optDebug = 0;
135   int optZeroPad = 0;
136   int optTrace = TRACE_NONE;
137   double optFilterParam = -1;
138   string optFilterName (SignalFilter::convertFilterIDToName (SignalFilter::FILTER_ABS_BANDLIMIT));
139   string optFilterMethodName (SignalFilter::convertFilterMethodIDToName (SignalFilter::FILTER_METHOD_CONVOLUTION));
140   string optInterpName (Backprojector::convertInterpIDToName (Backprojector::INTERP_LINEAR));
141   string optBackprojName (Backprojector::convertBackprojectIDToName (Backprojector::BPROJ_IDIFF3));
142   int optPreinterpolationFactor = 1;
143   int nx, ny;
144 #ifdef HAVE_MPI
145   ImageFile* imLocal;
146   int mpi_nview, mpi_ndet;
147   double mpi_detinc, mpi_rotinc, mpi_phmlen;
148   MPIWorld mpiWorld (argc, argv);
149 #endif
150
151   Timer timerProgram;
152
153 #ifdef HAVE_MPI
154   if (mpiWorld.getRank() == 0) {
155 #endif
156     while (1) {
157       int c = getopt_long(argc, argv, "", my_options, NULL);
158       char *endptr = NULL;
159       
160       if (c == -1)
161         break;
162       
163       switch (c)
164         {
165         case O_INTERP:
166           optInterpName = optarg;
167           break;
168         case O_PREINTERPOLATION_FACTOR:
169           optPreinterpolationFactor = strtol(optarg, &endptr, 10);
170           if (endptr != optarg + strlen(optarg)) {
171             pjrec_usage(argv[0]);
172             return(1);
173           }
174           break;
175         case O_FILTER:
176           optFilterName = optarg;
177           break;
178         case O_FILTER_METHOD:
179           optFilterMethodName = optarg;
180           break;
181         case O_BACKPROJ:
182           optBackprojName = optarg;
183           break;
184         case O_FILTER_PARAM:
185           optFilterParam = strtod(optarg, &endptr);
186           if (endptr != optarg + strlen(optarg)) {
187             pjrec_usage(argv[0]);
188             return(1);
189           }
190           break;
191         case O_ZEROPAD:
192           optZeroPad = strtol(optarg, &endptr, 10);
193           if (endptr != optarg + strlen(optarg)) {
194             pjrec_usage(argv[0]);
195             return(1);
196           }
197           break;
198         case O_VERBOSE:
199           optVerbose = 1;
200           break;
201         case O_DEBUG:
202           optDebug = 1;
203           break;
204         case O_TRACE:
205           if ((optTrace = TraceLevel::convertTraceNameToID(optarg)) == TRACE_INVALID) {
206             pjrec_usage(argv[0]);
207             return (1);
208           }
209           break;
210         case O_VERSION:
211 #ifdef VERSION
212           cout <<  "Version " <<  VERSION << endl;
213 #else
214           cout << "Unknown version number" << endl;
215 #endif
216           return (0);
217         case O_HELP:
218         case '?':
219           pjrec_usage(argv[0]);
220           return (0);
221         default:
222           pjrec_usage(argv[0]);
223           return (1);
224         }
225     }
226   
227     if (optind + 4 != argc) {
228       pjrec_usage(argv[0]);
229       return (1);
230     }
231
232     filenameProj = argv[optind];
233   
234     filenameImage = argv[optind + 1];
235   
236     nx = strtol(argv[optind + 2], &endptr, 10);
237     ny = strtol(argv[optind + 3], &endptr, 10);
238   
239     ostringstream filterDesc;
240     if (optFilterParam >= 0)
241       filterDesc << optFilterName << ": alpha=" << optFilterParam; 
242     else
243       filterDesc << optFilterName;
244
245     ostringstream label;
246     label << "pjrec: " << nx << "x" << ny << ", " << filterDesc.str() << ", " << optInterpName << ", preinterpolationFactor=" << optPreinterpolationFactor << ", " << optBackprojName;
247     remark = label.str();
248   
249     if (optVerbose)
250       cout << "Remark: " << remark << endl;
251 #ifdef HAVE_MPI
252   }
253 #endif
254
255 #ifdef HAVE_MPI
256   if (mpiWorld.getRank() == 0) {
257     projGlobal.read (filenameProj);
258     if (optVerbose)
259       projGlobal.printScanInfo();
260
261     mpi_ndet = projGlobal.nDet();
262     mpi_nview = projGlobal.nView();
263     mpi_detinc = projGlobal.detInc();
264     mpi_phmlen = projGlobal.phmLen();
265     mpi_rotinc = projGlobal.rotInc();
266   }
267
268   TimerCollectiveMPI timerBcast (mpiWorld.getComm());
269   mpiWorld.BcastString (optBackprojName);
270   mpiWorld.BcastString (optFilterName);
271   mpiWorld.BcastString (optFilterMethodName);
272   mpiWorld.BcastString (optInterpName);
273   mpiWorld.getComm().Bcast (&optVerbose, 1, MPI::INT, 0);
274   mpiWorld.getComm().Bcast (&optDebug, 1, MPI::INT, 0);
275   mpiWorld.getComm().Bcast (&optTrace, 1, MPI::INT, 0);
276   mpiWorld.getComm().Bcast (&optFilterParam, 1, MPI::DOUBLE, 0);
277   mpiWorld.getComm().Bcast (&optZeroPad, 1, MPI::INT, 0);
278   mpiWorld.getComm().Bcast (&optPreinterpolationFactor, 1, MPI::INT, 0);
279   mpiWorld.getComm().Bcast (&mpi_ndet, 1, MPI::INT, 0);
280   mpiWorld.getComm().Bcast (&mpi_nview, 1, MPI::INT, 0);
281   mpiWorld.getComm().Bcast (&mpi_detinc, 1, MPI::DOUBLE, 0);
282   mpiWorld.getComm().Bcast (&mpi_phmlen, 1, MPI::DOUBLE, 0);
283   mpiWorld.getComm().Bcast (&mpi_rotinc, 1, MPI::DOUBLE, 0);
284   mpiWorld.getComm().Bcast (&nx, 1, MPI::INT, 0);
285   mpiWorld.getComm().Bcast (&ny, 1, MPI::INT, 0);
286   if (optVerbose)
287       timerBcast.timerEndAndReport ("Time to broadcast variables");
288
289   mpiWorld.setTotalWorkUnits (mpi_nview);
290
291   Projections projLocal (mpiWorld.getMyLocalWorkUnits(), mpi_ndet);
292   projLocal.setDetInc (mpi_detinc);
293   projLocal.setPhmLen (mpi_phmlen);
294   projLocal.setRotInc (mpi_rotinc);
295
296   TimerCollectiveMPI timerScatter (mpiWorld.getComm());
297   ScatterProjectionsMPI (mpiWorld, projGlobal, projLocal, optDebug);
298   if (optVerbose)
299       timerScatter.timerEndAndReport ("Time to scatter projections");
300
301   if (mpiWorld.getRank() == 0) {
302     imGlobal = new ImageFile (nx, ny);
303   }
304
305   imLocal = new ImageFile (nx, ny);
306 #else
307   projGlobal.read (filenameProj);
308   if (optVerbose)
309     projGlobal.printScanInfo();
310
311   imGlobal = new ImageFile (nx, ny);
312 #endif
313
314 #ifdef HAVE_MPI
315   TimerCollectiveMPI timerReconstruct (mpiWorld.getComm());
316   projLocal.reconstruct (*imLocal, optFilterName.c_str(), optFilterParam, optFilterMethodName.c_str(), optZeroPad, optInterpName.c_str(), optPreinterpolationFactor, optBackprojName.c_str(), optTrace);
317   if (optVerbose)
318       timerReconstruct.timerEndAndReport ("Time to reconstruct");
319
320   TimerCollectiveMPI timerReduce (mpiWorld.getComm());
321   ReduceImageMPI (mpiWorld, imLocal, imGlobal);
322   if (optVerbose)
323       timerReduce.timerEndAndReport ("Time to reduce image");
324 #else
325   projGlobal.reconstruct (*imGlobal, optFilterName.c_str(), optFilterParam, optFilterMethodName.c_str(), optZeroPad, optInterpName.c_str(), optPreinterpolationFactor, optBackprojName.c_str(), optTrace);
326 #endif
327
328 #ifdef HAVE_MPI
329   if (mpiWorld.getRank() == 0)
330 #endif
331     {
332       double calcTime = timerProgram.timerEnd();
333       imGlobal->labelAdd (projGlobal.getLabel());
334       imGlobal->labelAdd (Array2dFileLabel::L_HISTORY, remark.c_str(), calcTime);
335       imGlobal->fileWrite (filenameImage);
336       if (optVerbose)
337         cout << "Run time: " << calcTime << " seconds" << endl;
338     }
339 #ifdef HAVE_MPI
340   MPI::Finalize();
341 #endif
342
343   return (0);
344 }
345
346
347 //////////////////////////////////////////////////////////////////////////////////////
348 // MPI Support Routines
349 //
350 //////////////////////////////////////////////////////////////////////////////////////
351
352 #ifdef HAVE_MPI
353 static void ScatterProjectionsMPI (MPIWorld& mpiWorld, Projections& projGlobal, Projections& projLocal, const int optDebug)
354 {
355   if (mpiWorld.getRank() == 0) {
356     for (int iProc = 0; iProc < mpiWorld.getNumProcessors(); iProc++) {
357       for (int iw = mpiWorld.getStartWorkUnit(iProc); iw <= mpiWorld.getEndWorkUnit(iProc); iw++) {
358         DetectorArray& detarray = projGlobal.getDetectorArray( iw );
359         int nDet = detarray.nDet();
360         DetectorValue* detval = detarray.detValues();
361
362         double viewAngle = detarray.viewAngle();
363         mpiWorld.getComm().Send(&nDet, 1, MPI::INT, iProc, 0);
364         mpiWorld.getComm().Send(&viewAngle, 1, MPI::DOUBLE, iProc, 0);
365         mpiWorld.getComm().Send(detval, nDet, MPI::FLOAT, iProc, 0);
366       }
367     }
368   }
369
370   for (int iw = 0; iw < mpiWorld.getMyLocalWorkUnits(); iw++) {
371     MPI::Status status;
372     int nDet;
373     double viewAngle;
374     DetectorValue* detval = projLocal.getDetectorArray(iw).detValues();
375
376     mpiWorld.getComm().Recv(&nDet, 1, MPI::INT, 0, 0, status);
377     mpiWorld.getComm().Recv(&viewAngle, 1, MPI::DOUBLE, 0, 0, status);
378     mpiWorld.getComm().Recv(detval, nDet, MPI::FLOAT, 0, 0, status);
379     projLocal.getDetectorArray(iw).setViewAngle( viewAngle );
380   }
381 }
382
383 static void
384 ReduceImageMPI (MPIWorld& mpiWorld, ImageFile* imLocal, ImageFile* imGlobal)
385 {
386   ImageFileArray vLocal = imLocal->getArray();
387
388   for (int ix = 0; ix < imLocal->nx(); ix++) {
389     void *recvbuf = NULL;
390     if (mpiWorld.getRank() == 0) {
391       ImageFileArray vGlobal = imGlobal->getArray();
392       recvbuf = vGlobal[ix];
393     }
394     mpiWorld.getComm().Reduce (vLocal[ix], recvbuf, imLocal->ny(), imLocal->getMPIDataType(), MPI::SUM, 0);
395   }
396 }
397
398 #endif
399
400
401 #ifndef NO_MAIN
402 int 
403 main (int argc, char* argv[])
404 {
405   int retval = 1;
406
407   try {
408     retval = pjrec_main(argc, argv);
409   } catch (exception e) {
410     cerr << "Exception: " << e.what() << endl;
411   } catch (...) {
412     cerr << "Unknown exception" << endl;
413   }
414
415   return (retval);
416 }
417 #endif
418