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