The Gaudi Framework  master (9f3f8895)
Loading...
Searching...
No Matches
PrecedenceRulesGraph.cpp
Go to the documentation of this file.
1/***********************************************************************************\
2* (c) Copyright 1998-2026 CERN for the benefit of the LHCb and ATLAS collaborations *
3* *
4* This software is distributed under the terms of the Apache version 2 licence, *
5* copied verbatim in the file "LICENSE". *
6* *
7* In applying this licence, CERN does not waive the privileges and immunities *
8* granted to it by virtue of its status as an Intergovernmental Organization *
9* or submit itself to any jurisdiction. *
10\***********************************************************************************/
11
12// Local includes
14#include "Visitors/Promoters.h"
15
16// Framework includes
18
19// STL includes
20#include <algorithm>
21#include <fstream>
22
23// Boost includes
24#include <boost/property_map/transform_value_property_map.hpp>
25
26#define ON_DEBUG if ( msgLevel( MSG::DEBUG ) )
27#define ON_VERBOSE if ( msgLevel( MSG::VERBOSE ) )
28
29namespace {
30 //---------------------------------------------------------------------------
32 const char* stateToString( const int& stateId ) {
33 switch ( stateId ) {
34 case 0:
35 return "FALSE";
36 case 1:
37 return "TRUE";
38 default:
39 return "UNDEFINED";
40 }
41 }
42} // namespace
43
44namespace concurrency {
45
46 //---------------------------------------------------------------------------
48
49 if ( std::find( m_parents.begin(), m_parents.end(), node ) == m_parents.end() ) m_parents.push_back( node );
50 }
51
52 //--------------------------------------------------------------------------
54
55 if ( std::find( m_children.begin(), m_children.end(), node ) == m_children.end() ) m_children.push_back( node );
56 }
57
58 //---------------------------------------------------------------------------
59 void DecisionNode::printState( std::stringstream& output, EventSlot& slot,
60 const unsigned int& recursionLevel ) const {
61
62 auto& node_decisions = slot.controlFlowState;
63 output << std::string( recursionLevel, ' ' ) << m_nodeName << " (" << m_nodeIndex << ")"
64 << ", w/ decision: " << stateToString( node_decisions[m_nodeIndex] ) << "(" << node_decisions[m_nodeIndex]
65 << ")" << std::endl;
66
67 for ( auto daughter : m_children ) daughter->printState( output, slot, recursionLevel + 2 );
68 }
69
70 //---------------------------------------------------------------------------
72
73 if ( visitor.visitEnter( *this ) ) {
74 // try to aggregate a decision
75 bool result = visitor.visit( *this );
76 return !result;
77 }
78
79 return false; // visitor was rejected (since the decision node has an aggregated decision already)
80 }
81
82 //---------------------------------------------------------------------------
83 void AlgorithmNode::printState( std::stringstream& output, EventSlot& slot,
84 const unsigned int& recursionLevel ) const {
85
86 auto& node_decisions = slot.controlFlowState;
87 auto& states = slot.algsStates;
88 std::string indent( recursionLevel, ' ' );
89 output << indent << m_nodeName << " (" << m_nodeIndex << ")"
90 << ", w/ decision: " << stateToString( node_decisions[m_nodeIndex] ) << "(" << node_decisions[m_nodeIndex]
91 << ")"
92 << ", in state: " << states[m_algoIndex] << std::endl;
93
94 // In a stall, CONTROLREADY nodes are interesting
96
97 // Check all data dependencies
98 output << indent << "========" << std::endl;
99 for ( auto dataNode : this->getInputDataNodes() ) {
100
101 // Was the data produced?
102 ConditionNode* conditionNode = dynamic_cast<ConditionNode*>( dataNode );
103 DataReadyPromoter visitor( slot, {} );
104 bool wasProduced = false;
105 if ( conditionNode ) {
106 // ConditionNodes always request data on visit()
107 // Instead take the opposite of visitEnter(), since you may not enter if it already exists
108 wasProduced = !visitor.visitEnter( *conditionNode );
109 } else {
110 // For DataNodes, the check is done in visit()
111 wasProduced = visitor.visit( *dataNode );
112 }
113
114 // Print out states of producer algs if data is missing
115 if ( !wasProduced ) {
116
117 // Say if it's conditions data or not
118 if ( conditionNode )
119 output << indent << "missing conditions data: " << dataNode->name() << std::endl;
120 else
121 output << indent << "missing data: " << dataNode->name() << std::endl;
122
123 // Find out if the algorithm needs it because of a tool
124 DataHandleFinder finder( dataNode->name() );
125 this->getAlgorithm()->acceptDHVisitor( &finder );
126 if ( finder.holderNames().size() > 1 ) {
127 output << indent << "required by tool:";
128 for ( auto const& holderName : finder.holderNames() ) {
129 if ( holderName != this->name() ) output << " " << holderName;
130 }
131 output << std::endl;
132 }
133
134 if ( conditionNode ) {
135 // State which IOVs the data exists for
136 output << indent << "current EventID: " << EventIDBase( slot.eventContext->eventID() ) << std::endl;
137 std::vector<EventIDRange> validRanges;
138 conditionNode->m_condSvc->validRanges( validRanges, dataNode->name() )
139 .ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
140 for ( auto& range : validRanges ) { output << indent << "interval of validity: " << range << std::endl; }
141 if ( validRanges.empty() ) output << indent << "no interval(s) of validity" << std::endl;
142 } else {
143 // State which algs produce this data
144 output << indent << "can be produced by alg(s): ";
145 for ( auto algoNode : dataNode->getProducers() ) {
146 output << "( " << algoNode->name() << " in state: " << states[algoNode->getAlgoIndex()] << " ) ";
147 }
148 output << std::endl;
149 }
150
151 // See where data is available (ignore conditions, since these are top-level)
152 if ( !conditionNode ) {
153 std::vector<EventSlot>* testSubSlots = &slot.allSubSlots;
154 auto* subSlotMap = &slot.subSlotsByNode;
155
156 // Examine the top-level slot if you did not start there
157 if ( slot.parentSlot ) {
158 visitor.m_slot = slot.parentSlot;
159 testSubSlots = &slot.parentSlot->allSubSlots;
160 subSlotMap = &slot.parentSlot->subSlotsByNode;
161 if ( visitor.visit( *dataNode ) ) {
162 output << indent << "data is available at whole-event level" << std::endl;
163 }
164 }
165
166 // Examine all sub slots, grouped by entry point
167 for ( auto& pair : *subSlotMap ) {
168 if ( pair.second.size() > 0 ) {
169 bool madeLine = false;
170
171 // Loop over the slots for this entry point
172 for ( int slotIndex : pair.second ) {
173
174 EventSlot* subSlot = &testSubSlots->at( slotIndex );
175 visitor.m_slot = subSlot;
176 if ( visitor.visit( *dataNode ) ) {
177
178 if ( !madeLine ) {
179 // Only mention this set of sub-slots at all if one has the data
180 output << indent << "data is available in sub-slot(s) ";
181 madeLine = true;
182 }
183 output << slotIndex << ", ";
184 }
185 }
186 if ( madeLine ) { output << "entered from " << pair.first << std::endl; }
187 }
188 }
189 }
190 }
191 }
192 output << indent << "========" << std::endl;
193 }
194 }
195
196 //---------------------------------------------------------------------------
198
199 if ( visitor.visitEnter( *this ) ) {
200 visitor.visit( *this );
201 return true; // visitor was accepted to promote the algorithm
202 }
203
204 return false; // visitor was rejected (since the algorithm already produced a decision)
205 }
206
207 //---------------------------------------------------------------------------
209
210 if ( std::find( m_parents.begin(), m_parents.end(), node ) == m_parents.end() ) m_parents.push_back( node );
211 }
212
213 //---------------------------------------------------------------------------
215
216 if ( std::find( m_outputs.begin(), m_outputs.end(), node ) == m_outputs.end() ) m_outputs.push_back( node );
217 }
218
219 //---------------------------------------------------------------------------
221
222 if ( std::find( m_inputs.begin(), m_inputs.end(), node ) == m_inputs.end() ) m_inputs.push_back( node );
223 }
224
225 //---------------------------------------------------------------------------
227 if ( serviceLocator()->existsService( "CondSvc" ) ) {
228 SmartIF<ICondSvc> condSvc{ serviceLocator()->service( "CondSvc" ) };
229 if ( condSvc.isValid() ) {
230 info() << "CondSvc found. DF precedence rules will be augmented with 'Conditions'" << endmsg;
232 }
233 }
234
235 // Detach condition algorithms from the CF realm
237 SmartIF<ICondSvc> condSvc{ serviceLocator()->service( "CondSvc", false ) };
238 auto& condAlgs = condSvc->condAlgs();
239 for ( const auto algo : condAlgs ) {
240 auto itA = m_algoNameToAlgoNodeMap.find( algo->name() );
241 if ( itA != m_algoNameToAlgoNodeMap.end() ) {
242 concurrency::AlgorithmNode* algoNode = itA->second.get();
243 debug() << "Detaching condition algorithm '" << algo->name() << "' from the CF realm.." << endmsg;
244 for ( auto parent : algoNode->getParentDecisionHubs() ) {
245 parent->m_children.erase( std::remove( parent->m_children.begin(), parent->m_children.end(), algoNode ),
246 parent->m_children.end() );
247 // clean up also auxiliary BGL-based graph of precedence rules
248 if ( m_enableAnalysis ) boost::remove_edge( node( algoNode->name() ), node( parent->name() ), m_PRGraph );
249 }
250 algoNode->m_parents.clear();
251
252 } else {
253 warning() << "Algorithm '" << algo->name() << "' is not registered in the graph" << endmsg;
254 }
255 }
256 }
257
259
260 if ( !sc.isSuccess() ) error() << "Could not build the data dependency realm." << endmsg;
261
262 return sc;
263 }
264
265 //---------------------------------------------------------------------------
266 void PrecedenceRulesGraph::printState( std::stringstream& output, EventSlot& slot,
267 const unsigned int& recursionLevel ) const {
268 if ( slot.parentSlot ) {
269 // Start at sub-slot entry point
270 m_decisionNameToDecisionHubMap.at( slot.entryPoint )->printState( output, slot, recursionLevel );
271 } else {
272 // Start at the head node for whole-event slots
273 m_headNode->printState( output, slot, recursionLevel );
274 }
275
276 // Find detached conditions algs in interesting states
278 bool firstPrint = true;
279 SmartIF<ICondSvc> condSvc{ serviceLocator()->service( "CondSvc", false ) };
280 auto& condAlgs = condSvc->condAlgs();
281 for ( const auto algo : condAlgs ) {
282 auto itA = m_algoNameToAlgoNodeMap.find( algo->name() );
283 if ( itA != m_algoNameToAlgoNodeMap.end() ) {
284
285 concurrency::AlgorithmNode* algoNode = itA->second.get();
286
287 // Ignore boring states (reduces verbosity)
288 auto& thisState = slot.algsStates[algoNode->getAlgoIndex()];
289 if ( thisState == AlgsExecutionStates::State::INITIAL ||
291 continue;
292
293 // Make output
294 if ( firstPrint ) {
295 firstPrint = false;
296 output << std::endl << "Detached algorithms:" << std::endl;
297 }
298 algoNode->printState( output, slot, recursionLevel );
299 }
300 }
301 }
302 }
303
304 //---------------------------------------------------------------------------
306
307 const std::string& algoName = algo->name();
308
309 m_algoNameToAlgoInputsMap[algoName] = algo->inputDataObjs();
310 m_algoNameToAlgoOutputsMap[algoName] = algo->outputDataObjs();
311
312 ON_VERBOSE {
313 verbose() << " Inputs of " << algoName << ": ";
314 for ( auto tag : algo->inputDataObjs() ) verbose() << tag << " | ";
315 verbose() << endmsg;
316
317 verbose() << " Outputs of " << algoName << ": ";
318 for ( auto tag : algo->outputDataObjs() ) verbose() << tag << " | ";
319 verbose() << endmsg;
320 }
321 }
322
323 //---------------------------------------------------------------------------
325
327
328 // Production of DataNodes by AlgorithmNodes (DataNodes are created here)
329 std::vector<decltype( m_algoNameToAlgoNodeMap )::value_type*> sortedAlgs;
330 for ( auto& algo : m_algoNameToAlgoNodeMap ) { sortedAlgs.push_back( &algo ); }
331 std::sort( sortedAlgs.begin(), sortedAlgs.end(),
332 []( const auto* a, const auto* b ) { return a->first < b->first; } );
333 for ( auto* algo : sortedAlgs ) {
334
335 auto& outputs = m_algoNameToAlgoOutputsMap[algo->first];
336 for ( auto output : outputs ) {
337 const auto sc = addDataNode( output );
338 if ( !sc.isSuccess() ) {
339 error() << "Extra producer (" << algo->first << ") for DataObject @ " << output
340 << " has been detected: this is not allowed." << endmsg;
341 global_sc = sc;
342 }
343 auto dataNode = getDataNode( output );
344 dataNode->addProducerNode( algo->second.get() );
345 algo->second->addOutputDataNode( dataNode );
346
347 // Mirror the action above in the BGL-based graph
348 if ( m_enableAnalysis ) boost::add_edge( node( algo->second->name() ), node( output.fullKey() ), m_PRGraph );
349 }
350 }
351
352 // Consumption of DataNodes by AlgorithmNodes
353 sortedAlgs.clear();
354 for ( auto& algo : m_algoNameToAlgoNodeMap ) { sortedAlgs.push_back( &algo ); }
355 std::sort( sortedAlgs.begin(), sortedAlgs.end(),
356 []( const auto* a, const auto* b ) { return a->first < b->first; } );
357 for ( auto* algo : sortedAlgs ) {
358
359 for ( auto input : m_algoNameToAlgoInputsMap[algo->first] ) {
360
361 auto itP = m_dataPathToDataNodeMap.find( input );
362
363 DataNode* dataNode = ( itP != m_dataPathToDataNodeMap.end() ? getDataNode( input ) : nullptr );
364 if ( dataNode ) {
365 dataNode->addConsumerNode( algo->second.get() );
366 algo->second->addInputDataNode( dataNode );
367
368 // Mirror the action above in the BGL-based graph
369 if ( m_enableAnalysis ) boost::add_edge( node( input.fullKey() ), node( algo->second->name() ), m_PRGraph );
370 }
371 }
372 }
373
374 return global_sc;
375 }
376
377 //---------------------------------------------------------------------------
379
381
383
384 auto& algoName = algo->name();
385
387
388 auto itA = m_algoNameToAlgoNodeMap.find( algoName );
389 if ( itA != m_algoNameToAlgoNodeMap.end() ) {
390 algoNode = itA->second.get();
391 } else {
392 auto r = m_algoNameToAlgoNodeMap.emplace(
393 algoName, std::make_unique<concurrency::AlgorithmNode>( *this, algo, m_nodeCounter, m_algoCounter ) );
394 algoNode = r.first->second.get();
395
396 // Mirror AlgorithmNode in the BGL-based graph
397 if ( m_enableAnalysis ) { boost::add_vertex( AlgoProps( algo, m_nodeCounter, m_algoCounter ), m_PRGraph ); }
400 ON_VERBOSE verbose() << "AlgorithmNode '" << algoName << "' added @ " << algoNode << endmsg;
401
402 registerIODataObjects( algo );
403 }
404
406 auto itP = m_decisionNameToDecisionHubMap.find( parentName );
407 if ( itP != m_decisionNameToDecisionHubMap.end() ) {
408 auto parentNode = itP->second.get();
409
410 parentNode->addDaughterNode( algoNode );
411 algoNode->addParentNode( parentNode );
412
413 // Mirror algorithm to CF parent relationship in the BGL-based graph
414 if ( m_enableAnalysis ) boost::add_edge( node( algo->name() ), node( parentName ), m_PRGraph );
415
416 ON_VERBOSE verbose() << "Attached AlgorithmNode '" << algo->name() << "' to parent DecisionNode '" << parentName
417 << "'" << endmsg;
418 } else {
420 error() << "Parent DecisionNode '" << parentName << "' was not found" << endmsg;
421 }
422
423 return sc;
424 }
425
426 //---------------------------------------------------------------------------
428
429 auto itD = m_dataPathToDataNodeMap.find( dataPath );
430 if ( itD != m_dataPathToDataNodeMap.end() ) return StatusCode::SUCCESS;
431
432 std::unique_ptr<concurrency::DataNode> dataNode;
434 dataNode = std::make_unique<concurrency::DataNode>( *this, dataPath );
435 ON_VERBOSE verbose() << " DataNode " << dataPath << " added @ " << dataNode.get() << endmsg;
436 // Mirror the action above in the BGL-based graph
437 if ( m_enableAnalysis ) boost::add_vertex( DataProps( dataPath ), m_PRGraph );
438 } else {
439 SmartIF<ICondSvc> condSvc{ serviceLocator()->service( "CondSvc", false ) };
440 if ( condSvc->isRegistered( dataPath ) ) {
441 dataNode = std::make_unique<concurrency::ConditionNode>( *this, dataPath, condSvc );
442 ON_VERBOSE verbose() << " ConditionNode " << dataPath << " added @ " << dataNode.get() << endmsg;
443 // Mirror the action above in the BGL-based graph
444 if ( m_enableAnalysis ) boost::add_vertex( CondDataProps( dataPath ), m_PRGraph );
445 } else {
446 dataNode = std::make_unique<concurrency::DataNode>( *this, dataPath );
447 ON_VERBOSE verbose() << " DataNode " << dataPath << " added @ " << dataNode.get() << endmsg;
448 // Mirror the action above in the BGL-based graph
449 if ( m_enableAnalysis ) boost::add_vertex( DataProps( dataPath ), m_PRGraph );
450 }
451 }
452 m_dataPathToDataNodeMap.emplace( dataPath, std::move( dataNode ) );
453 return StatusCode::SUCCESS;
454 }
455
456 //---------------------------------------------------------------------------
457 StatusCode PrecedenceRulesGraph::addDecisionHubNode( Gaudi::Algorithm* decisionHubAlgo, const std::string& parentName,
458 Concurrent modeConcurrent, PromptDecision modePromptDecision,
459 ModeOr modeOR, AllPass allPass, Inverted isInverted ) {
460
462
464
465 auto& decisionHubName = decisionHubAlgo->name();
466
467 auto itA = m_decisionNameToDecisionHubMap.find( decisionHubName );
468 concurrency::DecisionNode* decisionHubNode;
469 if ( itA != m_decisionNameToDecisionHubMap.end() ) {
470 decisionHubNode = itA->second.get();
471 } else {
472 auto r = m_decisionNameToDecisionHubMap.emplace(
473 decisionHubName,
474 std::make_unique<concurrency::DecisionNode>( *this, m_nodeCounter, decisionHubName, modeConcurrent,
475 modePromptDecision, modeOR, allPass, isInverted ) );
476 decisionHubNode = r.first->second.get();
477 // Mirror DecisionNode in the BGL-based graph
478 if ( m_enableAnalysis ) {
479 boost::add_vertex( DecisionHubProps( decisionHubName, m_nodeCounter, modeConcurrent, modePromptDecision, modeOR,
480 allPass, isInverted ),
481 m_PRGraph );
482 }
483
485
486 ON_VERBOSE verbose() << "DecisionNode '" << decisionHubName << "' added @ " << decisionHubNode << endmsg;
487 }
488
490 auto itP = m_decisionNameToDecisionHubMap.find( parentName );
491 if ( itP != m_decisionNameToDecisionHubMap.end() ) {
492 auto parentNode = itP->second.get();
493 parentNode->addDaughterNode( decisionHubNode );
494 decisionHubNode->addParentNode( parentNode );
495
496 // Mirror DecisionNode-to-DecisionNode relationship in the BGL-based graph
497 if ( m_enableAnalysis ) boost::add_edge( node( decisionHubName ), node( parentName ), m_PRGraph );
498
499 ON_VERBOSE verbose() << "Attached DecisionNode '" << decisionHubName << "' to parent DecisionNode '" << parentName
500 << "'" << endmsg;
501 } else {
503 error() << "Parent DecisionNode '" << parentName << "' was not found" << endmsg;
504 }
505
506 return sc;
507 }
508
509 //---------------------------------------------------------------------------
510 void PrecedenceRulesGraph::addHeadNode( const std::string& headName, concurrency::Concurrent modeConcurrent,
511 concurrency::PromptDecision modePromptDecision, concurrency::ModeOr modeOR,
512 concurrency::AllPass allPass, concurrency::Inverted isInverted ) {
513
514 auto itH = m_decisionNameToDecisionHubMap.find( headName );
515 if ( itH != m_decisionNameToDecisionHubMap.end() ) {
516 m_headNode = itH->second.get();
517 } else {
518 auto r = m_decisionNameToDecisionHubMap.emplace(
519 headName, std::make_unique<concurrency::DecisionNode>( *this, m_nodeCounter, headName, modeConcurrent,
520 modePromptDecision, modeOR, allPass, isInverted ) );
521 m_headNode = r.first->second.get();
522
523 // Mirror the action above in the BGL-based graph
524 if ( m_enableAnalysis ) {
525 boost::add_vertex( DecisionHubProps( headName, m_nodeCounter, modeConcurrent, modePromptDecision, modeOR,
526 allPass, isInverted ),
527 m_PRGraph );
528 }
529
531 }
532 }
533
534 //---------------------------------------------------------------------------
535 PRVertexDesc PrecedenceRulesGraph::node( const std::string& name ) const {
536 auto vp = vertices( m_PRGraph );
537 auto i = std::find_if( vp.first, vp.second, [&]( const PRVertexDesc& v ) {
538 return std::visit( precedence::VertexName(), m_PRGraph[v] ) == name;
539 } );
540 return i != vp.second ? *i : PRVertexDesc{};
541 }
542
543 //---------------------------------------------------------------------------
545 // iterate through Algorithm nodes
546 for ( auto& pr : m_algoNameToAlgoNodeMap ) pr.second->accept( visitor );
547
548 // iterate through DecisionHub nodes
549 for ( auto& pr : m_decisionNameToDecisionHubMap ) pr.second->accept( visitor );
550
551 // iterate through Data [and Conditions] nodes
552 for ( auto& pr : m_dataPathToDataNodeMap ) pr.second->accept( visitor );
553 }
554
555 //---------------------------------------------------------------------------
557
558 info() << "Starting ranking by data outputs .. " << endmsg;
559 for ( auto& pair : m_algoNameToAlgoNodeMap ) {
560 ON_DEBUG debug() << " Ranking " << pair.first << "... " << endmsg;
561 pair.second->accept( ranker );
562 ON_DEBUG debug() << " ... rank of " << pair.first << ": " << pair.second->getRank() << endmsg;
563 }
564 }
565
567 std::ostringstream ost;
568 dumpControlFlow( ost, m_headNode, 0 );
569 return ost.str();
570 }
571
573 const int& indent ) const {
574 ost << std::string( indent * 2, ' ' );
575 DecisionNode* dn = dynamic_cast<DecisionNode*>( node );
576 AlgorithmNode* an = dynamic_cast<AlgorithmNode*>( node );
577 if ( dn != 0 ) {
578 if ( node != m_headNode ) {
579 ost << node->name() << " [Seq] ";
580 ost << ( ( dn->m_modeConcurrent ) ? " [Concurrent] " : " [Sequential] " );
581 ost << ( ( dn->m_modePromptDecision ) ? " [Prompt] " : "" );
582 ost << ( ( dn->m_modeOR ) ? " [OR] " : "" );
583 ost << ( ( dn->m_allPass ) ? " [PASS] " : "" );
584 ost << "\n";
585 }
586 for ( const auto& i : dn->getDaughters() ) dumpControlFlow( ost, i, indent + 1 );
587 } else if ( an != 0 ) {
588 ost << node->name() << " [Alg] ";
589 auto ar = an->getAlgorithm();
590 ost << " [n= " << ar->cardinality() << "]";
591 ost << ( ( !ar->isClonable() ) ? " [unclonable] " : "" );
592 ost << "\n";
593 }
594 }
595
596 //---------------------------------------------------------------------------
598
599 const char idt[] = " ";
600 std::ostringstream ost;
601
602 ost << "\n" << idt << "====================================\n";
603 ost << idt << "Data origins and destinations:\n";
604 ost << idt << "====================================\n";
605
606 std::vector<const DataObjID*> vec;
607 vec.reserve( m_dataPathToDataNodeMap.size() );
608 for ( auto& pair : m_dataPathToDataNodeMap ) { vec.push_back( &pair.first ); }
609 std::sort( vec.begin(), vec.end(),
610 []( const DataObjID* a, const DataObjID* b ) { return a->fullKey() < b->fullKey(); } );
611
612 for ( const DataObjID* id : vec ) {
613 const DataNode& node = *m_dataPathToDataNodeMap.find( *id )->second;
614
615 for ( auto algoNode : node.getProducers() ) ost << idt << " " << algoNode->name() << "\n";
616
617 ost << idt << " V\n";
618 ost << idt << " o " << id << "\n";
619 ost << idt << " V\n";
620
621 for ( auto algoNode : node.getConsumers() ) ost << idt << " " << algoNode->name() << "\n";
622
623 ost << idt << "====================================\n";
624 }
625
626 return ost.str();
627 }
628
629 //---------------------------------------------------------------------------
630
631 void PrecedenceRulesGraph::dumpPrecRules( const std::filesystem::path& fileName, const EventSlot& slot ) {
632 std::ofstream myfile;
633 myfile.open( fileName.c_str(), std::ios::app );
634
635 // Declare properties to dump
636 boost::dynamic_properties dp;
637
638 dp.property( "Entity",
639 boost::make_transform_value_property_map(
640 []( const VariantVertexProps& v ) {
641 return std::visit( []( const auto& w ) { return boost::lexical_cast<std::string>( w ); }, v );
642 },
643 boost::get( boost::vertex_bundle, m_PRGraph ) ) );
644
645 auto add_prop = [&]( auto name, auto&& vis ) {
646 dp.property( name, boost::make_transform_value_property_map(
647 [vis = std::forward<decltype( vis )>( vis )]( const VariantVertexProps& v ) {
648 return std::visit( vis, v );
649 },
650 boost::get( boost::vertex_bundle, m_PRGraph ) ) );
651 };
652
653 add_prop( "Name", precedence::VertexName() );
654 add_prop( "Mode", precedence::GroupMode() );
655 add_prop( "Logic", precedence::GroupLogic() );
656 add_prop( "Decision Negation", precedence::DecisionNegation() );
657 add_prop( "Negative Decision Inversion", precedence::AllPass() );
658 add_prop( "Exit Policy", precedence::GroupExit() );
659 add_prop( "Operations", precedence::Operations() );
660 add_prop( "CF Decision", precedence::CFDecision( slot ) );
661 add_prop( "State", precedence::EntityState( slot, serviceLocator(), m_conditionsRealmEnabled ) );
662 add_prop( "Start Time (Epoch ns)", precedence::StartTime( slot, serviceLocator() ) );
663 add_prop( "End Time (Epoch ns)", precedence::EndTime( slot, serviceLocator() ) );
664 add_prop( "Runtime (ns)", precedence::Duration( slot, serviceLocator() ) );
665
666 boost::write_graphml( myfile, m_PRGraph, dp );
667
668 myfile.close();
669 }
670
671 //---------------------------------------------------------------------------
672 void PrecedenceRulesGraph::dumpPrecTrace( const std::filesystem::path& fileName, const EventSlot& slot ) {
673 std::ofstream myfile;
674 myfile.open( fileName.c_str(), std::ios::app );
675
676 // Fill runtimes (as this could not be done on the fly during trace assembling)
677 SmartIF<ITimelineSvc> timelineSvc = m_svcLocator->service<ITimelineSvc>( "TimelineSvc", false );
678 if ( !timelineSvc.isValid() ) {
679 warning() << "Failed to get the TimelineSvc, timing will not be added to "
680 << "the task precedence trace dump" << endmsg;
681 } else {
682
683 std::vector<long long int> start_times;
684
685 for ( auto vp = vertices( m_precTrace ); vp.first != vp.second; ++vp.first ) {
686 TimelineEvent te{};
687 te.algorithm = m_precTrace[*vp.first].m_name;
688 te.slot = slot.eventContext->slot();
689 te.event = slot.eventContext->evt();
690 // This calculates duration that is the difference between stop and start time which for asynchronous algorithms
691 // is not the same as the time spent in the algorithm itself. Perhaps it should be changed to elapsed time.
692 timelineSvc->getFirstMatching( te );
693 auto start_point = te.start;
694 timelineSvc->getLastMatching( te );
695 auto end_point = te.end;
696 long int runtime{ std::chrono::duration_cast<std::chrono::microseconds>( end_point - start_point ).count() };
697 m_precTrace[*vp.first].m_runtime = runtime;
698
699 long long int start{
700 std::chrono::duration_cast<std::chrono::nanoseconds>( start_point.time_since_epoch() ).count() };
701 m_precTrace[*vp.first].m_start = start;
702 if ( start != 0 ) start_times.push_back( start );
703 }
704
705 auto min = std::min_element( start_times.begin(), start_times.end() );
706
707 for ( auto vp = vertices( m_precTrace ); vp.first != vp.second; ++vp.first ) {
708
709 auto& oldValue = m_precTrace[*vp.first].m_start;
710
711 if ( oldValue != 0 ) oldValue = oldValue - *min;
712 }
713 }
714
715 // Declare properties to dump
716 boost::dynamic_properties dp;
717 using boost::get;
719 dp.property( "Name", get( &AlgoTraceProps::m_name, m_precTrace ) );
720 dp.property( "Rank", get( &AlgoTraceProps::m_rank, m_precTrace ) );
721 dp.property( "Run Time (us)", get( &AlgoTraceProps::m_runtime, m_precTrace ) );
722 dp.property( "Start Time (ns)", get( &AlgoTraceProps::m_start, m_precTrace ) );
723
724 boost::write_graphml( myfile, m_precTrace, dp );
725
726 myfile.close();
727 }
728
730
731 std::string u_name = u == nullptr ? "ENTRY" : u->name();
732 std::string v_name = v->name();
733
735
736 if ( !u ) {
737 auto itT = m_prec_trace_map.find( "ENTRY" );
738 if ( itT != m_prec_trace_map.end() ) {
739 source = itT->second;
740 } else {
741 source = boost::add_vertex( precedence::AlgoTraceProps( "ENTRY" ), m_precTrace );
742 m_prec_trace_map["ENTRY"] = source;
743 }
744 } else {
745 auto itS = m_prec_trace_map.find( u_name );
746 if ( itS != m_prec_trace_map.end() ) {
747 source = itS->second;
748 } else {
749
750 source =
751 boost::add_vertex( precedence::AlgoTraceProps( u_name, u->getAlgoIndex(), u->getRank() ), m_precTrace );
752 m_prec_trace_map[u_name] = source;
753 }
754 }
755
757
758 auto itP = m_prec_trace_map.find( v_name );
759 if ( itP != m_prec_trace_map.end() ) {
760 target = itP->second;
761 } else {
762
763 target = boost::add_vertex( precedence::AlgoTraceProps( v_name, v->getAlgoIndex(), v->getRank() ), m_precTrace );
764 m_prec_trace_map[v_name] = target;
765 }
766
767 boost::add_edge( source, target, m_precTrace );
768
769 ON_DEBUG debug() << u_name << "-->" << v_name << " precedence trait added" << endmsg;
770 }
771
772} // namespace concurrency
#define ON_VERBOSE
MsgStream & endmsg(MsgStream &s)
MsgStream Modifier: endmsg. Calls the output method of the MsgStream.
Definition MsgStream.h:198
#define ON_DEBUG
MsgStream & error() const
shortcut for the method msgStream(MSG::ERROR)
MsgStream & verbose() const
shortcut for the method msgStream(MSG::VERBOSE)
MsgStream & warning() const
shortcut for the method msgStream(MSG::WARNING)
MsgStream & debug() const
shortcut for the method msgStream(MSG::DEBUG)
MsgStream & info() const
shortcut for the method msgStream(MSG::INFO)
Implements the IDataHandleVisitor interface Class used to explore heirarchy of nested IDataHandleHold...
std::vector< std::string > & holderNames()
const DataObjIDColl & outputDataObjs() const override
const DataObjIDColl & inputDataObjs() const override
ContextEvt_t evt() const
const EventIDBase & eventID() const
ContextID_t slot() const
This class provides a unique identification for each event, in terms of run/event number and/or a tim...
Definition EventIDBase.h:53
Base class from which all concrete algorithm classes should be derived.
Definition Algorithm.h:87
void acceptDHVisitor(IDataHandleVisitor *) const override
const std::string & name() const override
The identifying name of the algorithm object.
virtual StatusCode validRanges(std::vector< EventIDRange > &ranges, const DataObjID &id) const =0
retrieve all valid ranges for one Object ID
virtual SmartIF< IService > & service(const Gaudi::Utils::TypeNameString &typeName, const bool createIf=true)=0
Returns a smart pointer to a service.
Small smart pointer class with automatic reference counting for IInterface.
Definition SmartIF.h:28
bool isValid() const
Allow for check if smart pointer is valid.
Definition SmartIF.h:69
This class is used for returning status codes from appropriate routines.
Definition StatusCode.h:64
void ignore() const
Allow discarding a StatusCode without warning.
Definition StatusCode.h:128
bool isSuccess() const
Definition StatusCode.h:302
constexpr static const auto SUCCESS
Definition StatusCode.h:99
constexpr static const auto FAILURE
Definition StatusCode.h:100
void addParentNode(DecisionNode *node)
Add a parent node.
std::vector< DecisionNode * > m_parents
Control flow parents of an AlgorithmNode (DecisionNodes).
std::vector< DataNode * > m_inputs
Algorithm inputs (DataNodes).
float getRank() const
Get Algorithm rank.
const std::vector< DataNode * > & getInputDataNodes() const
Get all consumer nodes.
const std::vector< DecisionNode * > & getParentDecisionHubs() const
Get all parent decision hubs.
std::vector< DataNode * > m_outputs
Algorithm outputs (DataNodes).
Gaudi::Algorithm * getAlgorithm() const
get Algorithm representatives
void addInputDataNode(DataNode *node)
Associate an AlgorithmNode, which is a data consumer of this one.
unsigned int getAlgoIndex() const
Get algorithm index.
void addOutputDataNode(DataNode *node)
Associate an AlgorithmNode, which is a data supplier for this one.
void printState(std::stringstream &output, EventSlot &slot, const unsigned int &recursionLevel) const override
Print a string representing the control flow state.
bool accept(IGraphVisitor &visitor) override
Visitor entry point.
unsigned int m_algoIndex
The index of the algorithm.
ControlFlowNode(PrecedenceRulesGraph &graph, unsigned int nodeIndex, const std::string &name)
Constructor.
const std::string & name() const
Get node name.
void addConsumerNode(AlgorithmNode *node)
Add relationship to consumer AlgorithmNode.
const std::vector< ControlFlowNode * > & getDaughters() const
Get children nodes.
bool m_modeOR
Whether acting as "and" (false) or "or" node (true).
bool m_modeConcurrent
Whether all daughters will be evaluated concurrently or sequentially.
void addDaughterNode(ControlFlowNode *node)
Add a daughter node.
bool m_allPass
Whether always passing regardless of daughter results.
void printState(std::stringstream &output, EventSlot &slot, const unsigned int &recursionLevel) const override
Print a string representing the control flow state.
std::vector< ControlFlowNode * > m_children
All direct daughter nodes in the tree.
bool accept(IGraphVisitor &visitor) override
Visitor entry point.
bool m_modePromptDecision
Whether to evaluate the hub decision ASA its child decisions allow to do that.
DecisionNode(PrecedenceRulesGraph &graph, unsigned int nodeIndex, const std::string &name, Concurrent modeConcurrent, PromptDecision modePromptDecision, ModeOr modeOR, AllPass allPass, Inverted isInverted)
Constructor.
void addParentNode(DecisionNode *node)
Add a parent node.
std::vector< DecisionNode * > m_parents
Direct parent nodes.
virtual bool visit(DecisionNode &)
virtual bool visitEnter(DecisionNode &) const
StatusCode addAlgorithmNode(Gaudi::Algorithm *daughterAlgo, const std::string &parentName)
Add algorithm node.
void addEdgeToPrecTrace(const AlgorithmNode *u, const AlgorithmNode *v)
set cause-effect connection between two algorithms in the precedence trace
void registerIODataObjects(const Gaudi::Algorithm *algo)
Register algorithm in the Data Dependency index.
precedence::PRGraph m_PRGraph
BGL-based graph of precedence rules.
std::unordered_map< std::string, std::unique_ptr< DecisionNode > > m_decisionNameToDecisionHubMap
Index: map of decision's name to DecisionHub.
void printState(std::stringstream &output, EventSlot &slot, const unsigned int &recursionLevel) const
Print a string representing the control flow state.
StatusCode initialize()
Initialize graph.
std::map< std::string, precedence::AlgoTraceVertex > m_prec_trace_map
StatusCode addDataNode(const DataObjID &dataPath)
Add DataNode that represents DataObject.
DecisionNode * m_headNode
the head node of the control flow graph
DataNode * getDataNode(const DataObjID &dataPath) const
Get DataNode by DataObject path using graph index.
std::unordered_map< std::string, DataObjIDColl > m_algoNameToAlgoInputsMap
Indexes: maps of algorithm's name to algorithm's inputs/outputs.
precedence::PrecTrace m_precTrace
facilities for algorithm precedence tracing
SmartIF< ISvcLocator > m_svcLocator
Service locator (needed to access the MessageSvc).
StatusCode buildDataDependenciesRealm()
Build data dependency realm WITH data object nodes participating.
std::string dumpDataFlow() const
Print out all data origins and destinations, as reflected in the EF graph.
PRVertexDesc node(const std::string &) const
std::unordered_map< DataObjID, std::unique_ptr< DataNode >, DataObjID_Hasher > m_dataPathToDataNodeMap
Index: map of data path to DataNode.
void addHeadNode(const std::string &headName, concurrency::Concurrent, concurrency::PromptDecision, concurrency::ModeOr, concurrency::AllPass, concurrency::Inverted)
Add a node, which has no parents.
StatusCode addDecisionHubNode(Gaudi::Algorithm *daughterAlgo, const std::string &parentName, concurrency::Concurrent, concurrency::PromptDecision, concurrency::ModeOr, concurrency::AllPass, concurrency::Inverted)
Add a node, which aggregates decisions of direct daughter nodes.
void accept(IGraphVisitor &visitor) const
An entry point to visit all graph nodes.
std::unordered_map< std::string, std::unique_ptr< AlgorithmNode > > m_algoNameToAlgoNodeMap
Index: map of algorithm's name to AlgorithmNode.
bool m_conditionsRealmEnabled
Enable conditions realm of precedence rules.
void dumpPrecRules(const std::filesystem::path &, const EventSlot &slot)
dump to file the precedence rules
unsigned int m_algoCounter
Total number of algorithm nodes in the graph.
void rankAlgorithms(IGraphVisitor &ranker) const
Rank Algorithm nodes by the number of data outputs.
std::unordered_map< std::string, DataObjIDColl > m_algoNameToAlgoOutputsMap
unsigned int m_nodeCounter
Total number of nodes in the graph.
std::string dumpControlFlow() const
Print out control flow of Algorithms and Sequences.
void dumpPrecTrace(const std::filesystem::path &, const EventSlot &slot)
dump to file the precedence trace
const std::string & name() const override
Retrieve name of the service.
SmartIF< ISvcLocator > & serviceLocator() const override
Retrieve pointer to service locator.
Gaudi::tagged_bool< class AllPass_tag > AllPass
Gaudi::tagged_bool< class Concurrent_tag > Concurrent
Gaudi::tagged_bool< class ModeOr_tag > ModeOr
Gaudi::tagged_bool< class PromptDecision_tag > PromptDecision
Gaudi::tagged_bool< class Inverted_tag > Inverted
boost::graph_traits< PrecTrace >::vertex_descriptor AlgoTraceVertex
boost::graph_traits< PRGraph >::vertex_descriptor PRVertexDesc
std::variant< AlgoProps, DecisionHubProps, DataProps, CondDataProps > VariantVertexProps
Class representing an event slot.
Definition EventSlot.h:23
std::unique_ptr< EventContext > eventContext
Cache for the eventContext.
Definition EventSlot.h:82
std::vector< EventSlot > allSubSlots
Actual sub-slot instances.
Definition EventSlot.h:99
EventSlot * parentSlot
Pointer to parent slot (null for top level).
Definition EventSlot.h:95
std::string entryPoint
Event Views bookkeeping (TODO: optimize view bookkeeping).
Definition EventSlot.h:93
std::unordered_map< std::string, std::vector< unsigned int > > subSlotsByNode
Listing of sub-slots by the node (name) they are attached to.
Definition EventSlot.h:97
AlgsExecutionStates algsStates
Vector of algorithms states.
Definition EventSlot.h:84
std::vector< int > controlFlowState
State of the control flow.
Definition EventSlot.h:86
time_point start
time_point end
std::string algorithm