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