source: trunk/Mars/mfileio/MWriteFitsFile.cc@ 18009

Last change on this file since 18009 was 17868, checked in by tbretz, 11 years ago
Adapted the AddContainer call to the changes in MWriteRootFile.
File size: 46.0 KB
Line 
1#include <TDataMember.h>
2#include <TClonesArray.h>
3
4#include "MLogManip.h"
5
6#include "MArrayS.h"
7#include "MArrayB.h"
8#include "MArrayF.h"
9
10#include "MRead.h"
11#include "MParList.h"
12#include "MStatusDisplay.h"
13
14#include "MLog.h"
15#include "MLogManip.h"
16#include "MWriteRootFile.h"
17
18#include "MWriteFitsFile.h"
19#include "MFitsArray.h"
20
21#include "MTime.h"
22
23//for find
24#include <algorithm>
25
26ClassImp(MWriteFitsFile);
27
28using namespace std;
29
30map<MUniqueFileId, MTopFitsGroup> MWriteFitsFile::fTopFitsGroups;
31
32
33
34// ----------------------------------------------------------------------------
35//
36// if fileMode == kSingleFile
37// Opens the top level group file, if it was not already opened by an other
38// instance of MWriteFitsFile.
39// if fileMode == kMultiFiles
40// fname defines the rules to build the output filenames from the current
41// input filename. The files are opened in the ReInit() method.
42//
43// opt = RECREATE : an existing file will be deleted
44// = NEW : an already existing file will not be deleted and the new
45// file is not created. Check with IsFileOpen() if the new
46// top level group could be opened.
47// name will be the name of the group
48// title will be written as keyword TITLE into the header
49//
50MWriteFitsFile::MWriteFitsFile(const char *fname,
51 FILE_MODE fileMode,
52 const Option_t *opt,
53 const char *name,
54 const char *title)
55{
56 fOpenOption = opt;
57 if (name && name[0] != 0)
58 fGroupName = name;
59 else
60 fGroupName = "MARS";
61
62 if (title)
63 fTitle = title;
64
65 iTopFitsGroup = fTopFitsGroups.end();
66
67 if (fileMode == kMultiFiles)
68 fRule = fname;
69 else
70 *fLog << err << "The new version of MWriteFitsFile does not support multiple tables in one file. Please use kMultiFiles instead" << endl;
71 //ETIENNE DEPREC
72 // iTopFitsGroup will be set by OpenTopLevelGroup, if a top level
73 // group can be assigned to this MWriteFitsFile.
74 //OpenTopLevelGroup(fname);
75}
76
77MWriteFitsFile::MWriteFitsFile(const Int_t comp,
78 const char* rule,
79 const Option_t* option,
80 const char* ftitle,
81 const char* name,
82 const char* title)
83{
84 fOpenOption = option;
85 if (name && name[0] != 0)
86 fGroupName = name;
87 else
88 fGroupName = "MARS";
89 if (title) fTitle = ftitle;
90 iTopFitsGroup = fTopFitsGroups.end();
91 //always kMultiFiles
92 fRule = rule;
93}
94// ----------------------------------------------------------------------------
95//
96// Closes the top level group, it is is not used by an other instance of
97// MWriteFitsFile.
98// std::map<TString, std::ofits*>
99MWriteFitsFile::~MWriteFitsFile()
100{
101 for (std::map<TString, ofits*>::iterator it=fFitsTables.begin(); it!= fFitsTables.end();it++)
102 {
103 if (it->second != NULL)
104 {
105 it->second->close();
106 delete it->second;
107 }
108 }
109// CloseTopLevelGroup();
110 DeleteArrayHelper();
111}
112
113// ----------------------------------------------------------------------------
114//
115// If the same file is already used by an other instance of MWriteFitsFile,
116// the user counter is increasesd.
117// Else: If the file exist and option is "RECREATE", the file is deleted and
118// recreated.
119// Finally the file with an empty group file is created.
120//
121void MWriteFitsFile::OpenTopLevelGroup(const char * fname)
122{
123 // get rid of environment variables, ~, ... in filename
124 char * expandedFileName = gSystem->ExpandPathName(fname);
125
126 // get unique identifier of the new file
127 struct stat fileId;
128 if (stat(expandedFileName, &fileId) == 0)
129 {
130 // file exist already
131 iTopFitsGroup = fTopFitsGroups.find(MUniqueFileId(fileId.st_dev, fileId.st_ino));
132 if (iTopFitsGroup != fTopFitsGroups.end())
133 {
134 *fLog << err << "You are trying to use an already existing file. Please choose a different file name (" << fname << ")" << endl;
135 exit(0);
136 // this group is already open. we use it as well
137 *fLog << inf2 << "Found open file '" << GetFileName() << "'... re-using." << endl;
138 iTopFitsGroup->second.IncreaseUsage();
139 delete [] expandedFileName;
140 return;
141 }
142
143 // file exist, but we cannot use
144 if (fOpenOption == "RECREATE")
145 // remove the file
146 unlink(expandedFileName);
147
148 else if (fOpenOption == "NEW")
149 {
150 *fLog << err << "File '" << expandedFileName << "' exist already." << endl;
151 delete [] expandedFileName;
152 return;
153 }
154 else
155 {
156 *fLog << err << "Unsupported option (" << fOpenOption.Data() << ") to open file " <<
157 expandedFileName << endl;
158 delete [] expandedFileName;
159 return;
160 }
161 }
162
163 // file does not yet exist or was deleted
164
165// try {
166// AstroRootGroup topGroup;
167// char wrTitle[fTitle.Length() + 1];
168// if (fTitle.Length() > 0)
169// {
170// strcpy(wrTitle, fTitle.Data());
171// topGroup.InitAttr("TITLE", "A", wrTitle);
172// }
173
174 //ETIENNE do not open top level group as using one file per table
175 //I kept this code active anyway, because it is checked elsewhere in the code that iTopFitsGroup is set.
176 ofits* topGroup = NULL;
177// ofits* topGroup = new ofits();
178// TString dol = expandedFileName;
179// topGroup->open(dol.Data());
180
181
182 // store this new file in fTopFitsGroups and get the iterator to the
183 // new group
184 stat(expandedFileName, &fileId);
185 iTopFitsGroup = fTopFitsGroups.insert(pair<MUniqueFileId, MTopFitsGroup>
186 (MUniqueFileId(fileId.st_dev, fileId.st_ino),
187 MTopFitsGroup(expandedFileName, topGroup) )).first;
188
189 delete [] expandedFileName;
190
191}
192
193// --------------------------------------------------------------------------
194//
195// Reduces the use - counter of the top level group. Closes the group
196// table, if the counter is 0, i.e. no other MWriteFitsFile instance uses
197// the same top level group.
198//
199
200void MWriteFitsFile::CloseTopLevelGroup()
201{
202 if (iTopFitsGroup != fTopFitsGroups.end())
203 {
204 iTopFitsGroup->second.DecreaseUsage();
205 if (iTopFitsGroup->second.GetNumUsage() <= 0)
206 fTopFitsGroups.erase(iTopFitsGroup);
207
208 iTopFitsGroup = fTopFitsGroups.end();
209 }
210}
211
212// --------------------------------------------------------------------------
213//
214// returns the name of the top level group file. It may be expanded if the
215// name, given by the user, contained environment variables of the ~ sign.
216// If no top level group is open, "no_open_file" is returned.
217//
218const char * MWriteFitsFile::GetFileName() const
219{
220 if (IsFileOpen())
221 return iTopFitsGroup->second.GetFileName().Data();
222 else
223 return "no_open_file";
224}
225
226// --------------------------------------------------------------------------
227//
228// Add a new Container to list of containers which should be written to the
229// file. Give the name of the container which will identify the container
230// in the parameterlist. tname is the name of the FITS table to which the
231// container should be written (Remark: one table can hold more than one
232// container). The default is the same name as the container name.
233// If "mus"t is set to kTRUE (the default), then the container must exist
234// in the parameterlist. The container will be ignored, if "must" is set to
235// kFALSE and the container does not exist in the parameterlist.
236//
237void MWriteFitsFile::AddContainer(const char *cName,
238 const char *tName,
239 Bool_t must, UInt_t max)
240{
241 if (cName == NULL || strlen(cName) == 0)
242 {
243 *fLog << warn << "Warning - container name in method MWriteFitsFile::"
244 "AddContainer not defined... ignored" << endl;
245 return;
246 }
247
248 // if tName is not defined, we use cName as the table name
249 TString tableName;
250 if (tName == NULL || strlen(tName) == 0)
251 tableName = cName;
252 else
253 tableName = tName;
254
255 // try to insert this container to the list of sub-tables. Write a
256 // warning, if the same container name was already defined and ignore
257 // this one.
258 if (fSubTables[tableName].insert( pair<TString, MFitsSubTable>
259 (cName, MFitsSubTable(must))).second == false)
260 {
261 *fLog << warn << "Warning - Container '"<< cName <<"' in table '" <<
262 tableName.Data() << "' already scheduled... ignored." << endl;
263 }
264}
265
266// --------------------------------------------------------------------------
267//
268// Add a new Container to list of containers which should be written to the
269// file. tname is the name of the FITS table to which the
270// container should be written (Remark: one table can hold more than one
271// container). The default is the same name as the container name.
272// "must" is ignored. It is just for compatibility with MWriteRootFiles.
273//
274void MWriteFitsFile::AddContainer(MParContainer *cont, const char *tName,
275 Bool_t must, UInt_t max)
276{
277 if (cont == NULL)
278 {
279 *fLog << warn << "Warning - container in method MWriteFitsFile::"
280 "AddContainer not defined... ignored" << endl;
281 return;
282 }
283
284 TString tableName;
285 if (tName == NULL || strlen(tName) == 0)
286 tableName = cont->IsA()->GetName();
287 else
288 tableName = tName;
289
290 TString cName = cont->IsA()->GetName();
291 if (fSubTables[tableName].insert( pair<TString, MFitsSubTable>
292 (cName, MFitsSubTable(cont, must))).second == false)
293 {
294 *fLog << warn << "Warning - Container '"<< cName.Data() <<
295 "' in table '" << tableName.Data() <<
296 "' already scheduled... ignored." << endl;
297 }
298}
299
300// --------------------------------------------------------------------------
301//
302// Tries to open the given output file.
303//
304Int_t MWriteFitsFile::PreProcess(MParList *pList)
305{
306 if (fRule.Length() != 0)
307 // the file is not yet open
308 return kTRUE;
309 //
310 // test whether file is now open or not
311 //
312 if (!IsFileOpen())
313 {
314 *fLog << err << dbginf << "Cannot open file '" << GetFileName() << "'" << endl;
315 return kFALSE;
316 }
317
318 *fLog << inf << "File '" << GetFileName() << "' open for writing." << endl;
319
320 //
321 // Get the containers (pointers) from the parameter list you want to write
322 //
323 if (!GetContainer(pList))
324 return kFALSE;
325
326 //
327 // write the container if it is already in changed state
328 //
329 return CheckAndWrite();
330
331}
332
333Int_t MWriteFitsFile::PostProcess()
334{
335 bool rc = true;
336 for (std::map<TString, ofits*>::iterator it=fFitsTables.begin(); it!= fFitsTables.end();it++)
337 {
338 rc &= it->second->close();
339 delete it->second;
340 it->second = NULL;
341 }
342
343 return rc;
344}
345
346void MWriteFitsFile::SetupHeaderKeys(MRawRunHeader &header)
347{
348 const MTime now(-1);
349 SetHeaderKey("ISMC",true,"Bool if File is Montecarlo File");
350 SetHeaderKey("TELESCOP", "FACT", "");
351 SetHeaderKey("PACKAGE", "MARS Cheobs", "");
352 SetHeaderKey("VERSION", "1.0", "");
353 SetHeaderKey("CREATOR", "Ceres", "");
354 SetHeaderKey("EXTREL", 1., "");
355 SetHeaderKey("COMPILED", __DATE__" " __TIME__, "");
356 //SetHeaderKey("REVISION", "0", "");
357 SetHeaderKey("ORIGIN", "FACT", "");
358 SetHeaderKey("DATE", now.GetStringFmt("%Y-%m-%dT%H:%M:%S").Data(), "");
359 SetHeaderKey("NIGHT", now.GetNightAsInt(), "");
360 SetHeaderKey("TIMESYS", "UTC", "");
361 SetHeaderKey("TIMEUNIT", "d", "");
362 SetHeaderKey("MJDREF", 40587, "");
363 //SetHeaderKey("BLDVER", 1, "");
364 SetHeaderKey("RUNID", header.GetRunNumber(), "");
365 SetHeaderKey("NBOARD", 40, "");
366 SetHeaderKey("NPIX", header.GetNumPixel(), "");
367 SetHeaderKey("NROI", header.GetNumSamplesHiGain(), "");
368 SetHeaderKey("NROITM", 0, "");
369 SetHeaderKey("TMSHIFT", 0, "");
370 SetHeaderKey("CAMERA", "MGeomCamFACT", "Montecarlo File");
371 SetHeaderKey("DAQ", "DRS4", "Montecarlo File");
372
373 // FTemme: ADCRANGE and ADC have to be calculated, using the values for
374 // the fadctype.
375// SetHeaderKey("ADCRANGE", 2000, "Dynamic range in mV");
376// SetHeaderKey("ADC", 12, "Resolution in bits");
377
378 switch(header.GetRunType())
379 {
380 case MRawRunHeader::kRTData|MRawRunHeader::kRTMonteCarlo:
381 SetHeaderKey("RUNTYPE", "data", "");
382 break;
383 case MRawRunHeader::kRTPedestal|MRawRunHeader::kRTMonteCarlo:
384 SetHeaderKey("RUNTYPE", "pedestal", "");
385 break;
386 case MRawRunHeader::kRTCalibration|MRawRunHeader::kRTMonteCarlo:
387 SetHeaderKey("RUNTYPE", "calibration", "");
388 break;
389 }
390// SetHeaderKey("ID", 777, "Board 0: Board ID");
391// SetHeaderKey("FMVER", 532, "Board 0: Firmware Version");
392// SetHeaderKey("DNA", "0", "");
393// SetHeaderKey("BOARD", 0, "");
394// SetHeaderKey("PRESC", 40, "");
395// SetHeaderKey("PHASE", 0, "");
396// SetHeaderKey("DAC0", 26500, "");
397// SetHeaderKey("DAC1", 0, "");
398// SetHeaderKey("DAC2", 0, "");
399// SetHeaderKey("DAC3", 0, "");
400// SetHeaderKey("DAC4", 28800, "");
401// SetHeaderKey("DAC5", 28800, "");
402// SetHeaderKey("DAC6", 28800, "");
403// SetHeaderKey("DAC7", 28800, "");
404 SetHeaderKey("REFCLK", header.GetFreqSampling(), "");
405 SetHeaderKey("DRSCALIB", false, "");
406// SetHeaderKey("TSTARTI", 0, "");
407// SetHeaderKey("TSTARTF", 0., "");
408// SetHeaderKey("TSTOPI", 0, "");
409// SetHeaderKey("TSTOPF", 0., "");
410// SetHeaderKey("DATE-OBS", "1970-01-01T00:00:00", "");
411// SetHeaderKey("DATE-END", "1970-01-01T00:00:00", "");
412// SetHeaderKey("NTRG", 0, "");
413// SetHeaderKey("NTRGPED", 0, "");
414// SetHeaderKey("NTRGLPE", 0, "");
415// SetHeaderKey("NTRGTIM", 0, "");
416// SetHeaderKey("NTRGLPI", 0, "");
417// SetHeaderKey("NTRGEXT1", 0, "");
418// SetHeaderKey("NTRGEXT2", 0, "");
419// SetHeaderKey("NTRGMISC", 0, "");
420}
421
422template<>
423std::string MWriteFitsFile::GetFitsString(const double& value)
424{
425 std::ostringstream returnVal;
426 returnVal << std::setprecision(value>1e-100 && value<1e100 ? 15 : 14) << value;
427 std::string temp = returnVal.str();
428 std::replace(temp.begin(), temp.end(), 'e', 'E');
429 if (temp.find_first_of('E')==std::string::npos && temp.find_first_of('.')==std::string::npos)
430 temp += ".";
431 return temp;
432}
433template<>
434std::string MWriteFitsFile::GetFitsString(const float& value)
435{
436 return GetFitsString((double)(value));
437}
438// --------------------------------------------------------------------------
439//
440// Opens all FITS files for all container, which were registered with the
441// AddContainer() - methods. The container is taken from the pList, if it
442// was registered just by its name.
443// Calling the AddContainer() after calling this method will not add new
444// containers to the list.
445//
446Bool_t MWriteFitsFile::GetContainer(MParList *pList)
447{
448 if (iTopFitsGroup == fTopFitsGroups.end())
449 // something went wrong while the top level group was created
450 return kFALSE;
451
452
453 // remove the extension from the filename
454 // this has been disabled for now
455 char fileNameNoExt[strlen(GetFileName()) + 1];
456 strcpy(fileNameNoExt, GetFileName());
457// char * pos = strrchr(fileNameNoExt, '.');
458// if (pos) *pos = 0;
459//*fLog << inf <<"Filename no ext: " << fileNameNoExt << endl;
460 // loop over all FITS tables which have to be created.
461 map<TString, map<TString, MFitsSubTable> >::iterator i_table =
462 fSubTables.begin();
463 while (i_table != fSubTables.end())
464 {
465
466 ofits* fitsTable = new ofits();
467 fitsTable->AllowCommentsTrimming(true);
468 TString dol = fileNameNoExt;
469 //get rid of the ".root" extension in the file name (if any)
470 if (dol(dol.Length()-5, dol.Length()) == ".root")
471 {
472 dol = dol(0, dol.Length()-5);
473 }
474 if (dol(dol.Length()-5, dol.Length()) == ".fits")
475 {
476 dol = dol(0, dol.Length()-5);
477 }
478 dol += "_";
479 dol += i_table->first;
480 dol += ".fits";
481 fitsTable->open(dol.Data());
482 *fLog << inf << "Opening FITS file: " << dol.Data() << endl;
483 fFitsTables[i_table->first] = fitsTable;
484 fTableObjectCreated[i_table->first] = true;
485 fTableHeaderWritten[i_table->first] = false;
486
487 // loop over all containers, which define a sub-table of the current table
488 Int_t num = 0;
489 map<TString, MFitsSubTable>::iterator i_subTable = i_table->second.begin();
490 while (i_subTable != i_table->second.end())
491 {
492
493 MFitsSubTable & subTable = i_subTable->second;
494 if (subTable.GetContainer() == NULL)
495 {
496 // container address is not yet known
497 const char * cname = i_subTable->first.Data();
498 MParContainer *cont = (MParContainer*)pList->FindObject(cname);
499 if (!cont)
500 {
501 // no corresponding container is available in pList
502 if (subTable.MustHave())
503 {
504 *fLog << err << "Cannot find parameter container '" << cname << "'." << endl;
505 return kFALSE;
506 }
507
508 // we can ignore this container, delete it from the map
509 *fLog << inf2 << "Unnecessary parameter container '" << cname << "' not found..." << endl;
510 map<TString, MFitsSubTable>::iterator i_tmp = i_subTable;
511 i_subTable++;
512 i_table->second.erase(i_tmp);
513 continue;
514 }
515
516 // we have our container address and can use it
517 subTable.SetContainer(cont);
518 }
519
520 // initialize all columns of the sub-table, defined by the current container
521 TClass * cl = i_subTable->second.GetContainer()->IsA();
522 if (!InitColumns(i_table->first, TString(cl->GetName()) + ".", fitsTable,
523 i_subTable->second.GetContainer(), cl) )
524 return kFALSE;
525
526 char attrName[10];
527 sprintf(attrName, "CLNAME%d", num);
528 num++;
529
530 InitAttr(attrName,
531 "A",
532 (void*)i_subTable->first.Data(),
533 NULL,
534 "MARS container name",
535 fitsTable);
536
537 i_subTable++;
538 }
539
540 // in case not all sub-tables were removed, we can now create the FITS table
541 if (i_table->second.size() > 0)
542 {
543 // create the DOL of the table. It will be something like:
544 // fileNameNoExt_dataName.fits[dataName]
545 TString dol = fileNameNoExt;
546 dol += "_";
547 dol += i_table->first;
548 dol += ".fits";
549
550 if (fOpenOption == "RECREATE")
551 // remove the file
552 unlink(dol.Data());
553
554 dol += "[";
555 dol += i_table->first;
556 dol += "]";
557// *fLog << err << "Reiner would have opened fits file: " << dol.Data() << endl;
558 //exit(0);
559 //fitsTable->open(dol.Data());
560
561 // attach the new table to the top level group
562 //TODO make sure that this attach below is not needed...
563 //iTopFitsGroup->second.Attach(fitsTable);
564 }
565
566 i_table++;
567 }
568
569 return kTRUE;
570}
571void MWriteFitsFile::InitAttr(const char* attrName,
572 const char* dataType,
573 void* var,
574 const char* unit,
575 const char* comment,
576 ofits* outFile)
577{
578 if (outFile == NULL)
579 return;
580 string dts(dataType);
581 string ans(attrName);
582 string cs;
583 if (comment != NULL)
584 cs = string(comment);
585 else
586 cs = "";
587 ostringstream val;
588 if ((dts == "bool") || (dts == "Bool_t") || (dts == "L"))
589 {
590 outFile->SetBool(ans, ((bool*)(var))[0], cs);
591 return;
592 }
593 if ((dts == "char") || (dts == "Char_t") || (dts == "S"))
594 {
595 val << ((char*)(var))[0];
596 outFile->SetStr(ans, val.str(), cs);
597 return;
598 }
599 if ((dts == "unsigned char") || (dts == "UChar_t") || (dts == "B"))
600 {
601 val << ((unsigned char*)(var))[0];
602 outFile->SetStr(ans, val.str(), cs);
603 return;
604 }
605 if ((dts == "short") || (dts == "Short_t") || (dts == "I"))
606 {
607 val << ((short*)(var))[0];
608 outFile->SetStr(ans, val.str(), cs);
609 return;
610 }
611 if ((dts == "unsigned short") || (dts == "UShort_t") || (dts == "U"))
612 {
613 val << ((unsigned short*)(var))[0];
614 outFile->SetStr(ans, val.str(), cs);
615 return;
616 }
617 if ((dts == "int") || (dts == "Int_t") || (dts == "V"))
618 {
619 outFile->SetInt(ans, ((int*)(var))[0], cs);
620 return;
621 }
622 if ((dts == "unsigned int") || (dts == "UInt_t") || (dts == "V"))
623 {
624 outFile->SetInt(ans, ((unsigned int*)(var))[0], cs);
625 return;
626 }
627 if ((dts == "long long") || (dts == "Long64_t") || (dts == "K"))
628 {
629 outFile->SetInt(ans, ((long long*)(var))[0], cs);
630 return;
631 }
632 if ((dts == "unsigned long long") || (dts == "ULong64_t") || (dts == "W"))
633 {
634 val << ((unsigned long long*)(var))[0];
635 outFile->SetStr(ans, val.str(), cs);
636 return;
637 }
638 if ((dts == "float") || (dts == "TFloat_t") || (dts == "E"))
639 {
640 outFile->SetFloat(ans, ((float*)(var))[0], cs);
641 return;
642 }
643 if ((dts == "double") || (dts == "TDouble_t") || (dts == "D"))
644 {
645 outFile->SetFloat(ans, ((double*)(var))[0], cs);
646 return;
647 }
648 if ((dts == "char*") || (dts == "A"))
649 {
650 outFile->SetStr(ans, string((char*)(var)), cs);
651 return;
652 }
653 //trigger error
654 *fLog << err << "Format string not recognized while adding header entry " << ans << " with type " << dts << endl;
655}
656// --------------------------------------------------------------------------
657//
658// This method is called when new data should be written to the FITS table.
659// In general only one row is written. (There are exceptions for Arrays).
660// A new row to a FITS table is written if at least for one container
661// (one sub-table) the ReadyToSave - flag is set.
662//
663Bool_t MWriteFitsFile::CheckAndWrite()
664{
665// try {
666
667 // loop over all tables
668 map<TString, map<TString, MFitsSubTable> >::iterator i_table =
669 fSubTables.begin();
670 while (i_table != fSubTables.end())
671 {
672 // is this table open?
673 if (fFitsTables.find(i_table->first) != fFitsTables.end())
674 {
675
676 // loop over all sub-tables
677 map<TString, MFitsSubTable>::iterator i_subTable = i_table->second.begin();
678 while (i_subTable != i_table->second.end())
679 {
680
681 if (i_subTable->second.GetContainer()->IsReadyToSave())
682 {
683 // first write the TClonesArray and set the size of the arrays
684 list<MArrayHelperBase*> & clHelper = fClHelper[i_table->first];
685 list<MArrayHelperBase*>::iterator i_clHelper = clHelper.begin();
686 while (i_clHelper != clHelper.end())
687 {
688 // write all entries in the TClonesArray in its FITS table
689 //removed this write because I do it elsewhere. is that alright ?
690 // (*i_clHelper)->Write();
691 i_clHelper++;
692 }
693
694 // write one line to this table
695 writeOneRow(i_table->first);
696// fFitsTables[i_table->first].Write();
697 break;
698 }
699 i_subTable++;
700 }
701 }
702
703 i_table++;
704 }
705// }
706// catch (exception &e)
707 // {
708 // *fLog << err << e.what() << endl;
709 // return kFALSE;
710 // }
711
712 return kTRUE;
713}
714
715string MWriteFitsFile::Trim(const string &str)
716{
717 // Trim Both leading and trailing spaces
718 const size_t first = str.find_first_not_of(' '); // Find the first character position after excluding leading blank spaces
719 const size_t last = str.find_last_not_of(' '); // Find the first character position from reverse af
720
721 // if all spaces or empty return an empty string
722 if (string::npos==first || string::npos==last)
723 return string();
724
725 return str.substr(first, last-first+1);
726}
727
728Bool_t MWriteFitsFile::VetoColumn(const std::string& colName)
729{
730 for (std::vector<string>::iterator it=fVetoedColumns.begin(); it != fVetoedColumns.end(); it++)
731 if (*it == colName)
732 {
733 *fLog << warn << "Warning: column " << colName << " is being vetoed twice" << endl;
734 return kFALSE;
735 }
736 fVetoedColumns.push_back(colName);
737 return kTRUE;
738}
739
740Bool_t MWriteFitsFile::SetBytesPerSample(const std::string& colName, uint32_t numBytes)
741{
742 for (map<string, uint32_t>::iterator it=fBytesPerSamples.begin(); it!=fBytesPerSamples.end(); it++)
743 if (it->first == colName)
744 {
745 *fLog << warn << "Warning: column " << colName << " bytes per sample is being redefined twice" << endl;
746 return kFALSE;
747 }
748 if (numBytes != 1 && numBytes != 2 && numBytes != 4 && numBytes != 8)
749 {
750 *fLog << warn << "Only powers of two are allowed for types re-mapping." << endl;
751 return kFALSE;
752 }
753 fBytesPerSamples[colName] = numBytes;
754 return kTRUE;
755}
756
757// --------------------------------------------------------------------------
758//
759// Initialize all columns in "fitsTable" of the class "classDef". The data
760// of this class are stored in a buffer, beginning at "baseAdr".
761//
762Bool_t MWriteFitsFile::InitColumns(const TString & tableName,
763 const TString & parentVarName,
764 ofits* fitsTable,
765 void * baseAdr,
766 TClass * classDef)
767{
768 // get all data members of the class
769 TList * dataMembers = classDef->GetListOfDataMembers();
770 TIter next(dataMembers);
771 TDataMember * dataMember;
772
773 // loop over all data members
774 while ((dataMember = (TDataMember*)next()) != NULL)
775 {
776 if (!dataMember->IsPersistent())
777 // don't store this variable
778 continue;
779
780 if (dataMember->Property() & ( G__BIT_ISENUM | G__BIT_ISSTATIC))
781 // we cannot store this
782 continue;
783
784 if (strcmp(dataMember->GetTrueTypeName(), "TClass*") == 0)
785 // we don't want to store this.
786 continue;
787
788 // is it an array of more than 1 dimension?
789 if (dataMember->GetArrayDim() > 1)
790 {
791 *fLog << err << "Two and more dimensional arrays of member variables"
792 " are not supported." << endl;
793 *fLog << "See variable " << dataMember->GetName() <<
794 " in container " << classDef->GetName() << endl;
795 return kFALSE;
796 }
797
798
799 // replace � by **2 in the comment field
800 string comment(dataMember->GetTitle());
801 string::size_type pos1, pos2;
802 if ((pos1 = comment.find(178)) != string::npos)
803 comment.replace(pos1, 1, "**2");
804
805 // get the optional mapping to the fits column names
806 string fitsOptions="";
807 string unit="unit";
808
809 pos1 = comment.find("{fits: ");
810 pos2 = comment.find('}');
811 std::map<string, string> fitsTokens;
812 if (pos1 != string::npos && pos2 != string::npos)
813 {
814 fitsOptions=comment.substr(pos1+7, (pos2-pos1)-7);
815 //do we have more than one option ?
816 string::size_type pos3= fitsOptions.find_first_of(';');
817 string::size_type pos4 = string::npos;
818 string key="";
819 string value="";
820 string keyValue="";
821 while (pos3 != string::npos)
822 {//we have at least 2 options left
823 // *fLog << err << "fitsOptions: " << fitsOptions << endl;
824 keyValue = fitsOptions.substr(0,pos3);
825 // *fLog << err << "keyValue: " << keyValue << endl;
826 pos4 = keyValue.find('=');
827 if (pos4 == string::npos)
828 {
829 *fLog << err << "Error while parsing comment \"" << comment << "\" from variable " << parentVarName + dataMember->GetName() << endl;
830 return kFALSE;
831 }
832 key = Trim(keyValue.substr(0, pos4));
833 value = Trim(keyValue.substr(pos4+1, pos3));
834 fitsTokens[key] = value;
835 // *fLog << err << "key: " << key << " value: " << value << endl;
836 fitsOptions = fitsOptions.substr(pos3+1, fitsOptions.size());
837 pos3 = fitsOptions.find_first_of(';');
838 }
839// *fLog << err << "fitsOptions: " << fitsOptions << endl;
840 keyValue = fitsOptions;
841 pos4 = keyValue.find('=');
842 if (pos4 == string::npos)
843 {
844 *fLog << err << "Error while parsing comment \"" << comment << "\" from variable " << parentVarName + dataMember->GetName() << endl;
845 return kFALSE;
846 }
847 key = Trim(keyValue.substr(0, pos4));
848 value = Trim(keyValue.substr(pos4+1, pos3));
849 fitsTokens[key] = value;
850// *fLog << err << "key: " << key << " value: " << value << endl;
851 }
852
853 TString colName = parentVarName + dataMember->GetName();
854
855 if (fitsTokens.find("unit") != fitsTokens.end())
856 unit = fitsTokens["unit"];
857 if (fitsTokens.find("name") != fitsTokens.end())
858 colName = fitsTokens["name"];
859
860 //check for column veto
861 if (std::find(fVetoedColumns.begin(), fVetoedColumns.end(), colName.Data())!=fVetoedColumns.end())
862 {
863 *fLog << inf << "Vetoing column " << colName.Data() << endl;
864 continue;
865 }
866
867 // set the array size
868 TString dataType = dataMember->GetTrueTypeName();
869
870 uint32_t dataLength = 0;
871 switch (dataMember->GetArrayDim())
872 {
873 case 0:
874 dataLength = 1;
875 break;
876 case 1:
877 dataLength = dataMember->GetMaxIndex(0);
878 break;
879 default:
880 *fLog << err << "n-dimensional array should have been discarded already " << colName.Data();
881 break;
882 };
883// if (dataLength == 0)
884// continue;
885
886 if (dataMember->Property() & G__BIT_ISCLASS)
887 {
888 // special treatment for classes
889 uint32_t arraySize = 0;
890 TString typeName;
891
892 if (strncmp(dataMember->GetTrueTypeName(), "MArray", 6) == 0)
893 {
894 if (strcmp(dataMember->GetTrueTypeName(), "MArrayS*") == 0)
895 {
896 typeName = "UShort_t";
897 arraySize = (*((MArrayS**)((char*)baseAdr + dataMember->GetOffset())))->GetSize();
898 InitSingleColumn(tableName,
899 arraySize,
900 typeName.Data(),
901 (char*)(*((MArrayS**)((char*)baseAdr + dataMember->GetOffset())))->GetArray(),
902 colName.Data(),
903 unit,
904 comment);
905 }
906 else if (strcmp(dataMember->GetTrueTypeName(), "MArrayB*") == 0)
907 {
908 typeName = "UChar_t";
909 arraySize = (*((MArrayB**)((char*)baseAdr + dataMember->GetOffset())))->GetSize();
910 InitSingleColumn(tableName,
911 arraySize,
912 typeName.Data(),
913 (char*)(*((MArrayB**)((char*)baseAdr + dataMember->GetOffset())))->GetArray(),
914 colName.Data(),
915 unit,
916 comment);
917 }
918 else if (strcmp(dataMember->GetTrueTypeName(), "MArrayF*") == 0)
919 {
920 typeName = "TFloat_t";
921 arraySize = (*((MArrayF**)((char*)baseAdr + dataMember->GetOffset())))->GetSize();
922 InitSingleColumn(tableName,
923 arraySize,
924 typeName.Data(),
925 (char*)(*((MArrayF**)((char*)baseAdr + dataMember->GetOffset())))->GetArray(),
926 colName.Data(),
927 unit,
928 comment);
929 }
930
931 else {
932 *fLog << err << dataMember->GetTrueTypeName() << " not yet implemented." << endl;
933 return kFALSE;
934 }
935
936
937 continue;
938 }
939 else if (strcmp(dataMember->GetTrueTypeName(), "TClonesArray") == 0)
940 {
941 *fLog << warn << "I'm skipping the TClonesArray for now" << endl;
942 continue;
943 // each TClonesArray requires a FITS table by itself.
944 MClonesArrayHelper * clHelper;
945
946 TClonesArray * cloneArray = (TClonesArray*)((char*)baseAdr + dataMember->GetOffset());
947 Bool_t status;
948 clHelper = new MClonesArrayHelper(cloneArray, fLog, status);
949 if (!status) return status;
950
951 fClHelper[tableName].push_back(clHelper);
952
953 // add one column in the parent table of the TClonesArray to store the
954 // number of entries in the TClonesArray.
955 InitSingleColumn(tableName,
956 1,
957 "UInt_t",
958 clHelper->GetArraySizePtr(),
959 colName.Data(),
960 unit,
961 comment);
962
963 // initialize the columns of the new FITS table, which will store the
964 // data entries of the TClonesArray
965 if (InitColumns(TString("noName"),
966 colName + "_",
967 fitsTable,
968 clHelper->GetDataBuffer(),
969 cloneArray->GetClass())
970 == kFALSE)
971 return kFALSE;
972
973 // the columns are initialized. We can create the FITS table
974 if (clHelper->OpenFitsTable(GetFileName(), dataMember->GetName(),
975 fOpenOption, fLog) == kFALSE)
976 return kFALSE;
977 }
978
979 else
980 {
981 // the current container has a variable of an other class. We create
982 // also columns of this other class in the same table
983 TClass * newClassDef = TClass::GetClass(dataMember->GetTrueTypeName(), kFALSE, kTRUE);
984 if (newClassDef)
985 {
986 if (InitColumns(tableName, colName + ".", fitsTable, (char*)baseAdr + dataMember->GetOffset(),
987 newClassDef) == kFALSE)
988 return kFALSE;
989 }
990 else
991 *fLog << warn << "Cannot write data of class " << colName + "." + dataMember->GetTrueTypeName() << endl;
992 }
993 continue;
994 }
995
996 InitSingleColumn(tableName,
997 dataLength,
998 dataType.Data(),
999 (char*)baseAdr + dataMember->GetOffset(),
1000 colName.Data(),
1001 unit,
1002 comment);
1003
1004 }
1005 return kTRUE;
1006}
1007void MWriteFitsFile::InitSingleColumn(const TString& tableName,
1008 uint32_t count,
1009 const string& typeName,
1010 void* dataPointer,
1011 const string& columnName,
1012 const string& unit,
1013 const string& comment)
1014{
1015 if (!fTableObjectCreated[tableName])
1016 {
1017 *fLog << err << "ERROR: Cannot init column " << columnName << " before assigning object: " << tableName << endl;
1018 return;
1019 }
1020 int typeFound = 0;
1021 char typeChar = '0';
1022 if ((typeName == "bool") || (typeName == "Bool_t") || (typeName == "L"))
1023 {
1024 typeChar = 'L';
1025 typeFound++;
1026 }
1027 if ((typeName == "char") || (typeName == "Char_t") || (typeName == "S"))
1028 {
1029 typeChar = 'A';
1030 typeFound++;
1031 }
1032 if ((typeName == "unsigned char") || (typeName == "UChar_t") || (typeName == "B"))
1033 {
1034 typeChar = 'A';
1035// *fLog << warn << "Converting unsigned char to char in fits file" << endl;
1036 typeFound++;
1037 }
1038 if ((typeName == "short") || (typeName == "Short_t") || (typeName == "I"))
1039 {
1040 typeChar = 'I';
1041 typeFound++;
1042 }
1043 if ((typeName == "unsigned short") || (typeName == "UShort_t") || (typeName == "U"))
1044 {
1045 typeChar = 'I';
1046// *fLog << warn << "Converting unsigned short to short in fits file" << endl;
1047 typeFound++;
1048 }
1049 if ((typeName == "int") || (typeName == "Int_t") || (typeName == "V"))
1050 {
1051 typeChar = 'J';
1052 typeFound++;
1053 }
1054 if ((typeName == "unsigned int") || (typeName == "UInt_t") || (typeName == "V"))
1055 {
1056 typeChar = 'J';
1057// *fLog << warn << "Converting unsigned int to int in fits file" << endl;
1058 typeFound++;
1059 }
1060 if ((typeName == "long long") || (typeName == "Long64_t") || (typeName == "K"))
1061 {
1062 typeChar = 'K';
1063 typeFound++;
1064 }
1065 if ((typeName == "unsigned long long") || (typeName == "ULong64_t") || (typeName == "W"))
1066 {
1067 typeChar = 'K';
1068// *fLog << warn << "Converting unsigned long to long in fits file" << endl;
1069 typeFound++;
1070 }
1071 if ((typeName == "float") || (typeName=="TFloat_t") || (typeName == "E"))
1072 {
1073 typeChar = 'E';
1074 typeFound++;
1075 }
1076 if ((typeName == "double") || (typeName == "TDouble_t") || (typeName == "D"))
1077 {
1078 typeChar = 'D';
1079 typeFound++;
1080 }
1081// if ((typeName == "char*") || (typeName == "A"))
1082// {
1083// typeFound++;
1084// }
1085 if (typeFound != 1)
1086 {
1087 *fLog << err << "We have a problem with the data type: " << typeName << endl;
1088 return;
1089 }
1090 uint32_t colWidth = 0;
1091 switch (typeChar)
1092 {
1093 case 'L': colWidth = 1*count; break;
1094 case 'A': colWidth = 1*count; break;
1095 case 'B': colWidth = 1*count; break;
1096 case 'I': colWidth = 2*count; break;
1097 case 'J': colWidth = 4*count; break;
1098 case 'K': colWidth = 8*count; break;
1099 case 'E': colWidth = 4*count; break;
1100 case 'D': colWidth = 8*count; break;
1101 default:
1102 *fLog << err << "ERROR: typeChar could not be resolved to an actual type" << endl;
1103 };
1104 //check for type remapping here
1105 if (fBytesPerSamples.find(columnName) != fBytesPerSamples.end())
1106 {
1107 if (typeChar != 'A')
1108 {
1109 *fLog << err << "Attempt to remap type " << typeChar << " to " << fBytesPerSamples[columnName] << " is only allowed on bytes (variable name: " << columnName << "). Ignoring column" << endl;
1110 return;
1111 }
1112 uint32_t bytesPerSample = fBytesPerSamples.find(columnName)->second;
1113 if (colWidth%bytesPerSample != 0)
1114 {
1115 *fLog << err << "Type remapping cannot be done using " << bytesPerSample << " bytes per sample on an array of char of size " << colWidth << ". Ignoring column " << columnName << endl;
1116 return;
1117 }
1118 switch (bytesPerSample)
1119 {
1120 case 1: count = count/1; typeChar = 'A'; break;
1121 case 2: count = count/2; typeChar = 'I'; break;
1122 case 4: count = count/4; typeChar = 'J'; break;
1123 case 8: count = count/8; typeChar = 'K'; break;
1124 default:
1125 *fLog << err << "ERROR: num bytes per sample = " << bytesPerSample << " should have been forbidden already" << endl;
1126 }
1127
1128 }
1129
1130 fDataPointers[tableName].push_back(dataPointer);
1131 fTypeChars[tableName].push_back(typeChar);
1132 fColSizes[tableName].push_back(count);
1133 fColWidth[tableName].push_back(colWidth);
1134
1135 //FIXME ofits does not allow for much liberty regarding the size of the column names.
1136 //Truncating them badly here, will probably cause other problems -> Modify ofits.h instead
1137 string truncatedName=columnName.substr((columnName.size()>40)?columnName.size()-40:0,columnName.size());
1138 string truncatedComment = comment.substr((comment.size()>10)?comment.size()-10:0,comment.size());
1139// *fLog << warn << "In table " << tableName << " Adding column |" << truncatedName << "| |" << truncatedComment << "| |" << count << "| |" << typeChar;
1140// *fLog << warn << "| Real: "<< columnName << " comment: " << comment << endl;
1141 fFitsTables[tableName]->AddColumn(count, typeChar, truncatedName, unit, truncatedComment);
1142}
1143
1144void MWriteFitsFile::writeOneRow(const TString& tableName)
1145{
1146 if (!fTableHeaderWritten[tableName])
1147 {
1148 for (vector<ofits::Key>::const_iterator it = fHeaderKeys.begin(); it != fHeaderKeys.end(); it++)
1149 fFitsTables[tableName]->SetRaw(it->key, it->value, it->comment);
1150 fFitsTables[tableName]->WriteTableHeader(tableName.Data());
1151 fTableHeaderWritten[tableName] = true;
1152 }
1153 if (!fTableObjectCreated[tableName])
1154 {
1155 *fLog << err << "This is not good. Please initialize the fits table before writing to it: " << tableName << endl;
1156 return;
1157 }
1158 //first calculate the size of one row
1159 uint32_t rowWidth = 0;
1160 for (uint32_t i=0;i<fTypeChars[tableName].size();i++)
1161 rowWidth += fColWidth[tableName][i];
1162 unsigned char* tempBuffer = new unsigned char[rowWidth];
1163 //then copy the data to be written contiguously
1164 uint32_t bytesCounter = 0;
1165 for (uint32_t i=0;i<fDataPointers[tableName].size();i++)
1166 {
1167 memcpy(&tempBuffer[bytesCounter], fDataPointers[tableName][i], fColWidth[tableName][i]);
1168 bytesCounter+=fColWidth[tableName][i];
1169 }
1170 if (fFitsTables[tableName]->WriteRow(tempBuffer, bytesCounter) == false)
1171 *fLog << err << "Error while writing to FITS table " << tableName << endl;
1172 else
1173 fFitsTables[tableName]->FlushNumRows();
1174
1175 delete[] tempBuffer;
1176}
1177Bool_t MWriteFitsFile::ReInit(MParList *pList)
1178{
1179 if (fRule.Length() == 0)
1180 // there is not rule defined. We keep the old file
1181 return MWriteFile::ReInit(pList);
1182
1183 MRead *read = (MRead*)pList->FindTask("MRead");
1184 if (!read)
1185 {
1186 *fLog << err;
1187 *fLog << "ERROR: No Task 'MRead' found in the tasklist. This task is" << endl;
1188 *fLog << " necessary to get the filename. Without a read-filename" << endl;
1189 *fLog << " no output-filename can be created... abort." << endl;
1190 *fLog << endl;
1191 return kFALSE;
1192 }
1193
1194
1195 // close the current files
1196 CloseTopLevelGroup();
1197 for (std::map<TString,ofits*>::iterator it=fFitsTables.begin(); it!=fFitsTables.end(); it++)
1198 {
1199 (it->second)->close();
1200 delete it->second;
1201 }
1202 fFitsTables.clear();
1203 fDataPointers.clear();
1204 fTypeChars.clear();
1205 fColSizes.clear();
1206 fColWidth.clear();
1207 fTableObjectCreated.clear();
1208 fTableHeaderWritten.clear();
1209 DeleteArrayHelper();
1210 fClHelper.clear();
1211
1212 // get new filename
1213 const TString readFileName = read->GetFullFileName();
1214 const TString newname = MWriteRootFile::SubstituteName(fRule, readFileName);
1215
1216 // create new files
1217 OpenTopLevelGroup(newname.Data());
1218 if (!IsFileOpen())
1219 return kFALSE;
1220
1221
1222 MRawRunHeader* header = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
1223 SetupHeaderKeys(*header);
1224
1225 if (GetContainer(pList) == kFALSE)
1226 return kFALSE;
1227
1228 // do, what has to be done in ReInit.
1229 return MWriteFile::ReInit(pList);
1230
1231}
1232
1233void MWriteFitsFile::DeleteArrayHelper()
1234{
1235 map<TString, list<MArrayHelperBase *> >::iterator i_helper1 = fClHelper.begin();
1236 while (i_helper1 != fClHelper.end())
1237 {
1238 list<MArrayHelperBase *>::iterator i_helper2 = i_helper1->second.begin();
1239 while(i_helper2 != i_helper1->second.end())
1240 {
1241 delete *i_helper2;
1242
1243 i_helper2++;
1244 }
1245
1246 i_helper1++;
1247 }
1248}
Note: See TracBrowser for help on using the repository browser.