r184: *** empty log message ***
[ctsim.git] / libctsim / projections.cpp
1 /*****************************************************************************
2 ** FILE IDENTIFICATION
3 **
4 **   Name:         projections.cpp         Projection data classes
5 **   Programmer:   Kevin Rosenberg
6 **   Date Started: Aug 84
7 **
8 **  This is part of the CTSim program
9 **  Copyright (C) 1983-2000 Kevin Rosenberg
10 **
11 **  $Id: projections.cpp,v 1.22 2000/08/25 15:59:13 kevin Exp $
12 **
13 **  This program is free software; you can redistribute it and/or modify
14 **  it under the terms of the GNU General Public License (version 2) as
15 **  published by the Free Software Foundation.
16 **
17 **  This program is distributed in the hope that it will be useful,
18 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
19 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 **  GNU General Public License for more details.
21 **
22 **  You should have received a copy of the GNU General Public License
23 **  along with this program; if not, write to the Free Software
24 **  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25 ******************************************************************************/
26
27 #include "ct.h"
28
29
30 /* NAME
31  *    Projections               Constructor for projections matrix storage 
32  *
33  * SYNOPSIS
34  *    proj = projections_create (filename, nView, nDet)
35  *    Projections& proj         Allocated projections structure & matrix
36  *    int nView                 Number of rotated view
37  *    int nDet                  Number of detectors
38  *
39  */
40
41 Projections::Projections (const Scanner& scanner)
42   : m_projData(0)
43 {
44   initFromScanner (scanner);
45 }
46
47
48 Projections::Projections (const int nView, const int nDet)
49   : m_projData(0)
50 {
51   init (nView, nDet);
52 }
53
54 Projections::Projections (void)
55   : m_projData(0)
56 {
57   init (0, 0);
58 }
59
60 Projections::~Projections (void)
61 {
62   deleteProjData();
63 }
64
65
66 void
67 Projections::init (const int nView, const int nDet)
68 {
69   m_nView = nView;
70   m_nDet = nDet;
71   newProjData ();
72 }
73
74 void
75 Projections::initFromScanner (const Scanner& scanner)
76 {
77   deleteProjData();
78   init (scanner.nView(), scanner.nDet());
79
80   m_phmLen = scanner.phmLen();
81   m_rotInc = scanner.rotInc();
82   m_detInc = scanner.detInc();
83   m_rotStart = 0;
84   m_detStart =  -(scanner.detLen() / 2) + (scanner.detInc() / 2);
85 }
86
87 void
88 Projections::setNView (int nView)  // used by MPI to reduce # of views
89 {
90   deleteProjData();
91   init (nView, m_nDet);
92 }
93
94 // NAME
95 // newProjData
96
97 void 
98 Projections::newProjData (void)
99 {
100   if (m_projData)
101     sys_error(ERR_WARNING, "m_projData != NULL [newProjData]");
102
103   if (m_nView > 0 && m_nDet) {
104     m_projData = new DetectorArray* [m_nView];
105
106     for (int i = 0; i < m_nView; i++)
107       m_projData[i] = new DetectorArray (m_nDet);
108   }
109 }
110
111
112 /* NAME
113  *   projections_free                   Free memory allocated to projections
114  *
115  * SYNOPSIS
116  *   projections_free(proj)
117  *   Projections& proj                          Projectionss to be deallocated
118  */
119
120 void 
121 Projections::deleteProjData (void)
122 {
123   if (m_projData != NULL) {
124     for (int i = 0; i < m_nView; i++)
125       delete m_projData[i];
126
127     delete m_projData;
128     m_projData = NULL;
129   }
130 }
131
132
133 /* NAME
134  *    Projections::headerWwrite         Write data header for projections file
135  *
136  */
137
138 bool 
139 Projections::headerWrite (fnetorderstream& fs)
140 {
141   kuint16 _hsize = m_headerSize;
142   kuint16 _signature = m_signature;
143   kuint32 _nView = m_nView;
144   kuint32 _nDet = m_nDet;
145   kuint32 _geom = m_geometry;
146   kuint16 _remarksize = m_remark.length();
147   kuint16 _year = m_year;
148   kuint16 _month = m_month;
149   kuint16 _day = m_day;
150   kuint16 _hour = m_hour;
151   kuint16 _minute = m_minute;
152   kuint16 _second = m_second;
153
154   kfloat64 _calcTime = m_calcTime;
155   kfloat64 _rotStart = m_rotStart;
156   kfloat64 _rotInc = m_rotInc;
157   kfloat64 _detStart = m_detStart;
158   kfloat64 _detInc = m_detInc;
159   kfloat64 _phmLen = m_phmLen;
160   
161   fs.seekp(0);
162   if (! fs)
163     return false;
164
165   fs.writeInt16 (_hsize);
166   fs.writeInt16 (_signature);
167   fs.writeInt32 (_nView);
168   fs.writeInt32 (_nDet);
169   fs.writeInt32 (_geom);
170   fs.writeFloat64 (_calcTime);
171   fs.writeFloat64 (_rotStart);
172   fs.writeFloat64 (_rotInc);
173   fs.writeFloat64 (_detStart);
174   fs.writeFloat64 (_detInc);
175   fs.writeFloat64 (_phmLen);
176   fs.writeInt16 (_year);
177   fs.writeInt16 (_month);
178   fs.writeInt16 (_day);
179   fs.writeInt16 (_hour);
180   fs.writeInt16 (_minute);
181   fs.writeInt16 (_second);
182   fs.writeInt16 (_remarksize);
183   fs.write (m_remark.c_str(), _remarksize);
184
185   m_headerSize = fs.tellp();
186   _hsize = m_headerSize;
187   fs.seekp(0);
188   fs.writeInt16 (_hsize);
189   if (! fs)
190       return false;
191   
192   return true;
193 }
194
195 /* NAME
196  *    projections_read_header         Read data header for projections file
197  *
198  */
199 bool
200 Projections::headerRead (fnetorderstream& fs)
201 {
202   kuint16 _hsize, _signature, _year, _month, _day, _hour, _minute, _second, _remarksize = 0;
203   kuint32 _nView, _nDet, _geom;
204   kfloat64 _calcTime, _rotStart, _rotInc, _detStart, _detInc, _phmLen;
205   
206   fs.seekg(0);
207   if (! fs)
208       return false;
209
210   fs.readInt16 (_hsize);
211   fs.readInt16 (_signature);
212   fs.readInt32 (_nView);
213   fs.readInt32 (_nDet);
214   fs.readInt32 (_geom);
215   fs.readFloat64 (_calcTime);
216   fs.readFloat64 (_rotStart);
217   fs.readFloat64 (_rotInc);
218   fs.readFloat64 (_detStart);
219   fs.readFloat64 (_detInc);
220   fs.readFloat64 (_phmLen);
221   fs.readInt16 (_year);
222   fs.readInt16 (_month);
223   fs.readInt16 (_day);
224   fs.readInt16 (_hour);
225   fs.readInt16 (_minute);
226   fs.readInt16 (_second);
227   fs.readInt16 (_remarksize);
228
229   if (! fs) {
230       sys_error (ERR_SEVERE, "Error reading header information , _remarksize=%d [projections_read_header]", _remarksize);
231       return false;
232   }
233
234   if (_signature != m_signature) {
235     sys_error (ERR_SEVERE, "File %s does not have a valid projection file signature", m_filename.c_str());
236     return false;
237   }
238
239   char remarkStorage[_remarksize+1];
240   fs.read (remarkStorage, _remarksize);
241   if (! fs) {
242     sys_error (ERR_SEVERE, "Error reading remark, _remarksize = %d", _remarksize);
243     return false;
244   }
245   remarkStorage[_remarksize] = 0;
246   m_remark = remarkStorage;
247
248   off_t _hsizeread = fs.tellg();
249   if (!fs || _hsizeread != _hsize) {
250       sys_error (ERR_WARNING, "File header size read %ld != file header size stored %ld [read_projections_header]\n_remarksize=%ld", (long int) _hsizeread, _hsize, _remarksize);
251       return false;
252   }
253   
254   m_headerSize = _hsize;
255   m_nView = _nView;
256   m_nDet = _nDet;
257   m_geometry = _geom;
258   m_calcTime = _calcTime;
259   m_rotStart = _rotStart;
260   m_rotInc = _rotInc;
261   m_detStart = _detStart;
262   m_detInc = _detInc;
263   m_phmLen = _phmLen;
264   m_year = _year;
265   m_month = _month;
266   m_day = _day;
267   m_hour = _hour;
268   m_minute = _minute;
269   m_second = _second;
270
271   m_label.setLabelType (Array2dFileLabel::L_HISTORY);
272   m_label.setLabelString (m_remark);
273   m_label.setCalcTime (m_calcTime);
274   m_label.setDateTime (m_year, m_month, m_day, m_hour, m_minute, m_second);
275
276   return true;
277 }
278
279 bool
280 Projections::read (const char* filename)
281 {
282   frnetorderstream fileRead (filename, ios::in | ios::binary);
283   m_filename = filename;
284
285   if (! fileRead)
286     return false;
287
288   if (! headerRead (fileRead))
289     return false;
290
291   deleteProjData ();
292   newProjData();
293
294   for (int i = 0; i < m_nView; i++) {
295     if (! detarrayRead (fileRead, *m_projData[i], i))
296       break;
297   }
298
299   fileRead.close();
300   return true;
301 }
302
303
304 bool
305 Projections::write (const char* filename)
306 {
307   frnetorderstream fs (filename, ios::out | ios::binary | ios::trunc | ios::ate);
308   m_filename = filename;
309   if (! fs) {
310     sys_error (ERR_SEVERE, "Error opening file %s for output [projections_create]", filename);
311     return false;
312   }
313
314   time_t t = time(NULL);
315   tm* lt = localtime(&t);
316   m_year = lt->tm_year;
317   m_month = lt->tm_mon;
318   m_day = lt->tm_mday;
319   m_hour = lt->tm_hour;
320   m_minute = lt->tm_min;
321   m_second = lt->tm_sec;
322
323   if (! headerWrite (fs))
324       return false;
325
326   if (m_projData != NULL) {
327     for (int i = 0; i < m_nView; i++) {
328       if (! detarrayWrite (fs, *m_projData[i], i))
329         break;
330     }
331   }
332   if (! fs)
333     return false;
334
335  fs.close();
336
337   return true;
338 }
339
340 /* NAME
341  *   detarrayRead               Read a Detector Array structure from the disk
342  *
343  * SYNOPSIS
344  *   detarrayRead (proj, darray, view_num)
345  *   DETARRAY *darray           Detector array storage location to be filled
346  *   int      view_num          View number to read
347  */
348
349 bool
350 Projections::detarrayRead (fnetorderstream& fs, DetectorArray& darray, const int iview)
351 {
352   const int detval_bytes = darray.nDet() * sizeof(kfloat32);
353   const int detheader_bytes = sizeof(kfloat64) /* view_angle */ + sizeof(kint32) /* nDet */;
354   const int view_bytes = detheader_bytes + detval_bytes;
355   const off_t start_data = m_headerSize + (iview * view_bytes);
356   DetectorValue* detval_ptr = darray.detValues();  
357   kfloat64 view_angle;
358   kuint32 nDet;
359
360   fs.seekg (start_data);
361
362   fs.readFloat64 (view_angle);
363   fs.readInt32 (nDet);
364   darray.setViewAngle (view_angle);
365   //  darray.setNDet ( nDet);
366   
367   for (unsigned int i = 0; i < nDet; i++) {
368       kfloat32 detval;
369       fs.readFloat32 (detval);
370       detval_ptr[i] = detval;
371   }
372   if (! fs)
373     return false;
374
375   return true;
376 }
377
378
379 /* NAME
380  *   detarrayWrite                      Write detector array data to the disk
381  *
382  * SYNOPSIS
383  *   detarrayWrite (darray, view_num)
384  *   DETARRAY *darray                   Detector array data to be written
385  *   int      view_num                  View number to write
386  *
387  * DESCRIPTION
388  *       This routine writes the detarray data from the disk sequentially to
389  *    the file that was opened with open_projections().  Data is written in
390  *    binary format.
391  */
392
393 bool
394 Projections::detarrayWrite (fnetorderstream& fs, const DetectorArray& darray, const int iview)
395 {
396   const int detval_bytes = darray.nDet() * sizeof(float);
397   const int detheader_bytes = sizeof(kfloat64) /* view_angle */ + sizeof(kint32) /* nDet */;
398   const int view_bytes = detheader_bytes + detval_bytes;
399   const off_t start_data = m_headerSize + (iview * view_bytes);
400   const DetectorValue* const detval_ptr = darray.detValues();  
401   kfloat64 view_angle = darray.viewAngle();
402   kuint32 nDet = darray.nDet();
403   
404   fs.seekp (start_data);
405   if (! fs) {
406     sys_error (ERR_SEVERE, "Error seeking detectory array [detarrayWrite]");
407     return false;
408   }
409
410   fs.writeFloat64 (view_angle);
411   fs.writeInt32 (nDet);
412
413   for (unsigned int i = 0; i < nDet; i++) {
414     kfloat32 detval = detval_ptr[i];
415     fs.writeFloat32 (detval);
416   }
417
418   if (! fs)
419     return (false);
420
421   return true;
422 }
423
424 /* NAME
425  *   prt_projections                    Print projections data
426  *
427  * SYNOPSIS
428  *   prt_projections (proj)
429  *   Projections& proj                  Projection data to be printed
430  */
431
432 void
433 Projections::printProjectionData (void)
434 {
435   printf("Projections Print\n\n");
436   printf("Description: %s\n", m_remark.c_str());
437   printf("nView = %d  nDet = %d\n", m_nView, m_nDet);
438   printf("rotStart = %8.4f   rotInc = %8.4f\n", m_rotStart, m_rotInc);
439   printf("detStart = %8.4f   detInc = %8.4f\n", m_detStart, m_detInc);
440
441   if (m_projData != NULL) {
442       for (int ir = 0; ir < m_nView; ir++) {
443           DetectorValue* detval = m_projData[ir]->detValues();
444           for (int id = 0; id < m_projData[ir]->nDet(); id++)
445               printf("%8.4f  ", detval[id]);
446           printf("\n");
447       }
448   }
449 }
450
451 void 
452 Projections::printScanInfo (void) const
453 {
454   printf ("Number of detectors: %d\n", m_nDet);
455   printf ("    Number of views: %d\n", m_nView);
456   printf ("             Remark: %s\n", m_remark.c_str());
457   printf ("             phmLen: %f\n", m_phmLen);
458   printf ("           detStart: %f\n", m_detStart);
459   printf ("             detInc: %f\n", m_detInc);
460   printf ("           rotStart: %f\n", m_rotStart);
461   printf ("             rotInc: %f\n", m_rotInc);
462 }
463
464
465
466 /* NAME
467  *   Projections::reconstruct      Reconstruct Image from Projections
468  *
469  * SYNOPSIS
470  *   im = proj.reconstruct (im, filt_type, filt_param, interp_type)
471  *   IMAGE *im                  Output image
472  *   int filt_type              Type of convolution filter to use
473  *   double filt_param          Filter specific parameter
474  *                              Currently, used only with Hamming filters
475  *   int interp_type            Type of interpolation method to use
476  *
477  * ALGORITHM
478  *
479  *      Calculate one-dimensional filter in spatial domain
480  *      Allocate & clear (zero) the 2d output image array
481  *      For each projection view
482  *          Convolve raysum array with filter
483  *          Backproject raysums and add (summate) to image array
484  *      end
485  */
486
487 bool
488 Projections::reconstruct (ImageFile& im, const char* const filterName, double filt_param, const char* const filterMethodName, const int zeropad, const char* filterGenerationName, const char* const interpName, int interpFactor, const char* const backprojectName, const int trace) const
489 {
490   double detInc = m_detInc;
491   int n_filteredProj = m_nDet * interpFactor;
492   double filteredProj [n_filteredProj];   // filtered projections
493
494 #ifdef HAVE_BSPLINE_INTERP
495   int spline_order = 0, zoom_factor = 0;
496   if (interp_type == I_BSPLINE) {
497     zoom_factor = interpFactor;
498     spline_order = 3;
499     zoom_factor = 3;
500     n_filteredProj = (m_nDet - 1) * (zoom_factor + 1) + 1;
501   }
502 #endif
503
504   double filterBW = 1. / detInc;
505   ProcessSignal processSignal (filterName, filterMethodName, filterBW, m_detInc, m_nDet, filt_param, "spatial", filterGenerationName, zeropad, interpFactor, trace);
506
507   if (processSignal.fail()) {
508       sys_error (ERR_SEVERE, "%s [Projections::reconstruct]", processSignal.failMessage().c_str());
509       return false;
510   }
511
512   if (trace)
513     cout << "Reconstruct: filter="<<filterName<< ", interp="<<interpName<<", backproject="<<backprojectName<<endl;
514
515 #if HAVE_SGP
516   int nVecFilter = processSignal.getNFilterPoints();
517   double plot_xaxis [nVecFilter];                       // array for plotting 
518
519   if (trace > TRACE_TEXT && nVecFilter > 0)  {
520     int i;
521     double f;
522     double filterInc = processSignal.getFilterIncrement();
523     for (i = 0, f = processSignal.getFilterMin(); i < nVecFilter; i++, f += filterInc)
524       plot_xaxis[i] = f;
525
526     if (processSignal.getFilter()) {
527       SGPDriver sgpDriver ("Filter Function");
528       SGP sgp (sgpDriver);
529       EZPlot ezplot (sgp);
530
531       ezplot.ezset ("title Filter Response");
532       ezplot.addCurve (plot_xaxis, processSignal.getFilter(), nVecFilter);
533       ezplot.plot();
534       cio_put_str ("Press any key to continue");
535       cio_kb_getc ();
536     }
537   }
538   if (trace >= TRACE_TEXT) {
539     printf ("nview=%d, ndet=%d, det_start=%.4f, detInc=%.4f\n", m_nView, m_nDet, m_detStart, m_detInc);
540   }
541 #endif  //HAVE_SGP
542
543   Backprojector bj (*this, im, backprojectName, interpName, interpFactor);
544   if (bj.fail()) {
545     sys_error (ERR_SEVERE, "%s [Projections::reconstruct]", bj.failMessage().c_str());
546     return false;
547   }
548
549   for (int iview = 0; iview < m_nView; iview++)  {
550     if (trace >= TRACE_TEXT) 
551       printf ("Reconstructing view %d (last = %d)\n",  iview, m_nView - 1);
552       
553     const DetectorArray& darray = getDetectorArray (iview);
554     const DetectorValue* detval = darray.detValues();
555
556     processSignal.filterSignal (detval, filteredProj);
557
558 #ifdef HAVE_BSPLINE_INTERP
559     if (interp_type == I_BSPLINE) 
560         bspline (m_nDet, zoom_factor, spline_order, filteredProj, filteredProj);
561     
562 #ifdef HAVE_SGP
563     if (trace >= TRACE_PLOT && interp_type == I_BSPLINE) {
564         bspline (m_nDet, zoom_factor, spline_order, filteredProj, filteredProj);
565       ezplot_1d (filteredProj, n_filteredProj);
566     }
567 #endif
568 #endif
569
570     bj.BackprojectView (filteredProj, darray.viewAngle());
571
572 #ifdef HAVE_SGP
573     if (trace >= TRACE_PLOT) {
574       SGPDriver sgpDriverProj ("Projection");
575       SGP sgpProj (sgpDriverProj);
576       EZPlot ezplotProj (sgpProj);
577
578       ezplotProj.ezset  ("clear");
579       ezplotProj.ezset ("title Filtered Projection");
580       ezplotProj.ezset  ("xticks major 5.");
581       ezplotProj.ezset  ("xlabel ");
582       ezplotProj.ezset  ("ylabel ");
583       ezplotProj.ezset  ("yporigin .5.");
584       ezplotProj.ezset  ("ylength .5.");
585       ezplotProj.ezset  ("box.");
586       ezplotProj.ezset  ("grid.");
587       ezplotProj.addCurve (plot_xaxis, detval, m_nDet);
588       ezplotProj.plot();
589       ezplotProj.ezset  ("clear");
590       ezplotProj.ezset  ("xticks major 5.");
591       ezplotProj.ezset  ("xlabel ");
592       ezplotProj.ezset  ("ylabel ");
593       ezplotProj.ezset  ("ylength .5.");
594       ezplotProj.ezset ("box");
595       ezplotProj.ezset ("grid");
596       ezplotProj.addCurve (plot_xaxis, filteredProj,  n_filteredProj);
597       ezplotProj.plot();
598
599       cout << "Do you want to exit with current pic (y/n)? " << flush;
600       char str[256];
601       fgets(str, sizeof(str), stdin);
602       if (tolower(str[0]) == 'y') {
603         break;
604       }
605     } 
606 #endif  //HAVE_SGP
607   }
608
609   return true;
610 }
611