source: fact/tools/pyscripts/pyfact/pyfits.h@ 13346

Last change on this file since 13346 was 13332, checked in by neise, 13 years ago
inserted getters for fits header information
  • Property svn:executable set to *
File size: 24.2 KB
Line 
1#ifndef MARS_fits
2#define MARS_fits
3
4#include <stdint.h>
5
6#include <map>
7#include <string>
8#include <sstream>
9#include <algorithm>
10
11#ifdef __EXCEPTIONS
12#include <stdexcept>
13#endif
14
15#ifdef __CINT__
16#define off_t size_t
17#endif
18
19#ifndef __MARS__
20#include <vector>
21#include <iomanip>
22#include <iostream>
23#define gLog cerr
24#define ___err___ ""
25#define ___all___ ""
26#else
27#include "MLog.h"
28#include "MLogManip.h"
29#define ___err___ err
30#define ___all___ all
31#endif
32
33#define HAVE_ZLIB
34#ifdef HAVE_ZLIB
35#include "izstream.h"
36#else
37#include <fstream>
38#define izstream ifstream
39#warning Support for zipped FITS files disabled.
40#endif
41
42namespace std
43{
44
45class fits : public izstream
46{
47public:
48 struct Entry
49 {
50 char type;
51 string value;
52 string comment;
53
54 template<typename T>
55 T Get() const
56 {
57 T t;
58
59 istringstream str(value);
60 str >> t;
61
62 return t;
63 }
64 };
65
66 struct Table
67 {
68 off_t offset;
69
70 string name;
71 size_t bytes_per_row;
72 size_t num_rows;
73 size_t num_cols;
74
75 struct Column
76 {
77 size_t offset;
78 size_t num;
79 size_t size;
80 char type;
81 string unit;
82 };
83
84 typedef map<string, Entry> Keys;
85 typedef map<string, Column> Columns;
86
87 Columns cols;
88 Keys keys;
89
90 //------------ vectors containing the same info as cols and keys------
91 // They are filled at the end of the contstuctor
92 // They are used py python, for retrieving the contents of the maps
93 // I did not find out how to return a map of <string, struct> via ROOT to python
94 // So I use this ugly hack. I guess its no problem, its just ugly
95 //
96 // btw: The way these variables are named, is imho as ugly as possible,
97 // but I will stick to it.
98 // usually a std::map contains key-value pairs
99 // that means the e.g. map<string, Entry> contains keys of type string
100 // and values of type Entry.
101 // but now the map itself was called 'keys', which means one should say:
102 // the keys of 'keys' are of type string
103 // and
104 // the value of 'keys' are of type Entry.
105 // not to forget that:
106 // one field of a value of 'keys' is named 'value'
107
108 // vectors for Keys keys;
109 vector<string> Py_KeyKeys;
110 vector<string> Py_KeyValues;
111 vector<string> Py_KeyComments;
112 vector<char> Py_KeyTypes;
113
114 // vectors for Columns cols;
115 vector<string> Py_ColumnKeys;
116 vector<size_t> Py_ColumnOffsets;
117 vector<size_t> Py_ColumnNums;
118 vector<size_t> Py_ColumnSizes;
119 vector<char> Py_ColumnTypes;
120 vector<string> Py_ColumnUnits;
121 //-end of----- vectors containing the same info as cols and keys------
122
123 string Trim(const string &str, char c=' ') const
124 {
125 // Trim Both leading and trailing spaces
126 const size_t pstart = str.find_first_not_of(c); // Find the first character position after excluding leading blank spaces
127 const size_t pend = str.find_last_not_of(c); // Find the first character position from reverse af
128
129 // if all spaces or empty return an empty string
130 if (string::npos==pstart || string::npos==pend)
131 return string();
132
133 return str.substr(pstart, pend-pstart+1);
134 }
135
136 bool Check(const string &key, char type, const string &value="") const
137 {
138 const Keys::const_iterator it = keys.find(key);
139 if (it==keys.end())
140 {
141 ostringstream str;
142 str << "Key '" << key << "' not found.";
143#ifdef __EXCEPTIONS
144 throw runtime_error(str.str());
145#else
146 gLog << ___err___ << "ERROR - " << str.str() << endl;
147 return false;
148#endif
149 }
150
151 if (it->second.type!=type)
152 {
153 ostringstream str;
154 str << "Wrong type for key '" << key << "': expected " << type << ", found " << it->second.type << ".";
155#ifdef __EXCEPTIONS
156 throw runtime_error(str.str());
157#else
158 gLog << ___err___ << "ERROR - " << str.str() << endl;
159 return false;
160#endif
161 }
162
163 if (!value.empty() && it->second.value!=value)
164 {
165 ostringstream str;
166 str << "Wrong value for key '" << key << "': expected " << value << ", found " << it->second.value << ".";
167#ifdef __EXCEPTIONS
168 throw runtime_error(str.str());
169#else
170 gLog << ___err___ << "ERROR - " << str.str() << endl;
171 return false;
172#endif
173 }
174
175 return true;
176 }
177
178 Keys ParseBlock(const vector<string> &vec) const
179 {
180 map<string,Entry> rc;
181
182 for (unsigned int i=0; i<vec.size(); i++)
183 {
184 const string key = Trim(vec[i].substr(0,8));
185 // Keywords without a value, like COMMENT / HISTORY
186 if (vec[i].substr(8,2)!="= ")
187 continue;
188
189 char type = 0;
190
191 string com;
192 string val = Trim(vec[i].substr(10));
193 if (val[0]=='\'')
194 {
195 // First skip all '' in the string
196 size_t p = 1;
197 while (1)
198 {
199 const size_t pp = val.find_first_of('\'', p);
200 if (pp==string::npos)
201 break;
202
203 p = val[pp+1]=='\'' ? pp+2 : pp+1;
204 }
205
206 // Now find the comment
207 const size_t ppp = val.find_first_of('/', p);
208
209 // Set value, comment and type
210 com = ppp==string::npos ? "" : Trim(val.substr(ppp+1));
211 val = Trim(val.substr(1, p-2));
212 type = 'T';
213 }
214 else
215 {
216 const size_t p = val.find_first_of('/');
217
218 com = Trim(val.substr(p+2));
219 val = Trim(val.substr(0, p));
220
221 if (val.empty() || val.find_first_of('T')!=string::npos || val.find_first_of('F')!=string::npos)
222 type = 'B';
223 else
224 type = val.find_last_of('.')==string::npos ? 'I' : 'F';
225 }
226
227 const Entry e = { type, val, com };
228 rc[key] = e;
229 }
230
231 return rc;
232 }
233
234 Table() : offset(0) { }
235 Table(const vector<string> &vec, off_t off) :
236 offset(off), keys(ParseBlock(vec))
237 {
238 if (!Check("XTENSION", 'T', "BINTABLE") ||
239 !Check("NAXIS", 'I', "2") ||
240 !Check("BITPIX", 'I', "8") ||
241 !Check("PCOUNT", 'I', "0") ||
242 !Check("GCOUNT", 'I', "1") ||
243 !Check("EXTNAME", 'T') ||
244 !Check("NAXIS1", 'I') ||
245 !Check("NAXIS2", 'I') ||
246 !Check("TFIELDS", 'I'))
247 return;
248
249 bytes_per_row = Get<size_t>("NAXIS1");
250 num_rows = Get<size_t>("NAXIS2");
251 num_cols = Get<size_t>("TFIELDS");
252
253 size_t bytes = 0;
254 for (size_t i=1; i<=num_cols; i++)
255 {
256 ostringstream num;
257 num << i;
258
259 if (!Check("TTYPE"+num.str(), 'T') ||
260 !Check("TFORM"+num.str(), 'T'))
261 return;
262
263 const string id = Get<string>("TTYPE"+num.str());
264 const string fmt = Get<string>("TFORM"+num.str());
265 const string unit = Get<string>("TUNIT"+num.str(), "");
266
267 istringstream sin(fmt);
268 int n = 0;
269 sin >> n;
270 if (!sin)
271 n = 1;
272
273 const char type = fmt[fmt.length()-1];
274
275 size_t size = 0;
276 switch (type)
277 {
278 // We could use negative values to mark floats
279 // otheriwse we could just cast them to int64_t?
280 case 'L': size = 1; break; // logical
281 // case 'X': size = n; break; // bits (n=number of bytes needed to contain all bits)
282 case 'B': size = 1; break; // byte
283 case 'I': size = 2; break; // short
284 case 'J': size = 4; break; // int
285 case 'K': size = 8; break; // long long
286 case 'E': size = 4; break; // float
287 case 'D': size = 8; break; // double
288 // case 'C': size = 8; break; // complex float
289 // case 'M': size = 16; break; // complex double
290 // case 'P': size = 8; break; // array descriptor (32bit)
291 // case 'Q': size = 16; break; // array descriptor (64bit)
292 default:
293 {
294 ostringstream str;
295 str << "FITS format TFORM='" << fmt << "' not yet supported.";
296#ifdef __EXCEPTIONS
297 throw runtime_error(str.str());
298#else
299 gLog << ___err___ << "ERROR - " << str.str() << endl;
300 return;
301#endif
302 }
303 }
304
305 const Table::Column col = { bytes, n, size, type, unit };
306
307 cols[id] = col;
308 bytes += n*size;
309 }
310
311 if (bytes!=bytes_per_row)
312 {
313#ifdef __EXCEPTIONS
314 throw runtime_error("Column size mismatch");
315#else
316 gLog << ___err___ << "ERROR - Column size mismatch" << endl;
317 return;
318#endif
319 }
320
321 name = Get<string>("EXTNAME");
322
323
324 Fill_Py_Vectors();
325 }
326
327 void Fill_Py_Vectors(void)
328 {
329 // Fill the Py_ vectors see line: 90ff
330 // vectors for Keys keys;
331 for (Keys::const_iterator it=keys.begin(); it!=keys.end(); it++)
332 {
333 Py_KeyKeys.push_back(it->first);
334 Py_KeyValues.push_back(it->second.value);
335 Py_KeyComments.push_back(it->second.comment);
336 Py_KeyTypes.push_back(it->second.type);
337 }
338
339 // vectors for Columns cols;
340 for (Columns::const_iterator it=cols.begin(); it!=cols.end(); it++)
341 {
342 Py_ColumnKeys.push_back(it->first);
343 Py_ColumnTypes.push_back(it->second.type);
344 Py_ColumnOffsets.push_back(it->second.offset);
345 Py_ColumnNums.push_back(it->second.num);
346 Py_ColumnSizes.push_back(it->second.size);
347 Py_ColumnUnits.push_back(it->second.unit);
348 }
349 }
350
351
352 void PrintKeys(bool display_all=false) const
353 {
354 for (Keys::const_iterator it=keys.begin(); it!=keys.end(); it++)
355 {
356 if (!display_all &&
357 (it->first.substr(0, 6)=="TTYPE" ||
358 it->first.substr(0, 6)=="TFORM" ||
359 it->first.substr(0, 6)=="TUNIT" ||
360 it->first=="TFIELDS" ||
361 it->first=="XTENSION" ||
362 it->first=="NAXIS" ||
363 it->first=="BITPIX" ||
364 it->first=="PCOUNT" ||
365 it->first=="GCOUNT")
366 )
367 continue;
368
369 gLog << ___all___ << setw(2) << it->second.type << '|' << it->first << '=' << it->second.value << '/' << it->second.comment << '|' << endl;
370 }
371 }
372
373 void PrintColumns() const
374 {
375 typedef map<pair<size_t, string>, Column> Sorted;
376
377 Sorted sorted;
378
379 for (Columns::const_iterator it=cols.begin(); it!=cols.end(); it++)
380 sorted[make_pair(it->second.offset, it->first)] = it->second;
381
382 for (Sorted::const_iterator it=sorted.begin(); it!=sorted.end(); it++)
383 {
384 gLog << ___all___ << setw(6) << it->second.offset << "| ";
385 gLog << it->second.num << 'x';
386 switch (it->second.type)
387 {
388 case 'L': gLog << "bool(8)"; break;
389 case 'B': gLog << "byte(8)"; break;
390 case 'I': gLog << "short(16)"; break;
391 case 'J': gLog << "int(32)"; break;
392 case 'K': gLog << "int(64)"; break;
393 case 'E': gLog << "float(32)"; break;
394 case 'D': gLog << "double(64)"; break;
395 }
396 gLog << ": " << it->first.second << " [" << it->second.unit << "]" << endl;
397 }
398 }
399
400 operator bool() const { return !name.empty(); }
401
402 bool HasKey(const string &key) const
403 {
404 return keys.find(key)!=keys.end();
405 }
406
407 // Values of keys are always signed
408 template<typename T>
409 T Get(const string &key) const
410 {
411 const map<string,Entry>::const_iterator it = keys.find(key);
412 if (it==keys.end())
413 {
414 ostringstream str;
415 str << "Key '" << key << "' not found." << endl;
416#ifdef __EXCEPTIONS
417 throw runtime_error(str.str());
418#else
419 gLog << ___err___ << "ERROR - " << str.str() << endl;
420 return 0;
421#endif
422 }
423 return it->second.Get<T>();
424 }
425
426 // Values of keys are always signed
427 template<typename T>
428 T Get(const string &key, const string &deflt) const
429 {
430 const map<string,Entry>::const_iterator it = keys.find(key);
431 return it==keys.end() ? deflt :it->second.Get<T>();
432 }
433
434 size_t GetN(const string &key) const
435 {
436 const Columns::const_iterator it = cols.find(key);
437 if (it==cols.end()){
438 ostringstream str;
439 str << "Key '" << key << "' not found." << endl;
440 str << "Possible keys are:" << endl;
441 for ( Columns::const_iterator it=cols.begin() ; it != cols.end(); ++it){
442 str << it->first << endl;
443 }
444#ifdef __EXCEPTIONS
445 throw runtime_error(str.str());
446#else
447 gLog << ___err___ << "ERROR - " << str.str() << endl;
448 return 0;
449#endif
450 }
451 return it==cols.end() ? 0 : it->second.num;
452 }
453 };
454
455private:
456 Table fTable;
457
458 typedef pair<void*, Table::Column> Address;
459 typedef vector<Address> Addresses;
460 //map<void*, Table::Column> fAddresses;
461 Addresses fAddresses;
462
463 vector<char> fBufferRow;
464 vector<char> fBufferDat;
465
466 size_t fRow;
467
468 vector<string> ReadBlock(vector<string> &vec)
469 {
470 bool endtag = false;
471 for (int i=0; i<36; i++)
472 {
473 char c[81];
474 c[80] = 0;
475 read(c, 80);
476 if (!good())
477 break;
478
479 if (c[0]==0)
480 return vector<string>();
481
482 string str(c);
483
484// if (!str.empty())
485// cout << setw(2) << i << "|" << str << "|" << (endtag?'-':'+') << endl;
486
487 if (str=="END ")
488 {
489 endtag = true;
490
491 // Make sure that no empty vector is returned
492 if (vec.size()%36==0)
493 vec.push_back(string("END = '' / "));
494 }
495
496 if (endtag)
497 continue;
498
499 vec.push_back(str);
500 }
501
502 return vec;
503 }
504
505 string Compile(const string &key, int16_t i=-1)
506 {
507 if (i<0)
508 return key;
509
510 ostringstream str;
511 str << key << i;
512 return str.str();
513 }
514
515public:
516 fits(const string &fname) : izstream(fname.c_str())
517 {
518 char simple[10];
519 read(simple, 10);
520 if (!good())
521 return;
522
523 if (memcmp(simple, "SIMPLE = ", 10))
524 {
525 clear(rdstate()|ios::badbit);
526#ifdef __EXCEPTIONS
527 throw runtime_error("File is not a FITS file.");
528#else
529 gLog << ___err___ << "ERROR - File is not a FITS file." << endl;
530 return;
531#endif
532 }
533
534 seekg(0);
535
536 while (good())
537 {
538 vector<string> block;
539 while (1)
540 {
541 // FIXME: Set limit on memory consumption
542 ReadBlock(block);
543 if (!good())
544 {
545 clear(rdstate()|ios::badbit);
546#ifdef __EXCEPTIONS
547 throw runtime_error("FITS file corrupted.");
548#else
549 gLog << ___err___ << "ERROR - FITS file corrupted." << endl;
550 return;
551#endif
552 }
553
554 if (block.size()%36)
555 break;
556 }
557
558 if (block.size()==0)
559 break;
560
561 if (block[0].substr(0, 9)=="SIMPLE =")
562 continue;
563
564 if (block[0].substr(0, 9)=="XTENSION=")
565 {
566 // FIXME: Check for table name
567
568 fTable = Table(block, tellg());
569 fRow = (size_t)-1;
570
571 //fTable.PrintKeys();
572
573 if (!fTable)
574 {
575 clear(rdstate()|ios::badbit);
576 return;
577 }
578
579 fBufferRow.resize(fTable.bytes_per_row);
580 fBufferDat.resize(fTable.bytes_per_row);
581
582 /*
583 // Next table should start at:
584 const size_t size = fTable.bytes_per_row*fTable.num_rows;
585 const size_t blks = size/(36*80);
586 const size_t rest = size%(36*80);
587
588 seekg((blks+(rest>0?1:0))*(36*80), ios::cur);
589 if (!good())
590 gLog << ___err___ << "File seems to be incomplete (less data than expected from header)." << endl;
591
592 fRow = fTable.num_rows;
593 */
594
595 break;
596 }
597 }
598 }
599
600 void ReadRow(size_t row)
601 {
602 // if (row!=fRow+1) // Fast seeking is ensured by izstream
603 seekg(fTable.offset+row*fTable.bytes_per_row);
604
605 fRow = row;
606
607 read(fBufferRow.data(), fBufferRow.size());
608 //fin.clear(fin.rdstate()&~ios::eofbit);
609 }
610
611 template<size_t N>
612 void revcpy(char *dest, const char *src, int num)
613 {
614 const char *pend = src + num*N;
615 for (const char *ptr = src; ptr<pend; ptr+=N, dest+=N)
616 reverse_copy(ptr, ptr+N, dest);
617 }
618
619 bool GetRow(size_t row)
620 {
621 ReadRow(row);
622 if (!good())
623 return good();
624
625 for (Addresses::const_iterator it=fAddresses.begin(); it!=fAddresses.end(); it++)
626 {
627 const Table::Column &c = it->second;
628
629 const char *src = fBufferRow.data() + c.offset;
630 char *dest = reinterpret_cast<char*>(it->first);
631
632 // Let the compiler do some optimization by
633 // knowing the we only have 1, 2, 4 and 8
634 switch (c.size)
635 {
636 case 1: memcpy (dest, src, c.num*c.size); break;
637 case 2: revcpy<2>(dest, src, c.num); break;
638 case 4: revcpy<4>(dest, src, c.num); break;
639 case 8: revcpy<8>(dest, src, c.num); break;
640 }
641 }
642
643 return good();
644 }
645
646 bool GetNextRow()
647 {
648 return GetRow(fRow+1);
649 }
650
651 bool SkipNextRow()
652 {
653 seekg(fTable.offset+(++fRow)*fTable.bytes_per_row);
654 return good();
655 }
656
657 static bool Compare(const Address &p1, const Address &p2)
658 {
659 return p1.first>p2.first;
660 }
661
662 template<typename T>
663 bool SetPtrAddress(const string &name, T *ptr, size_t cnt)
664 {
665 if (fTable.cols.count(name)==0)
666 {
667 ostringstream str;
668 str <<"SetPtrAddress('" << name << "') - Column not found." << endl;
669#ifdef __EXCEPTIONS
670 throw runtime_error(str.str());
671#else
672 gLog << ___err___ << "ERROR - " << str.str() << endl;
673 return false;
674#endif
675 }
676
677 if (sizeof(T)!=fTable.cols[name].size)
678 {
679 ostringstream str;
680 str << "SetPtrAddress('" << name << "') - Element size mismatch: expected "
681 << fTable.cols[name].size << " from header, got " << sizeof(T) << endl;
682#ifdef __EXCEPTIONS
683 throw runtime_error(str.str());
684#else
685 gLog << ___err___ << "ERROR - " << str.str() << endl;
686 return false;
687#endif
688 }
689
690 if (cnt!=fTable.cols[name].num)
691 {
692 ostringstream str;
693 str << "SetPtrAddress('" << name << "') - Element count mismatch: expected "
694 << fTable.cols[name].num << " from header, got " << cnt << endl;
695#ifdef __EXCEPTIONS
696 throw runtime_error(str.str());
697#else
698 gLog << ___err___ << "ERROR - " << str.str() << endl;
699 return false;
700#endif
701 }
702
703 // if (fAddresses.count(ptr)>0)
704 // gLog << warn << "SetPtrAddress('" << name << "') - Pointer " << ptr << " already assigned." << endl;
705
706 //fAddresses[ptr] = fTable.cols[name];
707 fAddresses.push_back(make_pair(ptr, fTable.cols[name]));
708 sort(fAddresses.begin(), fAddresses.end(), Compare);
709 return true;
710 }
711
712 template<class T>
713 bool SetRefAddress(const string &name, T &ptr)
714 {
715 return SetPtrAddress(name, &ptr, sizeof(ptr)/sizeof(T));
716 }
717
718 template<typename T>
719 bool SetVecAddress(const string &name, vector<T> &vec)
720 {
721 return SetPtrAddress(name, vec.data(), vec.size());
722 }
723
724 template<typename T>
725 T Get(const string &key) const
726 {
727 return fTable.Get<T>(key);
728 }
729
730 template<typename T>
731 T Get(const string &key, const string &deflt) const
732 {
733 return fTable.Get<T>(key, deflt);
734 }
735
736 bool SetPtrAddress(const string &name, void *ptr)
737 {
738 if (fTable.cols.count(name)==0)
739 {
740 ostringstream str;
741 str <<"SetPtrAddress('" << name << "') - Column not found." << endl;
742#ifdef __EXCEPTIONS
743 throw runtime_error(str.str());
744#else
745 gLog << ___err___ << "ERROR - " << str.str() << endl;
746 return false;
747#endif
748 }
749
750 // if (fAddresses.count(ptr)>0)
751 // gLog << warn << "SetPtrAddress('" << name << "') - Pointer " << ptr << " already assigned." << endl;
752
753 //fAddresses[ptr] = fTable.cols[name];
754 fAddresses.push_back(make_pair(ptr, fTable.cols[name]));
755 sort(fAddresses.begin(), fAddresses.end(), Compare);
756 return true;
757 }
758
759 bool HasKey(const string &key) const { return fTable.HasKey(key); }
760 int64_t GetInt(const string &key) const { return fTable.Get<int64_t>(key); }
761 uint64_t GetUInt(const string &key) const { return fTable.Get<uint64_t>(key); }
762 double GetFloat(const string &key) const { return fTable.Get<double>(key); }
763 string GetStr(const string &key) const { return fTable.Get<string>(key); }
764
765 size_t GetN(const string &key) const
766 {
767 return fTable.GetN(key);
768 }
769
770 size_t GetNumRows() const { return fTable.num_rows; }
771 size_t GetRow() const { return fRow; }
772
773 operator bool() const { return fTable && fTable.offset!=0; }
774
775 void PrintKeys() const { fTable.PrintKeys(); }
776 void PrintColumns() const { fTable.PrintColumns(); }
777
778 // 'Wrappers' for the Table's Getters of the Py Vectors
779 vector<string> GetPy_KeyKeys() {return fTable.Py_KeyKeys; }
780 vector<string> GetPy_KeyValues() {return fTable.Py_KeyValues; }
781 vector<string> GetPy_KeyComments() {return fTable.Py_KeyComments; }
782 vector<char> GetPy_KeyTypes() {return fTable.Py_KeyTypes; }
783
784 vector<string> GetPy_ColumnKeys() {return fTable.Py_ColumnKeys; }
785 vector<size_t> GetPy_ColumnOffsets() {return fTable.Py_ColumnOffsets; }
786 vector<size_t> GetPy_ColumnNums() {return fTable.Py_ColumnNums; }
787 vector<size_t> GetPy_ColumnSizes() {return fTable.Py_ColumnSizes;}
788 vector<char> GetPy_ColumnTypes() {return fTable.Py_ColumnTypes;}
789 vector<string> GetPy_ColumnUnits() {return fTable.Py_ColumnUnits;}
790
791};
792
793};
794#endif
Note: See TracBrowser for help on using the repository browser.