]> Creatis software - clitk.git/blob - common/clitkCommon.cxx
Add include
[clitk.git] / common / clitkCommon.cxx
1 /*=========================================================================
2   Program:   vv                     http://www.creatis.insa-lyon.fr/rio/vv
3
4   Authors belong to:
5   - University of LYON              http://www.universite-lyon.fr/
6   - Léon Bérard cancer center       http://www.centreleonberard.fr
7   - CREATIS CNRS laboratory         http://www.creatis.insa-lyon.fr
8
9   This software is distributed WITHOUT ANY WARRANTY; without even
10   the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11   PURPOSE.  See the copyright notices for more information.
12
13   It is distributed under dual licence
14
15   - BSD        See included LICENSE.txt file
16   - CeCILL-B   http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
17 ===========================================================================**/
18
19 #ifndef CLITKCOMMON_CXX
20 #define CLITKCOMMON_CXX
21
22 #include <itksys/SystemTools.hxx>
23
24 // clitk include 
25 #include "clitkCommon.h"
26
27 // std include 
28 #include <fstream>
29 #include <iomanip>
30 #include <sstream>
31 #include <cerrno>
32
33 //------------------------------------------------------------------
34 // skip line which begin with a sharp '#'
35 void clitk::skipComment(std::istream & is)
36 {
37   char c;
38   char line[1024];
39   if (is.eof()) return;
40   is >> c ;
41   while (is && (c == '#')) {
42     is.getline (line, 1024);
43     is >> c;
44     if (is.eof()) return;
45   }
46   if (!(is.fail()) && c != '\n')
47     is.unget();
48 } ////
49 //------------------------------------------------------------------
50
51 //------------------------------------------------------------------
52 // linear (rough) conversion from Hounsfield Unit to density
53 double clitk::HU2density(double HU)
54 {
55   return (HU+1000.0)/1000.0;
56 } ////
57 //------------------------------------------------------------------
58
59 //------------------------------------------------------------------
60 // Return filename extension
61 std::string clitk::GetExtension(const std::string& filename)
62 {
63   // This assumes that the final '.' in a file name is the delimiter
64   // for the file's extension type
65   const std::string::size_type it = filename.find_last_of( "." );
66   // This determines the file's type by creating a new string
67   // who's value is the extension of the input filename
68   // eg. "myimage.gif" has an extension of "gif"
69   std::string fileExt( filename, it+1, filename.length() );
70   return( fileExt );
71 } ////
72 //------------------------------------------------------------------
73
74
75 //------------------------------------------------------------------
76 // Return filename splitting in 1 or 2 parts : directory name (if exists) & filename
77 std::vector<std::string> clitk::SplitFilename(const std::string& filename)
78 {
79   std::vector<std::string> dirname;
80   std::string path = itksys::SystemTools::GetFilenamePath(filename);
81   std::vector<std::string> pathComponents;
82   itksys::SystemTools::SplitPath(filename.c_str(), pathComponents);
83   std::string fileName = pathComponents.back();
84   dirname.push_back(path);
85   dirname.push_back(fileName);
86   return( dirname );
87 } ////
88 //------------------------------------------------------------------
89
90
91 //------------------------------------------------------------------
92 // Display progression
93 void clitk::VerboseInProgress(const int nb, const int current, const int percentage)
94 {
95   static int previous = -1;
96   const int rounded = (100*current)/nb;
97   if (previous==rounded) return;
98   previous = rounded;
99
100   std::ostringstream oss;
101   oss << std::setw(4) << rounded << '%';
102
103   std::cout << oss.str() << std::flush;
104   for (unsigned int i=0; i<oss.str().length(); ++i)
105     std::cout << "\b" << std::flush;
106 }
107 //------------------------------------------------------------------
108
109 //------------------------------------------------------------------
110 // Display progression
111 void clitk::VerboseInProgressInPercentage(const int nb, const int current, const int percentage)
112 {
113   VerboseInProgress(nb, current, percentage);
114 }
115 //------------------------------------------------------------------
116
117 //------------------------------------------------------------------
118 // Convert a pixel type to another (downcast)
119 template<>
120 float clitk::PixelTypeDownCast(const double & x)
121 {
122   return (float)x;
123 }
124 //------------------------------------------------------------------
125
126 //------------------------------------------------------------------
127 // Convert a pixel type without casting
128 template<>
129 double clitk::PixelTypeDownCast(const double & x)
130 {
131   return x;
132 }
133 //------------------------------------------------------------------
134
135 //------------------------------------------------------------------
136 double clitk::rad2deg(const double anglerad)
137 {
138   return (anglerad/M_PI*180.0);
139 }
140 //------------------------------------------------------------------
141
142 //------------------------------------------------------------------
143 double clitk::deg2rad(const double angledeg)
144 {
145   return (angledeg*(M_PI/180.0));
146 }
147 //------------------------------------------------------------------
148
149 //------------------------------------------------------------------
150 int clitk::GetTypeSizeFromString(const std::string & type)
151 {
152 #define RETURN_SIZEOF_PIXEL(TYPENAME, TYPE)             \
153   if (type == #TYPENAME) return sizeof(TYPE);
154   RETURN_SIZEOF_PIXEL(char, char);
155   RETURN_SIZEOF_PIXEL(uchar, uchar);
156   RETURN_SIZEOF_PIXEL(unsigned char, uchar);
157   RETURN_SIZEOF_PIXEL(unsigned_char, uchar);
158   RETURN_SIZEOF_PIXEL(short, short);
159   RETURN_SIZEOF_PIXEL(ushort, ushort);
160   RETURN_SIZEOF_PIXEL(unsigned_short, ushort);
161   RETURN_SIZEOF_PIXEL(int, int);
162   RETURN_SIZEOF_PIXEL(uint, uint);
163   RETURN_SIZEOF_PIXEL(unsigned_int, uint);
164   RETURN_SIZEOF_PIXEL(float, float);
165   RETURN_SIZEOF_PIXEL(double, double);
166   return 0;
167 }
168 //------------------------------------------------------------------
169
170 //------------------------------------------------------------------
171 template<>
172 bool clitk::IsSameType<signed char>(std::string t)
173 {
174   if ((t==GetTypeAsString<signed char>()) || (t == "schar")) return true;
175   else return false;
176 }
177
178 template<>
179 bool clitk::IsSameType<char>(std::string t)
180 {
181   if ((t==GetTypeAsString<char>()) || (t == "char")) return true;
182   else return false;
183 }
184
185 template<>
186 bool clitk::IsSameType<unsigned char>(std::string t)
187 {
188   if ((t==GetTypeAsString<unsigned char>()) || (t == "uchar")) return true;
189   else return false;
190 }
191
192 template<>
193 bool clitk::IsSameType<unsigned short>(std::string t)
194 {
195   if ((t==GetTypeAsString<unsigned short>()) || (t == "ushort")) return true;
196   else return false;
197 }
198 //------------------------------------------------------------------
199
200 //------------------------------------------------------------------
201 void clitk::FindAndReplace(std::string & line,
202                            const std::string & tofind,
203                            const std::string & replacement)
204 {
205   int pos = line.find(tofind);
206   while (pos!= (int)std::string::npos) {
207     line.replace(pos, tofind.size(), replacement);
208     pos = line.find(tofind, pos+tofind.size()+1);
209   }
210 }
211 //------------------------------------------------------------------
212
213 //------------------------------------------------------------------
214 void clitk::FindAndReplace(std::string & line,
215                            const std::vector<std::string> & tofind,
216                            const std::vector<std::string> & toreplace)
217 {
218   for(unsigned int i=0; i<tofind.size(); i++) {
219     FindAndReplace(line, tofind[i], toreplace[i]);
220   }
221 }
222 //------------------------------------------------------------------
223
224 //------------------------------------------------------------------
225 void clitk::FindAndReplace(std::ifstream & in,
226                            const std::vector<std::string> & tofind,
227                            const std::vector<std::string> & toreplace,
228                            std::ofstream & out)
229 {
230   std::string line;
231   if (tofind.size() != toreplace.size()) {
232     std::cerr << "Error' tofind' is size=" << tofind.size() << std::endl;
233     std::cerr << "... while 'toreplace' is size=" << toreplace.size() << std::endl;
234     exit(0);
235   }
236   while (std::getline(in,line)) {
237     FindAndReplace(line, tofind, toreplace);
238     out << line << std::endl;
239   }
240 }
241 //------------------------------------------------------------------
242
243 //------------------------------------------------------------------
244 double clitk::ComputeEuclideanDistanceFromPointToPlane(const itk::ContinuousIndex<double, 3> point,
245     const itk::ContinuousIndex<double, 3> pointInPlane,
246     const itk::ContinuousIndex<double, 3> normalPlane)
247 {
248   // http://mathworld.wolfram.com/Plane.html
249   // http://mathworld.wolfram.com/Point-PlaneDistance.html
250   double a = normalPlane[0];
251   double b = normalPlane[1];
252   double c = normalPlane[2];
253   double x0 = pointInPlane[0];
254   double y0 = pointInPlane[1];
255   double z0 = pointInPlane[2];
256   double x = point[0];
257   double y = point[1];
258   double z = point[2];
259
260   double norm = sqrt(x0*x0 + y0*y0 + z0*z0);
261   DD(norm);
262   double d = -a*x0 - b*y0 - c*z0;
263   DD(d);
264   double distance = (a*x + b*y + c*z + d) / norm;
265
266   return distance;
267 }
268 //------------------------------------------------------------------
269
270 //--------------------------------------------------------------------
271 // Open a file for reading
272 void clitk::openFileForReading(std::ifstream & is, const std::string & filename)
273 {
274   is.open(filename.c_str(), std::ios::in | std::ios::binary);
275   if ( is.fail() ) {
276     clitkExceptionMacro("Could not open file for reading: " 
277                         << filename << ". Error is : <" 
278                         << strerror(errno) << ">");
279   }
280 }
281 //--------------------------------------------------------------------
282
283 //--------------------------------------------------------------------
284 // Open a file for writing
285 void clitk::openFileForWriting(std::ofstream & os, const std::string & filename)
286 {
287   os.open(filename.c_str(), std::ios::out);
288   if ( os.fail() ) {
289     clitkExceptionMacro("Could not open file for writing: " 
290                         << filename << ". Error is : <" 
291                         << strerror(errno) << ">");
292   }
293 }
294 //--------------------------------------------------------------------
295
296 //--------------------------------------------------------------------
297 double clitk::cotan(double i)
298 {
299   return(1.0 / tan(i));
300 }
301 double clitk::invcotan(double x)
302 {
303   //  http://mathworld.wolfram.com/InverseCotangent.html
304   double y;
305   if (x<0) {
306     y = -0.5*M_PI-atan(x);
307   } else {
308     y = 0.5*M_PI-atan(x);
309   }
310   return y;
311 }
312 //--------------------------------------------------------------------
313
314 //--------------------------------------------------------------------
315 std::streambuf * clitk_stdcerr_backup;
316 void clitk::disableStdCerr()
317 {
318   clitk_stdcerr_backup = std::cerr.rdbuf();
319   std::stringstream oss;
320   std::cerr.rdbuf( oss.rdbuf() );
321 }
322 //--------------------------------------------------------------------
323
324 //--------------------------------------------------------------------
325 void clitk::enableStdCerr()
326 {
327   std::cerr.rdbuf(clitk_stdcerr_backup);
328 }
329 //--------------------------------------------------------------------
330
331
332 //--------------------------------------------------------------------
333 void clitk::readDoubleFromFile(const std::string & filename, std::vector<double> & list)
334 {
335   std::ifstream is;
336   clitk::openFileForReading(is, filename);
337   list.clear();
338   while (is) {
339     clitk::skipComment(is);
340     double d;
341     is >> d;
342     if (is) list.push_back(d);
343   }
344 }
345 //--------------------------------------------------------------------
346
347
348 //--------------------------------------------------------------------
349 void clitk::PrintMemoryUsed()
350 {
351 #if defined(unix) || defined(__APPLE__)
352   rusage usage;  
353   getrusage(RUSAGE_SELF, &usage);
354   DD(usage.ru_maxrss);        /* maximum resident set size */ 
355   // DD(usage.ru_ixrss);         /* integral shared memory size */
356   // DD(usage.ru_idrss);         /* integral unshared data size */
357   // DD(usage.ru_isrss);         /* integral unshared stack size */
358 #endif
359 }
360 //--------------------------------------------------------------------
361
362
363 #endif /* end #define CLITKCOMMON_CXX */
364