source: fact/tools/rootmacros/fits.h@ 13151

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