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

Last change on this file since 12149 was 12149, checked in by lyard, 13 years ago
bug fix - fitsdump
File size: 34.1 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//cout << "data size: " << size << " width: " << width << " index: " << idx << endl;
333 int realwidth = (width == 0)? 1 : width;
334 sizes[idx] = size*realwidth;
335 }
336
337 //calculate the offsets in the vector.
338 vector<int> result(1, 0);
339
340 int size = 0;
341 int idx = 0;
342
343 for (map<int,int>::const_iterator it=sizes.begin(); it!=sizes.end(); it++)
344 {
345 size += it->second;
346 result.push_back(size);
347
348 if (it->first == ++idx)
349 continue;
350
351 cerr << "Expected index " << idx << ", but found " << it->first << endl;
352 return vector<int>();
353 }
354
355 return result;
356}
357
358// --------------------------------------------------------------------------
359//
360//! Loads the fits file based on the current parameters
361//
362bool FitsDumper::OpenFile(const string &filename)
363{
364 if (fFile)
365 delete fFile;
366
367 ostringstream str;
368 try
369 {
370 fFile = new CCfits::FITS(filename);
371 }
372 catch (CCfits::FitsException e)
373 {
374 cerr << "Could not open FITS file " << filename << " reason: " << e.message() << endl;
375 return false;
376 }
377
378 return true;
379}
380
381bool FitsDumper::OpenTable(const string &tablename)
382{
383 if (!fFile)
384 {
385 cerr << "No file open." << endl;
386 return false;
387 }
388
389 const multimap< string, CCfits::ExtHDU * > extMap = fFile->extension();
390 if (extMap.find(tablename) == extMap.end())
391 {
392 cerr << "Table '" << tablename << "' not found." << endl;
393 return false;
394 }
395
396 fTable = dynamic_cast<CCfits::Table*>(extMap.find(tablename)->second);
397 if (!fTable)
398 {
399 cerr << "Object '" << tablename << "' returned not a CCfits::Table." << endl;
400 return false;
401 }
402
403 map<string, CCfits::Column*>& tCols = fTable->column();
404 for (map<string, CCfits::Column*>::const_iterator it = tCols.begin(); it != tCols.end(); it++)
405 {
406 fColMap.insert(make_pair(it->first, static_cast<MyColumn*>(it->second)));
407 }
408// fColMap = fTable->column();
409
410 fTable->makeThisCurrent();
411
412 fTable->getComments();
413 fTable->getHistory();
414 fTable->readAllKeys();
415
416 return true;
417}
418
419
420void FitsDumper::List()
421{
422 if (!fFile)
423 {
424 cerr << "No file open." << endl;
425 return;
426 }
427
428 cout << "\nFile: " << fFile->name() << "\n";
429
430 const multimap< string, CCfits::ExtHDU * > extMap = fFile->extension();
431 for (std::multimap<string, CCfits::ExtHDU*>::const_iterator it=extMap.begin(); it != extMap.end(); it++)
432 {
433
434 CCfits::Table *table = dynamic_cast<CCfits::Table*>(extMap.find(it->first)->second);
435
436 table->makeThisCurrent();
437 table->readData();
438
439 cout << " " << it->first << " [" << table->rows() << "]\n";
440
441 const map<string, CCfits::Column*> &cols = table->column();
442
443// for (map<string, CCfits::Column*>::const_iterator id = cols.begin(); ib != cols.end(); ib++)
444// {
445// TFORM
446// }
447
448 for (map<string, CCfits::Column*>::const_iterator ic=cols.begin();
449 ic != cols.end(); ic++)
450 {
451 const MyColumn *col = static_cast<MyColumn*>(ic->second);
452
453 cout << " " << col->name() << "[" << col->width() << "] * " << col->scale() << " (" << col->unit() << ":" << ValueTypeToStr(col->type())<< ") " << col->comment() << "\n";
454 /*
455 inline size_t Column::repeat () const
456 inline bool Column::varLength () const
457 inline double Column::zero () const
458 inline const String& Column::display () const
459 inline const String& Column::dimen () const
460 inline const String& Column::TBCOL ()
461 inline const String& Column::TTYPE ()
462 inline const String& Column::TFORM ()
463 inline const String& Column::TDISP ()
464 inline const String& Column::TZERO ()
465 inline const String& Column::TDIM ()
466 inline const String& Column::TNULL ()
467 inline const String& Column::TLMIN ()
468 inline const String& Column::TLMAX ()
469 inline const String& Column::TDMAX ()
470 inline const String& Column::TDMIN ()
471 */
472 }
473 cout << '\n';
474 }
475 cout << flush;
476}
477
478class MyKeyword : public CCfits::Keyword
479{
480public:
481 CCfits::ValueType keytype() const { return CCfits::Keyword::keytype(); }
482};
483
484void FitsDumper::ListKeywords(ostream &out)
485{
486 map<string,CCfits::Keyword*> keys = fTable->keyWord();
487 for (map<string,CCfits::Keyword*>::const_iterator it=keys.begin();
488 it!=keys.end(); it++)
489 {
490 string str;
491 double d;
492 int l;
493
494 const MyKeyword *kw = static_cast<MyKeyword*>(it->second);
495 kw->keytype();
496 out << "## " << setw(8) << kw->name() << " = " << setw(10);
497 if (kw->keytype()==16)
498 out << ("'"+kw->value(str)+"'");
499 if (kw->keytype()==31)
500 out << kw->value(l);
501 if (kw->keytype()==82)
502 out << kw->value(d);
503 out << " / " << kw->comment() << endl;
504 }
505}
506
507void FitsDumper::ListHeader()
508{
509 if (!fTable)
510 {
511 cerr << "No table open." << endl;
512 return;
513 }
514
515 cout << "\nTable: " << fTable->name() << " (rows=" << fTable->rows() << ")\n";
516 if (!fTable->comment().empty())
517 cout << "Comment: \t" << fTable->comment() << '\n';
518 if (!fTable->history().empty())
519 cout << "History: \t" << fTable->history() << '\n';
520
521 ListKeywords(cout);
522 cout << endl;
523}
524
525bool FitsDumper::separateColumnsFromRanges(const vector<string>& list,
526 vector<pair<int, int> >& ranges,
527 vector<string>& listNamesOnly)
528{
529 for (vector<string>::const_iterator it=list.begin(); it!=list.end(); it++)
530 {
531 string columnNameOnly = *it;
532 unsigned long bracketIndex0 = columnNameOnly.find_first_of('[');
533 unsigned long bracketIndex1 = columnNameOnly.find_first_of(']');
534 unsigned long colonIndex = columnNameOnly.find_first_of(':');
535// cout << bracketIndex0 << " " << bracketIndex1 << " " << colonIndex << endl;
536 int columnStart = -1;
537 int columnEnd = -1;
538 if (bracketIndex0 != string::npos)
539 {//there is a range given. Extract the range
540 if (colonIndex != string::npos)
541 {//we have a range here
542 columnStart = atoi(columnNameOnly.substr(bracketIndex0+1, colonIndex-(bracketIndex0+1)).c_str());
543 columnEnd = atoi(columnNameOnly.substr(colonIndex+1, bracketIndex1-(colonIndex+1)).c_str());
544 columnEnd++;
545 }
546 else
547 {//only a single index there
548 columnStart = atoi(columnNameOnly.substr(bracketIndex0+1, bracketIndex1 - (bracketIndex0+1)).c_str());
549 columnEnd = columnStart+1;
550// cout << "Cstart " << columnStart << " end: " << columnEnd << endl;
551 }
552 columnNameOnly = columnNameOnly.substr(0, bracketIndex0);
553 }
554
555 if (fColMap.find(columnNameOnly) == fColMap.end())
556 {
557 cerr << "ERROR - Column '" << columnNameOnly << "' not found in table." << endl;
558 return false;
559 }
560// cout << "The column name is: " << columnNameOnly << endl;
561 MyColumn *cCol = static_cast<MyColumn*>(fColMap.find(columnNameOnly)->second);
562 if (bracketIndex0 == string::npos)
563 {//no range given: use the full range
564 ranges.push_back(make_pair(0, cCol->width()));
565 columnStart = 0;
566 columnEnd = 1;
567 }
568 else
569 {//use the range extracted earlier
570 if (columnStart < 0)
571 {
572 cerr << "ERROR - Start range for column " << columnNameOnly << " is less than zero (" << columnStart << "). Aborting" << endl;
573 return false;
574 }
575 if (columnEnd > cCol->width())
576 {
577 cerr << "ERROR - End range for column " << columnNameOnly << " is greater than the last element (" << cCol->width() << " vs " << columnEnd << "). Aborting" << endl;
578 return false;
579 }
580 ranges.push_back(make_pair(columnStart, columnEnd));
581 }
582// cout << "Will be exporting from " << columnStart << " to " << columnEnd-1 << " for column " << columnNameOnly << endl;
583 listNamesOnly.push_back(columnNameOnly);
584 }
585 return true;
586}
587// --------------------------------------------------------------------------
588//
589//! Perform the actual dump, based on the current parameters
590//
591bool FitsDumper::Dump(const string &filename, const vector<string> &list, int precision)
592{
593
594 //first of all, let's separate the columns from their ranges and check that the requested columns are indeed part of the file
595 vector<pair<int, int> > ranges;
596 vector<string> listNamesOnly;
597
598 if (!separateColumnsFromRanges(list, ranges, listNamesOnly))
599 {
600 cerr << "Something went wrong while extracting the columns names from parameters. Aborting" << endl;
601 return false;
602 }
603
604 // FIXME: Maybe do this when opening a table?
605 const vector<int> offsets = CalculateOffsets();
606 // for (int i=0;i<offsets.size(); i++)
607 // cout << offsets[i] << " ";
608// cout << endl;
609 if (offsets.size()==0)
610 return false;
611
612 ofstream out(filename=="-"?"/dev/stdout":filename);
613 if (!out)
614 {
615 cerr << "Cannot open file " << filename << ": " << strerror(errno) << endl;
616 return false;
617 }
618
619 out.precision(precision);
620
621 out << "## --------------------------------------------------------------------------\n";
622 if (filename!="-")
623 out << "## File: \t" << filename << '\n';
624 out << "## Table: \t" << fTable->name() << '\n';
625 if (!fTable->comment().empty())
626 out << "## Comment: \t" << fTable->comment() << '\n';
627 if (!fTable->history().empty())
628 out << "## History: \t" << fTable->history() << '\n';
629 out << "## NumRows: \t" << fTable->rows() << '\n';
630 out << "## --------------------------------------------------------------------------\n";
631 ListKeywords(out);
632 out << "## --------------------------------------------------------------------------\n";
633 out << "#\n";
634 //vector<pair<int, int> >::const_iterator rangesIt = ranges.begin();
635 //the above is soooo yesterday ;) let's try the new auto feature of c++0x
636 auto rangesIt = ranges.begin();
637 for (vector<string>::const_iterator it=listNamesOnly.begin(); it!=listNamesOnly.end(); it++, rangesIt++)
638 {
639 const MyColumn *col = static_cast<MyColumn*>(fTable->column()[*it]);
640 if (rangesIt->first != 0 || rangesIt->second != col->width())
641 {
642 out << "#";
643 for (int i=rangesIt->first; i<rangesIt->second; i++)
644 out << " " << col->name() << "[" << i << "]";
645 out << ": " << col->unit();
646 }
647 else
648 out << "# " << col->name() << "[" << col->width() << "]: " << col->unit();
649
650 if (!col->comment().empty())
651 out << " (" <<col->comment() << ")";
652 out << '\n';
653 }
654 out << "#" << endl;
655
656
657 // Loop over all columns in our list of requested columns
658 vector<MyColumn*> columns;
659 for (vector<string>::const_iterator it=listNamesOnly.begin(); it!=listNamesOnly.end(); it++)
660 {
661 MyColumn *cCol = static_cast<MyColumn*>(fColMap.find(*it)->second);
662 columns.push_back(cCol);
663 }
664 const int size = offsets[offsets.size()-1];
665 unsigned char* fitsBuffer = new unsigned char[size];
666
667 int status = 0;
668 for (int i=1; i<=fTable->rows(); i++)
669 {
670 fits_read_tblbytes(fFile->fitsPointer(), i, 1, size, fitsBuffer, &status);
671 if (status)
672 {
673 cerr << "An error occurred while reading fits row #" << i << " error code: " << status << endl;
674 break;
675 }
676 if (WriteRow(out, columns, offsets, fitsBuffer, ranges)<0)
677 {
678 status=1;
679 break;
680 }
681 }
682 delete[] fitsBuffer;
683
684 return status==0;
685}
686
687// --------------------------------------------------------------------------
688//
689//! Perform the actual dump, based on the current parameters
690//
691/*
692bool FitsDumper::Plot(const vector<string> &list)
693{
694 for (vector<string>::const_iterator it=list.begin(); it!=list.end(); it++)
695 if (fColMap.find(*it) == fColMap.end())
696 {
697 cerr << "WARNING - Column '" << *it << "' not found in table." << endl;
698 return false;
699 }
700
701 // FIXME: Maybe do this when opening a table?
702 const vector<int> offsets = CalculateOffsets();
703 if (offsets.size()==0)
704 return false;
705
706 // Loop over all columns in our list of requested columns
707 const CCfits::Column *col[3] =
708 {
709 list.size()>0 ? fColMap.find(list[0])->second : 0,
710 list.size()>1 ? fColMap.find(list[1])->second : 0,
711 list.size()>2 ? fColMap.find(list[2])->second : 0
712 };
713
714 const int size = offsets[offsets.size()-1];
715 unsigned char* fitsBuffer = new unsigned char[size];
716
717 const int idx = 0;
718
719 // CCfits starts counting at 1 not 0
720 const size_t pos[3] =
721 {
722 col[0] ? offsets[col[0]->index()-1] + idx*col[0]->width()*ValueTypeToSize(col[0]->type()) : 0,
723 col[1] ? offsets[col[1]->index()-1] + idx*col[1]->width()*ValueTypeToSize(col[1]->type()) : 0,
724 col[2] ? offsets[col[2]->index()-1] + idx*col[2]->width()*ValueTypeToSize(col[2]->type()) : 0
725 };
726
727 int status = 0;
728 for (int i=1; i<=fTable->rows(); i++)
729 {
730 fits_read_tblbytes(fFile->fitsPointer(), i, 1, size, fitsBuffer, &status);
731 if (status)
732 {
733 cerr << "An error occurred while reading fits row #" << i << " error code: " << status << endl;
734 break;
735 }
736
737 try
738 {
739 const double x[3] =
740 {
741 col[0] ? PtrToDouble(fitsBuffer+pos[0], col[0]->type()) : 0,
742 col[1] ? PtrToDouble(fitsBuffer+pos[1], col[1]->type()) : 0,
743 col[2] ? PtrToDouble(fitsBuffer+pos[2], col[2]->type()) : 0
744 };
745 }
746 catch (const runtime_error &e)
747 {
748 cerr << e.what() << endl;
749 status=1;
750 break;
751 }
752 }
753 delete[] fitsBuffer;
754
755 return status==0;
756}
757*/
758
759// --------------------------------------------------------------------------
760//
761//! Retrieves the configuration parameters
762//! @param conf
763//! the configuration object
764//
765int FitsDumper::ExecConfig(Configuration& conf)
766{
767 if (conf.Has("fitsfile"))
768 {
769 if (!OpenFile(conf.Get<string>("fitsfile")))
770 return -1;
771 }
772
773 if (conf.Get<bool>("list"))
774 List();
775
776 if (conf.Has("tablename"))
777 {
778 if (!OpenTable(conf.Get<string>("tablename")))
779 return -1;
780 }
781
782#ifdef PLOTTING_PLEASE
783 if (conf.Get<bool>("graph"))
784 {
785 if (!conf.Has("col"))
786 {
787 cout << "Please specify the columns that should be dumped as arguments. Aborting" << endl;
788 return 0;
789 }
790 doCurvesDisplay(conf.Get<vector<string>>("col"),
791 conf.Get<string>("tablename"));
792 return 1;
793 }
794#endif
795
796 if (conf.Get<bool>("header"))
797 ListHeader();
798
799 if (conf.Get<bool>("header") || conf.Get<bool>("list"))
800 return 1;
801
802 if (conf.Has("outfile"))
803 {
804 if (!conf.Has("col"))
805 {
806 cout << "Please specify the columns that should be dumped as arguments. Aborting" << endl;
807 return 0;
808 }
809 if (!Dump(conf.Get<string>("outfile"),
810 conf.Get<vector<string>>("col"),
811 conf.Get<int>("precision")))
812 return -1;
813 }
814
815
816 return 0;
817}
818
819void PrintUsage()
820{
821 cout <<
822 "fitsdump is a tool to dump data from a FITS table as ascii.\n"
823 "\n"
824 "Usage: fitsdump [OPTIONS] fitsfile col col ... \n"
825 " or: fitsdump [OPTIONS]\n";
826 cout << endl;
827}
828
829void PrintHelp()
830{
831 //
832}
833#ifdef PLOTTING_PLEASE
834int FitsDumper::doCurvesDisplay( const vector<string> &list, const string& tableName)
835{
836 //first of all, let's separate the columns from their ranges and check that the requested columns are indeed part of the file
837 vector<pair<int, int> > ranges;
838 vector<string> listNamesOnly;
839 if (!separateColumnsFromRanges(list, ranges, listNamesOnly))
840 {
841 cerr << "Something went wrong while extracting the columns names from parameters. Aborting" << endl;
842 return false;
843 }
844 vector<string> curvesNames;
845 stringstream str;
846 for (auto it=ranges.begin(), jt=listNamesOnly.begin(); it != ranges.end(); it++, jt++)
847 {
848 for (int i=it->first; i<it->second;i++)
849 {
850 str.str("");
851 str << *jt << "[" << i << "]";
852 curvesNames.push_back(str.str());
853 }
854 }
855 char* handle = new char[17];
856 sprintf(handle,"FitsDump Display");
857// Qt::HANDLE h = *handle;//NULL
858 int argc = 1;
859 char ** argv = &handle;
860 QApplication a(argc, argv);
861
862
863
864 QwtPlot* plot = new QwtPlot();
865 QwtPlotGrid* grid = new QwtPlotGrid;
866 grid->enableX(false);
867 grid->enableY(true);
868 grid->enableXMin(false);
869 grid->enableYMin(false);
870 grid->setMajPen(QPen(Qt::black, 0, Qt::DotLine));
871 grid->attach(plot);
872 plot->setAutoReplot(true);
873 string title = tableName;
874 plot->setAxisScaleDraw( QwtPlot::xBottom, new TimeScaleDraw());
875
876 QWidget window;
877 QHBoxLayout* layout = new QHBoxLayout(&window);
878 layout->setContentsMargins(0,0,0,0);
879 layout->addWidget(plot);
880
881 QwtPlotZoomer zoom(plot->canvas());
882 zoom.setRubberBandPen(QPen(Qt::gray, 2, Qt::DotLine));
883 zoom.setTrackerPen(QPen(Qt::gray));
884 int totalSize = 0;
885 for (unsigned int i=0;i<list.size();i++)
886 totalSize += ranges[i].second - ranges[i].first;
887 cout << "Total size: " << totalSize << endl;
888 vector<QwtPlotCurve*> curves(totalSize);
889 int ii=0;
890 for (auto it = curves.begin(), jt=curvesNames.begin(); it != curves.end(); it++, jt++)
891 {
892 *it = new QwtPlotCurve(jt->c_str());
893 switch (ii%6)
894 {
895 case 0:
896 (*it)->setPen(QColor(255,0,0));
897 break;
898 case 1:
899 (*it)->setPen(QColor(0,255,0));
900 break;
901 case 2:
902 (*it)->setPen(QColor(0,0,255));
903 break;
904 case 3:
905 (*it)->setPen(QColor(255,255,0));
906 break;
907 case 4:
908 (*it)->setPen(QColor(0,255,255));
909 break;
910 case 5:
911 (*it)->setPen(QColor(255,0,255));
912 break;
913 default:
914 (*it)->setPen(QColor(0,0,0));
915 };
916 ii++;
917 (*it)->setStyle(QwtPlotCurve::Lines);
918 (*it)->attach(plot);
919 }
920 plot->insertLegend(new QwtLegend(), QwtPlot::RightLegend);
921
922 const vector<int> offsets = CalculateOffsets();
923 if (offsets.size()==0)
924 return false;
925
926
927 // Loop over all columns in our list of requested columns
928 vector<MyColumn*> columns;
929 for (vector<string>::const_iterator it=listNamesOnly.begin(); it!=listNamesOnly.end(); it++)
930 {
931 MyColumn *cCol = static_cast<MyColumn*>(fColMap.find(*it)->second);
932 columns.push_back(cCol);
933 }
934 //add the time column to the given columns
935 MyColumn* timeCol = static_cast<MyColumn*>(fColMap.find("Time")->second);
936 if (!timeCol)
937 {
938 cerr << "Error: time column could not be found in given table. Aborting" << endl;
939 return false;
940 }
941 columns.push_back(timeCol);
942 ranges.push_back(make_pair(0,1));
943 /////
944 const int size = offsets[offsets.size()-1];
945 unsigned char* fitsBuffer = new unsigned char[size];
946
947// stringstream str;
948 str.str("");
949 int status = 0;
950
951 vector<double*> xValues(totalSize);
952 double* yValues;
953 cout.precision(10);
954 str.precision(20);
955 for (auto it=xValues.begin(); it!=xValues.end(); it++)
956 *it = new double[fTable->rows()];
957
958 yValues = new double[fTable->rows()];
959
960 for (int i=1; i<=fTable->rows(); i++)
961 {
962 fits_read_tblbytes(fFile->fitsPointer(), i, 1, size, fitsBuffer, &status);
963 if (status)
964 {
965 cerr << "An error occurred while reading fits row #" << i << " error code: " << status << endl;
966 break;
967 }
968 if (WriteRow(str, columns, offsets, fitsBuffer, ranges)<0)
969 {
970 status=1;
971 cerr << "An Error occured while reading the fits row " << i << endl;
972 return -1;
973 }
974// yValues[i-1] = i;
975 for (auto it=xValues.begin(); it!= xValues.end(); it++)
976 {
977 str >> (*it)[i-1];
978// cout << (*it)[i-1] << " ";
979 }
980 str >> yValues[i-1];
981 if (i==1)
982 {
983 Time t(yValues[0]);
984 title += " - " + t.GetAsStr("%Y-%m-%d");
985 plot->setTitle(title.c_str());
986 }
987// cout << yValues[i-1] << " ";
988// cout << endl;
989 }
990 //set the actual data.
991 auto jt = xValues.begin();
992 for (auto it=curves.begin(); it != curves.end(); it++, jt++)
993 (*it)->setRawData(yValues, *jt, fTable->rows());
994
995 QStack<QRectF> stack;
996 double minX, minY, maxX, maxY;
997 minX = minY = 1e10;
998 maxX = maxY = -1e10;
999 QRectF rect;
1000 QPointF point;
1001 for (auto it=curves.begin(); it!= curves.end(); it++)
1002 {
1003 rect = (*it)->boundingRect();
1004 point = rect.bottomRight();
1005 if (point.x() < minX) minX = point.x();
1006 if (point.y() < minY) minY = point.y();
1007 if (point.x() > maxX) maxX = point.x();
1008 if (point.y() > maxY) maxY = point.y();
1009 point = rect.topLeft();
1010 if (point.x() < minX) minX = point.x();
1011 if (point.y() < minY) minY = point.y();
1012 if (point.x() > maxX) maxX = point.x();
1013 if (point.y() > maxY) maxY = point.y();
1014 }
1015 QPointF bottomRight(maxX, minY);
1016 QPointF topLeft(minX, maxY);
1017 QPointF center((bottomRight+topLeft)/2.f);
1018 stack.push(QRectF(topLeft + (topLeft-center)*(.5f),bottomRight + (bottomRight-center)*(.5f)));
1019 zoom.setZoomStack(stack);
1020
1021 delete[] fitsBuffer;
1022 window.resize(600, 400);
1023 window.show();
1024
1025 a.exec();
1026
1027 for (auto it = curves.begin(); it != curves.end(); it++)
1028 delete *it;
1029 for (auto it = xValues.begin(); it != xValues.end(); it++)
1030 delete[] *it;
1031 delete[] yValues;
1032 delete[] handle;
1033 return 0;
1034}
1035#endif
1036
1037void SetupConfiguration(Configuration& conf)
1038{
1039 po::options_description configs("Fitsdump options");
1040 configs.add_options()
1041 ("fitsfile,f", var<string>()
1042#if BOOST_VERSION >= 104200
1043 ->required()
1044#endif
1045 , "Name of FITS file")
1046 ("tablename,t", var<string>("DATA")
1047#if BOOST_VERSION >= 104200
1048 ->required()
1049#endif
1050 , "Name of input table")
1051 ("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")
1052 ("outfile,o", var<string>("/dev/stdout"), "Name of output file (-:/dev/stdout)")
1053 ("precision,p", var<int>(20), "Precision of ofstream")
1054 ("list,l", po_switch(), "List all tables and columns in file")
1055 ("header,h", po_switch(), "Dump header of given table")
1056#ifdef PLOTTING_PLEASE
1057 ("graph,g", po_switch(), "Plot the columns instead of dumping them")
1058#endif
1059 ;
1060
1061 po::positional_options_description p;
1062 p.add("fitsfile", 1); // The first positional options
1063 p.add("col", -1); // All others
1064
1065 conf.AddOptions(configs);
1066 conf.SetArgumentPositions(p);
1067}
1068
1069int main(int argc, const char** argv)
1070{
1071 Configuration conf(argv[0]);
1072 conf.SetPrintUsage(PrintUsage);
1073 SetupConfiguration(conf);
1074
1075 if (!conf.DoParse(argc, argv, PrintHelp))
1076 return -1;
1077
1078 FitsDumper loader;
1079 return loader.ExecConfig(conf);
1080}
Note: See TracBrowser for help on using the repository browser.