e5c79e7364f67a15a0a1ec5ce4b08f01ed0d2df7
[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-2001 Kevin Rosenberg
10 **
11 **  $Id: projections.cpp,v 1.72 2001/03/29 21:25:49 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 const kuint16 Projections::m_signature = ('P'*256 + 'J');
30
31 const int Projections::POLAR_INTERP_INVALID = -1;
32 const int Projections::POLAR_INTERP_NEAREST = 0;
33 const int Projections::POLAR_INTERP_BILINEAR = 1;
34 const int Projections::POLAR_INTERP_BICUBIC = 2;
35
36 const char* const Projections::s_aszInterpName[] = 
37 {
38   {"nearest"},
39   {"bilinear"},
40 //  {"bicubic"},
41 };
42
43 const char* const Projections::s_aszInterpTitle[] = 
44 {
45   {"Nearest"},
46   {"Bilinear"},
47 //  {"Bicubic"},
48 };
49
50 const int Projections::s_iInterpCount = sizeof(s_aszInterpName) / sizeof(char*);
51
52
53
54 /* NAME
55 *    Projections                Constructor for projections matrix storage 
56 *
57 * SYNOPSIS
58 *    proj = projections_create (filename, nView, nDet)
59 *    Projections& proj          Allocated projections structure & matrix
60 *    int nView                  Number of rotated view
61 *    int nDet                   Number of detectors
62 *
63 */
64
65 Projections::Projections (const Scanner& scanner)
66 : m_projData(0)
67 {
68   initFromScanner (scanner);
69 }
70
71
72 Projections::Projections (const int nView, const int nDet)
73 : m_projData(0)
74 {
75   init (nView, nDet);
76 }
77
78 Projections::Projections (void)
79 : m_projData(0)
80 {
81   init (0, 0);
82 }
83
84 Projections::~Projections (void)
85 {
86   deleteProjData();
87 }
88
89 int
90 Projections::convertInterpNameToID (const char* const interpName)
91 {
92   int interpID = POLAR_INTERP_INVALID;
93   
94   for (int i = 0; i < s_iInterpCount; i++)
95     if (strcasecmp (interpName, s_aszInterpName[i]) == 0) {
96       interpID = i;
97       break;
98     }
99     
100     return (interpID);
101 }
102
103 const char*
104 Projections::convertInterpIDToName (const int interpID)
105 {
106   static const char *interpName = "";
107   
108   if (interpID >= 0 && interpID < s_iInterpCount)
109     return (s_aszInterpName[interpID]);
110   
111   return (interpName);
112 }
113
114 const char*
115 Projections::convertInterpIDToTitle (const int interpID)
116 {
117   static const char *interpTitle = "";
118   
119   if (interpID >= 0 && interpID < s_iInterpCount)
120     return (s_aszInterpTitle[interpID]);
121   
122   return (interpTitle);
123 }
124
125
126
127 void
128 Projections::init (const int nView, const int nDet)
129 {
130   m_label.setLabelType (Array2dFileLabel::L_HISTORY);
131   m_nView = nView;
132   m_nDet = nDet;
133   newProjData ();
134   
135   time_t t = time (NULL);
136   tm* lt = localtime (&t);
137   m_year = lt->tm_year;
138   m_month = lt->tm_mon;
139   m_day = lt->tm_mday;
140   m_hour = lt->tm_hour;
141   m_minute = lt->tm_min;
142   m_second = lt->tm_sec;
143 }
144
145 void
146 Projections::initFromScanner (const Scanner& scanner)
147 {
148   m_label.setLabelType (Array2dFileLabel::L_HISTORY);
149   deleteProjData();
150   init (scanner.nView(), scanner.nDet());
151   
152   m_rotInc = scanner.rotInc();
153   m_detInc = scanner.detInc();
154   m_detStart =  scanner.detStart();
155   m_geometry = scanner.geometry();
156   m_dFocalLength = scanner.focalLength();
157   m_dSourceDetectorLength = scanner.sourceDetectorLength();
158   m_dViewDiameter = scanner.viewDiameter();
159   m_rotStart = 0;
160   m_dFanBeamAngle = scanner.fanBeamAngle();
161 }
162
163 void
164 Projections::setNView (int nView)  // used by MPI to reduce # of views
165 {
166   deleteProjData();
167   init (nView, m_nDet);
168 }
169
170 // NAME
171 // newProjData
172
173 void 
174 Projections::newProjData (void)
175 {
176   if (m_projData)
177     sys_error(ERR_WARNING, "m_projData != NULL [newProjData]");
178   
179   if (m_nView > 0 && m_nDet) {
180     m_projData = new DetectorArray* [m_nView];
181     
182     for (int i = 0; i < m_nView; i++)
183       m_projData[i] = new DetectorArray (m_nDet);
184   }
185 }
186
187
188 /* NAME
189 *   projections_free                    Free memory allocated to projections
190 *
191 * SYNOPSIS
192 *   projections_free(proj)
193 *   Projections& proj                           Projectionss to be deallocated
194 */
195
196 void 
197 Projections::deleteProjData (void)
198 {
199   if (m_projData != NULL) {
200     for (int i = 0; i < m_nView; i++)
201       delete m_projData[i];
202     
203     delete m_projData;
204     m_projData = NULL;
205   }
206 }
207
208
209 /* NAME
210 *    Projections::headerWwrite         Write data header for projections file
211 *
212 */
213
214 bool 
215 Projections::headerWrite (fnetorderstream& fs)
216 {
217   kuint16 _hsize = m_headerSize;
218   kuint16 _signature = m_signature;
219   kuint32 _nView = m_nView;
220   kuint32 _nDet = m_nDet;
221   kuint32 _geom = m_geometry;
222   kuint16 _remarksize = m_remark.length();
223   kuint16 _year = m_year;
224   kuint16 _month = m_month;
225   kuint16 _day = m_day;
226   kuint16 _hour = m_hour;
227   kuint16 _minute = m_minute;
228   kuint16 _second = m_second;
229   
230   kfloat64 _calcTime = m_calcTime;
231   kfloat64 _rotStart = m_rotStart;
232   kfloat64 _rotInc = m_rotInc;
233   kfloat64 _detStart = m_detStart;
234   kfloat64 _detInc = m_detInc;
235   kfloat64 _viewDiameter = m_dViewDiameter;
236   kfloat64 _focalLength = m_dFocalLength;
237   kfloat64 _sourceDetectorLength = m_dSourceDetectorLength;
238   kfloat64 _fanBeamAngle = m_dFanBeamAngle;
239
240   fs.seekp(0);
241   if (! fs)
242     return false;
243   
244   fs.writeInt16 (_hsize);
245   fs.writeInt16 (_signature);
246   fs.writeInt32 (_nView);
247   fs.writeInt32 (_nDet);
248   fs.writeInt32 (_geom);
249   fs.writeFloat64 (_calcTime);
250   fs.writeFloat64 (_rotStart);
251   fs.writeFloat64 (_rotInc);
252   fs.writeFloat64 (_detStart);
253   fs.writeFloat64 (_detInc);
254   fs.writeFloat64 (_viewDiameter);
255   fs.writeFloat64 (_focalLength);
256   fs.writeFloat64 (_sourceDetectorLength);
257   fs.writeFloat64 (_fanBeamAngle);
258   fs.writeInt16 (_year);
259   fs.writeInt16 (_month);
260   fs.writeInt16 (_day);
261   fs.writeInt16 (_hour);
262   fs.writeInt16 (_minute);
263   fs.writeInt16 (_second);
264   fs.writeInt16 (_remarksize);
265   fs.write (m_remark.c_str(), _remarksize);
266   
267   m_headerSize = fs.tellp();
268   _hsize = m_headerSize;
269   fs.seekp(0);
270   fs.writeInt16 (_hsize);
271   if (! fs)
272     return false;
273   
274   return true;
275 }
276
277 /* NAME
278 *    projections_read_header         Read data header for projections file
279 *
280 */
281 bool
282 Projections::headerRead (fnetorderstream& fs)
283 {
284   kuint16 _hsize, _signature, _year, _month, _day, _hour, _minute, _second, _remarksize = 0;
285   kuint32 _nView, _nDet, _geom;
286   kfloat64 _calcTime, _rotStart, _rotInc, _detStart, _detInc, _focalLength, _sourceDetectorLength, _viewDiameter, _fanBeamAngle;
287   
288   fs.seekg(0);
289   if (! fs)
290     return false;
291   
292   fs.readInt16 (_hsize);
293   fs.readInt16 (_signature);
294   fs.readInt32 (_nView);
295   fs.readInt32 (_nDet);
296   fs.readInt32 (_geom);
297   fs.readFloat64 (_calcTime);
298   fs.readFloat64 (_rotStart);
299   fs.readFloat64 (_rotInc);
300   fs.readFloat64 (_detStart);
301   fs.readFloat64 (_detInc);
302   fs.readFloat64 (_viewDiameter);
303   fs.readFloat64 (_focalLength);
304   fs.readFloat64 (_sourceDetectorLength);
305   fs.readFloat64 (_fanBeamAngle);
306   fs.readInt16 (_year);
307   fs.readInt16 (_month);
308   fs.readInt16 (_day);
309   fs.readInt16 (_hour);
310   fs.readInt16 (_minute);
311   fs.readInt16 (_second);
312   fs.readInt16 (_remarksize);
313   
314   if (! fs) {
315     sys_error (ERR_SEVERE, "Error reading header information , _remarksize=%d [projections_read_header]", _remarksize);
316     return false;
317   }
318   
319   if (_signature != m_signature) {
320     sys_error (ERR_SEVERE, "File %s does not have a valid projection file signature", m_filename.c_str());
321     return false;
322   }
323   
324   char* pszRemarkStorage = new char [_remarksize+1];
325   fs.read (pszRemarkStorage, _remarksize);
326   if (! fs) {
327     sys_error (ERR_SEVERE, "Error reading remark, _remarksize = %d", _remarksize);
328     return false;
329   }
330   pszRemarkStorage[_remarksize] = 0;
331   m_remark = pszRemarkStorage;
332   delete pszRemarkStorage;
333   
334   off_t _hsizeread = fs.tellg();
335   if (!fs || _hsizeread != _hsize) {
336     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);
337     return false;
338   }
339   
340   m_headerSize = _hsize;
341   m_nView = _nView;
342   m_nDet = _nDet;
343   m_geometry = _geom;
344   m_calcTime = _calcTime;
345   m_rotStart = _rotStart;
346   m_rotInc = _rotInc;
347   m_detStart = _detStart;
348   m_detInc = _detInc;
349   m_dFocalLength = _focalLength;
350   m_dSourceDetectorLength = _sourceDetectorLength;
351   m_dViewDiameter = _viewDiameter;
352   m_dFanBeamAngle = _fanBeamAngle;
353   m_year = _year;
354   m_month = _month;
355   m_day = _day;
356   m_hour = _hour;
357   m_minute = _minute;
358   m_second = _second;
359   
360   m_label.setLabelType (Array2dFileLabel::L_HISTORY);
361   m_label.setLabelString (m_remark);
362   m_label.setCalcTime (m_calcTime);
363   m_label.setDateTime (m_year, m_month, m_day, m_hour, m_minute, m_second);
364   
365   return true;
366 }
367
368 bool
369 Projections::read (const std::string& filename)
370 {
371   return read (filename.c_str());
372 }
373
374
375 bool
376 Projections::read (const char* filename)
377 {
378   m_filename = filename;
379 #ifdef MSVC
380   frnetorderstream fileRead (m_filename.c_str(), std::ios::in | std::ios::binary);
381 #else
382   frnetorderstream fileRead (m_filename.c_str(), std::ios::in | std::ios::binary | std::ios::nocreate);
383 #endif
384   
385   if (fileRead.fail())
386     return false;
387   
388   if (! headerRead (fileRead))
389     return false;
390   
391   deleteProjData ();
392   newProjData();
393   
394   for (int i = 0; i < m_nView; i++) {
395     if (! detarrayRead (fileRead, *m_projData[i], i))
396       break;
397   }
398   
399   fileRead.close();
400   return true;
401 }
402
403
404 bool 
405 Projections::copyViewData (const std::string& filename, std::ostream& os, int startView, int endView)
406 {
407   return copyViewData (filename.c_str(), os, startView, endView);
408 }
409
410 bool 
411 Projections::copyViewData (const char* const filename, std::ostream& os, int startView, int endView)
412 {
413   frnetorderstream is (filename, std::ios::in | std::ios::binary);
414   kuint16 sizeHeader, signature;
415   kuint32 _nView, _nDet;
416   
417   is.seekg (0);
418   if (is.fail()) {
419     sys_error (ERR_SEVERE, "Unable to read projection file %s", filename);
420     return false;
421   }
422
423   is.readInt16 (sizeHeader);
424   is.readInt16 (signature);
425   is.readInt32 (_nView);
426   is.readInt32 (_nDet);
427   int nView = _nView;
428   int nDet = _nDet;
429   
430   if (signature != m_signature) {
431     sys_error (ERR_SEVERE, "Illegal signature in projection file %s", filename);
432     return false;
433   }
434   
435   if (startView < 0)
436     startView = 0;
437   if (startView > nView - 1)
438     startView = nView;
439   if (endView < 0 || endView > nView - 1)
440     endView = nView - 1;
441   
442   if (startView > endView) { // swap if start > end
443     int tempView = endView;
444     endView = startView;
445     startView = tempView;
446   }
447   
448   int sizeView = 8 /* view_angle */ + 4 /* nDet */ + (4 * nDet);
449   unsigned char* pViewData = new unsigned char [sizeView];
450   
451   for (int i = startView; i <= endView; i++) {
452     is.seekg (sizeHeader + i * sizeView);
453     is.read (reinterpret_cast<char*>(pViewData), sizeView);
454     os.write (reinterpret_cast<char*>(pViewData), sizeView);
455     if (is.fail() || os.fail())
456       break;
457   }
458   
459   delete pViewData;
460   if (is.fail()) 
461     sys_error (ERR_SEVERE, "Error reading projection file");
462   if (os.fail()) 
463     sys_error (ERR_SEVERE, "Error writing projection file");
464   
465   return (! (is.fail() | os.fail()));
466 }
467
468 bool 
469 Projections::copyHeader (const std::string& filename, std::ostream& os)
470 {
471   return copyHeader (filename.c_str(), os);
472 }
473
474 bool
475 Projections::copyHeader (const char* const filename, std::ostream& os)
476 {
477   frnetorderstream is (filename, std::ios::in | std::ios::binary);
478   kuint16 sizeHeader, signature;
479   is.readInt16 (sizeHeader);
480   is.readInt16 (signature);
481   is.seekg (0);
482   if (signature != m_signature) {
483     sys_error (ERR_SEVERE, "Illegal signature in projection file %s", filename);
484     return false;
485   }
486   
487   unsigned char* pHdrData = new unsigned char [sizeHeader];
488   is.read (reinterpret_cast<char*>(pHdrData), sizeHeader);
489   if (is.fail()) {
490     sys_error (ERR_SEVERE, "Error reading header");
491     return false;
492   }
493   
494   os.write (reinterpret_cast<char*>(pHdrData), sizeHeader);
495   if (os.fail()) {
496     sys_error (ERR_SEVERE, "Error writing header");
497     return false;
498   }
499   
500   return true;
501 }
502
503 bool
504 Projections::write (const std::string& filename)
505 {
506   return write (filename.c_str());
507 }
508
509 bool
510 Projections::write (const char* filename)
511 {
512   frnetorderstream fs (filename, std::ios::out | std::ios::binary | std::ios::trunc | std::ios::ate);
513   m_filename = filename;
514   if (! fs) {
515     sys_error (ERR_SEVERE, "Error opening file %s for output [projections_create]", filename);
516     return false;
517   }
518   
519   if (! headerWrite (fs))
520     return false;
521   
522   if (m_projData != NULL) {
523     for (int i = 0; i < m_nView; i++) {
524       if (! detarrayWrite (fs, *m_projData[i], i))
525         break;
526     }
527   }
528   if (! fs)
529     return false;
530   
531   fs.close();
532   
533   return true;
534 }
535
536 /* NAME
537 *   detarrayRead                Read a Detector Array structure from the disk
538 *
539 * SYNOPSIS
540 *   detarrayRead (proj, darray, view_num)
541 *   DETARRAY *darray            Detector array storage location to be filled
542 *   int      view_num           View number to read
543 */
544
545 bool
546 Projections::detarrayRead (fnetorderstream& fs, DetectorArray& darray, const int iview)
547 {
548   const int detval_bytes = darray.nDet() * sizeof(kfloat32);
549   const int detheader_bytes = sizeof(kfloat64) /* view_angle */ + sizeof(kint32) /* nDet */;
550   const int view_bytes = detheader_bytes + detval_bytes;
551   const off_t start_data = m_headerSize + (iview * view_bytes);
552   DetectorValue* detval_ptr = darray.detValues();  
553   kfloat64 view_angle;
554   kuint32 nDet;
555   
556   fs.seekg (start_data);
557   
558   fs.readFloat64 (view_angle);
559   fs.readInt32 (nDet);
560   darray.setViewAngle (view_angle);
561   //  darray.setNDet ( nDet);
562   
563   for (unsigned int i = 0; i < nDet; i++) {
564     kfloat32 detval;
565     fs.readFloat32 (detval);
566     detval_ptr[i] = detval;
567   }
568   if (! fs)
569     return false;
570   
571   return true;
572 }
573
574
575 /* NAME
576 *   detarrayWrite                       Write detector array data to the disk
577 *
578 * SYNOPSIS
579 *   detarrayWrite (darray, view_num)
580 *   DETARRAY *darray                    Detector array data to be written
581 *   int      view_num                   View number to write
582 *
583 * DESCRIPTION
584 *       This routine writes the detarray data from the disk sequentially to
585 *    the file that was opened with open_projections().  Data is written in
586 *    binary format.
587 */
588
589 bool
590 Projections::detarrayWrite (fnetorderstream& fs, const DetectorArray& darray, const int iview)
591 {
592   const int detval_bytes = darray.nDet() * sizeof(float);
593   const int detheader_bytes = sizeof(kfloat64) /* view_angle */ + sizeof(kint32) /* nDet */;
594   const int view_bytes = detheader_bytes + detval_bytes;
595   const off_t start_data = m_headerSize + (iview * view_bytes);
596   const DetectorValue* const detval_ptr = darray.detValues();  
597   kfloat64 view_angle = darray.viewAngle();
598   kuint32 nDet = darray.nDet();
599   
600   fs.seekp (start_data);
601   if (! fs) {
602     sys_error (ERR_SEVERE, "Error seeking detectory array [detarrayWrite]");
603     return false;
604   }
605   
606   fs.writeFloat64 (view_angle);
607   fs.writeInt32 (nDet);
608   
609   for (unsigned int i = 0; i < nDet; i++) {
610     kfloat32 detval = detval_ptr[i];
611     fs.writeFloat32 (detval);
612   }
613   
614   if (! fs)
615     return (false);
616   
617   return true;
618 }
619
620 /* NAME
621 *   printProjectionData                 Print projections data
622 *
623 * SYNOPSIS
624 *   printProjectionData ()
625 */
626
627 void
628 Projections::printProjectionData ()
629 {
630   printProjectionData (0, nView() - 1);
631 }
632
633 void
634 Projections::printProjectionData (int startView, int endView)
635 {
636   printf("Projections Data\n\n");
637   printf("Description: %s\n", m_remark.c_str());
638   printf("Geometry: %s\n", Scanner::convertGeometryIDToName (m_geometry));
639   printf("nView       = %8d             nDet = %8d\n", m_nView, m_nDet);
640   printf("focalLength = %8.4f   ViewDiameter = %8.4f\n", m_dFocalLength, m_dViewDiameter);
641   printf("fanBeamAngle= %8.4f SourceDetector = %8.4f\n", convertRadiansToDegrees(m_dFanBeamAngle), m_dSourceDetectorLength);
642   printf("rotStart    = %8.4f         rotInc = %8.4f\n", m_rotStart, m_rotInc);
643   printf("detStart    = %8.4f         detInc = %8.4f\n", m_detStart, m_detInc);
644   if (m_projData != NULL) {
645     if (startView < 0)
646       startView = 0;
647     if (endView < 0)
648       endView = m_nView - 1;
649     if (startView > m_nView - 1)
650       startView = m_nView - 1;
651     if (endView > m_nView - 1)
652       endView = m_nView - 1;
653     for (int ir = startView; ir <= endView - 1; ir++) {
654       printf("View %d: angle %f\n", ir, m_projData[ir]->viewAngle());
655       DetectorValue* detval = m_projData[ir]->detValues();
656       for (int id = 0; id < m_projData[ir]->nDet(); id++)
657         printf("%8.4f  ", detval[id]);
658       printf("\n");
659     }
660   }
661 }
662
663 void 
664 Projections::printScanInfo (std::ostringstream& os) const
665 {
666   os << "Number of detectors: " << m_nDet << "\n";
667   os << "Number of views: " << m_nView<< "\n";
668   os << "Description: " << m_remark.c_str()<< "\n";
669   os << "Geometry: " << Scanner::convertGeometryIDToName (m_geometry)<< "\n";
670   os << "Focal Length: " << m_dFocalLength<< "\n";
671   os << "Source Detector Length: " << m_dSourceDetectorLength << "\n";
672   os << "View Diameter: " << m_dViewDiameter<< "\n";
673   os << "Fan Beam Angle: " << convertRadiansToDegrees(m_dFanBeamAngle) << "\n";
674   os << "detStart: " << m_detStart<< "\n";
675   os << "detInc: " << m_detInc<< "\n";
676   os << "rotStart: " << m_rotStart<< "\n";
677   os << "rotInc: " << m_rotInc<< "\n";
678 }
679
680
681 bool 
682 Projections::convertPolar (ImageFile& rIF, int iInterpolationID)
683 {
684   unsigned int nx = rIF.nx();
685   unsigned int ny = rIF.ny();
686   ImageFileArray v = rIF.getArray();
687   ImageFileArray vImag = rIF.getImaginaryArray();
688
689   if (! v || nx == 0 || ny == 0)
690     return false;
691
692   Projections* pProj = this;
693   if (m_geometry == Scanner::GEOMETRY_EQUIANGULAR || m_geometry == Scanner::GEOMETRY_EQUILINEAR)
694     pProj = interpolateToParallel();
695   
696   Array2d<double> adView (nx, ny);
697   Array2d<double> adDet (nx, ny);
698   double** ppdView = adView.getArray();
699   double** ppdDet = adDet.getArray();
700
701   std::complex<double>** ppcDetValue = new std::complex<double>* [pProj->m_nView];
702   unsigned int iView;
703   for (iView = 0; iView < pProj->m_nView; iView++) {
704     ppcDetValue[iView] = new std::complex<double> [pProj->m_nDet];
705     DetectorValue* detval = pProj->getDetectorArray (iView).detValues();
706     for (unsigned int iDet = 0; iDet < pProj->m_nDet; iDet++)
707       ppcDetValue[iView][iDet] = std::complex<double>(detval[iDet], 0);
708   }
709
710   pProj->calcArrayPolarCoordinates (nx, ny, ppdView, ppdDet, pProj->m_nDet, 1., pProj->m_detInc);
711
712   pProj->interpolatePolar (v, vImag, nx, ny, ppcDetValue, ppdView, ppdDet, pProj->m_nView, pProj->m_nDet, 
713     pProj->m_nDet, iInterpolationID);
714
715   for (iView = 0; iView < pProj->m_nView; iView++)
716     delete [] ppcDetValue[iView];
717   delete [] ppcDetValue;
718
719   if (m_geometry == Scanner::GEOMETRY_EQUIANGULAR || m_geometry == Scanner::GEOMETRY_EQUILINEAR)
720     delete pProj;
721
722   return true;
723 }
724
725
726 bool 
727 Projections::convertFFTPolar (ImageFile& rIF, int iInterpolationID, int iZeropad)
728 {
729 #ifndef HAVE_FFTW
730   rIF.arrayDataClear();
731   return false;
732 #else
733   unsigned int nx = rIF.nx();
734   unsigned int ny = rIF.ny();
735   ImageFileArray v = rIF.getArray();
736   if (! rIF.isComplex())
737     rIF.convertRealToComplex();
738   ImageFileArray vImag = rIF.getImaginaryArray();
739
740   if (! v || nx == 0 || ny == 0)
741     return false;
742   
743   if (m_geometry != Scanner::GEOMETRY_PARALLEL) {
744     sys_error (ERR_WARNING, "convertFFTPolar supports Parallel only");
745     return false;
746   }
747
748   int iInterpDet = nx;
749   int iNumInterpDetWithZeros = ProcessSignal::addZeropadFactor (iInterpDet, iZeropad);
750
751   double dZeropadRatio = static_cast<double>(iNumInterpDetWithZeros) / static_cast<double>(iInterpDet);
752
753   fftw_plan plan = fftw_create_plan (iNumInterpDetWithZeros, FFTW_FORWARD, FFTW_IN_PLACE | FFTW_ESTIMATE | FFTW_USE_WISDOM);
754
755   fftw_complex* pcIn = new fftw_complex [iNumInterpDetWithZeros];
756   std::complex<double>** ppcDetValue = new std::complex<double>* [m_nView];
757   double dInterpScale = (m_nDet-1) / static_cast<double>(iInterpDet-1) / SQRT2;
758   
759   double dFFTScale = 1. / static_cast<double>(iInterpDet * iInterpDet);
760   int iMidPoint = iInterpDet / 2;
761   double dMidPoint = static_cast<double>(iInterpDet) / 2.;
762   int iZerosAdded = iNumInterpDetWithZeros - iInterpDet;
763   for (unsigned int iView = 0; iView < m_nView; iView++) {
764     DetectorValue* detval = getDetectorArray(iView).detValues();
765     LinearInterpolator<DetectorValue> projInterp (detval, m_nDet);
766     for (unsigned int iDet = 0; iDet < iInterpDet; iDet++) {
767       double dInterpPos = (m_nDet / 2.) + (iDet - dMidPoint) * dInterpScale;
768       pcIn[iDet].re = projInterp.interpolate (dInterpPos) * dInterpScale;
769       pcIn[iDet].im = 0;
770     }
771     Fourier::shuffleFourierToNaturalOrder (pcIn, iInterpDet);
772     if (iZerosAdded > 0) {
773       for (unsigned int iDet1 = iMidPoint; iDet1 < iInterpDet; iDet1++)
774         pcIn[iDet1+iZerosAdded] = pcIn[iDet1];
775       for (unsigned int iDet2 = iMidPoint; iDet2 < iMidPoint + iZerosAdded; iDet2++) 
776         pcIn[iDet2].re = pcIn[iDet2].im = 0;
777     }
778
779     fftw_one (plan, pcIn, NULL);
780
781     ppcDetValue[iView] = new std::complex<double> [iNumInterpDetWithZeros];
782     for (unsigned int iD = 0; iD < iNumInterpDetWithZeros; iD++) {
783       ppcDetValue[iView][iD] = std::complex<double> (pcIn[iD].re * dFFTScale, pcIn[iD].im * dFFTScale); 
784     }
785
786     Fourier::shuffleFourierToNaturalOrder (ppcDetValue[iView], iNumInterpDetWithZeros);
787   }
788   delete [] pcIn;
789
790   fftw_destroy_plan (plan);  
791   
792   Array2d<double> adView (nx, ny);
793   Array2d<double> adDet (nx, ny);
794   double** ppdView = adView.getArray();
795   double** ppdDet = adDet.getArray();
796   calcArrayPolarCoordinates (nx, ny, ppdView, ppdDet, iNumInterpDetWithZeros, dZeropadRatio, 
797     m_detInc * dInterpScale);
798
799   interpolatePolar (v, vImag, nx, ny, ppcDetValue, ppdView, ppdDet, m_nView, m_nDet, iNumInterpDetWithZeros,
800     iInterpolationID);
801
802   for (int i = 0; i < m_nView; i++)
803     delete [] ppcDetValue[i];
804   delete [] ppcDetValue;
805
806   return true;
807 #endif
808 }
809
810
811 void
812 Projections::calcArrayPolarCoordinates (unsigned int nx, unsigned int ny, double** ppdView, double** ppdDet,
813                                         int iNumDetWithZeros, double dZeropadRatio, double dDetInc)
814 {
815 //  double dLength = viewDiameter();
816   double dLength = phmLen();
817   double xMin = -dLength / 2;
818   double xMax = xMin + dLength;
819   double yMin = -dLength / 2;
820   double yMax = yMin + dLength;
821   double xCent = (xMin + xMax) / 2;
822   double yCent = (yMin + yMax) / 2;
823
824   xMin = (xMin - xCent) * dZeropadRatio + xCent;
825   xMax = (xMax - xCent) * dZeropadRatio + xCent;
826   yMin = (yMin - yCent) * dZeropadRatio + yCent;
827   yMax = (yMax - yCent) * dZeropadRatio + yCent;
828
829   double xInc = (xMax - xMin) / nx;     // size of cells
830   double yInc = (yMax - yMin) / ny;
831
832   // +1 is correct for frequency data, ndet-1 is correct for projections
833   int iDetCenter = (iNumDetWithZeros - 1) / 2;  // index refering to L=0 projection 
834   if (isEven (iNumDetWithZeros))
835     iDetCenter = (iNumDetWithZeros + 1) / 2;    
836
837   // Calculates polar coordinates (view#, det#) for each point on phantom grid
838   double x = xMin + xInc / 2;   // Rectang coords of center of pixel 
839   for (unsigned int ix = 0; ix < nx; x += xInc, ix++) {
840     double y = yMin + yInc / 2;
841     for (unsigned int iy = 0; iy < ny; y += yInc, iy++) {
842       double r = ::sqrt (x * x + y * y);
843       double phi = atan2 (y, x);
844
845       if (phi < 0)
846         phi += TWOPI;
847       if (phi >= PI) {
848         phi -= PI;
849         r = -r;
850       }
851       
852       ppdView[ix][iy] = (phi - m_rotStart) / m_rotInc;
853       ppdDet[ix][iy] = (r / dDetInc) + iDetCenter;
854     }
855   }
856 }
857
858 void
859 Projections::interpolatePolar (ImageFileArray& v, ImageFileArray& vImag,
860      unsigned int nx, unsigned int ny, std::complex<double>** ppcDetValue, double** ppdView, 
861      double** ppdDet, unsigned int nView, unsigned int nDet, unsigned int nDetWithZeros, int iInterpolationID)
862 {
863   typedef std::complex<double> complexValue;
864
865   BilinearInterpolator<complexValue>* pBilinear;  
866   if (iInterpolationID == POLAR_INTERP_BILINEAR)
867     pBilinear = new BilinearInterpolator<complexValue> (ppcDetValue, nView, nDetWithZeros);
868
869   BicubicPolyInterpolator<complexValue>* pBicubic;  
870   if (iInterpolationID == POLAR_INTERP_BICUBIC)
871     pBicubic = new BicubicPolyInterpolator<complexValue> (ppcDetValue, nView, nDetWithZeros);
872
873   for (unsigned int ix = 0; ix < ny; ix++) {
874     for (unsigned int iy = 0; iy < ny; iy++) {
875
876       if (iInterpolationID == POLAR_INTERP_NEAREST) {
877         unsigned int iView = nearest<int> (ppdView[ix][iy]);
878         unsigned int iDet = nearest<int> (ppdDet[ix][iy]);
879         if (iView == nView) {
880           iView = 0;
881           iDet = m_nDet - iDet;
882         }
883         if (iDet >= 0 && iDet < nDetWithZeros && iView >= 0 && iView < nView) {
884           v[ix][iy] = ppcDetValue[iView][iDet].real();
885           if (vImag)
886             vImag[ix][iy] = ppcDetValue[iView][iDet].imag();
887         } else
888           v[ix][iy] = 0;
889
890       } else if (iInterpolationID == POLAR_INTERP_BILINEAR) {
891         std::complex<double> vInterp = pBilinear->interpolate (ppdView[ix][iy], ppdDet[ix][iy]);
892         v[ix][iy] = vInterp.real();
893         if (vImag)
894           vImag[ix][iy] = vInterp.imag();
895       } else if (iInterpolationID == POLAR_INTERP_BICUBIC) {
896         std::complex<double> vInterp = pBicubic->interpolate (ppdView[ix][iy], ppdDet[ix][iy]);
897         v[ix][iy] = vInterp.real();
898         if (vImag)
899           vImag[ix][iy] = vInterp.imag();
900       }
901     }
902   }
903 }
904
905 bool
906 Projections::initFromSomatomAR_STAR (int iNViews, int iNDets, unsigned char* pData, unsigned long lDataLength)
907 {
908   init (iNViews, iNDets);
909   m_geometry = Scanner::GEOMETRY_EQUIANGULAR;
910   m_dFocalLength = 510;
911   m_dSourceDetectorLength = 890;
912   m_detInc = convertDegreesToRadians (3.06976 / 60);
913   m_dFanBeamAngle = iNDets * m_detInc;
914   m_detStart = -(m_dFanBeamAngle / 2);
915   m_rotInc = TWOPI / static_cast<double>(iNViews);
916   m_rotStart = 0;
917   m_dViewDiameter = sin (m_dFanBeamAngle / 2) * m_dFocalLength * 2;
918
919   if (! ((iNViews == 750 && lDataLength == 1560000L) || (iNViews == 950 && lDataLength == 1976000L) 
920                 || (iNViews == 1500 && lDataLength == 3120000)))
921     return false;
922
923   double dCenter = (iNDets - 1.) / 2.; // change from (Nm+1)/2 because of 0 vs. 1 indexing
924   double* pdCosScale = new double [iNDets];
925   for (int i = 0; i < iNDets; i++)
926     pdCosScale[i] = 1. / cos ((i - dCenter) * m_detInc);
927
928   long lDataPos = 0;
929   for (int iv = 0; iv < iNViews; iv++) {
930     unsigned char* pArgBase = pData + lDataPos;
931     unsigned char* p = pArgBase+0; SwapBytes4IfLittleEndian (p);
932     long lProjNumber = *reinterpret_cast<long*>(p);
933
934     p = pArgBase+20;  SwapBytes4IfLittleEndian (p);
935     long lEscale = *reinterpret_cast<long*>(p);
936
937     p = pArgBase+28;  SwapBytes4IfLittleEndian (p);
938     long lTime = *reinterpret_cast<long*>(p);
939
940     p = pArgBase + 4; SwapBytes4IfLittleEndian (p);
941     double dAlpha = *reinterpret_cast<float*>(p) + HALFPI;
942
943     p = pArgBase+12; SwapBytes4IfLittleEndian (p);
944     double dAlign = *reinterpret_cast<float*>(p);
945
946     p = pArgBase + 16; SwapBytes4IfLittleEndian (p);
947     double dMaxValue = *reinterpret_cast<float*>(p);
948
949     DetectorArray& detArray = getDetectorArray (iv);
950     detArray.setViewAngle (dAlpha);
951     DetectorValue* detval = detArray.detValues();
952
953     double dViewScale = 1. / (2294.4871 * ::pow (2.0, -lEscale));
954     lDataPos += 32;
955     for (int id = 0; id < iNDets; id++) {
956       int iV = pData[lDataPos+1] + (pData[lDataPos] << 8);
957       if (iV > 32767)   // two's complement signed conversion
958         iV = iV - 65536;
959       detval[id] = iV * dViewScale * pdCosScale[id];
960       lDataPos += 2;
961     }
962 #if 1
963     for (int k = iNDets - 2; k >= 0; k--)
964       detval[k+1] = detval[k];
965     detval[0] = 0;
966 #endif
967   }
968
969   delete pdCosScale;
970   return true;
971 }
972
973 Projections*
974 Projections::interpolateToParallel () const
975 {
976   if (m_geometry == Scanner::GEOMETRY_PARALLEL)
977     return const_cast<Projections*>(this);
978
979   int nDet = m_nDet;
980   int nView = m_nView;
981   Projections* pProjNew = new Projections (nView, nDet);
982   pProjNew->m_geometry = Scanner::GEOMETRY_PARALLEL;
983   pProjNew->m_dFocalLength = m_dFocalLength;
984   pProjNew->m_dSourceDetectorLength = m_dSourceDetectorLength;
985   pProjNew->m_dViewDiameter = m_dViewDiameter;
986   pProjNew->m_dFanBeamAngle = m_dFanBeamAngle;
987   pProjNew->m_calcTime  = 0;
988   pProjNew->m_remark = m_remark;
989   pProjNew->m_remark += "; Interpolate to Parallel";
990   pProjNew->m_label.setLabelType (Array2dFileLabel::L_HISTORY);
991   pProjNew->m_label.setLabelString (pProjNew->m_remark);
992   pProjNew->m_label.setCalcTime (pProjNew->m_calcTime);
993   pProjNew->m_label.setDateTime (pProjNew->m_year, pProjNew->m_month, pProjNew->m_day, pProjNew->m_hour, pProjNew->m_minute, pProjNew->m_second);
994
995   pProjNew->m_rotStart = 0;
996 #ifdef CONVERT_PARALLEL_PI
997   pProjNew->m_rotInc = PI / nView;;
998 #else
999   pProjNew->m_rotInc = TWOPI / nView;
1000 #endif
1001   pProjNew->m_detStart = -m_dViewDiameter / 2;
1002   pProjNew->m_detInc = m_dViewDiameter / nDet;
1003   if (isEven (nDet)) // even
1004     pProjNew->m_detInc = m_dViewDiameter / (nDet - 1);
1005
1006   ParallelRaysums parallel (this, ParallelRaysums::THETA_RANGE_NORMALIZE_TO_TWOPI);
1007
1008   double* pdThetaValuesForT = new double [pProjNew->nView()];
1009   double* pdRaysumsForT = new double [pProjNew->nView()];
1010
1011   // interpolate to evenly spaced theta (views)
1012   double dDetPos = pProjNew->m_detStart;
1013   for (int iD = 0; iD < pProjNew->nDet(); iD++, dDetPos += pProjNew->m_detInc) {
1014       parallel.getThetaAndRaysumsForT (iD, pdThetaValuesForT, pdRaysumsForT);
1015
1016     double dViewAngle = m_rotStart;
1017     int iLastFloor = -1;
1018     for (int iV = 0; iV < pProjNew->nView(); iV++, dViewAngle += pProjNew->m_rotInc) {
1019       DetectorValue* detValues = pProjNew->getDetectorArray (iV).detValues();
1020       LinearInterpolator<double> interp (pdThetaValuesForT, pdRaysumsForT, pProjNew->nView(), false);
1021       detValues[iD] = interp.interpolate (dViewAngle, &iLastFloor);
1022     }
1023   }
1024   delete pdThetaValuesForT;
1025   delete pdRaysumsForT;
1026
1027   // interpolate to evenly space t (detectors)
1028   double* pdOriginalDetPositions = new double [pProjNew->nDet()];
1029   parallel.getDetPositions (pdOriginalDetPositions);
1030
1031   double* pdDetValueCopy = new double [pProjNew->nDet()];
1032   double dViewAngle = m_rotStart;
1033   for (int iV = 0; iV < pProjNew->nView(); iV++, dViewAngle += pProjNew->m_rotInc) {
1034     DetectorArray& detArray = pProjNew->getDetectorArray (iV);
1035     DetectorValue* detValues = detArray.detValues();
1036     detArray.setViewAngle (dViewAngle);
1037
1038     for (int i = 0; i < pProjNew->nDet(); i++)
1039       pdDetValueCopy[i] =   detValues[i];
1040
1041     double dDetPos = pProjNew->m_detStart;
1042     int iLastFloor = -1;
1043     LinearInterpolator<double> interp (pdOriginalDetPositions, pdDetValueCopy, pProjNew->nDet(), false);
1044     for (int iD = 0; iD < pProjNew->nDet(); iD++, dDetPos += pProjNew->m_detInc)
1045       detValues[iD] = interp.interpolate (dDetPos, &iLastFloor);
1046   }
1047   delete pdDetValueCopy;
1048   delete pdOriginalDetPositions;
1049
1050   return pProjNew;
1051 }
1052
1053
1054 ///////////////////////////////////////////////////////////////////////////////
1055 //
1056 // Class ParallelRaysums
1057 //
1058 // Used for converting divergent beam raysums into Parallel raysums
1059 //
1060 ///////////////////////////////////////////////////////////////////////////////
1061
1062 ParallelRaysums::ParallelRaysums (const Projections* pProjections, int iThetaRange)
1063 : m_iNumCoordinates(0), m_iNumView(pProjections->nView()), m_iNumDet(pProjections->nDet()),
1064   m_iThetaRange (iThetaRange), m_pCoordinates(NULL)
1065 {
1066   int iGeometry = pProjections->geometry();
1067   double dDetInc = pProjections->detInc();
1068   double dDetStart = pProjections->detStart();
1069   double dFocalLength = pProjections->focalLength();
1070
1071   m_iNumCoordinates =  m_iNumView * m_iNumDet;
1072   m_pCoordinates = new ParallelRaysumCoordinate [m_iNumCoordinates];
1073   m_vecpCoordinates.reserve (m_iNumCoordinates);
1074   for (int i = 0; i < m_iNumCoordinates; i++)
1075     m_vecpCoordinates[i] = m_pCoordinates + i;
1076
1077   int iCoordinate = 0;
1078   for (int iV = 0; iV < m_iNumView; iV++) {
1079     double dViewAngle = pProjections->getDetectorArray(iV).viewAngle();
1080     const DetectorValue* detValues = pProjections->getDetectorArray(iV).detValues();
1081
1082     double dDetPos = dDetStart;
1083     for (int iD = 0; iD < m_iNumDet; iD++) {
1084       ParallelRaysumCoordinate* pC = m_vecpCoordinates[iCoordinate++];
1085
1086       if (iGeometry == Scanner::GEOMETRY_PARALLEL) {
1087         pC->m_dTheta = dViewAngle;
1088         pC->m_dT = dDetPos;
1089       } else if (iGeometry == Scanner::GEOMETRY_EQUILINEAR) {
1090         double dFanAngle = atan (dDetPos / pProjections->sourceDetectorLength());
1091         pC->m_dTheta = dViewAngle + dFanAngle;
1092         pC->m_dT = dFocalLength * sin(dFanAngle);        
1093
1094       } else if (iGeometry == Scanner::GEOMETRY_EQUIANGULAR) {
1095         // fan angle is same as dDetPos
1096         pC->m_dTheta = dViewAngle + dDetPos;
1097         pC->m_dT = dFocalLength * sin (dDetPos);        
1098       }
1099       if (m_iThetaRange != THETA_RANGE_UNCONSTRAINED) {
1100         pC->m_dTheta = normalizeAngle (pC->m_dTheta);
1101         if (m_iThetaRange == THETA_RANGE_FOLD_TO_PI && pC->m_dTheta >= PI) {
1102           pC->m_dTheta -= PI;
1103           pC->m_dT = -pC->m_dT;
1104         }
1105       }
1106       pC->m_dRaysum = detValues[iD];
1107       dDetPos += dDetInc;
1108     }
1109   }
1110 }
1111
1112 ParallelRaysums::~ParallelRaysums()
1113 {
1114   delete m_pCoordinates;
1115 }
1116
1117 ParallelRaysums::CoordinateContainer&
1118 ParallelRaysums::getSortedByTheta()
1119 {
1120   if (m_vecpSortedByTheta.size() == 0) {
1121     m_vecpSortedByTheta.resize (m_iNumCoordinates);
1122     for (int i = 0; i < m_iNumCoordinates; i++)
1123       m_vecpSortedByTheta[i] = m_vecpCoordinates[i];
1124     std::sort (m_vecpSortedByTheta.begin(), m_vecpSortedByTheta.end(), ParallelRaysumCoordinate::compareByTheta);
1125   }
1126
1127   return m_vecpSortedByTheta;
1128 }
1129
1130 ParallelRaysums::CoordinateContainer&
1131 ParallelRaysums::getSortedByT()
1132 {
1133   if (m_vecpSortedByT.size() == 0) {
1134     m_vecpSortedByT.resize (m_iNumCoordinates);
1135     for (int i = 0; i < m_iNumCoordinates; i++)
1136       m_vecpSortedByT[i] = m_vecpCoordinates[i];
1137     std::sort (m_vecpSortedByT.begin(), m_vecpSortedByT.end(), ParallelRaysumCoordinate::compareByT);
1138   }
1139
1140   return m_vecpSortedByT;
1141 }
1142
1143
1144 void
1145 ParallelRaysums::getLimits (double* dMinT, double* dMaxT, double* dMinTheta, double* dMaxTheta) const
1146 {
1147   if (m_iNumCoordinates <= 0)
1148     return;
1149
1150   *dMinT = *dMaxT = m_vecpCoordinates[0]->m_dT;
1151   *dMinTheta = *dMaxTheta = m_vecpCoordinates[0]->m_dTheta;
1152
1153   for (int i = 0; i < m_iNumCoordinates; i++) {
1154     double dT = m_vecpCoordinates[i]->m_dT;
1155     double dTheta = m_vecpCoordinates[i]->m_dTheta;
1156
1157     if (dT < *dMinT)
1158       *dMinT = dT;
1159     else if (dT > *dMaxT)
1160       *dMaxT = dT;
1161
1162     if (dTheta < *dMinTheta)
1163       *dMinTheta = dTheta;
1164     else if (dTheta > *dMaxTheta)
1165       *dMaxTheta = dTheta;
1166   }
1167 }
1168
1169 void
1170 ParallelRaysums::getThetaAndRaysumsForT (int iTheta, double* pTheta, double* pRaysum)
1171 {
1172   const CoordinateContainer& coordsT = getSortedByT();
1173
1174   int iBase = iTheta * m_iNumView;
1175   for (int i = 0; i < m_iNumView; i++) {
1176     int iPos = iBase + i;
1177     pTheta[i] = coordsT[iPos]->m_dTheta;
1178     pRaysum[i] = coordsT[iPos]->m_dRaysum;
1179   }
1180 }
1181
1182 void
1183 ParallelRaysums::getDetPositions (double* pdDetPos)
1184 {
1185   const CoordinateContainer& coordsT = getSortedByT();
1186
1187   int iPos = 0;
1188   for (int i = 0; i < m_iNumDet; i++) {
1189     pdDetPos[i] = coordsT[iPos]->m_dT;
1190     iPos += m_iNumView;
1191   }
1192 }