AANTupleStream.cxx 21.6 KB
Newer Older
1
/*
2
  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
3
4
5
6
7
8
9
10
11
*/

#include "AnalysisTools/AANTupleStream.h"
#include "AnalysisTools/AANTupleParams.h"

#include "AnalysisUtils/AANTTreeMap.h"

#include "AthenaPoolUtilities/AthenaAttributeList.h"

12
#include "Gaudi/Interfaces/IOptionsSvc.h"
13
14
15
16
17
18
19
20
21
#include "GaudiKernel/IAlgManager.h"
#include "GaudiKernel/ISvcLocator.h"
#include "GaudiKernel/IAddressCreator.h"
#include "GaudiKernel/IOpaqueAddress.h"
#include "GaudiKernel/MsgStream.h"
#include "GaudiKernel/ITHistSvc.h"
#include "GaudiKernel/ListItem.h"
#include "GaudiKernel/ServiceHandle.h"
#include "GaudiKernel/IIoComponentMgr.h"
22

23
24
25
26
27
28
29
30
31
32
33
#include "StoreGate/StoreGateSvc.h"
#include "SGTools/DataProxy.h"
#include "PersistentDataModel/DataHeader.h"
#include "StoreGate/DataHandle.h"

#include "RootCollection/AttributeListLayout.h"
#include "CoralBase/AttributeList.h"
#include "CoralBase/AttributeListSpecification.h"

#include "EventInfo/EventInfo.h"
#include "EventInfo/EventID.h"
34
#include "xAODEventInfo/EventInfo.h"
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

#include "TFile.h"
#include "TTree.h"
#include "TText.h"
#include "TBranch.h"
#include "TInterpreter.h"

#include <map>
#include <string>
#include <algorithm>

using namespace AANTupleParams;

// Standard Constructor
AANTupleStream::AANTupleStream(const std::string& name, ISvcLocator* pSvcLocator) 
50
  : AthLegacySequence(name, pSvcLocator),
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
    m_persSvc      ("EventPersistencySvc", name),
    m_attribSpec(0),
    m_schemaDone(false),
    m_tree(0),
    m_tokenBranch(0),
    m_tHistSvc     ("THistSvc", name)
{
  declareProperty("OutputName",           m_fileName="AANTuple.root");
  declareProperty("ExtraRefNames",        m_extraRefNames);
  declareProperty("WriteInputDataHeader", m_writeInputDH=false);
  declareProperty("ExistDataHeader",      m_existDH=true);
  declareProperty("StreamName",           m_streamName=c_streamName);
  declareProperty("LateSchemaWriting",    m_lateSchema=false);
  declareProperty("TreeName",             m_treeName=c_treeName);
  declareProperty("Macro",                m_macro="");
  declareProperty("Members",              m_membersNames);
  declareProperty("FilterAlgs",           m_acceptNames);

  m_tokenCString[0] = '\0';
}


// Standard Destructor
AANTupleStream::~AANTupleStream()  
{
}


// initialize data writer
StatusCode AANTupleStream::initialize() 
{
  ATH_MSG_DEBUG ("In initialize ");
  // register with the I/O component manager
  {
    ServiceHandle<IIoComponentMgr> iomgr ("IoComponentMgr", this->name());
    if ( !iomgr.retrieve().isSuccess() ) {
      ATH_MSG_ERROR ("Could not retrieve IIoComponentMgr/IoComponentMgr !");
      return StatusCode::FAILURE;
    }
    if ( !iomgr->io_register (this).isSuccess() ) {
      ATH_MSG_ERROR ("Could not register with the I/O component mgr !");
      return StatusCode::FAILURE;
    }
    if ( !iomgr->io_register (this,
			      IIoComponentMgr::IoMode::WRITE,
			      m_fileName).isSuccess() ) {
      ATH_MSG_ERROR ("Could not register [" << this->name() << "]["
		     << m_fileName << "] with the I/O component manager !");
      return StatusCode::FAILURE;
    }
  }

  // StoreGateSvc
  StatusCode sc = evtStore().retrieve();
  if ( !sc.isSuccess() )
    {
      ATH_MSG_ERROR ("Could not locate default store");
      return sc;
    }

  // set up the persistency service:
  sc = m_persSvc.retrieve();
  if ( !sc.isSuccess() )
    {
      ATH_MSG_ERROR ("Could not locate persistency service");
      return sc;
    }

  // instantiate AttrListSpec and add attributes for Run# and Event# 
  m_attribSpec = new coral::AttributeListSpecification;
  m_attribSpec->extend( name_RunNumber,   "unsigned int" );
  m_attribSpec->extend( name_EventNumber, "unsigned int" );

  // Add on specification for extra refs
  std::vector<std::string> extraRefs = m_extraRefNames.value();
  for (unsigned int i = 0; i < extraRefs.size(); ++i)
    {
      // Append _ref to name of attribute
      std::string name = extraRefs[i] + "_ref";
      m_attribSpec->extend(name, "string");
    }

  if (!m_lateSchema) {
    sc = initSchema();
    if (sc.isFailure())
      return sc;
  }

  // initialize sub-algos
  sc = initialize_subAlgos();
  if ( sc.isFailure() )
    {
      ATH_MSG_ERROR ("Could not initialize sub-algos");
      return sc;
    }      

  // get filters
  sc = getFilters();
  if ( sc.isFailure() )
    {
      ATH_MSG_ERROR ("Could not get filters");
      return sc;
    }      

  ATH_MSG_DEBUG ("End initialize ");
156
157

  return AthLegacySequence::initialize();
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
}


// initialize output collection
StatusCode AANTupleStream::initCollection() 
{
  // write schema
  writeAttributeListSpecification();

  // setup TTree
  setupTree();

  // setup Token
  m_tokenBranch = m_tree->GetBranch(c_tokenBranchName);
  m_tokenBranch->SetAddress(m_tokenCString);

  return StatusCode::SUCCESS;
}


// terminate data writer
StatusCode AANTupleStream::finalize() 
{
  ATH_MSG_INFO ("finalize");

  // exec macro
  if (m_macro != "")
    {
      // save current dir
      std::string curDir = gDirectory->GetPath();
      // go to the root dir of output file
      gDirectory->cd((m_fileName+":/").c_str());
      // exec
      // G__exec_tempfile(m_macro.c_str());
      // MN: that should be the equivalent new call:
      gInterpreter->ExecuteMacro(m_macro.c_str());
      // back to the current dir
      gDirectory->cd(curDir.c_str());
    }

198
  return AthLegacySequence::finalize();
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
}


// Work entry point
StatusCode AANTupleStream::execute() 
{
  StatusCode sc;

  if (!m_schemaDone) {
    sc = initSchema();
    if (sc.isFailure())
      return sc;
  }

  // execute sub-algos
  sc = execute_subAlgos();
  if ( sc.isFailure() )
    {
      ATH_MSG_ERROR ("Could not execute sub-algos");
      return sc;
    }      

  std::map<std::string,std::string> inputRefs;
  std::string ref;

  // Get tokens specified by item list
  if (m_existDH)
    {
      // get token
      const DataHandle<DataHeader> beg; 
      const DataHandle<DataHeader> ending; 
      StatusCode status = evtStore()->retrieve(beg,ending);
      if (status.isFailure() || beg==ending)
	{
	  ATH_MSG_WARNING ("No DataHeaders present in StoreGate");
	  return  StatusCode::FAILURE;
	}

      // look for header
      for (; beg != ending; ++beg)
	if (m_writeInputDH == beg->isInput()) break;

      if (beg==ending)
	{
	  ATH_MSG_WARNING ("No appropriate DataHeader present in StoreGate");
	  return  StatusCode::FAILURE;
	}

      // get the ref
      while (getRef(ClassID_traits<DataHeader>::ID(), beg.key(), ref) == StatusCode::FAILURE)
	{
	  ++beg;
	  if (beg==ending)
	    {
	      ATH_MSG_ERROR ("No refs found");
	      return StatusCode::FAILURE;
	    }
	}

      ATH_MSG_DEBUG ("Found token: Key=" << beg.key() << ", Ref=" << ref);

      // Get a single input header ref if requested
      const DataHeader* hdr=0;
      hdr = beg;
      if (hdr->sizeProvenance())
	{
	  std::vector<DataHeaderElement>::const_iterator it =
	    (const_cast<DataHeader*>(hdr)->beginProvenance());
	  std::vector<DataHeaderElement>::const_iterator itE = 
	    (const_cast<DataHeader*>(hdr)->endProvenance());
	  // grab refs for those
	  for (; it!=itE; ++it)
	    {
	      std::string tmpRef = (*it).getToken() != NULL
		? (*it).getToken()->toString()
		: "";
	      inputRefs.insert(std::make_pair(it->getKey(),tmpRef));
	      ATH_MSG_DEBUG ("Found ref for input header: Key=" << it->getKey()
			     << ", Ref=" << tmpRef);
	    }
	}
    }
  
  // create Attrlist, add attributes and if extra ref is requested, append to the end

  ATH_MSG_DEBUG ("create AttributeList");
  // AthenaAttributeList  newAttr(*m_attribSpec);
  coral::AttributeList newAttr(*m_attribSpec);

288
  unsigned int runNumber   = 0;
289
  unsigned int eventNumber = 0;
290

291
292
  // retrieve event info
  const EventInfo* eventInfo;
293
294
  eventInfo = evtStore()->tryConstRetrieve<EventInfo>();
  if ( !eventInfo )
295
    {
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
      // Try to get the xAOD::EventInfo
      const xAOD::EventInfo* eventInfoX{nullptr};
      sc = evtStore()->retrieve(eventInfoX);
      if (sc.isFailure())
        {
          ATH_MSG_ERROR ("Cannot get event info.");
          return sc;
        }
      else
        {
          runNumber   = eventInfoX->runNumber();
          eventNumber = eventInfoX->eventNumber();
        }
    }
  else
    {
      runNumber   = eventInfo->event_ID()->run_number();
      eventNumber = eventInfo->event_ID()->event_number();
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
    }

  // add global event tag data
  newAttr[ name_RunNumber   ].setValue( runNumber );
  newAttr[ name_EventNumber ].setValue( eventNumber );

  // add back nav ref's
  ATH_MSG_DEBUG ("Append extra ref");
  std::vector<std::string> extraRefs = m_extraRefNames.value();
  std::map<std::string,std::string>::iterator itRef  = inputRefs.begin();
  std::map<std::string,std::string>::iterator itRefE = inputRefs.end();
  for (; itRef != itRefE; ++itRef)
    {
      std::string name = itRef->first + "_ref";
      if (extraRefs.end() != std::find(extraRefs.begin(),extraRefs.end(),itRef->first))
	{
	  newAttr[name].setValue(std::string(itRef->second));
	  ATH_MSG_DEBUG (" Added extra ref to new attribute list - name: " 
			 << name << " " << itRef->second);
	}
    }

  // write if filters passed
  if (isEventAccepted())
    {
      ATH_MSG_DEBUG ("write attributes to collection");
  
      // write token plus attributes
      try
	{
	  writeTokenAttrList(ref, newAttr);
	} 
      catch (std::exception &e)
	{
	  ATH_MSG_ERROR 
	    ("Caught exception from collection add of Pool attributes. "
	     "Message: " << e.what());
	  return StatusCode::FAILURE;
	}
    }
  
  ATH_MSG_DEBUG ("done successfully");

  return StatusCode::SUCCESS;
}

  
void AANTupleStream::writeAttributeListSpecification()
{
  // go to the root dir of output file
364
  TDirectory::TContext save;
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
  gDirectory->cd((m_fileName+":/").c_str());

  AttributeListLayout all;
  // store schema in the schema object
  for( coral::AttributeListSpecification::const_iterator iter = m_attribSpec->begin();
       iter != m_attribSpec->end(); ++iter) {
     all.m_layout.push_back( make_pair( iter->name(), iter->typeName() ) );
  }
  // write schema object
  all.Write(c_attributeListLayoutName);
}


void AANTupleStream::setupTree()
{
  static std::map<std::string,char> typeDict;
  if (!typeDict.size())
    {
      typeDict["double"] = 'D';   
      typeDict["long double"] = 'D';    // only 64 bit doubles are supported 
      typeDict["float"] = 'F';
      typeDict["int"] = 'i';
      typeDict["unsigned int"] = 'I';
      typeDict["long"] = 'i';           // support for 64 bit integers introduced with ROOT 4.00/08 
      typeDict["unsigned long"] = 'I';  // support for 64 bit integers introduced with ROOT 4.00/08 
      typeDict["short"] = 's';
      typeDict["unsigned short"] = 'S';
      typeDict["char"] = 'b';           // AttributeLists's "get_root_type_char(...)" returned 'C' ??? 
      typeDict["unsigned char"] = 'B';  // AttributeLists's "get_root_type_char(...)" returned 's' ???
      typeDict["bool"] = 'B';           // AttributeLists's "get_root_type_char(...)" returned 'i' ???
      typeDict["string"] = 'C';
      typeDict["Token"] = 'C';
    }

  // go to the root dir of output file
400
  TDirectory::TContext save;
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
  gDirectory->cd((m_fileName+":/").c_str());
  
  // instantiate TTree
  m_tree = new TTree(m_treeName.c_str(), m_treeName.c_str());

  // add branches for attributes
  for(coral::AttributeListSpecification::const_iterator iter=m_attribSpec->begin(); iter!=m_attribSpec->end(); ++iter)
    {
      std::string type = "/?";
      type[1] = typeDict[iter->typeName()];
      std::string leaflist = iter->name() + type;
      m_tree->Branch(iter->name().c_str(),0,leaflist.c_str());
    }

  // add Token branch
  std::string leaflist = c_tokenBranchName;
  leaflist += "/C";
  m_tree->Branch(c_tokenBranchName,0,leaflist.c_str());

  // set TTree
  AANTTreeMap::setTree(m_streamName,m_tree);
}


// Get the string form of a ref for a given clid and key
StatusCode AANTupleStream::getRef(CLID id, const std::string& key, std::string& ref)
{
  // Must access the SG proxy to get the IOpaqueAddress
  SG::DataProxy* itemProxy = 0;
  ATH_MSG_DEBUG ("Retrieving proxy for " << id << " " << key);
  itemProxy = evtStore()->proxy(id, key);
  if (!itemProxy)
    {
      ATH_MSG_ERROR ("Could not get proxy ");
      return(StatusCode::FAILURE);
    }
  else
    {
      ATH_MSG_DEBUG (" found proxy for ("<< id << ",\"" << key << "\") ");
    }
  
  if (!itemProxy)
    {
      ATH_MSG_ERROR ("Empty proxy ");
      return(StatusCode::FAILURE);
    }
  
  // Get IOpaqueAddress from the proxy
  IOpaqueAddress* addr = itemProxy->address();
  if (!addr)
    {
      ATH_MSG_DEBUG ("Could not get address for clid "
		     << itemProxy->clID() << " " << itemProxy->name());
      return( StatusCode::FAILURE);
    }

  // Convert IOpaqueAddress to string via the persistency
  // service. And then remove header to extract the token.
  std::string saddr;

  StatusCode sc = m_persSvc->convertAddress(addr, saddr);   
  if (sc.isFailure()) 
    {
      ATH_MSG_ERROR 
	("Could not get string from IOpaqueAddress for clid " << id
	 << " " << key
467
	 << " is BAD_STORAGE_TYPE: "<< (sc == IConversionSvc::Status::BAD_STORAGE_TYPE));
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
      return( StatusCode::FAILURE);
    }
		    

  // We assume here some knowledge of the form of the AthenaPool
  // string address
  std::string hdr;
  sc = splitAddress(saddr, " /> ", hdr, ref);
  if (sc.isFailure()) 
    {
      ATH_MSG_ERROR ("Could not get split off token. string address " << saddr);
      return( StatusCode::FAILURE);
    }
  
  ATH_MSG_DEBUG ("String address " << ref);

  return StatusCode::SUCCESS;
}


// Extract the address header and data from an IOpaqueAddress in
// string form
StatusCode AANTupleStream::splitAddress( const std::string& address,
					 const std::string& match,
					 std::string&       address_header,
					 std::string&       address_data ) const
{
495
  ATH_MSG_DEBUG ("splitAddress " << endmsg
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
		 << "   address :  " << address
		 << "   match :  " << match);
  
  std::string::size_type p1;

  p1 = address.find( match );
  if (p1 != std::string::npos) 
    {
      address_header = address.substr( 0, p1+match.size());
      
      address_data = address.substr( p1+match.size() );
    } 
  else 
    {
      return StatusCode::FAILURE;
    }

  ATH_MSG_DEBUG ("   address_header :  " << address_header
514
		 << endmsg
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
		 << "   address_data   :  " << address_data);

  return StatusCode::SUCCESS;
}


// write Token and Attributes to the output collection
bool AANTupleStream::writeTokenAttrList( const std::string& token, const coral::AttributeList& attributeList )
{
  // set addresses for attributes
  coral::AttributeList::const_iterator attIter = attributeList.begin();
  const TObjArray* branches = m_tree->GetListOfBranches();
  std::vector<std::string> tokenStringDump;
  // loop over all attributes
  for (unsigned int i=0; i<attributeList.size(); ++i)
    {
      TBranch* branch = (TBranch*)branches->UncheckedAt(i);
      // string attributes
      if (attIter->specification().type() == typeid(std::string))
	{
	  const std::string& str = attIter->data<std::string>();
536
	  if( str.length()+1 >= s_maxLengthOfStrings )
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
	    {
	      throw std::runtime_error("String is too long : RootCollection::pool2Root<std::string>"); 
	    }
	  branch->SetAddress( (void*)str.c_str() );
	}
      // Token
      else if(attIter->specification().typeName() == "Token")
	{
	  tokenStringDump.push_back( attIter->data<std::string>() );
	  branch->SetAddress( (void*) tokenStringDump.back().c_str() );
	}
      // else
      else
	{
	  branch->SetAddress( (void*)attIter->addressOfData() );
	}
      ++attIter;  
    }

  // set address for Token
  m_tokenBranch->SetAddress((void*)token.c_str());

  // fill TTree
  m_tree->Fill();

  // releases Token
  m_tokenBranch->SetAddress(m_tokenCString); 

  return true;
}


// initialize sub-algos
StatusCode AANTupleStream::initialize_subAlgos()
{
  StatusCode sc = StatusCode::SUCCESS;
  
  Algorithm* algo;
  std::vector<std::string>::const_iterator it;
  std::vector<std::string>::const_iterator itend = m_membersNames.end( );
  for (it = m_membersNames.begin(); it != itend; ++it)
    {
      // Parse the name for a syntax of the form:
      //
      // <type>/<name>
      //
      // Where <name> is the algorithm instance name, and <type> is the
      // algorithm class type (being a subclass of Algorithm).
      ListItem foo(*it);
      std::string theType = foo.type();
      std::string theName = foo.name();

      // create sub-algorithm
      ATH_MSG_INFO (" -> creating sub-algorithm " << (*it));
      sc =  createSubAlgorithm( theType,theName, algo );
      if (sc.isFailure())
593
594
595
596
        {
          ATH_MSG_FATAL (" ERROR creating sub-alg." << (*it));
          return StatusCode::FAILURE;
        }
597
598
599
600
601
602
603
604
605
606
607
608
609
    }

  return sc;
}


// execute sub-algos
StatusCode AANTupleStream::execute_subAlgos()
{
  StatusCode sc = StatusCode::SUCCESS;
  
  ATH_MSG_DEBUG ("in execute_subAlgos() ...");

610
611
  const EventContext& ctx = Gaudi::Hive::currentContext();
  
612
613
614
615
616
617
618
  // -- run subalgorithms
  for ( unsigned int i=0; i < m_membersNames.size(); ++i )
    {
      ATH_MSG_DEBUG (" -> calling sub-algorithm " << m_membersNames[i]);
      // skip disabled algo
      if (! (*(this->subAlgorithms()))[i]->isEnabled()) continue ;
      
619
      sc = (*(this->subAlgorithms()))[i]->execute(ctx);
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
      if ( sc.isFailure())
	{
	  ATH_MSG_ERROR
	    (" ERROR executing sub-algorithm:" << m_membersNames[i]);
	  return StatusCode::FAILURE;
	}
    }
  return sc;
}


// get filters
StatusCode AANTupleStream::getFilters()
{
  ATH_MSG_DEBUG ("in getFilters()");
  
  // no filter
  if (m_acceptNames.empty())
    return StatusCode::SUCCESS;



  // old way to get ApplicationMgr crash with gaudi 21 (dynamic_cast fails)
  //  IAlgManager* theAlgMgr;
//   IInterface* ptmp;
//   StatusCode sc = serviceLocator()->getService("ApplicationMgr",
//                                                IAlgManager::interfaceID(),
//                                                ptmp);

//   if (sc.isFailure())
//     {
//       ATH_MSG_FATAL ("Can't locate ApplicationMgr!!!");
//       return sc;
//     }
//   theAlgMgr = dynamic_cast<IAlgManager*> (ptmp);

  // new safe way to get ApplicationMgr (gaudi 21 and backward compatible)
  ServiceHandle<IAlgManager> theAlgMgr("ApplicationMgr", this->name());
  if (theAlgMgr==0){
    ATH_MSG_FATAL ("Can't locate    ApplicationMgr!!!");
    return StatusCode::FAILURE;
  }
  

  // loop over all alg names
  std::vector<std::string>::const_iterator it;
  std::vector<std::string>::const_iterator itend = m_acceptNames.end();
  for (it = m_acceptNames.begin(); it != itend; ++it)
    {
      IAlgorithm* ialg;
      // get Alg
      StatusCode sc = theAlgMgr->getAlgorithm(*it, ialg);

      if (sc.isFailure() )
	{
	  ATH_MSG_ERROR ("Can't get Filter Alg : " << *it);
	  return StatusCode::FAILURE;
	}
      Algorithm *theAlg = dynamic_cast<Algorithm*>(ialg);
      if (theAlg==0 )
	{
	  ATH_MSG_ERROR ("Can't cast Filter Alg : " << *it);
	  return StatusCode::FAILURE;
	}
      ATH_MSG_DEBUG (" -> getting Filter Alg success " << *it);
      // push back
      m_acceptAlgs.push_back(theAlg);
    }
  return StatusCode::SUCCESS;
}


// Loop over all Algorithms in the accept list to see
// whether any have been executed and have their filter
// passed flag set. Any match causes the event to be
// provisionally accepted.
bool AANTupleStream::isEventAccepted() const
{
  // no filter
  if (m_acceptAlgs.empty())
    return true;
701
702
703

  const EventContext& ctx = Gaudi::Hive::currentContext();
  
704
705
706
707
708
709
  // loop over all algs
  std::vector<Algorithm*>::const_iterator it;
  std::vector<Algorithm*>::const_iterator itend = m_acceptAlgs.end();
  for (it = m_acceptAlgs.begin(); it != itend; ++it)
    {
      const Algorithm* theAlgorithm = (*it);
710
711
      if ( theAlgorithm->execState(ctx).state() == AlgExecState::State::Done &&
             ( ! theAlgorithm->execState(ctx).filterPassed() ) )
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
	return false;
    }

  return true;
}

StatusCode
AANTupleStream::initSchema()
{
  m_schemaDone = true;

  StatusCode sc = m_tHistSvc.retrieve();
  if (sc.isFailure())
  {
    ATH_MSG_ERROR ("Unable to retrieve pointer to THistSvc");
    return sc;
  }

  // initialize output collection
  sc = initCollection();
  if ( sc.isFailure() )
  {
    ATH_MSG_ERROR ("Could not init collection");
    return sc;
  }

  // register TTree to THistSvc
  sc = m_tHistSvc->regTree("/"+m_streamName+"/"+m_treeName, m_tree);
  if ( sc.isFailure() )
  {
    ATH_MSG_ERROR ("Could not register TTree");
    return sc;
  }

  /// dump
  m_tree->Print();

  return sc;
}

StatusCode
AANTupleStream::io_reinit()
{
  ServiceHandle<IIoComponentMgr> iomgr ("IoComponentMgr", this->name());
  if ( !iomgr.retrieve().isSuccess() ) {
    ATH_MSG_ERROR ("Could not retrieve IIoComponentMgr/IoComponentMgr !");
    return StatusCode::FAILURE;
  }

761
  ServiceHandle<Gaudi::Interfaces::IOptionsSvc> josvc ("JobOptionsSvc", this->name());
762
  if ( !josvc.retrieve().isSuccess() ) {
763
    ATH_MSG_ERROR ("Could not retrieve IOptionsSvc/JobOptionsSvc !");
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
    return StatusCode::FAILURE;
  }

  // check the I/O manager knows about me
  if ( !iomgr->io_hasitem (this) ) {
    ATH_MSG_ERROR ("I/O component mgr does not know about ourselves !");
    return StatusCode::FAILURE;
  }

  // check there is actually something to do...
  if ( !iomgr->io_contains (this, m_fileName) ) {
    ATH_MSG_DEBUG 
      ("I/O component mgr does not have any entry about ["<< m_fileName<<"]");
    return StatusCode::SUCCESS;
  }

  if ( !iomgr->io_retrieve (this, m_fileName).isSuccess() ) {
    ATH_MSG_ERROR ("Could not retrieve new name for [" << m_fileName << "] !");
    return StatusCode::FAILURE;
  }
  
  // recreate the proper property value...
786
787
  std::vector<std::string> outvec = {"AANT DATAFILE='" + m_fileName + "' OPT='RECREATE'"};
  josvc->set("THistSvc.Output", Gaudi::Utils::toString(outvec));
788
789
790
791
792
793
794
795
796
797

  // handle schema...
  if (!m_schemaDone) {
    if ( !initSchema().isSuccess() ) {
      ATH_MSG_ERROR ("Could not initialize schema !");
    }
  }

  return StatusCode::SUCCESS;
}