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