2d94be905dfe2f61a1c75e88740bdc74144233f1
[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.12 2000/06/19 17:58:13 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   ImageFile *imGlobal = NULL;
107   Projections projGlobal;
108   char *pj_name, *im_filename = NULL;
109   string remark;
110   char *endptr;
111   int opt_verbose = 0;
112   int opt_debug = 0;
113   int opt_trace = TRACE_NONE;
114   double opt_filter_param = 1;
115   FilterType opt_filter = FILTER_ABS_BANDLIMIT;
116   InterpolationType opt_interp = I_LINEAR;
117   int opt_interp_param = 1;
118   BackprojType opt_backproj = O_BPROJ_DIFF2;
119   int nx, ny;
120 #ifdef HAVE_MPI
121   ImageFile *imLocal;
122   int mpi_nview, mpi_ndet;
123   double mpi_detinc, mpi_rotinc, mpi_phmlen;
124   MPIWorld mpiWorld (argc, argv);
125 #endif
126
127   Timer timerProgram;
128
129 #ifdef HAVE_MPI
130   if (mpiWorld.getRank() == 0) {
131 #endif
132     while (1) {
133       int c = getopt_long(argc, argv, "", my_options, NULL);
134       char *endptr = NULL;
135       
136       if (c == -1)
137         break;
138       
139       switch (c)
140         {
141         case O_INTERP:
142           if ((opt_interp = opt_set_interpolation(optarg)) < 0) {
143             ctrec_usage(argv[0]);
144             return (1);
145           }
146           break;
147         case O_FILTER:
148           if ((opt_filter = opt_set_filter(optarg)) < 0) {
149             ctrec_usage(argv[0]);
150             return (1);
151           }
152           break;
153         case O_BACKPROJ:
154           if ((opt_backproj = opt_set_backproj(optarg)) < 0) {
155               ctrec_usage(argv[0]);
156               return (1);
157           }
158           break;
159         case O_FILTER_PARAM:
160           opt_filter_param = strtod(optarg, &endptr);
161           if (endptr != optarg + strlen(optarg)) {
162             ctrec_usage(argv[0]);
163           }
164           break;
165         case O_VERBOSE:
166           opt_verbose = 1;
167           break;
168         case O_DEBUG:
169           opt_debug = 1;
170           break;
171         case O_TRACE:
172           if ((opt_trace = opt_set_trace(optarg)) < 0) {
173             ctrec_usage(argv[0]);
174             return (1);
175           }
176           break;
177         case O_VERSION:
178 #ifdef VERSION
179           cout <<  "Version " <<  VERSION << endl;
180 #else
181           cout << "Unknown version number" << endl;
182 #endif
183           return (0);
184         case O_HELP:
185         case '?':
186           ctrec_usage(argv[0]);
187           return (0);
188         default:
189           ctrec_usage(argv[0]);
190           return (1);
191         }
192     }
193   
194     if (optind + 4 != argc) {
195       ctrec_usage(argv[0]);
196       return (1);
197     }
198
199     pj_name = argv[optind];
200   
201     im_filename = argv[optind + 1];
202   
203     nx = strtol(argv[optind + 2], &endptr, 10);
204     ny = strtol(argv[optind + 3], &endptr, 10);
205   
206     ostringstream filt_name;
207     if (opt_filter == FILTER_G_HAMMING || opt_filter == FILTER_ABS_G_HAMMING)
208       filt_name << name_of_filter (opt_filter) << ": alpha=" << opt_filter_param; 
209     else
210       filt_name << name_of_filter (opt_filter);
211   
212     ostringstream label;
213     label << "Reconstruct: " << nx << "x" << ny << ", " << filt_name.str() << ", " << name_of_interpolation (opt_interp) << ", " << name_of_backproj(opt_backproj);
214     remark = label.str();
215   
216     if (opt_verbose)
217       cout << "Remark: " << remark << endl;
218 #ifdef HAVE_MPI
219   }
220 #endif
221
222 #ifdef HAVE_MPI
223   if (mpiWorld.getRank() == 0) {
224     projGlobal.read (pj_name);
225     if (opt_verbose)
226       projGlobal.printScanInfo();
227
228     mpi_ndet = projGlobal.nDet();
229     mpi_nview = projGlobal.nView();
230     mpi_detinc = projGlobal.detInc();
231     mpi_phmlen = projGlobal.phmLen();
232     mpi_rotinc = projGlobal.rotInc();
233   }
234
235   TimerCollectiveMPI timerBcast (mpiWorld.getComm());
236   mpiWorld.getComm().Bcast (&opt_verbose, 1, MPI::INT, 0);
237   mpiWorld.getComm().Bcast (&opt_debug, 1, MPI::INT, 0);
238   mpiWorld.getComm().Bcast (&opt_trace, 1, MPI::INT, 0);
239   mpiWorld.getComm().Bcast (&opt_filter, 1, MPI::INT, 0);
240   mpiWorld.getComm().Bcast (&opt_interp, 1, MPI::INT, 0);
241   mpiWorld.getComm().Bcast (&opt_filter_param, 1, MPI::DOUBLE, 0);
242   mpiWorld.getComm().Bcast (&opt_interp_param, 1, MPI::INT, 0);
243   mpiWorld.getComm().Bcast (&opt_backproj, 1, MPI::INT, 0);
244   mpiWorld.getComm().Bcast (&mpi_ndet, 1, MPI::INT, 0);
245   mpiWorld.getComm().Bcast (&mpi_nview, 1, MPI::INT, 0);
246   mpiWorld.getComm().Bcast (&mpi_detinc, 1, MPI::DOUBLE, 0);
247   mpiWorld.getComm().Bcast (&mpi_phmlen, 1, MPI::DOUBLE, 0);
248   mpiWorld.getComm().Bcast (&mpi_rotinc, 1, MPI::DOUBLE, 0);
249   mpiWorld.getComm().Bcast (&nx, 1, MPI::INT, 0);
250   mpiWorld.getComm().Bcast (&ny, 1, MPI::INT, 0);
251   if (opt_verbose)
252       timerBcast.timerEndAndReport ("Time to broadcast variables");
253
254   mpiWorld.setTotalWorkUnits (mpi_nview);
255
256   Projections projLocal (mpiWorld.getMyLocalWorkUnits(), mpi_ndet);
257   projLocal.setDetInc (mpi_detinc);
258   projLocal.setPhmLen (mpi_phmlen);
259   projLocal.setRotInc (mpi_rotinc);
260
261   TimerCollectiveMPI timerScatter (mpiWorld.getComm());
262   ScatterProjectionsMPI (mpiWorld, projGlobal, projLocal, opt_debug);
263   if (opt_verbose)
264       timerScatter.timerEndAndReport ("Time to scatter projections");
265
266   if (mpiWorld.getRank() == 0) {
267     imGlobal = new ImageFile (im_filename, nx, ny);
268     imGlobal->fileCreate();
269   }
270
271   imLocal = new ImageFile (nx, ny);
272 #else
273   projGlobal.read (pj_name);
274   if (opt_verbose)
275     projGlobal.printScanInfo();
276
277   imGlobal = new ImageFile (im_filename, nx, ny);
278   imGlobal->fileCreate();
279 #endif
280
281 #ifdef HAVE_MPI
282   TimerCollectiveMPI timerReconstruct (mpiWorld.getComm());
283   proj_reconst (*imLocal, projLocal, opt_filter, opt_filter_param, opt_interp, opt_interp_param, opt_backproj, opt_trace);
284   if (opt_verbose)
285       timerReconstruct.timerEndAndReport ("Time to reconstruct");
286
287   TimerCollectiveMPI timerReduce (mpiWorld.getComm());
288   ReduceImageMPI (mpiWorld, imLocal, imGlobal);
289   if (opt_verbose)
290       timerReduce.timerEndAndReport ("Time to reduce image");
291 #else
292   proj_reconst (*imGlobal, projGlobal, opt_filter, opt_filter_param, opt_interp, opt_interp_param, opt_backproj, opt_trace);
293 #endif
294
295 #ifdef HAVE_MPI
296   if (mpiWorld.getRank() == 0)
297 #endif
298     {
299       double calcTime = timerProgram.timerEnd();
300       imGlobal->arrayDataWrite ();
301       imGlobal->labelAdd (Array2dFileLabel::L_HISTORY, projGlobal.remark(), projGlobal.calcTime());
302       imGlobal->labelAdd (Array2dFileLabel::L_HISTORY, remark.c_str(), calcTime);
303       imGlobal->fileClose ();
304       if (opt_verbose)
305         cout << "Run time: " << calcTime << " seconds" << endl;
306     }
307 #ifdef HAVE_MPI
308   MPI::Finalize();
309 #endif
310
311   return (0);
312 }
313
314
315 //////////////////////////////////////////////////////////////////////////////////////
316 // MPI Support Routines
317 //
318 //////////////////////////////////////////////////////////////////////////////////////
319
320 #ifdef HAVE_MPI
321 static void ScatterProjectionsMPI (MPIWorld& mpiWorld, Projections& projGlobal, Projections& projLocal, const int opt_debug)
322 {
323   if (mpiWorld.getRank() == 0) {
324     for (int iProc = 0; iProc < mpiWorld.getNumProcessors(); iProc++) {
325       for (int iw = mpiWorld.getStartWorkUnit(iProc); iw <= mpiWorld.getEndWorkUnit(iProc); iw++) {
326         DetectorArray& detarray = projGlobal.getDetectorArray( iw );
327         int nDet = detarray.nDet();
328         DetectorValue* detval = detarray.detValues();
329
330         double viewAngle = detarray.viewAngle();
331         mpiWorld.getComm().Send(&nDet, 1, MPI::INT, iProc, 0);
332         mpiWorld.getComm().Send(&viewAngle, 1, MPI::DOUBLE, iProc, 0);
333         mpiWorld.getComm().Send(detval, nDet, MPI::FLOAT, iProc, 0);
334       }
335     }
336   }
337
338   for (int iw = 0; iw < mpiWorld.getMyLocalWorkUnits(); iw++) {
339     MPI::Status status;
340     int nDet;
341     double viewAngle;
342     DetectorValue* detval = projLocal.getDetectorArray(iw).detValues();
343
344     mpiWorld.getComm().Recv(&nDet, 1, MPI::INT, 0, 0, status);
345     mpiWorld.getComm().Recv(&viewAngle, 1, MPI::DOUBLE, 0, 0, status);
346     mpiWorld.getComm().Recv(detval, nDet, MPI::FLOAT, 0, 0, status);
347     projLocal.getDetectorArray(iw).setViewAngle( viewAngle );
348   }
349 }
350
351 static void
352 ReduceImageMPI (MPIWorld& mpiWorld, ImageFile* imLocal, ImageFile* imGlobal)
353 {
354   ImageFileArray vLocal = imLocal->getArray();
355
356   for (int ix = 0; ix < imLocal->nx(); ix++) {
357     void *recvbuf = NULL;
358     if (mpiWorld.getRank() == 0) {
359       ImageFileArray vGlobal = imGlobal->getArray();
360       recvbuf = vGlobal[ix];
361     }
362     mpiWorld.getComm().Reduce (vLocal[ix], recvbuf, imLocal->ny(), imLocal->getMPIDataType(), MPI::SUM, 0);
363   }
364 }
365
366 #endif
367
368
369 #ifndef NO_MAIN
370 int 
371 main (int argc, char* argv[])
372 {
373   int retval = 1;
374
375   try {
376     retval = ctrec_main(argc, argv);
377   } catch (exception e) {
378     cerr << "Exception: " << e.what() << endl;
379   } catch (...) {
380     cerr << "Unknown exception" << endl;
381   }
382
383   return (retval);
384 }
385 #endif
386