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