source: trunk/MagicSoft/Mars/mfileio/MWriteRootFile.cc@ 9344

Last change on this file since 9344 was 9343, checked in by tbretz, 16 years ago
*** empty log message ***
File size: 36.5 KB
Line 
1/* ======================================================================== *\
2!
3! *
4! * This file is part of MARS, the MAGIC Analysis and Reconstruction
5! * Software. It is distributed to you in the hope that it can be a useful
6! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
7! * It is distributed WITHOUT ANY WARRANTY.
8! *
9! * Permission to use, copy, modify and distribute this software and its
10! * documentation for any purpose is hereby granted without fee,
11! * provided that the above copyright notice appear in all copies and
12! * that both that copyright notice and this permission notice appear
13! * in supporting documentation. It is provided "as is" without express
14! * or implied warranty.
15! *
16!
17!
18! Author(s): Thomas Bretz, 6/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
19!
20! Copyright: Software Development, 2000-2009
21!
22!
23\* ======================================================================== */
24
25/////////////////////////////////////////////////////////////////////////////
26//
27// MWriteRootFile
28//
29// This is a writer to store several containers to a root file.
30// The containers are added with AddContainer.
31// To understand how it works, see base class MWriteFile
32//
33// Warning: Look at the Warning in MTaskList.
34//
35// There is a special mode of operation which opens a new file for each new
36// file read by the reading task (opening the new file is initiated by
37// ReInit()) For more details see the corresponding constructor.
38//
39// Memory based trees
40// ------------------
41// It is possible to store the data into memory (TTrees) instead of
42// writing the data into a file. To do this either call the default
43// constructor or specify 'memory' as option in the constructor.
44//
45// Afterwards the tree can be found using
46// gROOT->GetListOfFiles()->FindObject("treename")
47//
48// Currently(!) the tree is not deleted at all! Please make sure to
49// delete it if it is not used anymore - otherwise you could wast a LOT
50// of memory. Please consider that this behaviour might change in the
51// future.
52//
53// Such trees are usefull if you want to use more basic root-tools
54// like TMultiLayerPerceptron or TEventList.
55//
56// If you want to process such memory based Trees using Mars make sure,
57// that you don't need data from the RunHeader tree because you can
58// only use MReadTree but not MReadMarsFile with such a tree.
59//
60/////////////////////////////////////////////////////////////////////////////
61#include "MWriteRootFile.h"
62
63#include <fstream>
64
65#include <TFile.h>
66#include <TTree.h>
67#include <TPRegexp.h>
68
69#include "MLog.h"
70#include "MLogManip.h"
71
72#include "MRead.h"
73#include "MParList.h"
74#include "MStatusDisplay.h"
75
76ClassImp(MRootFileBranch);
77ClassImp(MWriteRootFile);
78
79using namespace std;
80
81const TString MWriteRootFile::gsDefName = "MWriteRootFile";
82const TString MWriteRootFile::gsDefTitle = "Task which writes a root-output file";
83
84void MWriteRootFile::Init(const char *name, const char *title)
85{
86 fName = name ? name : gsDefName.Data();
87 fTitle = title ? title : gsDefTitle.Data();
88
89 //
90 // Set the Arrays the owner of its entries. This means, that the
91 // destructor of the arrays will delete all its entries.
92 //
93 fBranches.SetOwner();
94 fCopies.SetOwner();
95
96 //
97 // Believing the root user guide, TTree instances are owned by the
98 // directory (file) in which they are. This means we don't have to
99 // care about their destruction.
100 //
101 //fTrees.SetOwner();
102
103 gROOT->GetListOfCleanups()->Add(this); // To remove fOut if deleted
104 SetBit(kMustCleanup);
105}
106
107// --------------------------------------------------------------------------
108//
109// Try to get the file from gROOT->GetListOfFiles. (In case the file name
110// is /dev/null we look for a file with name /dev/null and the given title)
111// If it is found fOut is set to it and returned.
112// Otherwise a new file is opened and returned.
113//
114TFile *MWriteRootFile::OpenFile(const char *name, Option_t *option, const char *title, Int_t comp)
115{
116 TFile *file = 0;
117
118 if (TString(name)=="/dev/null")
119 {
120 TIter Next(gROOT->GetListOfFiles());
121 TObject *obj = 0;
122 while ((obj=Next()))
123 if (TString(obj->GetName())=="/dev/null" && TString(obj->GetTitle())==title)
124 {
125 *fLog << inf2 << "Found open file '/dev/null' <Title=" << title << ">... re-using." << endl;
126 file = dynamic_cast<TFile*>(obj);
127 break;
128 }
129 }
130 else
131 {
132 file = dynamic_cast<TFile*>(gROOT->GetListOfFiles()->FindObject(name));
133
134 // If the file was not found with its name try its expanded name
135 if (!file)
136 {
137 TString fqp(name);
138 gSystem->ExpandPathName(fqp);
139 file = dynamic_cast<TFile*>(gROOT->GetListOfFiles()->FindObject(fqp));
140 }
141
142 if (file)
143 {
144 *fLog << inf2;
145 *fLog << "Found open file '" << name << "'... re-using." << endl;
146 *fLog << inf3;
147 *fLog << "Make sure that you do NOT write to trees which are" << endl;
148 *fLog << "scheduled already by a different MWriteRootFile..." << endl;
149 }
150 }
151
152 if (!file)
153 {
154 file = new TFile(name, option, title, comp);
155 if (!file->IsOpen())
156 {
157 delete file;
158 return NULL;
159 }
160
161 *fLog << inf3 << "New file '" << name << "' ";
162 if (!TString(title).IsNull())
163 *fLog << "<Title=" << title << "> ";
164 *fLog << "created." << endl;
165
166 file->SetOption(option); // IMPORTANT!
167 file->SetBit(kMustCleanup);
168 ResetBit(kIsNotOwner);
169 return file;
170 }
171
172 fOut = file;
173 fOut->SetBit(kMustCleanup);
174 SetBit(kIsNotOwner);
175
176 return fOut;
177}
178
179// --------------------------------------------------------------------------
180//
181// Default constructor. It is there to support some root stuff.
182// Don't use it.
183//
184MWriteRootFile::MWriteRootFile() : fOut(NULL)
185{
186 Init();
187}
188
189// --------------------------------------------------------------------------
190//
191// Use this constructor to run in a special mode.
192//
193// In this mode for each input file a new output file is written. This
194// happens in ReInit.
195//
196// comp: Compression Level (see TFile, TBranch)
197// rule: Rule to create output file name (see SubstituteName())
198// overwrite: Allow newly created file to overwrite old files ("RECREATE")
199// ftitle: File title stored in the file (see TFile)
200// name, title: Name and title of this object
201//
202// Until the first file is opened a dummy file with name /dev/null is
203// opened to allow creation of trees and branches in the file.
204// To distinguish between different /dev/null-files the given title is used.
205//
206MWriteRootFile::MWriteRootFile(const Int_t comp,
207 const char *rule,
208 const Option_t *option,
209 const char *ftitle,
210 const char *name,
211 const char *title) : fSplitRule(rule)
212{
213 Init(name, title);
214
215 //
216 // Open a TFile in dummy mode! This is necessary to be able to create
217 // the trees and branches, which are then (in ReInit) moved to
218 // a valid file. (Stupid workaround - but does a good job)
219 //
220 fOut = OpenFile("/dev/null", option, ftitle, comp);
221}
222
223// --------------------------------------------------------------------------
224//
225// Specify the name of the root file. You can also give an option ("UPDATE"
226// and "RECREATE" would make sense only) as well as the file title and
227// compression factor. To a more detaild description of the options see
228// TFile.
229//
230// To create a memory based TTree use
231// fname = name of TTree
232// option = "memory"
233// Make sure you do not read from a tree with the same name!
234//
235MWriteRootFile::MWriteRootFile(const char *fname,
236 const Option_t *option,
237 const char *ftitle,
238 const Int_t comp,
239 const char *name,
240 const char *title) : fOut(NULL)
241{
242 Init(name, title);
243
244 TString opt(option);
245 opt.ToLower();
246
247 //
248 // Check if we are writing to memory
249 //
250 if (opt.Contains("memory", TString::kIgnoreCase))
251 {
252 fSplitRule = fname;
253 return;
254 }
255
256 //
257 // If no name is given we open the TFile in some kind of dummy mode...
258 //
259 TString str(fname);
260 if (str.IsNull())
261 {
262 fOut = new TFile("/dev/null", "READ", ftitle, comp);
263 fOut->SetBit(kMustCleanup);
264 return;
265 }
266
267 if (!str.EndsWith(".root", TString::kIgnoreCase))
268 str += ".root";
269
270 //
271 // Open the rootfile
272 //
273 fOut = OpenFile(str, opt, ftitle, comp);
274}
275
276// --------------------------------------------------------------------------
277//
278// Prints some statistics about the file to the screen. And closes the file
279// properly.
280//
281void MWriteRootFile::Close()
282{
283 //
284 // Print some statistics to the looging out.
285 //
286 if (fOut && !TestBit(kIsNotOwner))
287 {
288 Print();
289
290 //
291 // If the file is still open (no error) write the keys. This is necessary
292 // for appearance of the all trees and branches.
293 //
294 if (IsFileOpen())
295 fOut->Write();
296
297 //
298 // Delete the file. This'll also close the file (if open)
299 //
300 *fLog << inf3 << "Closing file " << fOut->GetName() << "." << endl;
301 delete fOut;
302
303 //
304 // Remark:
305 // - Trees are automatically deleted by the the file
306 // (unless file.SetDirectory(0) was called)
307 // - Branches are automatically deleted by the tree destructor
308 //
309 }
310
311 fOut = 0;
312}
313
314// --------------------------------------------------------------------------
315//
316// call Close()
317//
318MWriteRootFile::~MWriteRootFile()
319{
320 Close();
321}
322
323// --------------------------------------------------------------------------
324//
325// Prints all trees with the actually number of written entries to log-out.
326//
327void MWriteRootFile::Print(Option_t *) const
328{
329 if (!fOut)
330 return;
331
332 *fLog << all << underline << "File: " << GetFileName() << dec << endl;
333
334 Bool_t cont = kFALSE;
335
336 TObject *obj;
337 TIter NextBranch(&fBranches);
338 while ((obj=NextBranch()))
339 {
340 MRootFileBranch *b = (MRootFileBranch*)obj;
341
342 if (!b->GetTree() || b->GetTree()->TestBit(kIsNewTree))
343 continue;
344
345 TBranch *branch = b->GetBranch();
346
347 TString name = b->GetTree()->GetName();
348 name += '.';
349 name += branch->GetName();
350
351 *fLog << " + " << name.Strip(TString::kTrailing, '.') << ": \t" << (ULong_t)branch->GetEntries() << " entries." << endl;
352 cont = kTRUE;
353 }
354
355 TTree *t = NULL;
356 TIter NextTree(&fTrees);
357 while ((t=(TTree*)NextTree()))
358 if (t->TestBit(kIsNewTree))
359 {
360 *fLog << " + " << t->GetName() << ": \t" << (ULong_t)t->GetEntries() << " entries." << endl;
361 cont = kTRUE;
362 }
363
364 TIter NextKey(fOut->GetList());
365
366 while ((obj=NextKey()))
367 {
368 if (!obj->InheritsFrom(TTree::Class()))
369 continue;
370
371 if (fTrees.FindObject(obj) && obj->TestBit(kIsNewTree))
372 continue;
373
374 *fLog << " - " << obj->GetName() << ": \t" << (ULong_t)((TTree*)obj)->GetEntries() << " entries." << endl;
375 cont = kTRUE;
376 }
377
378 if (!cont)
379 *fLog << " No contents." << endl;
380
381 *fLog << endl;
382}
383
384// --------------------------------------------------------------------------
385//
386// Add a new Container to list of containers which should be written to the
387// file. Give the name of the container which will identify the container
388// in the parameterlist. tname is the name of the tree to which the
389// container should be written (Remark: one tree can hold more than one
390// container). The default is the same name as the container name.
391// You can slso specify a title for the tree. This is only
392// used the first time this tree in 'mentioned'. As default the title
393// is the name of the tree.
394//
395void MWriteRootFile::AddContainer(const char *cname, const char *tname, Bool_t must)
396{
397 if (!fOut && !tname)
398 tname = fSplitRule;
399
400 TIter Next(&fBranches);
401 TObject *o=0;
402 while ((o=Next()))
403 if (TString(o->GetName())==TString(tname) && TString(o->GetTitle())==TString(cname))
404 {
405 *fLog << warn;
406 *fLog << "WARNING - Container '" << cname << "' in Tree '" << tname << "' already scheduled... ignored." << endl;
407 return;
408 }
409
410 //
411 // create a new entry in the list of branches to write and
412 // add the entry to the list.
413 //
414 MRootFileBranch *entry = new MRootFileBranch(AddSerialNumber(cname), tname, must);
415 fBranches.AddLast(entry);
416
417 if (tname && tname[0])
418 AddToBranchList(Form("%s.%s", (const char*)AddSerialNumber(cname), tname));
419}
420
421// --------------------------------------------------------------------------
422//
423// Add a new Container to list of containers which should be written to the
424// file. Give the pointer to the container. tname is the name of the tree to
425// which the container should be written (Remark: one tree can hold more than
426// one container). The default is the same name as the container name.
427// You can slso specify a title for the tree. This is only
428// used the first time this tree in 'mentioned'. As default the title
429// is the name of the tree.
430//
431void MWriteRootFile::AddContainer(MParContainer *cont, const char *tname, Bool_t must)
432{
433 if (!fOut && !tname)
434 tname = fSplitRule;
435
436 TIter Next(&fBranches);
437 TObject *o=0;
438 while ((o=Next()))
439 if (TString(o->GetName())==TString(tname) &&
440 static_cast<MRootFileBranch*>(o)->GetContainer()==cont)
441 {
442 *fLog << warn;
443 *fLog << "WARNING - Container " << cont << " in Tree '" << tname << "' already scheduled... ignored." << endl;
444 return;
445 }
446
447 //
448 // create a new entry in the list of branches to write and
449 // add the entry to the list.
450 //
451 MRootFileBranch *entry = new MRootFileBranch(cont, tname, must);
452 fBranches.AddLast(entry);
453}
454
455// --------------------------------------------------------------------------
456//
457// If you want to copy a full tree (or some branches of some trees)
458// completely from one file to another one you can use this
459//
460void MWriteRootFile::AddCopySource(const char *tname, const char *bname)
461{
462 fCopies.Add(new TNamed(tname, bname?bname:"*"));
463 fCopies.Sort();
464}
465
466// --------------------------------------------------------------------------
467//
468// Add a new Container to list of containers which should be written to the
469// file. Give the pointer to the container. tname is the name of the tree to
470// which the container should be written (Remark: one tree can hold more than
471// one container). The default is the same name as the container name.
472// You can slso specify a title for the tree. This is only
473// used the first time this tree in 'mentioned'. As default the title
474// is the name of the tree.
475//
476Bool_t MWriteRootFile::GetContainer(MParList *pList)
477{
478 //
479 // loop over all branches which are 'marked' as branches to get written.
480 //
481 MRootFileBranch *entry;
482
483 TIter Next(&fBranches);
484 while ((entry=(MRootFileBranch*)Next()))
485 {
486 //
487 // Get the pointer to the container. If the pointer is NULL it seems,
488 // that the user identified the container by name.
489 //
490 MParContainer *cont = entry->GetContainer();
491 if (!cont)
492 {
493 //
494 // Get the name and try to find a container with this name
495 // in the parameter list.
496 //
497 const char *cname = entry->GetContName();
498 cont = (MParContainer*)pList->FindObject(cname);
499 if (!cont)
500 {
501 //
502 // No corresponding container is found
503 //
504 if (entry->MustHave())
505 {
506 *fLog << err << "Cannot find parameter container '" << cname << "'." << endl;
507 return kFALSE;
508 }
509
510 *fLog << inf2 << "Unnecessary parameter container '" << cname << "' not found..." << endl;
511 delete fBranches.Remove(entry);
512 continue;
513 }
514
515 //
516 // The container is found. Put the pointer into the entry.
517 //
518 entry->SetContainer(cont);
519 }
520
521 //
522 // Get container name, tree name and tree title of this entry.
523 //
524 const char *cname = cont->GetName();
525 const char *tname = entry->GetName();
526 const TString ttitle(Form("Tree containing %s", cont->GetDescriptor().Data()));
527
528 //
529 // if the tree name is NULL this idetifies it to use the default:
530 // the container name.
531 //
532 if (tname[0] == '\0')
533 tname = cname;
534
535 //
536 // Check if the tree is already existing (part of the file or memory)
537 //
538 TTree *tree = fOut ? (TTree*)fOut->Get(tname) : dynamic_cast<TTree*>(gROOT->FindObject(tname));
539 if (!fOut && tree)
540 {
541 if (tree->GetCurrentFile())
542 {
543 *fLog << err;
544 *fLog << "ERROR - You are trying to write data into a memory stored root tree," << endl;
545 *fLog << " because you either called the default constructor or have" << endl;
546 *fLog << " instantiated MWriteRootFile using the write option 'memory'." << endl;
547 *fLog << " This tree '" << tname << "' is already existing in" << endl;
548 *fLog << " memory (gROOT->FindObject) and is already belonging to a" << endl;
549 *fLog << " file (" << tree->GetCurrentFile()->GetName() << ")." << endl;
550 *fLog << " This can - for example - happen if you are reading from a" << endl;
551 *fLog << " tree with the same name. The easiest solution in this case" << endl;
552 *fLog << " is to change the name of the tree you want to write to." << endl;
553 *fLog << endl;
554 return kFALSE;
555 }
556 *fLog << inf << "Tree '" << tname << "' found already in Memory... using." << endl;
557 }
558
559 if (!tree)
560 {
561 //
562 // if the tree doesn't exist create a new tree. Use the tree
563 // name as title if title is NULL.
564 // And add the tree to the list of trees
565 //
566 TDirectory *save = gDirectory;
567 if (fOut)
568 fOut->cd();
569 else
570 gROOT->cd();
571
572 tree = new TTree(tname, ttitle, fOut ? 99 : 1);
573 fTrees.AddLast(tree);
574
575 //
576 // If the tree does not already exist in the file mark this
577 // tree as a branch created by MWriteRootFile
578 //
579 tree->SetBit(kIsNewTree);
580
581 *fLog << inf << "Tree " << tname << " created in " << gDirectory->GetName() << endl;
582
583 gDirectory = save;
584 }
585
586 //
587 // In case the file is opened as 'UPDATE' the tree may still not
588 // be in the list. Because it neither was created previously,
589 // nor this time, so the corresponding entries is marked as a
590 // single branch to be filled. --> Add it to the list of trees.
591 //
592 if (!fTrees.FindObject(tree))
593 fTrees.AddLast(tree);
594
595 //
596 // Now we have a valid tree. Search the list of trees for this tree
597 // Add a pointer to the entry in the tree list to this branch-entry
598 //
599 entry->SetTree(tree);
600
601 TString branchname(cname);
602 branchname.Append(".");
603
604 //
605 // Try to get the branch from the file.
606 // If the branch already exists the user specified one branch twice.
607 //
608 TBranch *branch = tree->GetBranch(branchname);
609 if (branch)
610 {
611 *fLog << inf << "Branch '" << cname << "' already existing... updating." << endl;
612 branch->SetAddress(entry->GetAddress());
613
614 if (!fSplitRule.IsNull() && fOut)
615 {
616 *fLog << warn << endl;
617 *fLog << "WARNING: You are updating an existing branch. For this case" << endl;
618 *fLog << " file-splitting mode is not allowed... disabled!" << endl;
619 *fLog << endl;
620 fSplitRule = "";
621 }
622 }
623 else
624 {
625 //
626 // Create a new branch in the actual tree. The branch has the name
627 // container name. The type of the container is given by the
628 // ClassName entry in the container. The Address is the address of a
629 // pointer to the container (gotten from the branch entry). As
630 // Basket size we specify a (more or less) common default value.
631 // The containers should be written in Splitlevel=1
632 //
633 *fLog << inf << "Creating Branch '" << cname << "' ";
634 if ((TString)cname!=(TString)cont->ClassName())
635 *fLog << "[" << cont->ClassName() << "] ";
636 *fLog << "in tree " << tree->GetName() << "... " << flush;
637
638 branch = tree->Branch(branchname, cont->ClassName(), entry->GetAddress());
639
640 //
641 // If the branch couldn't be created we have a problem.
642 //
643 if (!branch)
644 {
645 *fLog << endl;
646 *fLog << err << "Unable to create branch '" << cname << "'." << endl;
647 return kFALSE;
648 }
649
650 *fLog << "done." << endl;
651
652 if (!tree->TestBit(kIsNewTree) && !fSplitRule.IsNull())
653 {
654 *fLog << warn << endl;
655 *fLog << "WARNING: You have created a new branch in an existing tree." << endl;
656 *fLog << " For this case file-splitting mode is not allowed... disabled!" << endl;
657 *fLog << endl;
658 fSplitRule= "";
659 }
660 }
661
662 //
663 // Tell the entry also which branch belongs to it (this is necessary
664 // for branches belonging to already existing tree, UPDATE-mode)
665 //
666 entry->SetBranch(branch);
667 }
668
669 return kTRUE;
670}
671
672// --------------------------------------------------------------------------
673//
674// Checks all given containers (branch entries) for the write flag.
675// If the write flag is set the corresponding Tree is marked to get filled.
676// All Trees which are marked to be filled are filled with all their
677// branches.
678// In case of a file opened in 'UPDATE' mode, single branches can be
679// filled, too. WARNING - for the moment there is no check whether
680// you filled the correct number of events into the branch, so that
681// each of the other branches in the tree has the correct corresponding
682// number of new entries in the new branch!
683// Be carefull: If only one container (corresponding to a branch) of a tree
684// has the write flag, all containers in this tree are filled!
685//
686Bool_t MWriteRootFile::CheckAndWrite()
687{
688 TObject *obj;
689
690 //
691 // Loop over all branch entries
692 //
693 TIter NextBranch(&fBranches);
694 while ((obj=NextBranch()))
695 {
696 MRootFileBranch *b = (MRootFileBranch*)obj;
697
698 //
699 // Check for the Write flag
700 //
701 if (!b->GetContainer()->IsReadyToSave())
702 continue;
703
704 //
705 // If the write flag of the branch entry is set, set the write flag of
706 // the corresponding tree entry.
707 //
708 if (b->GetTree()->TestBit(kIsNewTree))
709 b->GetTree()->SetBit(kFillTree);
710 else
711 {
712 if (!b->GetBranch()->Fill())
713 {
714 *fLog << err << "ERROR - Zero bytes written to branch '" << b->GetBranch()->GetName() << "'... abort." << endl;
715 return kFALSE;
716 }
717 }
718 }
719
720 //
721 // Loop over all tree entries
722 //
723 const Int_t n = fTrees.GetEntriesFast();
724
725 for (int idx=0; idx<n; idx++)
726 {
727 TTree *t = (TTree*)fTrees[idx];
728
729 //
730 // Check the write flag of the tree
731 //
732 if (!t->TestBit(kFillTree))
733 continue;
734
735 //
736 // If the write flag is set, fill the tree (with the corresponding
737 // branches/containers), delete the write flag and increase the number
738 // of written/filled entries.
739 //
740 t->ResetBit(kFillTree);
741
742 if (!t->Fill())
743 {
744 *fLog << err << "ERROR - Zero bytes written to tree '" << t->GetName() << "'... abort." << endl;
745 return kFALSE;
746 }
747 }
748
749 //
750 // If we are writing into memory we don't split into seperate files
751 //
752 if (!fOut || TestBit(kIsNotOwner))
753 return kTRUE;
754
755 //
756 // For more information see TTree:ChangeFile()
757 //
758 TTree *t0 = (TTree*)fTrees[0];
759 if (!t0 || fOut==t0->GetCurrentFile())
760 return kTRUE;
761
762 // FIXME: THIS IS EMITTED FOR ALL CONSEQUTIVE EVENTS!
763 *fLog << warn << endl;
764 *fLog << "WARNING - MWriteRootFile: Root's TTree/TFile has opened a new file" << endl;
765 *fLog << " automatically. You can change this behaviour using TTree::SetMaxTreeSize." << endl;
766 *fLog << " You won't be able to read splitted files correctly with MReadMarsFile if" << endl;
767 *fLog << " they have more than one entry in 'RunHeaders' or you try to read more than" << endl;
768 *fLog << " one of such sequences at once." << endl;
769 *fLog << endl;
770
771 return kTRUE;
772}
773
774// --------------------------------------------------------------------------
775//
776// Open a new file with the name fname. Move all trees and branches from the
777// old file to the new file.
778//
779Bool_t MWriteRootFile::ChangeFile(const char *fname)
780{
781 const Int_t compr = fOut ? fOut->GetCompressionLevel() : 0;
782 const TString title = fOut ? fOut->GetTitle() : "";
783 const TString opt = fOut ? fOut->GetOption() : "";
784
785 // Open new file with old setup
786 TFile *newfile = OpenFile(fname, opt, title, compr);
787 if (newfile && newfile==fOut)
788 {
789 *fLog << inf << "Found open file " << fname << "... using." << endl;
790 return kTRUE;
791 }
792 if (!newfile)
793 {
794 *fLog << err << "ERROR - Cannot open new file " << fname << endl;
795 return kFALSE;
796 }
797
798 if (!fOut)
799 {
800 *fLog << err << "ERROR - MWriteRootFile::ChangeFile... something went terribly wrong!" << endl;
801 *fLog << " fname: " << fname << endl;
802 *fLog << " Please start debugging!" << endl;
803 return kFALSE;
804 }
805
806 *fLog << inf << "Open new file " << fname << " (Title=" << title << ", Option=" << opt << ", Compression=" << compr << ")" << endl;
807
808 // Print statistics of old file
809 const TString n = GetFileName();
810 if (!n.IsNull() && n!=TString("/dev/null"))
811 Print();
812
813 if (fOut->IsOpen())
814 fOut->Write();
815
816 // Move all trees from the old file to the new file
817 TObject *obj=0;
818 while ((obj = fOut->GetList()->First()))
819 {
820 // Remove obj from old file (otherwise deleting
821 // the old file will delete the objs)
822 fOut->GetList()->Remove(obj);
823
824 // If this is not a tree do nothing.
825 if (!obj->InheritsFrom(TTree::Class()))
826 continue;
827
828 // process all trees in the old file
829 TTree *t = (TTree*)obj;
830
831 // reset and move to new file (this is done implicitly for all branches)
832 t->Reset();
833 t->SetDirectory(newfile);
834 }
835
836 // Close/delete the old file (keys already written above)
837 *fLog << inf3 << "Closing file " << fOut->GetName() << "." << endl;
838 delete fOut;
839
840 // Replace current with new file
841 fOut = newfile;
842
843 // Change current directory to new file
844 gFile = fOut;
845
846 return kTRUE;
847}
848
849// --------------------------------------------------------------------------
850//
851// A rule looks like:
852// "s/source/destination/"
853//
854// For more details on regular expression see a proper documentation,
855// for example, "man 7 regex" if installed, or TPRegexp.
856//
857// Here is an example:
858//
859// Example:
860// inputfile: /data/MAGIC/Period016/rootdata/20040621_23210_D_Mkn421_E.root
861// rule: /([0-9]+_[0-9]+)_D_(.*[.]root)/\\/outpath\\/$1_Y_$2/
862// outfile: /outpath/20040621_23210_Y_Mkn421_E.root
863//
864// Please make sure that all / in your rules are correctly escaped, i.e.
865// in the string stored in memory it must look like \/ and in the string
866// your set in your program it must look \\/.
867//
868// Note, that this function has been made static to allow your to
869// test your split rules, i.e. regular expressions.
870//
871TString MWriteRootFile::SubstituteName(const char *regexp, TString fname)
872{
873 // Remove the path from the filename
874 if (fname.Last('/')>=0)
875 fname.Remove(0, fname.Last('/')+1);
876
877 // Regular expression to split the rule into its contents
878 static const TString sed("s/((\\\\/|[^/])*)/((\\\\/|[^/])*)/([gimosxd]*)");
879
880 // Do splitting
881 TObjArray *subStrL = TPRegexp(sed).MatchS(regexp);
882 if (subStrL->GetEntries()!=6)
883 {
884 gLog << err << "ERROR - SubstituteName: Evaluating regexp " << regexp << " failed." << endl;
885 subStrL->Print();
886 delete subStrL;
887 return "";
888 }
889
890 /*const*/ TString reg = (*subStrL)[1]->GetName(); // Regular expression to search for
891 /*const*/ TString tar = (*subStrL)[3]->GetName(); // Regular expression for replacing
892 const TString mod = (*subStrL)[5]->GetName(); // Possible modifiers (e.g. 'a')
893
894 delete subStrL;
895
896 // Unescpae slashes in paths
897 reg.ReplaceAll("\\/", "/");
898 tar.ReplaceAll("\\/", "/");
899
900 // Do substitution
901 const Int_t nrSub = TPRegexp(reg).Substitute(fname, tar, mod);
902 if (nrSub==0)
903 {
904 gLog << err << "ERROR - Substituting due to SplitRule failed." << endl;
905 gLog << " Source FileName: " << fname << endl;
906 gLog << " Search Rexexp: " << reg << endl;
907 gLog << " Replace Rexexp: " << tar << endl;
908 gLog << " Modifiers: " << mod << endl;
909 return "";
910 }
911
912 return fname;
913}
914
915// --------------------------------------------------------------------------
916//
917// Writes a copy of the TTree t to the currently open file using
918// TTree::CloneTree()
919//
920void MWriteRootFile::CopyTree(TTree &t) const
921{
922 TString out = "Copy of tree ";
923 out += t.GetName();
924 out += " in progress...";
925
926 if (fDisplay)
927 fDisplay->SetStatusLine2(out);
928
929 *fLog << inf << out << flush;
930
931 // When a new file has been opened the old clone (if existing) has
932 // been moved to the new file. We could now use CopyTree but then
933 // we would have to unpack all data and repack it. Instead
934 // we delete the moved old tree.
935 // FIXME: In priciple we could delete a "wrong" tree with the same name.
936 // Should we flag the clones and delete them in ChangeFile?
937 TObject *old = fOut->GetList()->Remove(fOut->GetList()->FindObject(t.GetName()));
938 delete old;
939
940 // Now we clone the tree without unpacking and repacking.
941 // When it has not been moved it will be deleted in the TFile destructor
942 /*TTree *clone =*/ t.CloneTree(-1, "fast");
943 //clone->Write();
944 //delete clone;
945
946 *fLog << "done." << endl;
947
948 if (fDisplay)
949 {
950 out += " done.";
951 fDisplay->SetStatusLine2(out);
952 }
953}
954
955// --------------------------------------------------------------------------
956//
957// Make all copies requested from the currently open file into the new
958// file.
959//
960Bool_t MWriteRootFile::MakeCopies(const char *fname) const
961{
962 if (fCopies.GetEntries()==0)
963 return kTRUE;
964
965 TFile *file = dynamic_cast<TFile*>(gROOT->GetListOfFiles()->FindObject(fname));
966 if (!file)
967 {
968 *fLog << err << "ERROR - MakeCopies: File " << fname << " not found in gROOT->GetListOfFiles()... abort." << endl;
969 return kFALSE;
970 }
971
972 TIter Next(&fCopies);
973 TObject *o=0;
974 TTree *t=0;
975
976 fOut->cd();
977 while ((o=Next()))
978 {
979 TTree *gettree = dynamic_cast<TTree*>(file->Get(o->GetName()));
980 if (!gettree)
981 {
982 *fLog << err << "ERROR - MakeCopies: Tree " << o->GetName() << " not found in file " << fname << "... abort." << endl;
983 return kFALSE;
984 }
985
986 gettree->SetBranchStatus(o->GetTitle(), 1);
987
988 // First Execution
989 if (t==gettree)
990 continue;
991
992 // Check if its the first call
993 if (t)
994 CopyTree(*t);
995 t = gettree;
996 }
997
998 if (t)
999 CopyTree(*t);
1000
1001 return kTRUE;
1002}
1003
1004// --------------------------------------------------------------------------
1005//
1006// ReInit. If file splitting is not allowed call MWriteFile::ReInit.
1007//
1008// In other cases get MRead from the TaskList (splitting is switched of if
1009// this is impossible).
1010//
1011// Convert the input- into a new output file-name.
1012//
1013// Open a new file, change all trees to the new file (calling ChangeFile()),
1014// and close the old one.
1015//
1016// Call MWriteFile::ReInit()
1017//
1018Bool_t MWriteRootFile::ReInit(MParList *pList)
1019{
1020 MRead *read = (MRead*)pList->FindTask("MRead");
1021 if (fSplitRule.IsNull() && fCopies.GetEntries()>0 && fOut)
1022 {
1023 if (!read)
1024 {
1025 *fLog << err;
1026 *fLog << "ERROR: No Task 'MRead' found in the tasklist. This task is" << endl;
1027 *fLog << " necessary to get the filename. Without a filename file" << endl;
1028 *fLog << " AddCopySource cannot be used... abort." << endl;
1029 *fLog << endl;
1030 return kFALSE;
1031 }
1032 if (!MakeCopies(read->GetFullFileName()))
1033 return kFALSE;
1034
1035 }
1036
1037 if (fSplitRule.IsNull() || !(fOut || TestBit(kIsNotOwner)))
1038 return MWriteFile::ReInit(pList);
1039
1040 if (!read)
1041 {
1042 *fLog << warn;
1043 *fLog << "WARNING: No Task 'MRead' found in the tasklist. This task is" << endl;
1044 *fLog << " necessary to get the filename. Without a filename file" << endl;
1045 *fLog << " file splitting is not allowed... disabled!" << endl;
1046 *fLog << endl;
1047 fSplitRule = "";
1048 return kTRUE;
1049 }
1050
1051
1052 const TString oldname = read->GetFullFileName();
1053 const TString newname = SubstituteName(fSplitRule, oldname);
1054 if (!ChangeFile(newname))
1055 return kFALSE;
1056
1057 if (!MakeCopies(oldname))
1058 return kFALSE;
1059
1060 return MWriteFile::ReInit(pList);
1061}
1062
1063// --------------------------------------------------------------------------
1064//
1065// return open state of the root file. If the file is 'memory' kTRUE is
1066// returned.
1067//
1068Bool_t MWriteRootFile::IsFileOpen() const
1069{
1070 if (!fOut)
1071 return kTRUE;
1072
1073 const char *n = fOut->GetName();
1074 return n==0 || *n==0 ? kTRUE : fOut->IsOpen();
1075}
1076
1077// --------------------------------------------------------------------------
1078//
1079// return name of the root-file. If the file is "memory" "<memory>" is
1080// returned.
1081//
1082const char *MWriteRootFile::GetFileName() const
1083{
1084 if (!fOut)
1085 return "<memory>";
1086
1087 const char *n = fOut->GetName();
1088 return n==0 || *n==0 ? "<dummy>" : n;
1089}
1090
1091// --------------------------------------------------------------------------
1092//
1093// cd into file. See TFile::cd(). If the file is "memory" kTRUE is returned.
1094//
1095Bool_t MWriteRootFile::cd(const char *path)
1096{
1097 return fOut ? fOut->cd(path) : kTRUE;
1098}
1099
1100// --------------------------------------------------------------------------
1101//
1102// If the output file is deleted set fOut to NULL.
1103// Call MTask::RecursiveRemove
1104//
1105void MWriteRootFile::RecursiveRemove(TObject *obj)
1106{
1107 if (obj==fOut)
1108 fOut=NULL;
1109
1110 MWriteFile::RecursiveRemove(obj);
1111}
1112
1113// --------------------------------------------------------------------------
1114//
1115// Implementation of SavePrimitive. Used to write the call to a constructor
1116// to a macro. In the original root implementation it is used to write
1117// gui elements to a macro-file.
1118//
1119void MWriteRootFile::StreamPrimitive(ostream &out) const
1120{
1121 out << " MWriteRootFile " << GetUniqueName();
1122 if (fOut)
1123 {
1124 out << "(\"";
1125 out << fOut->GetName() << "\", \"";
1126 out << fOut->GetOption() << "\", \"";
1127 out << fOut->GetTitle() << "\", ";
1128 out << fOut->GetCompressionLevel();
1129 out << ")";
1130 }
1131 out << ";" << endl;
1132
1133 if (fName!=gsDefName)
1134 out << " " << GetUniqueName() << ".SetName(\"" << fName << "\");" << endl;
1135 if (fTitle!=gsDefTitle)
1136 out << " " << GetUniqueName() << ".SetTitle(\"" << fTitle << "\");" << endl;
1137
1138 MRootFileBranch *entry;
1139 TIter Next(&fBranches);
1140 while ((entry=(MRootFileBranch*)Next()))
1141 {
1142 out << " " << GetUniqueName() << ".AddContainer(";
1143
1144 if (entry->GetContainer())
1145 {
1146 entry->GetContainer()->SavePrimitive(out);
1147 out << "&" << entry->GetContainer()->GetUniqueName();
1148 }
1149 else
1150 out << "\"" << entry->GetContName() << "\"";
1151
1152 out << ", \"" << entry->GetName() << "\"";
1153 if (!entry->MustHave())
1154 out << ", kFALSE";
1155
1156 out <<");" << endl;
1157 }
1158}
1159
Note: See TracBrowser for help on using the repository browser.