File: BinTable.cxx

package info (click to toggle)
ccfits 2.5%2Bdfsg-2
  • links: PTS
  • area: main
  • in suites: bullseye
  • size: 3,620 kB
  • sloc: cpp: 15,148; sh: 10,115; makefile: 91
file content (483 lines) | stat: -rw-r--r-- 14,937 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//	Astrophysics Science Division,
//	NASA/ Goddard Space Flight Center
//	HEASARC
//	http://heasarc.gsfc.nasa.gov
//	e-mail: ccfits@legacy.gsfc.nasa.gov
//
//	Original author: Ben Dorman

// ColumnCreator
#include "ColumnCreator.h"
// Column
#include "Column.h"
// BinTable
#include "BinTable.h"
#ifdef SSTREAM_DEFECT
#include <strstream>
#else
#include <sstream>
#endif
#include <utility>

namespace CCfits {

  // Class CCfits::BinTable 

  BinTable::BinTable(const BinTable &right)
      : Table(right)
  {
  }

  BinTable::BinTable (FITSBase* p, const String &hduName, bool readFlag, const std::vector<String>& keys, int version)
      : Table(p, BinaryTbl, hduName, version)
  {

  init(readFlag,keys);
  }

  BinTable::BinTable (FITSBase* p, const String &hduName, int rows, const std::vector<String>& columnName, const std::vector<String>& columnFmt, const std::vector<String>& columnUnit, int version)
      : Table(p, BinaryTbl, hduName, rows,  columnName, columnFmt, columnUnit, version)
  {
  long           repeat=0;
  long           width=0;
  int            status=0;
  int            colType=0;

  ColumnCreator create(this);

  for (int i=0; i < numCols(); i++)
  {
     status = fits_binary_tform(const_cast<char *>(columnFmt[i].c_str()), 
				&colType, &repeat, &width, &status);

     string unitString("");
     if (i < static_cast<int>(columnUnit.size()))
        unitString = columnUnit[i];
     Column *newCol = create.createColumn(i+1, ValueType(colType),
                                columnName[i], columnFmt[i], 
                                unitString,repeat,width);
     setColumn(columnName[i], newCol);
     newCol->setLimits(ValueType(colType));

  }
  }

  BinTable::BinTable (FITSBase* p, int number)
        : Table(p,BinaryTbl,number)
  {
  init();
  }


  BinTable::~BinTable()
  {
  }


  void BinTable::readTableHeader (int ncols, std::vector<String>& colName, std::vector<String>& colFmt, std::vector<String>& colUnit)
  {
   int   status=0;
   char  hduName[FLEN_KEYWORD];

   char** columnName = new char*[ncols];
   char** columnFmt  = new char*[ncols];
   char** columnUnit = new char*[ncols];
   int i = 0; // for MS VC++  
   for( ; i < ncols; i++)
   {
      columnName[i] = new char[FLEN_KEYWORD];
      columnFmt[i]  = new char[FLEN_KEYWORD];
      columnUnit[i] = new char[FLEN_KEYWORD];
   }

   long pct = 0;
   long nr  = 0;
   int tf  = 0;
   status = fits_read_btblhdr(fitsPointer(), ncols, &nr, &tf, columnName,
			      columnFmt, columnUnit, hduName, &pct,&status);
   pcount(pct);
   rows(nr);
   numCols(tf);

   for( i = 0; i < ncols; i++)
   {
      colName[i] = String(columnName[i]);
      colFmt[i]  = String(columnFmt[i]);
      colUnit[i] = String(columnUnit[i]);
      delete [] columnName[i];
      delete [] columnFmt[i];
      delete [] columnUnit[i];
   }

   delete [] columnName;
   delete [] columnFmt;
   delete [] columnUnit;

   // throw the exception after the garbage has been collected.

   if (status != 0)  throw FitsError(status);
  }

  BinTable * BinTable::clone (FITSBase* p) const
  {
  BinTable* cloned = new BinTable(*this);
  cloned->parent() = p;
  return cloned;
  }

  void BinTable::readData (bool readFlag, const std::vector<String>& keys)
  {
   int             rowsRead=0;
   std::vector<String>     varCols;
   int status = 0;
   long rowSize = 0;

   // grab the optimal rowsize using the get_rowsize call. It just
   // might have changed since the Table HDU was constructed so it should
   // be set just before reading takes place.
   if (fits_get_rowsize(fitsPointer(), &rowSize, &status))  throw FitsError(status);

   // if a set of strings were supplied, interpret these as
   // keywords and columns to be read.

   ColMap::iterator endColumn = column().end();
   size_t keysRead = 0;
   size_t nkey=keys.size();

   // get a container for keys which correspond to columns.
   std::vector<String> colKeys;
   colKeys.reserve(nkey);


   if (nkey > 0)
   {
       // first, look for keywords if strings are supplied and read them.
        for (keysRead = 0; keysRead < nkey; keysRead++)
        {
                try
                {
                        // after the read function is called by the ctor,
                        // the columns in the table have been indexed.
                        // check that the key in question is not a column
                        // name. 
                        if (column().find(keys[keysRead]) == endColumn)   readKeyword(keys[keysRead]);
                        else colKeys.push_back(keys[keysRead]);
                }
                catch (HDU::NoSuchKeyword)
                {
                        continue;
                }
                catch (...)
                {
                        throw;
                }
        } 
   }  

   // if readFlag is false, don't get any data. 

   if (!readFlag) return;      


   for (rowsRead=0; rowsRead< rows() ; rowsRead+=rowSize)
   {     
        ColMap::iterator col;
        if (colKeys.size() > 0)
        {
                for (size_t i=0; i < colKeys.size() ; i++)
                {
                        // if a set of keys was entered, read the data in the ones
                        // that correspond to columns, as checked earlier
                        col = column().find(colKeys[i]); 
                        Column&  current = *((*col).second);
	                // if the column is not of variable repeat count... 
                        if (!current.varLength())
                        {
                             current.readData(rowsRead+1,
                                             current.repeat()*std::min<size_t>(rowSize,rows()-rowsRead),1);
                        }
                        else
                        {
                        // store the column numbers of variable columns for later.
                             varCols.push_back(current.name());
                        }
                }
        }
        else
        {
                // if no keys that correspond to column names were supplied, read all the data.
	        for(col = column().begin(); col != column().end(); col++ )
                {      
                        Column& current = *(*col).second;
	                if (!current.varLength()) 
                        { 
                                current.readData(rowsRead+1,
                                          current.repeat()*std::min<size_t>(rowSize,rows() - rowsRead),1);
                        }
                        else
                        {
                                varCols.push_back(current.name());
                        }

                }
         }
   }

   // if successful, mark read columns.

   if (colKeys.size() ==  0)
   {
        // mark all columns read
        for (ColMap::iterator col = column().begin(); 
                col != column().end(); ++col) 
        {
                if (!(*col).second->varLength()) (*col).second->isRead(true);
        }
   }
   else
   {
        for (size_t i=0; i < colKeys.size() ; i++)
        {
                // if a set of keys was entered, read the data in the ones
                // that correspond to columns, as checked earlier.
                ColMap::iterator col = column().find(colKeys[i]);

                if (!(*col).second->varLength()) (*col).second->isRead(true);
        }

   }


   // now read the variable length columns that were found earlier.

   if (varCols.size() > 0 ) readVariableColumns(varCols);
  }

  void BinTable::readVariableColumns (const std::vector<String> &varColumns)
  {
    int   rowsRead=0;
    int   status=0;
    int   sz=varColumns.size();


    int i = 0;
    while ( i < sz && status == 0 )  
    {
       // Get bin size for the current column 
       Column& thisColumn = column(varColumns[i]);
       int colnum = thisColumn.index();
       if (thisColumn.type() == VTstring)
       {
          // Variable-length string columns must be treated differently.
          //  They are still represented as scalar columns rather than
          //  vector columns.  Their variation refers to the string lengths,
          //  not the number of elements in a row.
          thisColumn.readData(1, rows(), 1);
       }
       else
       {
          FITSUtil::auto_array_ptr<long> pBinSizes(new long[rows()]);
          long*  binSizes = pBinSizes.get();
          FITSUtil::auto_array_ptr<long> pOffsets(new long[rows()]);
          long*  offsets  = pOffsets.get();
          status = fits_read_descripts(fitsPointer(), colnum, 1, rows() , binSizes,
				       offsets, &status);
          if (status != 0) break;
          
          // Read vector column rows one at a time.
          for (rowsRead=0; rowsRead < rows() ; rowsRead++)
          {
	     if (binSizes[rowsRead] > 0)
	        thisColumn.readData(rowsRead+1, binSizes[rowsRead], 1);
          }
       }
       column(varColumns[i]).isRead(true);
       i++;

    }


    if (status != 0)  throw FitsError(status);
  }

  void BinTable::addColumn (ValueType type, const String& columnName, long repeatWidth, const String& colUnit, long decimals, size_t columnNumber)
  {
#ifdef SSTREAM_DEFECT
        std::ostrstream tformStr;
#else
        std::ostringstream tformStr;          
#endif

        // we do NOT support the extension allowed by cfitsio whereby multiple
        // strings can be saved in a binary table column cell.

        String diag;   

        if ( repeatWidth != 1 && type != Tstring && type != VTstring) 
        { 
                tformStr << repeatWidth;       
        }

        if (type < 0) tformStr << 'P';

        switch (type)
        {
                case Tstring:
                        tformStr << repeatWidth << 'A';
                        break;
                case VTstring:
                   // For variable string cols, cannot precede 'PA' with a number > 1.
                   tformStr << 'A';
                   break;
                case Tbyte:
                case VTbyte:
                        tformStr << 'B';
                        break;                
                case Tbit:
                case VTbit:
                        tformStr << 'X';             
                        break; 

                case Tlogical:
                case VTlogical:
                        tformStr << 'L';             
                        break;   

                case Tushort:
                case VTushort:
                        tformStr << 'U';
                        break;

                case Tshort:
                case VTshort:
                        tformStr << 'I';
                        break;

                case Tulong:
                case VTulong:
                        tformStr << 'V';
                        break;

                case Tlong:
                case VTlong:
                        tformStr << 'J';
                        break;   

                case Tlonglong:
                case VTlonglong:
                        tformStr << 'K';
                        break;        
                case Tuint:
                case VTuint:
                        tformStr << 'V';
                        break;

                case Tint:
                case VTint:
                        tformStr << 'J';
                        break;  

                case Tfloat:
                case VTfloat:
                        tformStr << 'E';
                        break;  

                case Tdouble:
                case VTdouble:
                        tformStr << 'D';
                        break;  

                case Tcomplex:
                case VTcomplex:
                        tformStr << 'C';
                        break;  

                case Tdblcomplex:
                case VTdblcomplex:
                        tformStr << 'M';
                        break;  

                default:           
                        diag += "Unrecognized data type for column: ";
                        diag += columnName;
                        throw InvalidColumnSpecification(diag);            
        }
#ifdef SSTREAM_DEFECT
        tformStr << std::ends;
#endif

        makeThisCurrent(); 
          
        int status(0);
        int colNum(0);
        if ( columnNumber == 0)
        {
            // add one to number of existing columns.
            if (fits_get_num_cols(fitsPointer(),&colNum,&status)) throw FitsError(status);
            colNum +=1;
        }
        else 
        {
                colNum = columnNumber;
        }

        String tfString(tformStr.str());
        // the C prototypes don't use const, so these casts are necessary.       
        char* tform = const_cast<char*>(tfString.c_str());      
        char* ttype = const_cast<char*>(columnName.c_str());

        if (fits_insert_col(fitsPointer(),colNum,ttype,tform,&status)) throw FitsError(status);


        if (colUnit.size()) 
        {           
                    std::ostringstream ustream;
                    char unitComment[] = "";
                    ustream << "TUNIT" << colNum;
                    if (fits_write_key (fitsPointer(), Tstring,
                               const_cast<char*>(ustream.str().c_str()),
                               const_cast<char*>(colUnit.c_str()), 
                               unitComment, &status))
                    {
                               throw FitsError (status);
                    }

        }


        ColumnCreator create(this);
        if (columnNumber != 0) reindex(columnNumber, true);
        if (type == Tstring)
        {
           // For fixed-width scalar string cols, TFORM is "wA" where 'w' is the
           // string length.  Store this value in Column::m_width and just set
           // m_repeat to 1. [For vector columns the format would be
           // "rAw" where r corresponds to m_repeat, but these are not currently
           // supported in CCfits.]
           setColumn(columnName,create.createColumn(colNum,type,columnName,tfString,
                 colUnit,1,repeatWidth));                
        }
        else if (type == VTstring)
        {
           // For variable string column, Column::m_width could only refer to the
           //  width of the largest string in the col (the value 'w' in "PA(w)")
           //  This can't be known at column creation time (CFITSIO determines the
           //  'w' each time the file is closed), so just set the m_width to 1.
           setColumn(columnName,create.createColumn(colNum,type,columnName,tfString,
                 colUnit,1,1));                
        }
        else
        {
           Column *newCol = create.createColumn(colNum,type,columnName,tfString,
                colUnit,repeatWidth,1);
           setColumn(columnName,newCol);
           newCol->setLimits(type);
        }
        

  }
  

  // Additional Declarations

} // namespace CCfits