source: trunk/FACT++/src/fitsdump.cc@ 12105

Last change on this file since 12105 was 12099, checked in by tbretz, 13 years ago
Removed a compiler warning
File size: 33.9 KB
Line 
1//****************************************************************
2/** @class FitsDumper
3
4 @brief Dumps contents of fits tables to stdout or a file
5
6 */
7 //****************************************************************
8#include "Configuration.h"
9
10#include <map>
11#include <fstream>
12
13#include <CCfits/CCfits>
14
15//#define PLOTTING_PLEASE
16
17#ifdef PLOTTING_PLEASE
18#include <QPen>
19#include <QtGui>
20#include <QApplication>
21
22#include <qwt_plot.h>
23#include <qwt_plot_grid.h>
24#include <qwt_plot_curve.h>
25#include <qwt_plot_zoomer.h>
26#include <qwt_legend.h>
27#include <qwt_scale_draw.h>
28
29#include "Time.h"
30#endif
31
32using namespace std;
33
34class MyColumn : public CCfits::Column
35{
36public:
37 const string &comment() const { return CCfits::Column::comment(); }
38 long width() const
39 {//the width() method seems to be buggy (or empty ?) as it always return 1... redo it ourselves.
40 string inter = format();
41 inter = inter.substr(0, inter.size()-1);
42 return atoi(inter.c_str());
43 }
44};
45
46#ifdef PLOTTING_PLEASE
47class TimeScaleDraw: public QwtScaleDraw
48{
49public:
50 virtual QwtText label(double v) const
51 {
52 Time t(v);
53 string time = t.GetAsStr("%H:%M:%S%F");
54 while (time[time.size()-1] == '0' && time.size() > 2)
55 {
56 time = time.substr(0, time.size()-1);
57 }
58 return QwtText(time.c_str());
59 }
60};
61#endif
62
63class FitsDumper
64{
65public:
66 FitsDumper();
67 ~FitsDumper();
68
69private:
70
71 CCfits::FITS *fFile; /// FITS pointer
72 CCfits::Table *fTable; /// Table pointer
73 map<string, MyColumn*> fColMap; /// map between the column names and their CCfits objects
74
75 // Convert CCfits::ValueType into a human readable string
76 string ValueTypeToStr(CCfits::ValueType type) const;
77
78 // Convert CCfits::ValueType into a number of associated bytes
79 int ValueTypeToSize(CCfits::ValueType type) const;
80
81 /// Calculate the buffer size required to read a row of the fits table, as well as the offsets to each column
82 vector<int> CalculateOffsets() const;
83
84 template<class T>
85 T PtrToValue(const unsigned char* &ptr) const;
86// template<class T>
87// double PtrToDouble(const unsigned char *ptr) const;
88// double PtrToDouble(const unsigned char *ptr, CCfits::ValueType type) const;
89
90 /// Write a single row of the selected data
91 int WriteRow(ostream &, const vector<MyColumn*> &, const vector<int> &, unsigned char *, const vector<pair<int, int> >&) const;
92
93 bool OpenFile(const string &); /// Open a file
94 bool OpenTable(const string &); /// Open a table
95
96 /// Lists all columns of an open file
97 void List();
98 void ListHeader();
99 void ListKeywords(ostream &);
100
101 bool separateColumnsFromRanges(const vector<string>& list,
102 vector<pair<int, int> >& ranges,
103 vector<string>& listNamesOnly);
104 /// Perform the dumping, based on the current dump list
105 bool Dump(const string &, const vector<string> &list, int);
106 ///Display the selected columns values VS time
107#ifdef PLOTTING_PLEASE
108 int doCurvesDisplay( const vector<string> &list, const string& tableName);
109#endif
110 // bool Plot(const vector<string> &list);
111
112public:
113 ///Configures the fitsLoader from the config file and/or command arguments.
114 int ExecConfig(Configuration& conf);
115};
116
117// --------------------------------------------------------------------------
118//
119//! Constructor
120//! @param out
121//! the ostream where to redirect the outputs
122//
123FitsDumper::FitsDumper() : fFile(0), fTable(0)
124{
125}
126
127// --------------------------------------------------------------------------
128//
129//! Destructor
130//
131FitsDumper::~FitsDumper()
132{
133 if (fFile)
134 delete fFile;
135}
136
137
138string FitsDumper::ValueTypeToStr(CCfits::ValueType type) const
139{
140 switch (type)
141 {
142 case CCfits::Tbyte: return "uint8_t";
143 case CCfits::Tushort: return "uint16_t";
144 case CCfits::Tshort: return "int16_t";
145 case CCfits::Tuint: return "uint32_t";
146 case CCfits::Tint: return "int32_t";
147 case CCfits::Tulong: return "uint32_t";
148 case CCfits::Tlong: return "int32_t";
149 case CCfits::Tlonglong: return "int64_t";
150 case CCfits::Tfloat: return "float";
151 case CCfits::Tdouble: return "double";
152
153 default:
154 return "unknwown";
155 }
156}
157
158int FitsDumper::ValueTypeToSize(CCfits::ValueType type) const
159{
160 switch (type)
161 {
162 case CCfits::Tbyte: return sizeof(uint8_t);
163 case CCfits::Tushort:
164 case CCfits::Tshort: return sizeof(uint16_t);
165 case CCfits::Tuint:
166 case CCfits::Tint:
167 case CCfits::Tulong:
168 case CCfits::Tlong: return sizeof(uint32_t);
169 case CCfits::Tlonglong: return sizeof(uint64_t);
170 case CCfits::Tfloat: return sizeof(float);
171 case CCfits::Tdouble: return sizeof(double);
172
173 default:
174 return 0;
175 }
176}
177
178template<class T>
179T FitsDumper::PtrToValue(const unsigned char* &ptr) const
180{
181 T t;
182 reverse_copy(ptr, ptr+sizeof(T), reinterpret_cast<unsigned char*>(&t));
183 ptr += sizeof(T);
184
185 return t;
186}
187/*
188template<class T>
189double FitsDumper::PtrToDouble(const unsigned char *ptr) const
190{
191 T t;
192 reverse_copy(ptr, ptr+sizeof(T), reinterpret_cast<unsigned char*>(&t));
193 return t;
194}
195
196double FitsDumper::PtrToDouble(const unsigned char *ptr, CCfits::ValueType type) const
197{
198 switch (type)
199 {
200 case CCfits::Tbyte: return PtrToDouble<uint8_t> (ptr);
201 case CCfits::Tushort: return PtrToDouble<uint16_t>(ptr);
202 case CCfits::Tuint:
203 case CCfits::Tulong: return PtrToDouble<uint32_t>(ptr);
204 case CCfits::Tshort: return PtrToDouble<int16_t> (ptr);
205 case CCfits::Tint:
206 case CCfits::Tlong: return PtrToDouble<int32_t> (ptr);
207 case CCfits::Tlonglong: return PtrToDouble<int64_t> (ptr);
208 case CCfits::Tfloat: return PtrToDouble<float> (ptr);
209 case CCfits::Tdouble: return PtrToDouble<double> (ptr);
210
211 default:
212 throw runtime_error("Data type not implemented yet.");
213 }
214}
215*/
216
217// --------------------------------------------------------------------------
218//
219//! Writes a single row of the selected FITS data to the output file.
220//!
221//! Data type \b not yet implemented:
222//! CCfits::Tnull, CCfits::Tbit, CCfits::Tlogical, CCfits::Tstring,
223//! CCfits::Tcomplex, CCfits::Tdblcomplex, CCfits::VTbit,
224//! CCfits::VTbyte, CCfits::VTlogical, CCfits::VTushort,
225//! CCfits::VTshort, CCfits::VTuint, CCfits::VTint, CCfits::VTulong,
226//! CCfits::VTlong, CCfits::VTlonglong, CCfits::VTfloat,
227//! CCfits::VTdouble, CCfits::VTcomplex, CCfits::VTdblcomplex
228//!
229//! @param offsets
230//! a vector containing the offsets to the columns (in bytes)
231//! @param targetFile
232//! the ofstream where to write to
233//! @param fitsBuffer
234//! the memory were the row has been loaded by cfitsio
235//
236int FitsDumper::WriteRow(ostream &out, const vector<MyColumn*> &list, const vector<int> &offsets, unsigned char* fitsBuffer, const vector<pair<int, int> >& ranges) const
237{
238 int cnt = 0;
239 vector<pair<int, int> >::const_iterator jt = ranges.begin();
240 for (vector<MyColumn*>::const_iterator it=list.begin(); it!=list.end(); it++, jt++)
241 {
242 if (jt == ranges.end())
243 {
244 cout << "ERROR: END OF RANGE POINTER REACHED" << endl;
245 return false;
246 }
247 const MyColumn *col = *it;
248
249 // CCfits starts counting at 1 not 0
250 const int offset = offsets[col->index()-1];
251
252 // Get the pointer to the array which we are supposed to print
253 const unsigned char *ptr = fitsBuffer + offset;
254
255 // Loop over all array entries
256 int sizeToSkip = 0;
257 switch (col->type())
258 {
259 case CCfits::Tbyte: sizeToSkip = sizeof(uint8_t); break;
260 case CCfits::Tushort: sizeToSkip = sizeof(uint16_t); break;
261 case CCfits::Tuint:
262 case CCfits::Tulong: sizeToSkip = sizeof(uint32_t); break;
263 case CCfits::Tshort: sizeToSkip = sizeof(int16_t); break;
264 case CCfits::Tint:
265 case CCfits::Tlong: sizeToSkip = sizeof(int32_t); break;
266 case CCfits::Tlonglong: sizeToSkip = sizeof(int64_t); break;
267 case CCfits::Tfloat: sizeToSkip = sizeof(float); break;
268 case CCfits::Tdouble: sizeToSkip = sizeof(double); break;
269 default:
270 cerr << "Data type not implemented yet." << endl;
271 return 0;
272 }
273 ptr += sizeToSkip*jt->first;
274 for (int width=jt->first; width<jt->second; width++)
275 {
276 switch (col->type())
277 {
278 case CCfits::Tbyte: out << PtrToValue<uint8_t> (ptr); break;
279 case CCfits::Tushort: out << PtrToValue<uint16_t>(ptr); break;
280 case CCfits::Tuint:
281 case CCfits::Tulong: out << PtrToValue<uint32_t>(ptr); break;
282 case CCfits::Tshort: out << PtrToValue<int16_t> (ptr); break;
283 case CCfits::Tint:
284 case CCfits::Tlong: out << PtrToValue<int32_t> (ptr); break;
285 case CCfits::Tlonglong: out << PtrToValue<int64_t> (ptr); break;
286 case CCfits::Tfloat: out << PtrToValue<float> (ptr); break;
287 case CCfits::Tdouble: out << PtrToValue<double> (ptr); break;
288
289 default:
290 cerr << "Data type not implemented yet." << endl;
291 return 0;
292 }
293
294 out << " ";
295 cnt++;
296 }
297 }
298
299 if (cnt>0)
300 out << endl;
301
302 if (out.fail())
303 {
304 cerr << "ERROR - writing output: " << strerror(errno) << endl;
305 return -1;
306 }
307
308 return cnt;
309}
310
311// --------------------------------------------------------------------------
312//
313//! Calculates the required buffer size for reading one row of the current
314//! table. Also calculates the offsets to all the columns
315//
316vector<int> FitsDumper::CalculateOffsets() const
317{
318 map<int,int> sizes;
319
320 for (map<string, MyColumn*>::const_iterator it=fColMap.begin();
321 it!=fColMap.end(); it++)
322 {
323 const int &width = it->second->width();
324 const int &idx = it->second->index();
325
326 const int size = ValueTypeToSize(it->second->type());
327 if (size==0)
328 {
329 cerr << "Data type " << (int)it->second->type() << " not implemented yet." << endl;
330 return vector<int>();
331 }
332
333 sizes[idx] = size*width;
334 }
335
336 //calculate the offsets in the vector.
337 vector<int> result(1, 0);
338
339 int size = 0;
340 int idx = 0;
341
342 for (map<int,int>::const_iterator it=sizes.begin(); it!=sizes.end(); it++)
343 {
344 size += it->second;
345 result.push_back(size);
346
347 if (it->first == ++idx)
348 continue;
349
350 cerr << "Expected index " << idx << ", but found " << it->first << endl;
351 return vector<int>();
352 }
353
354 return result;
355}
356
357// --------------------------------------------------------------------------
358//
359//! Loads the fits file based on the current parameters
360//
361bool FitsDumper::OpenFile(const string &filename)
362{
363 if (fFile)
364 delete fFile;
365
366 ostringstream str;
367 try
368 {
369 fFile = new CCfits::FITS(filename);
370 }
371 catch (CCfits::FitsException e)
372 {
373 cerr << "Could not open FITS file " << filename << " reason: " << e.message() << endl;
374 return false;
375 }
376
377 return true;
378}
379
380bool FitsDumper::OpenTable(const string &tablename)
381{
382 if (!fFile)
383 {
384 cerr << "No file open." << endl;
385 return false;
386 }
387
388 const multimap< string, CCfits::ExtHDU * > extMap = fFile->extension();
389 if (extMap.find(tablename) == extMap.end())
390 {
391 cerr << "Table '" << tablename << "' not found." << endl;
392 return false;
393 }
394
395 fTable = dynamic_cast<CCfits::Table*>(extMap.find(tablename)->second);
396 if (!fTable)
397 {
398 cerr << "Object '" << tablename << "' returned not a CCfits::Table." << endl;
399 return false;
400 }
401
402 map<string, CCfits::Column*>& tCols = fTable->column();
403 for (map<string, CCfits::Column*>::const_iterator it = tCols.begin(); it != tCols.end(); it++)
404 {
405 fColMap.insert(make_pair(it->first, static_cast<MyColumn*>(it->second)));
406 }
407// fColMap = fTable->column();
408
409 fTable->makeThisCurrent();
410
411 fTable->getComments();
412 fTable->getHistory();
413 fTable->readAllKeys();
414
415 return true;
416}
417
418
419void FitsDumper::List()
420{
421 if (!fFile)
422 {
423 cerr << "No file open." << endl;
424 return;
425 }
426
427 cout << "\nFile: " << fFile->name() << "\n";
428
429 const multimap< string, CCfits::ExtHDU * > extMap = fFile->extension();
430 for (std::multimap<string, CCfits::ExtHDU*>::const_iterator it=extMap.begin(); it != extMap.end(); it++)
431 {
432
433 CCfits::Table *table = dynamic_cast<CCfits::Table*>(extMap.find(it->first)->second);
434
435 table->makeThisCurrent();
436 table->readData();
437
438 cout << " " << it->first << " [" << table->rows() << "]\n";
439
440 const map<string, CCfits::Column*> &cols = table->column();
441
442// for (map<string, CCfits::Column*>::const_iterator id = cols.begin(); ib != cols.end(); ib++)
443// {
444// TFORM
445// }
446
447 for (map<string, CCfits::Column*>::const_iterator ic=cols.begin();
448 ic != cols.end(); ic++)
449 {
450 const MyColumn *col = static_cast<MyColumn*>(ic->second);
451
452 cout << " " << col->name() << "[" << col->width() << "] * " << col->scale() << " (" << col->unit() << ":" << ValueTypeToStr(col->type())<< ") " << col->comment() << "\n";
453 /*
454 inline size_t Column::repeat () const
455 inline bool Column::varLength () const
456 inline double Column::zero () const
457 inline const String& Column::display () const
458 inline const String& Column::dimen () const
459 inline const String& Column::TBCOL ()
460 inline const String& Column::TTYPE ()
461 inline const String& Column::TFORM ()
462 inline const String& Column::TDISP ()
463 inline const String& Column::TZERO ()
464 inline const String& Column::TDIM ()
465 inline const String& Column::TNULL ()
466 inline const String& Column::TLMIN ()
467 inline const String& Column::TLMAX ()
468 inline const String& Column::TDMAX ()
469 inline const String& Column::TDMIN ()
470 */
471 }
472 cout << '\n';
473 }
474 cout << flush;
475}
476
477class MyKeyword : public CCfits::Keyword
478{
479public:
480 CCfits::ValueType keytype() const { return CCfits::Keyword::keytype(); }
481};
482
483void FitsDumper::ListKeywords(ostream &out)
484{
485 map<string,CCfits::Keyword*> keys = fTable->keyWord();
486 for (map<string,CCfits::Keyword*>::const_iterator it=keys.begin();
487 it!=keys.end(); it++)
488 {
489 string str;
490 double d;
491 int l;
492
493 const MyKeyword *kw = static_cast<MyKeyword*>(it->second);
494 kw->keytype();
495 out << "## " << setw(8) << kw->name() << " = " << setw(10);
496 if (kw->keytype()==16)
497 out << ("'"+kw->value(str)+"'");
498 if (kw->keytype()==31)
499 out << kw->value(l);
500 if (kw->keytype()==82)
501 out << kw->value(d);
502 out << " / " << kw->comment() << endl;
503 }
504}
505
506void FitsDumper::ListHeader()
507{
508 if (!fTable)
509 {
510 cerr << "No table open." << endl;
511 return;
512 }
513
514 cout << "\nTable: " << fTable->name() << " (rows=" << fTable->rows() << ")\n";
515 if (!fTable->comment().empty())
516 cout << "Comment: \t" << fTable->comment() << '\n';
517 if (!fTable->history().empty())
518 cout << "History: \t" << fTable->history() << '\n';
519
520 ListKeywords(cout);
521 cout << endl;
522}
523
524bool FitsDumper::separateColumnsFromRanges(const vector<string>& list,
525 vector<pair<int, int> >& ranges,
526 vector<string>& listNamesOnly)
527{
528 for (vector<string>::const_iterator it=list.begin(); it!=list.end(); it++)
529 {
530 string columnNameOnly = *it;
531 unsigned long bracketIndex0 = columnNameOnly.find_first_of('[');
532 unsigned long bracketIndex1 = columnNameOnly.find_first_of(']');
533 unsigned long colonIndex = columnNameOnly.find_first_of(':');
534// cout << bracketIndex0 << " " << bracketIndex1 << " " << colonIndex << endl;
535 int columnStart = -1;
536 int columnEnd = -1;
537 if (bracketIndex0 != string::npos)
538 {//there is a range given. Extract the range
539 if (colonIndex != string::npos)
540 {//we have a range here
541 columnStart = atoi(columnNameOnly.substr(bracketIndex0+1, colonIndex-(bracketIndex0+1)).c_str());
542 columnEnd = atoi(columnNameOnly.substr(colonIndex+1, bracketIndex1-(colonIndex+1)).c_str());
543 columnEnd++;
544 }
545 else
546 {//only a single index there
547 columnStart = atoi(columnNameOnly.substr(bracketIndex0+1, bracketIndex1 - (bracketIndex0+1)).c_str());
548 columnEnd = columnStart+1;
549// cout << "Cstart " << columnStart << " end: " << columnEnd << endl;
550 }
551 columnNameOnly = columnNameOnly.substr(0, bracketIndex0);
552 }
553
554 if (fColMap.find(columnNameOnly) == fColMap.end())
555 {
556 cerr << "ERROR - Column '" << columnNameOnly << "' not found in table." << endl;
557 return false;
558 }
559// cout << "The column name is: " << columnNameOnly << endl;
560 MyColumn *cCol = static_cast<MyColumn*>(fColMap.find(columnNameOnly)->second);
561 if (bracketIndex0 == string::npos)
562 {//no range given: use the full range
563 ranges.push_back(make_pair(0, cCol->width()));
564 columnStart = 0;
565 columnEnd = 1;
566 }
567 else
568 {//use the range extracted earlier
569 if (columnStart < 0)
570 {
571 cerr << "ERROR - Start range for column " << columnNameOnly << " is less than zero (" << columnStart << "). Aborting" << endl;
572 return false;
573 }
574 if (columnEnd > cCol->width())
575 {
576 cerr << "ERROR - End range for column " << columnNameOnly << " is greater than the last element (" << cCol->width() << " vs " << columnEnd << "). Aborting" << endl;
577 return false;
578 }
579 ranges.push_back(make_pair(columnStart, columnEnd));
580 }
581// cout << "Will be exporting from " << columnStart << " to " << columnEnd-1 << " for column " << columnNameOnly << endl;
582 listNamesOnly.push_back(columnNameOnly);
583 }
584 return true;
585}
586// --------------------------------------------------------------------------
587//
588//! Perform the actual dump, based on the current parameters
589//
590bool FitsDumper::Dump(const string &filename, const vector<string> &list, int precision)
591{
592
593 //first of all, let's separate the columns from their ranges and check that the requested columns are indeed part of the file
594 vector<pair<int, int> > ranges;
595 vector<string> listNamesOnly;
596
597 if (!separateColumnsFromRanges(list, ranges, listNamesOnly))
598 {
599 cerr << "Something went wrong while extracting the columns names from parameters. Aborting" << endl;
600 return false;
601 }
602
603 // FIXME: Maybe do this when opening a table?
604 const vector<int> offsets = CalculateOffsets();
605 if (offsets.size()==0)
606 return false;
607
608 ofstream out(filename=="-"?"/dev/stdout":filename);
609 if (!out)
610 {
611 cerr << "Cannot open file " << filename << ": " << strerror(errno) << endl;
612 return false;
613 }
614
615 out.precision(precision);
616
617 out << "## --------------------------------------------------------------------------\n";
618 if (filename!="-")
619 out << "## File: \t" << filename << '\n';
620 out << "## Table: \t" << fTable->name() << '\n';
621 if (!fTable->comment().empty())
622 out << "## Comment: \t" << fTable->comment() << '\n';
623 if (!fTable->history().empty())
624 out << "## History: \t" << fTable->history() << '\n';
625 out << "## NumRows: \t" << fTable->rows() << '\n';
626 out << "## --------------------------------------------------------------------------\n";
627 ListKeywords(out);
628 out << "## --------------------------------------------------------------------------\n";
629 out << "#\n";
630 //vector<pair<int, int> >::const_iterator rangesIt = ranges.begin();
631 //the above is soooo yesterday ;) let's try the new auto feature of c++0x
632 auto rangesIt = ranges.begin();
633 for (vector<string>::const_iterator it=listNamesOnly.begin(); it!=listNamesOnly.end(); it++, rangesIt++)
634 {
635 const MyColumn *col = static_cast<MyColumn*>(fTable->column()[*it]);
636 if (rangesIt->first != 0 || rangesIt->second != col->width())
637 {
638 out << "#";
639 for (int i=rangesIt->first; i<rangesIt->second; i++)
640 out << " " << col->name() << "[" << i << "]";
641 out << ": " << col->unit();
642 }
643 else
644 out << "# " << col->name() << "[" << col->width() << "]: " << col->unit();
645
646 if (!col->comment().empty())
647 out << " (" <<col->comment() << ")";
648 out << '\n';
649 }
650 out << "#" << endl;
651
652
653 // Loop over all columns in our list of requested columns
654 vector<MyColumn*> columns;
655 for (vector<string>::const_iterator it=listNamesOnly.begin(); it!=listNamesOnly.end(); it++)
656 {
657 MyColumn *cCol = static_cast<MyColumn*>(fColMap.find(*it)->second);
658 columns.push_back(cCol);
659 }
660 const int size = offsets[offsets.size()-1];
661 unsigned char* fitsBuffer = new unsigned char[size];
662
663 int status = 0;
664 for (int i=1; i<=fTable->rows(); i++)
665 {
666 fits_read_tblbytes(fFile->fitsPointer(), i, 1, size, fitsBuffer, &status);
667 if (status)
668 {
669 cerr << "An error occurred while reading fits row #" << i << " error code: " << status << endl;
670 break;
671 }
672 if (WriteRow(out, columns, offsets, fitsBuffer, ranges)<0)
673 {
674 status=1;
675 break;
676 }
677 }
678 delete[] fitsBuffer;
679
680 return status==0;
681}
682
683// --------------------------------------------------------------------------
684//
685//! Perform the actual dump, based on the current parameters
686//
687/*
688bool FitsDumper::Plot(const vector<string> &list)
689{
690 for (vector<string>::const_iterator it=list.begin(); it!=list.end(); it++)
691 if (fColMap.find(*it) == fColMap.end())
692 {
693 cerr << "WARNING - Column '" << *it << "' not found in table." << endl;
694 return false;
695 }
696
697 // FIXME: Maybe do this when opening a table?
698 const vector<int> offsets = CalculateOffsets();
699 if (offsets.size()==0)
700 return false;
701
702 // Loop over all columns in our list of requested columns
703 const CCfits::Column *col[3] =
704 {
705 list.size()>0 ? fColMap.find(list[0])->second : 0,
706 list.size()>1 ? fColMap.find(list[1])->second : 0,
707 list.size()>2 ? fColMap.find(list[2])->second : 0
708 };
709
710 const int size = offsets[offsets.size()-1];
711 unsigned char* fitsBuffer = new unsigned char[size];
712
713 const int idx = 0;
714
715 // CCfits starts counting at 1 not 0
716 const size_t pos[3] =
717 {
718 col[0] ? offsets[col[0]->index()-1] + idx*col[0]->width()*ValueTypeToSize(col[0]->type()) : 0,
719 col[1] ? offsets[col[1]->index()-1] + idx*col[1]->width()*ValueTypeToSize(col[1]->type()) : 0,
720 col[2] ? offsets[col[2]->index()-1] + idx*col[2]->width()*ValueTypeToSize(col[2]->type()) : 0
721 };
722
723 int status = 0;
724 for (int i=1; i<=fTable->rows(); i++)
725 {
726 fits_read_tblbytes(fFile->fitsPointer(), i, 1, size, fitsBuffer, &status);
727 if (status)
728 {
729 cerr << "An error occurred while reading fits row #" << i << " error code: " << status << endl;
730 break;
731 }
732
733 try
734 {
735 const double x[3] =
736 {
737 col[0] ? PtrToDouble(fitsBuffer+pos[0], col[0]->type()) : 0,
738 col[1] ? PtrToDouble(fitsBuffer+pos[1], col[1]->type()) : 0,
739 col[2] ? PtrToDouble(fitsBuffer+pos[2], col[2]->type()) : 0
740 };
741 }
742 catch (const runtime_error &e)
743 {
744 cerr << e.what() << endl;
745 status=1;
746 break;
747 }
748 }
749 delete[] fitsBuffer;
750
751 return status==0;
752}
753*/
754
755// --------------------------------------------------------------------------
756//
757//! Retrieves the configuration parameters
758//! @param conf
759//! the configuration object
760//
761int FitsDumper::ExecConfig(Configuration& conf)
762{
763 if (conf.Has("fitsfile"))
764 {
765 if (!OpenFile(conf.Get<string>("fitsfile")))
766 return -1;
767 }
768
769 if (conf.Get<bool>("list"))
770 List();
771
772 if (conf.Has("tablename"))
773 {
774 if (!OpenTable(conf.Get<string>("tablename")))
775 return -1;
776 }
777
778#ifdef PLOTTING_PLEASE
779 if (conf.Get<bool>("graph"))
780 {
781 if (!conf.Has("col"))
782 {
783 cout << "Please specify the columns that should be dumped as arguments. Aborting" << endl;
784 return 0;
785 }
786 doCurvesDisplay(conf.Get<vector<string>>("col"),
787 conf.Get<string>("tablename"));
788 return 1;
789 }
790#endif
791
792 if (conf.Get<bool>("header"))
793 ListHeader();
794
795 if (conf.Get<bool>("header") || conf.Get<bool>("list"))
796 return 1;
797
798 if (conf.Has("outfile"))
799 {
800 if (!conf.Has("col"))
801 {
802 cout << "Please specify the columns that should be dumped as arguments. Aborting" << endl;
803 return 0;
804 }
805 if (!Dump(conf.Get<string>("outfile"),
806 conf.Get<vector<string>>("col"),
807 conf.Get<int>("precision")))
808 return -1;
809 }
810
811
812 return 0;
813}
814
815void PrintUsage()
816{
817 cout <<
818 "fitsdump is a tool to dump data from a FITS table as ascii.\n"
819 "\n"
820 "Usage: fitsdump [OPTIONS] fitsfile col col ... \n"
821 " or: fitsdump [OPTIONS]\n";
822 cout << endl;
823}
824
825void PrintHelp()
826{
827 //
828}
829#ifdef PLOTTING_PLEASE
830int FitsDumper::doCurvesDisplay( const vector<string> &list, const string& tableName)
831{
832 //first of all, let's separate the columns from their ranges and check that the requested columns are indeed part of the file
833 vector<pair<int, int> > ranges;
834 vector<string> listNamesOnly;
835 if (!separateColumnsFromRanges(list, ranges, listNamesOnly))
836 {
837 cerr << "Something went wrong while extracting the columns names from parameters. Aborting" << endl;
838 return false;
839 }
840 vector<string> curvesNames;
841 stringstream str;
842 for (auto it=ranges.begin(), jt=listNamesOnly.begin(); it != ranges.end(); it++, jt++)
843 {
844 for (int i=it->first; i<it->second;i++)
845 {
846 str.str("");
847 str << *jt << "[" << i << "]";
848 curvesNames.push_back(str.str());
849 }
850 }
851 char* handle = new char[17];
852 sprintf(handle,"FitsDump Display");
853// Qt::HANDLE h = *handle;//NULL
854 int argc = 1;
855 char ** argv = &handle;
856 QApplication a(argc, argv);
857
858
859
860 QwtPlot* plot = new QwtPlot();
861 QwtPlotGrid* grid = new QwtPlotGrid;
862 grid->enableX(false);
863 grid->enableY(true);
864 grid->enableXMin(false);
865 grid->enableYMin(false);
866 grid->setMajPen(QPen(Qt::black, 0, Qt::DotLine));
867 grid->attach(plot);
868 plot->setAutoReplot(true);
869 string title = tableName;
870 plot->setAxisScaleDraw( QwtPlot::xBottom, new TimeScaleDraw());
871
872 QWidget window;
873 QHBoxLayout* layout = new QHBoxLayout(&window);
874 layout->setContentsMargins(0,0,0,0);
875 layout->addWidget(plot);
876
877 QwtPlotZoomer zoom(plot->canvas());
878 zoom.setRubberBandPen(QPen(Qt::gray, 2, Qt::DotLine));
879 zoom.setTrackerPen(QPen(Qt::gray));
880 int totalSize = 0;
881 for (unsigned int i=0;i<list.size();i++)
882 totalSize += ranges[i].second - ranges[i].first;
883 cout << "Total size: " << totalSize << endl;
884 vector<QwtPlotCurve*> curves(totalSize);
885 int ii=0;
886 for (auto it = curves.begin(), jt=curvesNames.begin(); it != curves.end(); it++, jt++)
887 {
888 *it = new QwtPlotCurve(jt->c_str());
889 switch (ii%6)
890 {
891 case 0:
892 (*it)->setPen(QColor(255,0,0));
893 break;
894 case 1:
895 (*it)->setPen(QColor(0,255,0));
896 break;
897 case 2:
898 (*it)->setPen(QColor(0,0,255));
899 break;
900 case 3:
901 (*it)->setPen(QColor(255,255,0));
902 break;
903 case 4:
904 (*it)->setPen(QColor(0,255,255));
905 break;
906 case 5:
907 (*it)->setPen(QColor(255,0,255));
908 break;
909 default:
910 (*it)->setPen(QColor(0,0,0));
911 };
912 ii++;
913 (*it)->setStyle(QwtPlotCurve::Lines);
914 (*it)->attach(plot);
915 }
916 plot->insertLegend(new QwtLegend(), QwtPlot::RightLegend);
917
918 const vector<int> offsets = CalculateOffsets();
919 if (offsets.size()==0)
920 return false;
921
922
923 // Loop over all columns in our list of requested columns
924 vector<MyColumn*> columns;
925 for (vector<string>::const_iterator it=listNamesOnly.begin(); it!=listNamesOnly.end(); it++)
926 {
927 MyColumn *cCol = static_cast<MyColumn*>(fColMap.find(*it)->second);
928 columns.push_back(cCol);
929 }
930 //add the time column to the given columns
931 MyColumn* timeCol = static_cast<MyColumn*>(fColMap.find("Time")->second);
932 if (!timeCol)
933 {
934 cerr << "Error: time column could not be found in given table. Aborting" << endl;
935 return false;
936 }
937 columns.push_back(timeCol);
938 ranges.push_back(make_pair(0,1));
939 /////
940 const int size = offsets[offsets.size()-1];
941 unsigned char* fitsBuffer = new unsigned char[size];
942
943// stringstream str;
944 str.str("");
945 int status = 0;
946
947 vector<double*> xValues(totalSize);
948 double* yValues;
949 cout.precision(10);
950 str.precision(20);
951 for (auto it=xValues.begin(); it!=xValues.end(); it++)
952 *it = new double[fTable->rows()];
953
954 yValues = new double[fTable->rows()];
955
956 for (int i=1; i<=fTable->rows(); i++)
957 {
958 fits_read_tblbytes(fFile->fitsPointer(), i, 1, size, fitsBuffer, &status);
959 if (status)
960 {
961 cerr << "An error occurred while reading fits row #" << i << " error code: " << status << endl;
962 break;
963 }
964 if (WriteRow(str, columns, offsets, fitsBuffer, ranges)<0)
965 {
966 status=1;
967 cerr << "An Error occured while reading the fits row " << i << endl;
968 return -1;
969 }
970// yValues[i-1] = i;
971 for (auto it=xValues.begin(); it!= xValues.end(); it++)
972 {
973 str >> (*it)[i-1];
974// cout << (*it)[i-1] << " ";
975 }
976 str >> yValues[i-1];
977 if (i==1)
978 {
979 Time t(yValues[0]);
980 title += " - " + t.GetAsStr("%Y-%m-%d");
981 plot->setTitle(title.c_str());
982 }
983// cout << yValues[i-1] << " ";
984// cout << endl;
985 }
986 //set the actual data.
987 auto jt = xValues.begin();
988 for (auto it=curves.begin(); it != curves.end(); it++, jt++)
989 (*it)->setRawData(yValues, *jt, fTable->rows());
990
991 QStack<QRectF> stack;
992 double minX, minY, maxX, maxY;
993 minX = minY = 1e10;
994 maxX = maxY = -1e10;
995 QRectF rect;
996 QPointF point;
997 for (auto it=curves.begin(); it!= curves.end(); it++)
998 {
999 rect = (*it)->boundingRect();
1000 point = rect.bottomRight();
1001 if (point.x() < minX) minX = point.x();
1002 if (point.y() < minY) minY = point.y();
1003 if (point.x() > maxX) maxX = point.x();
1004 if (point.y() > maxY) maxY = point.y();
1005 point = rect.topLeft();
1006 if (point.x() < minX) minX = point.x();
1007 if (point.y() < minY) minY = point.y();
1008 if (point.x() > maxX) maxX = point.x();
1009 if (point.y() > maxY) maxY = point.y();
1010 }
1011 QPointF bottomRight(maxX, minY);
1012 QPointF topLeft(minX, maxY);
1013 QPointF center((bottomRight+topLeft)/2.f);
1014 stack.push(QRectF(topLeft + (topLeft-center)*(.5f),bottomRight + (bottomRight-center)*(.5f)));
1015 zoom.setZoomStack(stack);
1016
1017 delete[] fitsBuffer;
1018 window.resize(600, 400);
1019 window.show();
1020
1021 a.exec();
1022
1023 for (auto it = curves.begin(); it != curves.end(); it++)
1024 delete *it;
1025 for (auto it = xValues.begin(); it != xValues.end(); it++)
1026 delete[] *it;
1027 delete[] yValues;
1028 delete[] handle;
1029 return 0;
1030}
1031#endif
1032
1033void SetupConfiguration(Configuration& conf)
1034{
1035 po::options_description configs("Fitsdump options");
1036 configs.add_options()
1037 ("fitsfile,f", var<string>()
1038#if BOOST_VERSION >= 104200
1039 ->required()
1040#endif
1041 , "Name of FITS file")
1042 ("tablename,t", var<string>("DATA")
1043#if BOOST_VERSION >= 104200
1044 ->required()
1045#endif
1046 , "Name of input table")
1047 ("col,c", vars<string>(), "List of columns to dump\narg is a list of columns, separated by a space.\nAdditionnally, a list of sub-columns can be added\ne.g. Data[3] will dump sub-column 3 of column Data\nData[3:4] will dump sub-columns 3 and 4\nOmitting this argument dump the entire column\nnota: all indices start at zero")
1048 ("outfile,o", var<string>("/dev/stdout"), "Name of output file (-:/dev/stdout)")
1049 ("precision,p", var<int>(20), "Precision of ofstream")
1050 ("list,l", po_switch(), "List all tables and columns in file")
1051 ("header,h", po_switch(), "Dump header of given table")
1052#ifdef PLOTTING_PLEASE
1053 ("graph,g", po_switch(), "Plot the columns instead of dumping them")
1054#endif
1055 ;
1056
1057 po::positional_options_description p;
1058 p.add("fitsfile", 1); // The first positional options
1059 p.add("col", -1); // All others
1060
1061 conf.AddOptions(configs);
1062 conf.SetArgumentPositions(p);
1063}
1064
1065int main(int argc, const char** argv)
1066{
1067 Configuration conf(argv[0]);
1068 conf.SetPrintUsage(PrintUsage);
1069 SetupConfiguration(conf);
1070
1071 if (!conf.DoParse(argc, argv, PrintHelp))
1072 return -1;
1073
1074 FitsDumper loader;
1075 return loader.ExecConfig(conf);
1076}
Note: See TracBrowser for help on using the repository browser.