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