source: trunk/Mars/mcore/fits.h@ 12727

Last change on this file since 12727 was 12722, checked in by lyard, 13 years ago
added a few accessor functions
File size: 21.6 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 = "Empty";//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 bool HasColumn(const string& col) const
345 {
346 return cols.find(col)!=cols.end();
347 }
348
349 const Columns& getColumns() const
350 {
351 return cols;
352 }
353
354 const Keys& getKeys() const
355 {
356 return keys;
357 }
358
359
360
361 // Values of keys are always signed
362 template<typename T>
363 T Get(const string &key) const
364 {
365 const map<string,Entry>::const_iterator it = keys.find(key);
366 if (it==keys.end())
367 {
368 ostringstream str;
369 str << "Key '" << key << "' not found." << endl;
370#ifdef __EXCEPTIONS
371 throw runtime_error(str.str());
372#else
373 gLog << ___err___ << "ERROR - " << str.str() << endl;
374 return T();
375#endif
376 }
377 return it->second.Get<T>();
378 }
379
380 // Values of keys are always signed
381 template<typename T>
382 T Get(const string &key, const string &deflt) const
383 {
384 const map<string,Entry>::const_iterator it = keys.find(key);
385 return it==keys.end() ? deflt :it->second.Get<T>();
386 }
387
388 size_t GetN(const string &key) const
389 {
390 const Columns::const_iterator it = cols.find(key);
391 return it==cols.end() ? 0 : it->second.num;
392 }
393 };
394
395private:
396 Table fTable;
397
398 typedef pair<void*, Table::Column> Address;
399 typedef vector<Address> Addresses;
400 //map<void*, Table::Column> fAddresses;
401 Addresses fAddresses;
402
403 vector<char> fBufferRow;
404 vector<char> fBufferDat;
405
406 size_t fRow;
407
408 bool ReadBlock(vector<string> &vec)
409 {
410 int endtag = 0;
411 for (int i=0; i<36; i++)
412 {
413 char c[81];
414 c[80] = 0;
415 read(c, 80);
416 if (!good())
417 break;
418
419// if (c[0]==0)
420// return vector<string>();
421
422 string str(c);
423
424// if (!str.empty())
425// cout << setw(2) << i << "|" << str << "|" << (endtag?'-':'+') << endl;
426
427 if (endtag==2 || str=="END ")
428 {
429 endtag = 2; // valid END tag found
430 continue;
431 }
432
433 if (endtag==1 || str==" ")
434 {
435 endtag = 1; // end tag not found, but expected to be there
436 continue;
437 }
438
439 vec.push_back(str);
440 }
441
442 // Make sure that no empty vector is returned
443 if (endtag && vec.size()%36==0)
444 vec.push_back(string("END = '' / "));
445
446 return endtag==2;
447 }
448
449 string Compile(const string &key, int16_t i=-1)
450 {
451 if (i<0)
452 return key;
453
454 ostringstream str;
455 str << key << i;
456 return str.str();
457 }
458
459public:
460 fits(const string &fname, bool force=false) : izstream(fname.c_str())
461 {
462 char simple[10];
463 read(simple, 10);
464 if (!good())
465 return;
466
467 if (memcmp(simple, "SIMPLE = ", 10))
468 {
469 clear(rdstate()|ios::badbit);
470#ifdef __EXCEPTIONS
471 throw runtime_error("File is not a FITS file.");
472#else
473 gLog << ___err___ << "ERROR - File is not a FITS file." << endl;
474 return;
475#endif
476 }
477
478 seekg(0);
479
480 while (good())
481 {
482 vector<string> block;
483 while (1)
484 {
485 // FIXME: Set limit on memory consumption
486 const int rc = ReadBlock(block);
487 if (!good())
488 {
489 clear(rdstate()|ios::badbit);
490#ifdef __EXCEPTIONS
491 throw runtime_error("FITS file corrupted.");
492#else
493 gLog << ___err___ << "ERROR - FITS file corrupted." << endl;
494 return;
495#endif
496 }
497
498 if (block.size()%36)
499 {
500 if (!rc && !force)
501 {
502 clear(rdstate()|ios::badbit);
503#ifdef __EXCEPTIONS
504 throw runtime_error("END keyword missing in FITS header.");
505#else
506 gLog << ___err__ << "ERROR - END keyword missing in FITS file... file might be corrupted." << endl;
507 return;
508#endif
509 }
510 break;
511 }
512 }
513
514 if (block.size()==0)
515 break;
516
517 if (block[0].substr(0, 9)=="SIMPLE =")
518 continue;
519
520 if (block[0].substr(0, 9)=="XTENSION=")
521 {
522 // FIXME: Check for table name
523
524 fTable = Table(block, tellg());
525 fRow = (size_t)-1;
526
527 //fTable.PrintKeys();
528
529 if (!fTable)
530 {
531 clear(rdstate()|ios::badbit);
532 return;
533 }
534
535 fBufferRow.resize(fTable.bytes_per_row);
536 fBufferDat.resize(fTable.bytes_per_row);
537
538 /*
539 // Next table should start at:
540 const size_t size = fTable.bytes_per_row*fTable.num_rows;
541 const size_t blks = size/(36*80);
542 const size_t rest = size%(36*80);
543
544 seekg((blks+(rest>0?1:0))*(36*80), ios::cur);
545 if (!good())
546 gLog << ___err___ << "File seems to be incomplete (less data than expected from header)." << endl;
547
548 fRow = fTable.num_rows;
549 */
550
551 break;
552 }
553 }
554 }
555
556 void ReadRow(size_t row)
557 {
558 // if (row!=fRow+1) // Fast seeking is ensured by izstream
559 seekg(fTable.offset+row*fTable.bytes_per_row);
560
561 fRow = row;
562
563 read(fBufferRow.data(), fBufferRow.size());
564 //fin.clear(fin.rdstate()&~ios::eofbit);
565 }
566
567 template<size_t N>
568 void revcpy(char *dest, const char *src, int num)
569 {
570 const char *pend = src + num*N;
571 for (const char *ptr = src; ptr<pend; ptr+=N, dest+=N)
572 reverse_copy(ptr, ptr+N, dest);
573 }
574
575 bool GetRow(size_t row)
576 {
577 ReadRow(row);
578 if (!good())
579 return good();
580
581 for (Addresses::const_iterator it=fAddresses.begin(); it!=fAddresses.end(); it++)
582 {
583 const Table::Column &c = it->second;
584
585 const char *src = fBufferRow.data() + c.offset;
586 char *dest = reinterpret_cast<char*>(it->first);
587
588 // Let the compiler do some optimization by
589 // knowing the we only have 1, 2, 4 and 8
590 switch (c.size)
591 {
592 case 1: memcpy (dest, src, c.num*c.size); break;
593 case 2: revcpy<2>(dest, src, c.num); break;
594 case 4: revcpy<4>(dest, src, c.num); break;
595 case 8: revcpy<8>(dest, src, c.num); break;
596 }
597 }
598
599 return good();
600 }
601
602 bool GetNextRow()
603 {
604 return GetRow(fRow+1);
605 }
606
607 bool SkipNextRow()
608 {
609 seekg(fTable.offset+(++fRow)*fTable.bytes_per_row);
610 return good();
611 }
612
613 static bool Compare(const Address &p1, const Address &p2)
614 {
615 return p1.first>p2.first;
616 }
617
618 template<typename T>
619 bool SetPtrAddress(const string &name, T *ptr, size_t cnt)
620 {
621 if (fTable.cols.count(name)==0)
622 {
623 ostringstream str;
624 str << "SetPtrAddress('" << name << "') - Column not found." << endl;
625#ifdef __EXCEPTIONS
626 throw runtime_error(str.str());
627#else
628 gLog << ___err___ << "ERROR - " << str.str() << endl;
629 return false;
630#endif
631 }
632
633 if (sizeof(T)!=fTable.cols[name].size)
634 {
635 ostringstream str;
636 str << "SetPtrAddress('" << name << "') - Element size mismatch: expected "
637 << fTable.cols[name].size << " from header, got " << sizeof(T) << endl;
638#ifdef __EXCEPTIONS
639 throw runtime_error(str.str());
640#else
641 gLog << ___err___ << "ERROR - " << str.str() << endl;
642 return false;
643#endif
644 }
645
646 if (cnt!=fTable.cols[name].num)
647 {
648 ostringstream str;
649 str << "SetPtrAddress('" << name << "') - Element count mismatch: expected "
650 << fTable.cols[name].num << " from header, got " << cnt << endl;
651#ifdef __EXCEPTIONS
652 throw runtime_error(str.str());
653#else
654 gLog << ___err___ << "ERROR - " << str.str() << endl;
655 return false;
656#endif
657 }
658
659 // if (fAddresses.count(ptr)>0)
660 // gLog << warn << "SetPtrAddress('" << name << "') - Pointer " << ptr << " already assigned." << endl;
661
662 //fAddresses[ptr] = fTable.cols[name];
663 fAddresses.push_back(make_pair(ptr, fTable.cols[name]));
664 sort(fAddresses.begin(), fAddresses.end(), Compare);
665 return true;
666 }
667
668 template<class T>
669 bool SetRefAddress(const string &name, T &ptr)
670 {
671 return SetPtrAddress(name, &ptr, sizeof(ptr)/sizeof(T));
672 }
673
674 template<typename T>
675 bool SetVecAddress(const string &name, vector<T> &vec)
676 {
677 return SetPtrAddress(name, vec.data(), vec.size());
678 }
679
680 template<typename T>
681 T Get(const string &key) const
682 {
683 return fTable.Get<T>(key);
684 }
685
686 template<typename T>
687 T Get(const string &key, const string &deflt) const
688 {
689 return fTable.Get<T>(key, deflt);
690 }
691
692 bool SetPtrAddress(const string &name, void *ptr)
693 {
694 if (fTable.cols.count(name)==0)
695 {
696 ostringstream str;
697 str <<"SetPtrAddress('" << name << "') - Column not found." << endl;
698#ifdef __EXCEPTIONS
699 throw runtime_error(str.str());
700#else
701 gLog << ___err___ << "ERROR - " << str.str() << endl;
702 return false;
703#endif
704 }
705
706 // if (fAddresses.count(ptr)>0)
707 // gLog << warn << "SetPtrAddress('" << name << "') - Pointer " << ptr << " already assigned." << endl;
708
709 //fAddresses[ptr] = fTable.cols[name];
710 fAddresses.push_back(make_pair(ptr, fTable.cols[name]));
711 sort(fAddresses.begin(), fAddresses.end(), Compare);
712 return true;
713 }
714
715 bool HasKey(const string &key) const { return fTable.HasKey(key); }
716 bool HasColumn(const string& col) const { return fTable.HasColumn(col);}
717 const Table::Columns& getColumns() const { return fTable.getColumns();}
718 const Table::Keys& getKeys() const { return fTable.getKeys();}
719
720 int64_t GetInt(const string &key) const { return fTable.Get<int64_t>(key); }
721 uint64_t GetUInt(const string &key) const { return fTable.Get<uint64_t>(key); }
722 double GetFloat(const string &key) const { return fTable.Get<double>(key); }
723 string GetStr(const string &key) const { return fTable.Get<string>(key); }
724
725 size_t GetN(const string &key) const
726 {
727 return fTable.GetN(key);
728 }
729
730 size_t GetNumRows() const { return fTable.num_rows; }
731 size_t GetRow() const { return fRow; }
732
733 operator bool() const { return fTable && fTable.offset!=0; }
734
735 void PrintKeys() const { fTable.PrintKeys(); }
736 void PrintColumns() const { fTable.PrintColumns(); }
737};
738
739};
740#endif
Note: See TracBrowser for help on using the repository browser.