Salome HOME
[EDF12520] : Optimization of placements of Kernel containers in ForEachLoop/HP Contai...
[modules/yacs.git] / src / engine / DynParaLoop.cxx
1 // Copyright (C) 2006-2016  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "DynParaLoop.hxx"
21 #include "LinkInfo.hxx"
22 #include "OutPort.hxx"
23 #include "Container.hxx"
24 #include "ComponentInstance.hxx"
25 #include "ServiceNode.hxx"
26 #include "InlineNode.hxx"
27 #include "ElementaryNode.hxx"
28 #include "Visitor.hxx"
29
30 #include <list>
31 #include <vector>
32
33 //#define _DEVDEBUG_
34 #include "YacsTrace.hxx"
35
36 using namespace std;
37 using namespace YACS::ENGINE;
38
39 const char DynParaLoop::NAME_OF_SPLITTED_SEQ_OUT[] = "evalSamples";
40 const char DynParaLoop::OLD_NAME_OF_SPLITTED_SEQ_OUT[] = "SmplPrt"; // For backward compatibility with 5.1.4
41
42 const char DynParaLoop::NAME_OF_NUMBER_OF_BRANCHES[]="nbBranches";
43
44 DynParaLoop::DynParaLoop(const std::string& name, TypeCode *typeOfDataSplitted)
45   : ComposedNode(name),_node(0),_initNode(0),_finalizeNode(0),_nbOfEltConsumed(0),
46     _nbOfBranches(NAME_OF_NUMBER_OF_BRANCHES,this,Runtime::_tc_int),
47     _splittedPort(NAME_OF_SPLITTED_SEQ_OUT,this,typeOfDataSplitted),_initializingCounter(0),_unfinishedCounter(0),_failedCounter(0),_weight(1.)
48 {
49 }
50
51 DynParaLoop::~DynParaLoop()
52 {
53   delete _node;
54   delete _initNode;
55   delete _finalizeNode;
56 }
57
58 DynParaLoop::DynParaLoop(const DynParaLoop& other, ComposedNode *father, bool editionOnly)
59   : ComposedNode(other,father), _nbOfBranches(other._nbOfBranches,this),
60     _splittedPort(other._splittedPort,this), _node(0), _initNode(0), _finalizeNode(0),
61     _nbOfEltConsumed(0),_initializingCounter(0),_unfinishedCounter(0),_failedCounter(0),_weight(1.)
62 {
63   if(other._node)
64     _node=other._node->clone(this,editionOnly);
65   if(other._initNode)
66     _initNode=other._initNode->clone(this,editionOnly);
67   if(other._finalizeNode)
68     _finalizeNode = other._finalizeNode->clone(this,editionOnly);
69   const AnyOutputPort& startOfLinksToReproduce=other._splittedPort;
70   set<InPort *> endsOfLinksToReproduce=startOfLinksToReproduce.edSetInPort();
71   for(set<InPort *>::iterator iter=endsOfLinksToReproduce.begin();iter!=endsOfLinksToReproduce.end();iter++)
72     edAddLink(&_splittedPort,getInPort(other.getPortName(*iter)));
73 }
74
75 Node *DynParaLoop::edSetNode(Node *node)
76 {
77   return checkConsistencyAndSetNode(_node, node);
78 }
79
80 //! This method is used to factorize methods edSetNode, edSetInitNode and edSetFinalizeNode
81 Node * DynParaLoop::checkConsistencyAndSetNode(Node* &nodeToReplace, Node* node)
82 {
83   if (node == NULL || nodeToReplace == node)
84     return 0;
85   if (node->_father)
86     throw Exception(string("Can't set node: node ") + node->getName() + " is not orphan.");
87   if (_node && _node != nodeToReplace && _node->getName() == node->getName())
88     throw Exception(string("Can't set node: node ") + node->getName() +
89                     " has the same name than exec node already in " + _name + ".");
90   if (_initNode && _initNode != nodeToReplace && _initNode->getName() == node->getName())
91     throw Exception(string("Can't set node: node ") + node->getName() +
92                     " has the same name than init node already in " + _name + ".");
93   if (_finalizeNode && _finalizeNode != nodeToReplace && _finalizeNode->getName() == node->getName())
94     throw Exception(string("Can't set node: node ") + node->getName() +
95                     " has the same name than finalize node already in " + _name + ".");
96   checkNoCrossHierachyWith(node);
97   ComposedNode::edRemoveChild(nodeToReplace);
98   Node * ret = nodeToReplace;
99   nodeToReplace = node;
100   nodeToReplace->_father = this;
101   // set _modified flag so that edUpdateState can refresh state
102   modified();
103   return ret;
104 }
105
106 void DynParaLoop::init(bool start)
107 {
108   ComposedNode::init(start);
109   if(!_node)
110     {
111       string what("DynParaLoop::init : no node specified for ForEachLoop with name "); what +=_name;
112       throw Exception(what);
113     }
114   _node->init(start);
115   if (_initNode) _initNode->init(start);
116   if (_finalizeNode) _finalizeNode->init(start);
117   _nbOfBranches.exInit(start);
118   _splittedPort.exInit();
119   _nbOfEltConsumed=0;
120   _failedCounter=0;
121 }
122
123 Node *DynParaLoop::edSetInitNode(Node *node)
124 {
125   return checkConsistencyAndSetNode(_initNode, node);
126 }
127
128 Node * DynParaLoop::edSetFinalizeNode(Node * node)
129 {
130   return checkConsistencyAndSetNode(_finalizeNode, node);
131 }
132
133 //! Connect an OutPort to an InPort and add control link if necessary
134 /*!
135  * Connect the ports with a data link (edAddLink)
136  * In a Loop don't add control flow link : use this only to add data back links
137  *
138  * \param start : the OutPort to connect
139  * \param end : the InPort to connect
140  * \return  true if a new link has been created, false otherwise.
141  */
142 bool DynParaLoop::edAddDFLink(OutPort *start, InPort *end) throw(YACS::Exception)
143 {
144   return edAddLink(start,end);
145 }
146
147 int DynParaLoop::getNumberOfInputPorts() const
148 {
149   return ComposedNode::getNumberOfInputPorts()+1;
150 }
151
152 int DynParaLoop::getNumberOfOutputPorts() const
153 {
154   return ComposedNode::getNumberOfOutputPorts()+1;
155 }
156
157 /*!
158  * DynParaLoop creates at runtime (exupdateState) clone of nodes. One clone per branch.
159  * This method returns the id of the branch given the node \a node.
160  * If \a node is not a dynamically created node in \a this -1 is returned.
161  */
162 int DynParaLoop::getBranchIDOfNode(Node *node) const
163 {
164   if(_node)
165     {
166       for(std::vector<Node *>::const_iterator it=_execNodes.begin();it!=_execNodes.end();it++)
167         if(node==*it)
168           return std::distance(_execNodes.begin(),it);
169     }
170   if(_finalizeNode)
171     {
172       for(std::vector<Node *>::const_iterator it=_execFinalizeNodes.begin();it!=_execFinalizeNodes.end();it++)
173         if(node==*it)
174           return std::distance(_execFinalizeNodes.begin(),it);
175     }
176   if(_initNode)
177     {
178       for(std::vector<Node *>::const_iterator it=_execInitNodes.begin();it!=_execInitNodes.end();it++)
179         if(node==*it)
180           return std::distance(_execInitNodes.begin(),it);
181     }
182   return -1;
183 }
184
185 std::list<OutputPort *> DynParaLoop::getSetOfOutputPort() const
186 {
187   list<OutputPort *> ret=ComposedNode::getSetOfOutputPort();
188   ret.push_back((OutputPort *)&_splittedPort);
189   return ret;
190 }
191
192 std::list<OutputPort *> DynParaLoop::getLocalOutputPorts() const
193 {
194   list<OutputPort *> ret=ComposedNode::getLocalOutputPorts();
195   ret.push_back((OutputPort *)&_splittedPort);
196   return ret;
197 }
198
199 OutPort *DynParaLoop::getOutPort(const std::string& name) const throw(YACS::Exception)
200 {
201   if (name == NAME_OF_SPLITTED_SEQ_OUT || name == OLD_NAME_OF_SPLITTED_SEQ_OUT)
202     return (OutPort *)&_splittedPort;
203   return ComposedNode::getOutPort(name);
204 }
205
206
207 OutputPort *DynParaLoop::getOutputPort(const std::string& name) const throw(YACS::Exception)
208 {
209   if (name == NAME_OF_SPLITTED_SEQ_OUT || name == OLD_NAME_OF_SPLITTED_SEQ_OUT)
210     return (OutputPort *)&_splittedPort;
211   return ComposedNode::getOutputPort(name);
212 }
213
214 bool DynParaLoop::isPlacementPredictableB4Run() const
215 {
216   return false;
217 }
218
219 Node *DynParaLoop::edRemoveNode()
220 {
221   return removeNode(_node);
222 }
223
224 //! This method is used to factorize methods edRemoveNode, edRemoveInitNode and edRemoveFinalizeNode
225 Node * DynParaLoop::removeNode(Node* &nodeToRemove)
226 {
227   if (!nodeToRemove)
228     return NULL;
229   ComposedNode::edRemoveChild(nodeToRemove);
230   Node * ret = nodeToRemove;
231   nodeToRemove = NULL;
232   modified();
233   return ret;
234 }
235
236 Node *DynParaLoop::edRemoveInitNode()
237 {
238   return removeNode(_initNode);
239 }
240
241 Node * DynParaLoop::edRemoveFinalizeNode()
242 {
243   return removeNode(_finalizeNode);
244 }
245
246 void DynParaLoop::edRemoveChild(Node *node) throw(YACS::Exception)
247 {
248   ComposedNode::edRemoveChild(node);
249   if(node==_node)
250     _node=0;
251   if(node==_initNode)
252     _initNode=0;
253   if(node==_finalizeNode)
254     _finalizeNode=0;
255   modified();
256 }
257
258 bool DynParaLoop::edAddChild(Node *DISOWNnode) throw(YACS::Exception)
259 {
260   return edSetNode(DISOWNnode);
261 }
262
263 std::list<Node *> DynParaLoop::edGetDirectDescendants() const
264 {
265   list<Node *> ret;
266   if(_node)
267     ret.push_back(_node);
268   if(_initNode)
269     ret.push_back(_initNode);
270   if(_finalizeNode)
271     ret.push_back(_finalizeNode);
272   return ret;
273 }
274
275 std::list<InputPort *> DynParaLoop::getSetOfInputPort() const
276 {
277   list<InputPort *> ret=ComposedNode::getSetOfInputPort();
278   ret.push_back((InputPort *)&_nbOfBranches);
279   return ret;
280 }
281
282 InputPort *DynParaLoop::getInputPort(const std::string& name) const throw(YACS::Exception)
283 {
284   if(name==NAME_OF_NUMBER_OF_BRANCHES)
285     return (InputPort *)&_nbOfBranches;
286   return ComposedNode::getInputPort(name);
287 }
288
289 std::list<InputPort *> DynParaLoop::getLocalInputPorts() const
290 {
291   list<InputPort *> ret=ComposedNode::getLocalInputPorts();
292   ret.push_back((InputPort *)&_nbOfBranches);
293   return ret;
294 }
295
296 unsigned DynParaLoop::getNumberOfBranchesCreatedDyn() const throw(YACS::Exception)
297 {
298   if(_execNodes.empty())
299     throw Exception("ForEachLoop::getNumberOfBranches : No branches created dynamically ! - ForEachLoop needs to run or to be runned to call getNumberOfBranches");
300   else
301     return _execNodes.size();
302 }
303
304 Node *DynParaLoop::getChildByShortName(const std::string& name) const throw(YACS::Exception)
305 {
306   if (_node && name == _node->getName())
307     return _node;
308   if (_initNode && name == _initNode->getName())
309     return  _initNode;
310   if (_finalizeNode && name == _finalizeNode->getName())
311     return  _finalizeNode;
312   std::string what("node "); what+= name ; what+=" is not a child of DynParaLoop node "; what += getName();
313   throw Exception(what);
314 }
315
316 Node *DynParaLoop::getChildByNameExec(const std::string& name, unsigned id) const throw(YACS::Exception)
317 {
318   if(id>=getNumberOfBranchesCreatedDyn())
319     throw Exception("ForEachLoop::getChildByNameExec : invalid id - too large compared with dynamically created branches.");
320   if (_node && name == _node->getName())
321     return _execNodes[id];
322   if (_initNode && name == _initNode->getName())
323     return _execInitNodes[id];
324   if (_finalizeNode && name == _finalizeNode->getName())
325     return _execFinalizeNodes[id];
326   std::string what("node "); what+= name ; what+=" is not a child of DynParaLoop node "; what += getName();
327   throw Exception(what);
328 }
329
330 void DynParaLoop::cleanDynGraph()
331 {
332   vector<Node *>::iterator iter;
333   for(iter=_execNodes.begin() ; iter!=_execNodes.end() ; iter++)
334     delete *iter;
335   _execNodes.clear();
336   for(iter=_execInitNodes.begin() ; iter!=_execInitNodes.end() ; iter++)
337     delete *iter;
338   _execInitNodes.clear();
339   for(iter=_execFinalizeNodes.begin() ; iter!=_execFinalizeNodes.end() ; iter++)
340     delete *iter;
341   _execFinalizeNodes.clear();
342 }
343
344 /*!
345  * This method applies on newly cloned on exec nodes (_execNodes/_execInitNodes)
346  * the setting of input ports coming from outside of 'this'
347  */
348 void DynParaLoop::prepareInputsFromOutOfScope(int branchNb)
349 {
350   set< InPort * > portsToSetVals=getAllInPortsComingFromOutsideOfCurrentScope();
351
352   // This tweak is to fix problems with nested dynamic loops where links are not cloned properly
353   list<InPort *> temp = getSetOfInPort();
354   for(list<InPort *>::iterator iter2=temp.begin();iter2!=temp.end();iter2++)
355     {
356       if ((*iter2)->edSetOutPort().size() == 1 && *(*iter2)->edSetOutPort().begin() == NULL)
357         {
358           portsToSetVals.insert(*iter2);
359         }
360     }
361
362   // local input ports are not candidates for dynamically duplicated inport.
363   list<InputPort *> localPorts = getLocalInputPorts();
364   for(list<InputPort *>::iterator iter = localPorts.begin() ; iter != localPorts.end() ; iter++)
365     portsToSetVals.erase(*iter);
366   for(set< InPort * >::iterator iter=portsToSetVals.begin();iter!=portsToSetVals.end();iter++)
367     {
368       InputPort *curPortCasted=(InputPort *) *iter;//Cast granted by ForEachLoop::buildDelegateOf(InPort)
369       void *val=curPortCasted->get();
370       InputPort *portToSet=getDynInputPortByAbsName(branchNb,getInPortName(*iter),true);
371       if(portToSet)//portToSet==0 in case of portToSet==_splitterNode._dataPortToDispatch of ForEach
372         {
373           portToSet->put((const void *)val);
374           portToSet->edNotifyReferencedBy(0);//This is to indicate that somewhere somebody deals with this inputport
375           //even if no direct physical link exists. This exclusively for _execNodes[branchNb]::init on the next turn of loop.
376         }
377     }
378 }
379
380 void DynParaLoop::putValueOnBranch(Any *val, unsigned branchId, bool first)
381 {
382   bool isDispatched = false;
383   set<InPort *> inPrtLkdWthSplttdPrt=_splittedPort.edSetInPort();
384   for(set<InPort *>::iterator iter=inPrtLkdWthSplttdPrt.begin();iter!=inPrtLkdWthSplttdPrt.end();iter++)
385     {
386       std::string portNameOnCurPrt=getPortName(*iter);
387       InputPort *portOnGivenBranch=getDynInputPortByAbsName(branchId,portNameOnCurPrt,first);//Cast granted because impossible to have cross protocol with _splittedPort
388       //see OptimizerLoop::buildDelegateOf
389       if(portOnGivenBranch)
390         {
391           if(first)
392             portOnGivenBranch->edNotifyReferencedBy(0);
393           InputPort *traducer=getRuntime()->adapt(portOnGivenBranch,
394                                                   Runtime::RUNTIME_ENGINE_INTERACTION_IMPL_NAME,_splittedPort.edGetType());
395           traducer->put((const void *)val);
396           isDispatched = true;
397           if(traducer!=portOnGivenBranch)
398             delete traducer;
399         }
400     }
401   if ( isDispatched )
402     {
403       Any *tmp=val->clone();
404       _splittedPort.setValue(tmp);
405       tmp->decrRef();
406     }
407 }
408
409 DynParaLoop::TypeOfNode DynParaLoop::getIdentityOfNotifyerNode(const Node *node, unsigned& id)
410 {
411   vector<Node *>::iterator iter;
412   id=0;
413   for (iter=_execNodes.begin() ; iter!=_execNodes.end() ; iter++,id++)
414     if (*iter==node)
415       return WORK_NODE;
416   id=0;
417   for (iter=_execInitNodes.begin() ; iter!=_execInitNodes.end() ; iter++,id++)
418     if (*iter==node)
419       return INIT_NODE;
420   id=0;
421   for (iter=_execFinalizeNodes.begin() ; iter!=_execFinalizeNodes.end() ; iter++,id++)
422     if (*iter==node)
423       return FINALIZE_NODE;
424 }
425
426 void DynParaLoop::setWeight(double newVal)
427 {
428   if(newVal<=0.)
429     throw Exception("DynParaLoop::setWeight : invalid input value !");
430   _weight=newVal;
431 }
432
433 bool DynParaLoop::isMultiplicitySpecified(unsigned& value) const
434 {
435   if(_nbOfBranches.edIsManuallyInitialized())
436     if(_nbOfBranches.edGetNumberOfLinks()==0)
437       {
438         value=_nbOfBranches.getIntValue();
439         return true;
440       }
441   return false;
442 }
443
444 void DynParaLoop::forceMultiplicity(unsigned value)
445 {
446   _nbOfBranches.edRemoveAllLinksLinkedWithMe();
447   _nbOfBranches.edInit((int)value);
448 }
449
450 void DynParaLoop::buildDelegateOf(InPort * & port, OutPort *initialStart, const std::list<ComposedNode *>& pointsOfView)
451 {
452   string typeOfPortInstance=port->getNameOfTypeOfCurrentInstance();
453   if(typeOfPortInstance!=InputPort::NAME)
454     throw Exception("DynParaLoop::buildDelegateOf : A link with datastream end inside DynParaLoop is not possible");
455 }
456
457 void DynParaLoop::buildDelegateOf(std::pair<OutPort *, OutPort *>& port, InPort *finalTarget, const std::list<ComposedNode *>& pointsOfView)
458 {
459   std::string linkName("(");
460   linkName += port.first->getName()+" to "+finalTarget->getName()+")";
461   if(_initNode)
462     if(isInMyDescendance(port.first->getNode())==_initNode)
463       throw Exception(std::string("Illegal link within a parallel loop: \
464 a link starting from the init node can't leave the scope of the loop.")
465                     + linkName);
466
467   if(_finalizeNode)
468     if(isInMyDescendance(port.first->getNode())==_finalizeNode)
469       throw Exception(std::string("Illegal link within a parallel loop: \
470 an output port of the finalize node can't be linked.")
471                     + linkName);
472
473   if(port.first==&_splittedPort)
474     throw Exception(std::string("Illegal link within a parallel loop: \
475 the 'evalSamples' port must be linked within the scope of the loop.")
476                     + linkName);
477 }
478
479 void DynParaLoop::checkCFLinks(const std::list<OutPort *>& starts, InputPort *end, unsigned char& alreadyFed, bool direction, LinkInfo& info) const
480 {
481   const char what[]="DynParaLoop::checkCFLinks : internal error.";
482   //First dealing checkCFLinks forwarding...
483   if(isInMyDescendance(end->getNode())==0)//no chance that _splittedPort is in starts due to buildDelegate.
484     solveObviousOrDelegateCFLinks(starts,end,alreadyFed,direction,info);
485   else
486     {//no forwarding here.
487       if(starts.size()!=1)
488         throw Exception(what);
489       //ASSERT(direction) : see DynParaLoop::checkControlDependancy only 'fw' filled.
490       if(alreadyFed==FREE_ST)
491         alreadyFed=FED_ST;
492       else if(alreadyFed==FED_ST)
493         {//Shame ! splittedPort fills a port already fed...
494           info.pushInfoLink(*(starts.begin()),end,I_USELESS);
495         }
496     }
497 }
498
499 /*!
500  * \param start : start port
501  * \param end : end port
502  * \param cross indicates if start -> end link is a DS link behind.
503  * \param fw out parameter.
504  * \param fwCross out parameter storing links where a cross has been detected.
505  * \param bw out parameter where backward links are stored.
506  * \param info : collected information
507  */
508 void DynParaLoop::checkControlDependancy(OutPort *start, InPort *end, bool cross,
509                                          std::map < ComposedNode *,  std::list < OutPort * >, SortHierarc >& fw,
510                                          std::vector<OutPort *>& fwCross,
511                                          std::map< ComposedNode *, std::list < OutPort *>, SortHierarc >& bw,
512                                          LinkInfo& info) const
513 {
514     fw[(ComposedNode *)this].push_back(start);
515 }
516
517 void DynParaLoop::checkLinkPossibility(OutPort *start, const std::list<ComposedNode *>& pointsOfViewStart,
518                                 InPort *end, const std::list<ComposedNode *>& pointsOfViewEnd) throw(YACS::Exception)
519 {
520   ComposedNode::checkLinkPossibility(start, pointsOfViewStart, end, pointsOfViewEnd);
521   Node * startNode = isInMyDescendance(start->getNode());
522   Node * endNode = isInMyDescendance(end->getNode());
523   std::string linkName("(");
524   linkName += start->getName()+" to "+end->getName()+")";
525   
526   if(start == &_splittedPort && endNode != _node)
527     throw Exception(std::string("Illegal link within a parallel loop: \
528 the 'evalSamples' port can only be connected to the working node of the loop.")
529                     + linkName);
530   
531   if(_finalizeNode && _finalizeNode == startNode)
532     throw Exception(std::string("Illegal link within a parallel loop: \
533 the finalize node can't be the origin of a link.")
534                     + linkName);
535   
536   if(_initNode && _node == startNode && _initNode == endNode)
537     throw Exception(std::string("Illegal link within a parallel loop: \
538 can't make a link from the working node to the init node.")
539                     + linkName);
540   
541   if(_finalizeNode && _node == startNode && _finalizeNode == endNode)
542     throw Exception(std::string("Illegal link within a parallel loop: \
543 can't make a link from the working node to the finalize node.")
544                     + linkName);
545 }
546
547 /*!
548  * \note : For a given name 'name' of port in absolute form from this, returns the corresponding InputPort 
549  *         instance of the port for the branch # 'branchNb'. 
550  *         The port can be part of _node or _initNode if it exists (if 'initNodeAdmitted' is true).
551  *         \b WARNING : no check performed on  'branchNb' value to see if it is compatible with size of '_execNodes'.
552  *         This method is called to dispatch value on each InputPort linked to this->._splitterNode._splittedPort
553  */
554 InputPort *DynParaLoop::getDynInputPortByAbsName(int branchNb, const std::string& name, bool initNodeAdmitted)
555 {
556   string portName, nodeName;
557   splitNamesBySep(name,Node::SEP_CHAR_IN_PORT,nodeName,portName,true);
558   Node *staticChild = getChildByName(nodeName);
559   Node *desc=isInMyDescendance(staticChild);
560   if(desc==_node)
561     {
562       splitNamesBySep(name,Node::SEP_CHAR_IN_PORT,nodeName,portName,false);
563       return _execNodes[branchNb]->getInputPort(portName);
564     }
565   else if(desc==_initNode)
566     if(initNodeAdmitted)
567       {
568         splitNamesBySep(name,Node::SEP_CHAR_IN_PORT,nodeName,portName,false);
569         return _execInitNodes[branchNb]->getInputPort(portName);
570       }
571   return 0;
572 }
573
574 void DynParaLoop::checkBasicConsistency() const throw(YACS::Exception)
575 {
576   DEBTRACE("DynParaLoop::checkBasicConsistency");
577   ComposedNode::checkBasicConsistency();
578   if(!_node)
579     throw Exception("For a dynamic loop, internal node is mandatory");
580 }
581
582 std::string DynParaLoop::getErrorReport()
583 {
584   DEBTRACE("DynParaLoop::getErrorReport: " << getName() << " " << _state);
585   YACS::StatesForNode effectiveState=getEffectiveState();
586
587   if(effectiveState != YACS::INVALID &&  effectiveState != YACS::ERROR && effectiveState != YACS::FAILED)
588     return "";
589
590   std::string report="<error node= " + getName();
591   switch(effectiveState)
592     {
593     case YACS::INVALID:
594       report=report+" state= INVALID";
595       break;
596     case YACS::ERROR:
597       report=report+" state= ERROR";
598       break;
599     case YACS::FAILED:
600       report=report+" state= FAILED";
601       break;
602     default:
603       break;
604     }
605   report=report + ">\n" ;
606   if(_errorDetails != "")
607     report=report+_errorDetails+"\n";
608
609   if(_execNodes.empty())
610     {
611       // edition node
612       list<Node *> constituents=edGetDirectDescendants();
613       for(list<Node *>::iterator iter=constituents.begin(); iter!=constituents.end(); iter++)
614         {
615           std::string rep=(*iter)->getErrorReport();
616           if(rep != "")
617             {
618               report=report+rep+"\n";
619             }
620         }
621     }
622   else
623     {
624       // execution nodes
625       for(vector<Node *>::iterator iter=_execInitNodes.begin();iter!=_execInitNodes.end();iter++)
626         {
627           std::string rep=(*iter)->getErrorReport();
628           if(rep != "")
629             {
630               report=report+rep+"\n";
631             }
632         }
633       for(vector<Node *>::iterator iter=_execNodes.begin();iter!=_execNodes.end();iter++)
634         {
635           std::string rep=(*iter)->getErrorReport();
636           if(rep != "")
637             {
638               report=report+rep+"\n";
639             }
640         }
641       for(vector<Node *>::iterator iter=_execFinalizeNodes.begin();iter!=_execFinalizeNodes.end();iter++)
642         {
643           std::string rep=(*iter)->getErrorReport();
644           if(rep != "")
645             {
646               report=report+rep+"\n";
647             }
648         }
649     }
650
651   report=report+"</error>";
652   return report;
653 }
654
655 void DynParaLoop::forwardExecStateToOriginalBody(Node *execNode)
656 {
657   unsigned int id;
658   Node * origNode = NULL;
659   switch (getIdentityOfNotifyerNode(execNode,id))
660     {
661     case INIT_NODE:
662     {
663       origNode = _initNode;
664       break;
665     }
666     case WORK_NODE:
667     {
668       origNode = _node;
669       break;
670     }
671     case FINALIZE_NODE:
672     {
673       origNode = _finalizeNode;
674       break;
675     }
676     default:
677       YASSERT(false)
678     }
679
680   YASSERT(origNode != NULL)
681   origNode->setState(execNode->getState());
682   origNode->setErrorDetails(execNode->getErrorDetails());
683
684   ComposedNode* compNode = dynamic_cast<ComposedNode*>(origNode);
685   ComposedNode* compNodeExe = dynamic_cast<ComposedNode*>(execNode);
686   if (compNode && compNodeExe)
687     {
688       list<Node *> aChldn = compNodeExe->getAllRecursiveConstituents();
689       list<Node *>::iterator iter=aChldn.begin();
690       for(;iter!=aChldn.end();iter++)
691         {
692           Node* node=compNode->getChildByName(compNodeExe->getChildName(*iter));
693           node->setState((*iter)->getState());
694           node->setErrorDetails((*iter)->getErrorDetails());
695         }
696     }
697 }
698
699 //! Method used to notify the node that a child node has failed
700 /*!
701  * Update the current state and return the change state
702  *
703  *  \param node : the child node that has failed
704  *  \return the state change
705  */
706 YACS::Event DynParaLoop::updateStateOnFailedEventFrom(Node *node, const Executor *execInst)
707 {
708   DEBTRACE("DynParaLoop::updateStateOnFailedEventFrom " << node->getName());
709   setState(YACS::FAILED);
710   forwardExecStateToOriginalBody(node);
711   unsigned int id;
712   switch (getIdentityOfNotifyerNode(node,id))
713     {
714     case INIT_NODE:
715     {
716       _node->setState(YACS::FAILED);
717       if (_finalizeNode != NULL) _finalizeNode->setState(YACS::FAILED);
718       break;
719     }
720     case WORK_NODE:
721     {
722       if (_finalizeNode != NULL) _finalizeNode->setState(YACS::FAILED);
723       break;
724     }
725     }
726   return YACS::ABORT;
727 }
728
729 //! Clone nodes and make their placement consistent with the placement of the original ones.
730 /*!
731  *  For instance, if two original nodes are placed on a component comp1 in a container cont1
732  *  and a third one is placed on a component comp2 in the container cont1, the clones of the two
733  *  first nodes will be placed on a component comp3 in a container cont2 and the third clone
734  *  will be placed on a component comp4 in the container cont2.
735  */
736 vector<Node *> DynParaLoop::cloneAndPlaceNodesCoherently(const vector<Node *> & origNodes)
737 {
738   DEBTRACE("Begin cloneAndPlaceNodesCoherently")
739   vector<Node *> clones;
740   DeploymentTree treeToDup;
741   vector<list<ElementaryNode *> > origElemNodeList;
742   for (int i=0 ; i<origNodes.size() ; i++)
743     {
744       DEBTRACE("Cloning node " << i)
745       if (origNodes[i] == NULL)
746         {
747           DEBTRACE("Cloning node " << i << ", NULL" )
748           clones.push_back(NULL);
749           origElemNodeList.push_back(list<ElementaryNode *>());
750         }
751       else
752         {
753           DEBTRACE("Cloning node " << i << "," << origNodes[i]->getName())
754           clones.push_back(origNodes[i]->simpleClone(this, false));
755           list<ElementaryNode *> tasks = origNodes[i]->getRecursiveConstituents();
756           origElemNodeList.push_back(tasks);
757           for (list< ElementaryNode *>::iterator iter=tasks.begin() ; iter!=tasks.end() ; iter++)
758             treeToDup.appendTask(*iter, (*iter)->getDynClonerIfExists(this));
759         }
760     }
761   
762   // Build the links between clones.
763   // Only the links starting from initNode are possible.
764   if(_initNode)
765   {
766     std::vector< std::pair<OutPort *, InPort *> > outLinks = _initNode->getSetOfLinksLeavingCurrentScope();
767     std::vector< std::pair<OutPort *, InPort *> >::const_iterator it;
768     for(it=outLinks.begin(); it!=outLinks.end(); it++)
769     {
770       OutPort *startPort = it->first;
771       InPort *endPort = it->second;
772       Node* destNode = isInMyDescendance(endPort->getNode());
773       if(destNode == _node)
774         edAddLink(clones[0]->getOutPort(startPort->getName()),
775                   clones[1]->getInPort(endPort->getName()));
776       if(destNode == _finalizeNode)
777         edAddLink(clones[0]->getOutPort(startPort->getName()),
778                   clones[2]->getInPort(endPort->getName()));
779     }
780   }
781
782   DEBTRACE("Placing nodes...")
783   vector<Container *> conts=treeToDup.getAllContainers();
784
785   //iterate on all containers
786   for(vector<Container *>::iterator iterCt=conts.begin();iterCt!=conts.end();iterCt++)
787     {
788       DEBTRACE("Container " << ((*iterCt)?(*iterCt)->getName():"NULL"))
789       vector<ComponentInstance *> comps=treeToDup.getComponentsLinkedToContainer(*iterCt);
790       Container *contCloned=0;
791       if((*iterCt))
792         contCloned=(*iterCt)->clone();
793
794       //iterate on all component instances linked to the container
795       for(vector<ComponentInstance *>::iterator iterCp=comps.begin();iterCp!=comps.end();iterCp++)
796         {
797           DEBTRACE("Component " << (*iterCp)->getCompoName())
798           vector<Task *> tasks=treeToDup.getTasksLinkedToComponent(*iterCp);
799           ComponentInstance *curCloned=(*iterCp)->clone();
800           DEBTRACE("Assign container " << (*iterCp)->getCompoName())
801           curCloned->setContainer(contCloned);
802           for(vector<Task *>::iterator iterT=tasks.begin();iterT!=tasks.end();iterT++)
803             {
804               DEBTRACE("Task " << ((ElementaryNode *)(*iterT))->getName())
805               int i = 0;
806               ElementaryNode * origElemNode = NULL;
807               for (i=0 ; i<origNodes.size() ; i++)
808                 if (origNodes[i] != NULL)
809                   {
810                     DEBTRACE("Looking in original node " << i)
811                     list<ElementaryNode *>::iterator res=find(origElemNodeList[i].begin(),
812                                                               origElemNodeList[i].end(),
813                                                               (ElementaryNode *)(*iterT));
814                     if (res != origElemNodeList[i].end()) {
815                       origElemNode = *res;
816                       break;
817                     }
818                   }
819
820               YASSERT(origElemNode != NULL)
821               DEBTRACE("Found task in node " << i)
822               ServiceNode * nodeC = NULL;
823               if (origNodes[i] == origElemNode)
824                 nodeC = (ServiceNode *)clones[i];
825               else
826                 {
827                   string childName = ((ComposedNode *)origNodes[i])->getChildName(origElemNode);
828                   nodeC = (ServiceNode *)clones[i]->getChildByName(childName);
829                 }
830               DEBTRACE("Assign component: " << (*iterCp)->getCompoName() << "," << nodeC->getName())
831               nodeC->setComponent(curCloned);
832             }
833           curCloned->decrRef();
834         }
835
836       // iterate on all tasks linked to the container
837       vector<Task *> tasks=treeToDup.getTasksLinkedToContainer(*iterCt);
838       for(vector<Task *>::iterator iterT=tasks.begin();iterT!=tasks.end();iterT++)
839         {
840           DEBTRACE("Task " << ((ElementaryNode *)(*iterT))->getName())
841           int i = 0;
842           ElementaryNode * origElemNode = NULL;
843           for (i=0 ; i<origNodes.size() ; i++)
844             if (origNodes[i] != NULL)
845               {
846                 DEBTRACE("Looking in original node " << i)
847                 list<ElementaryNode *>::iterator res=find(origElemNodeList[i].begin(),
848                                                           origElemNodeList[i].end(),
849                                                           (ElementaryNode *)(*iterT));
850                 if (res != origElemNodeList[i].end()) 
851                   {
852                     origElemNode = *res;
853                     break;
854                   }
855               }
856           YASSERT(origElemNode != NULL)
857           DEBTRACE("Found task in node " << i)
858           InlineFuncNode * nodeC = NULL;
859           if (origNodes[i] == origElemNode)
860             {
861               nodeC = (InlineFuncNode *)clones[i];
862             }
863           else
864             {
865               string childName = ((ComposedNode *)origNodes[i])->getChildName(origElemNode);
866               nodeC = (InlineFuncNode *)clones[i]->getChildByName(childName);
867             }
868           DEBTRACE("Assign container " << nodeC->getName() << "," << contCloned->getName())
869           nodeC->setContainer(contCloned);
870         }
871
872       // ended with current container
873       if(contCloned)
874         contCloned->decrRef();
875     }
876
877   DEBTRACE("End cloneAndPlaceNodesCoherently")
878   return clones;
879 }
880
881 void DynParaLoop::accept(Visitor *visitor)
882 {
883   visitor->visitDynParaLoop(this);
884 }
885
886 Node * DynParaLoop::getInitNode()
887 {
888   return _initNode;
889 }
890
891 Node * DynParaLoop::getExecNode()
892 {
893   return _node;
894 }
895
896 Node * DynParaLoop::getFinalizeNode()
897 {
898   return _finalizeNode;
899 }
900
901 int DynParaLoop::getMaxLevelOfParallelism() const
902 {
903   return _nbOfBranches.getIntValue() * _node->getMaxLevelOfParallelism();
904 }
905
906 void DynParaLoop::partitionRegardingDPL(const PartDefinition *pd, std::map<ComposedNode *, YACS::BASES::AutoRefCnt<PartDefinition> >& zeMap)
907 {
908   YACS::BASES::AutoRefCnt<PartDefinition> pd2(pd->copy());
909   zeMap[this]=pd2;
910   if(_node)
911     _node->partitionRegardingDPL(pd,zeMap);
912 }
913
914 void DynParaLoop::shutdown(int level)
915 {
916   if(level==0)return;
917   if(!_node) return;
918
919   std::vector<Node *>::iterator iter;
920   for (iter=_execNodes.begin() ; iter!=_execNodes.end() ; iter++)
921     (*iter)->shutdown(level);
922   for (iter=_execInitNodes.begin() ; iter!=_execInitNodes.end() ; iter++)
923     (*iter)->shutdown(level);
924   for (iter=_execFinalizeNodes.begin() ; iter!=_execFinalizeNodes.end() ; iter++)
925     (*iter)->shutdown(level);
926 }