]> SALOME platform Git repositories - modules/yacs.git/blob - src/engine/DynParaLoop.cxx
Salome HOME
WIP
[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 DynParaLoop::DynParaLoop(const std::string& name, TypeCode *typeOfDataSplitted)
43   : ComposedNode(name),_node(0),_initNode(0),_finalizeNode(0),_nbOfEltConsumed(0),
44     _nbOfBranches(this),
45     _splittedPort(NAME_OF_SPLITTED_SEQ_OUT,this,typeOfDataSplitted),_initializingCounter(0),_unfinishedCounter(0),_failedCounter(0),_weight(), _loopWeight(0)
46 {
47   _weight.setDefaultLoop();
48 }
49
50 DynParaLoop::~DynParaLoop()
51 {
52   delete _node;
53   delete _initNode;
54   delete _finalizeNode;
55 }
56
57 DynParaLoop::DynParaLoop(const DynParaLoop& other, ComposedNode *father, bool editionOnly)
58   : ComposedNode(other,father), _nbOfBranches(other._nbOfBranches,this),
59     _splittedPort(other._splittedPort,this), _node(0), _initNode(0), _finalizeNode(0),
60     _nbOfEltConsumed(0),_initializingCounter(0),_unfinishedCounter(0),_failedCounter(0),_weight(other._weight), _loopWeight(other._loopWeight)
61 {
62   if(other._node)
63     _node=other._node->clone(this,editionOnly);
64   if(other._initNode)
65     _initNode=other._initNode->clone(this,editionOnly);
66   if(other._finalizeNode)
67     _finalizeNode = other._finalizeNode->clone(this,editionOnly);
68   const AnyOutputPort& startOfLinksToReproduce=other._splittedPort;
69   set<InPort *> endsOfLinksToReproduce=startOfLinksToReproduce.edSetInPort();
70   for(set<InPort *>::iterator iter=endsOfLinksToReproduce.begin();iter!=endsOfLinksToReproduce.end();iter++)
71     edAddLink(&_splittedPort,getInPort(other.getPortName(*iter)));
72 }
73
74 Node *DynParaLoop::edSetNode(Node *node)
75 {
76   return checkConsistencyAndSetNode(_node, node);
77 }
78
79 //! This method is used to factorize methods edSetNode, edSetInitNode and edSetFinalizeNode
80 Node * DynParaLoop::checkConsistencyAndSetNode(Node* &nodeToReplace, Node* node)
81 {
82   if (node == NULL || nodeToReplace == node)
83     return 0;
84   if (node->_father)
85     throw Exception(string("Can't set node: node ") + node->getName() + " is not orphan.");
86   if (_node && _node != nodeToReplace && _node->getName() == node->getName())
87     throw Exception(string("Can't set node: node ") + node->getName() +
88                     " has the same name than exec node already in " + _name + ".");
89   if (_initNode && _initNode != nodeToReplace && _initNode->getName() == node->getName())
90     throw Exception(string("Can't set node: node ") + node->getName() +
91                     " has the same name than init node already in " + _name + ".");
92   if (_finalizeNode && _finalizeNode != nodeToReplace && _finalizeNode->getName() == node->getName())
93     throw Exception(string("Can't set node: node ") + node->getName() +
94                     " has the same name than finalize node already in " + _name + ".");
95   checkNoCrossHierachyWith(node);
96   ComposedNode::edRemoveChild(nodeToReplace);
97   Node * ret = nodeToReplace;
98   nodeToReplace = node;
99   nodeToReplace->_father = this;
100   // set _modified flag so that edUpdateState can refresh state
101   modified();
102   return ret;
103 }
104
105 void DynParaLoop::init(bool start)
106 {
107   ComposedNode::init(start);
108   if(!_node)
109     {
110       string what("DynParaLoop::init : no node specified for ForEachLoop with name "); what +=_name;
111       throw Exception(what);
112     }
113   _node->init(start);
114   if (_initNode) _initNode->init(start);
115   if (_finalizeNode) _finalizeNode->init(start);
116   _nbOfBranches.exInit(start);
117   _splittedPort.exInit();
118   _nbOfEltConsumed=0;
119   _failedCounter=0;
120 }
121
122 Node *DynParaLoop::edSetInitNode(Node *node)
123 {
124   return checkConsistencyAndSetNode(_initNode, node);
125 }
126
127 Node * DynParaLoop::edSetFinalizeNode(Node * node)
128 {
129   return checkConsistencyAndSetNode(_finalizeNode, node);
130 }
131
132 //! Connect an OutPort to an InPort and add control link if necessary
133 /*!
134  * Connect the ports with a data link (edAddLink)
135  * In a Loop don't add control flow link : use this only to add data back links
136  *
137  * \param start : the OutPort to connect
138  * \param end : the InPort to connect
139  * \return  true if a new link has been created, false otherwise.
140  */
141 bool DynParaLoop::edAddDFLink(OutPort *start, InPort *end) throw(YACS::Exception)
142 {
143   return edAddLink(start,end);
144 }
145
146 int DynParaLoop::getNumberOfInputPorts() const
147 {
148   return ComposedNode::getNumberOfInputPorts()+1;
149 }
150
151 int DynParaLoop::getNumberOfOutputPorts() const
152 {
153   return ComposedNode::getNumberOfOutputPorts()+1;
154 }
155
156 /*!
157  * DynParaLoop creates at runtime (exupdateState) clone of nodes. One clone per branch.
158  * This method returns the id of the branch given the node \a node.
159  * If \a node is not a dynamically created node in \a this -1 is returned.
160  */
161 int DynParaLoop::getBranchIDOfNode(Node *node) const
162 {
163   if(_node)
164     {
165       for(std::vector<Node *>::const_iterator it=_execNodes.begin();it!=_execNodes.end();it++)
166         if(node==*it)
167           return std::distance(_execNodes.begin(),it);
168     }
169   if(_finalizeNode)
170     {
171       for(std::vector<Node *>::const_iterator it=_execFinalizeNodes.begin();it!=_execFinalizeNodes.end();it++)
172         if(node==*it)
173           return std::distance(_execFinalizeNodes.begin(),it);
174     }
175   if(_initNode)
176     {
177       for(std::vector<Node *>::const_iterator it=_execInitNodes.begin();it!=_execInitNodes.end();it++)
178         if(node==*it)
179           return std::distance(_execInitNodes.begin(),it);
180     }
181   return -1;
182 }
183
184 std::list<OutputPort *> DynParaLoop::getSetOfOutputPort() const
185 {
186   list<OutputPort *> ret=ComposedNode::getSetOfOutputPort();
187   ret.push_back((OutputPort *)&_splittedPort);
188   return ret;
189 }
190
191 std::list<OutputPort *> DynParaLoop::getLocalOutputPorts() const
192 {
193   list<OutputPort *> ret=ComposedNode::getLocalOutputPorts();
194   ret.push_back((OutputPort *)&_splittedPort);
195   return ret;
196 }
197
198 OutPort *DynParaLoop::getOutPort(const std::string& name) const throw(YACS::Exception)
199 {
200   if (name == NAME_OF_SPLITTED_SEQ_OUT || name == OLD_NAME_OF_SPLITTED_SEQ_OUT)
201     return (OutPort *)&_splittedPort;
202   return ComposedNode::getOutPort(name);
203 }
204
205
206 OutputPort *DynParaLoop::getOutputPort(const std::string& name) const throw(YACS::Exception)
207 {
208   if (name == NAME_OF_SPLITTED_SEQ_OUT || name == OLD_NAME_OF_SPLITTED_SEQ_OUT)
209     return (OutputPort *)&_splittedPort;
210   return ComposedNode::getOutputPort(name);
211 }
212
213 bool DynParaLoop::isPlacementPredictableB4Run() const
214 {
215   return false;
216 }
217
218 Node *DynParaLoop::edRemoveNode()
219 {
220   return removeNode(_node);
221 }
222
223 //! This method is used to factorize methods edRemoveNode, edRemoveInitNode and edRemoveFinalizeNode
224 Node * DynParaLoop::removeNode(Node* &nodeToRemove)
225 {
226   if (!nodeToRemove)
227     return NULL;
228   ComposedNode::edRemoveChild(nodeToRemove);
229   Node * ret = nodeToRemove;
230   nodeToRemove = NULL;
231   modified();
232   return ret;
233 }
234
235 Node *DynParaLoop::edRemoveInitNode()
236 {
237   return removeNode(_initNode);
238 }
239
240 Node * DynParaLoop::edRemoveFinalizeNode()
241 {
242   return removeNode(_finalizeNode);
243 }
244
245 void DynParaLoop::edRemoveChild(Node *node) throw(YACS::Exception)
246 {
247   ComposedNode::edRemoveChild(node);
248   if(node==_node)
249     _node=0;
250   if(node==_initNode)
251     _initNode=0;
252   if(node==_finalizeNode)
253     _finalizeNode=0;
254   modified();
255 }
256
257 bool DynParaLoop::edAddChild(Node *DISOWNnode) throw(YACS::Exception)
258 {
259   return edSetNode(DISOWNnode);
260 }
261
262 std::list<Node *> DynParaLoop::edGetDirectDescendants() const
263 {
264   list<Node *> ret;
265   if(_node)
266     ret.push_back(_node);
267   if(_initNode)
268     ret.push_back(_initNode);
269   if(_finalizeNode)
270     ret.push_back(_finalizeNode);
271   return ret;
272 }
273
274 std::list<InputPort *> DynParaLoop::getSetOfInputPort() const
275 {
276   list<InputPort *> ret=ComposedNode::getSetOfInputPort();
277   ret.push_back(_nbOfBranches.getPort());
278   return ret;
279 }
280
281 InputPort *DynParaLoop::getInputPort(const std::string& name) const throw(YACS::Exception)
282 {
283   if(NbBranches::IsBranchPortName(name))
284     return _nbOfBranches.getPort();
285   return ComposedNode::getInputPort(name);
286 }
287
288 std::list<InputPort *> DynParaLoop::getLocalInputPorts() const
289 {
290   list<InputPort *> ret=ComposedNode::getLocalInputPorts();
291   ret.push_back(_nbOfBranches.getPort());
292   return ret;
293 }
294
295 unsigned DynParaLoop::getNumberOfBranchesCreatedDyn() const throw(YACS::Exception)
296 {
297   if(_execNodes.empty())
298     throw Exception("ForEachLoop::getNumberOfBranches : No branches created dynamically ! - ForEachLoop needs to run or to be runned to call getNumberOfBranches");
299   else
300     return _execNodes.size();
301 }
302
303 Node *DynParaLoop::getChildByShortName(const std::string& name) const throw(YACS::Exception)
304 {
305   if (_node && name == _node->getName())
306     return _node;
307   if (_initNode && name == _initNode->getName())
308     return  _initNode;
309   if (_finalizeNode && name == _finalizeNode->getName())
310     return  _finalizeNode;
311   std::string what("node "); what+= name ; what+=" is not a child of DynParaLoop node "; what += getName();
312   throw Exception(what);
313 }
314
315 Node *DynParaLoop::getChildByNameExec(const std::string& name, unsigned id) const throw(YACS::Exception)
316 {
317   if(id>=getNumberOfBranchesCreatedDyn())
318     throw Exception("ForEachLoop::getChildByNameExec : invalid id - too large compared with dynamically created branches.");
319   if (_node && name == _node->getName())
320     return _execNodes[id];
321   if (_initNode && name == _initNode->getName())
322     return _execInitNodes[id];
323   if (_finalizeNode && name == _finalizeNode->getName())
324     return _execFinalizeNodes[id];
325   std::string what("node "); what+= name ; what+=" is not a child of DynParaLoop node "; what += getName();
326   throw Exception(what);
327 }
328
329 void DynParaLoop::cleanDynGraph()
330 {
331   vector<Node *>::iterator iter;
332   for(iter=_execNodes.begin() ; iter!=_execNodes.end() ; iter++)
333     delete *iter;
334   _execNodes.clear();
335   for(iter=_execInitNodes.begin() ; iter!=_execInitNodes.end() ; iter++)
336     delete *iter;
337   _execInitNodes.clear();
338   for(iter=_execFinalizeNodes.begin() ; iter!=_execFinalizeNodes.end() ; iter++)
339     delete *iter;
340   _execFinalizeNodes.clear();
341 }
342
343 /*!
344  * This method applies on newly cloned on exec nodes (_execNodes/_execInitNodes)
345  * the setting of input ports coming from outside of 'this'
346  */
347 void DynParaLoop::prepareInputsFromOutOfScope(int branchNb)
348 {
349   set< InPort * > portsToSetVals=getAllInPortsComingFromOutsideOfCurrentScope();
350
351   // This tweak is to fix problems with nested dynamic loops where links are not cloned properly
352   list<InPort *> temp = getSetOfInPort();
353   for(list<InPort *>::iterator iter2=temp.begin();iter2!=temp.end();iter2++)
354     {
355       if ((*iter2)->edSetOutPort().size() == 1 && *(*iter2)->edSetOutPort().begin() == NULL)
356         {
357           portsToSetVals.insert(*iter2);
358         }
359     }
360
361   // local input ports are not candidates for dynamically duplicated inport.
362   list<InputPort *> localPorts = getLocalInputPorts();
363   for(list<InputPort *>::iterator iter = localPorts.begin() ; iter != localPorts.end() ; iter++)
364     portsToSetVals.erase(*iter);
365   for(set< InPort * >::iterator iter=portsToSetVals.begin();iter!=portsToSetVals.end();iter++)
366     {
367       InputPort *curPortCasted=(InputPort *) *iter;//Cast granted by ForEachLoop::buildDelegateOf(InPort)
368       void *val=curPortCasted->get();
369       InputPort *portToSet=getDynInputPortByAbsName(branchNb,getInPortName(*iter),true);
370       if(portToSet)//portToSet==0 in case of portToSet==_splitterNode._dataPortToDispatch of ForEach
371         {
372           portToSet->put((const void *)val);
373           portToSet->edNotifyReferencedBy(nullptr,false);//This is to indicate that somewhere somebody deals with this inputport
374           //even if no direct physical link exists. This exclusively for _execNodes[branchNb]::init on the next turn of loop.
375           //false is put as 2nd parameter to tell to portToSet, do not touch to the data in case of squeezeMemory.
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 loopWeight)
427 {
428   if(loopWeight<=0.)
429     throw Exception("DynParaLoop::setWeight : invalid input value !");
430   _loopWeight=loopWeight;
431 }
432
433 ComplexWeight* DynParaLoop::getWeight()
434 {
435   if (_loopWeight>0.)
436     _weight.setLoopWeight(_loopWeight, _node->getMaxLevelOfParallelism()); // not done in setWeight because _node can be null at that time
437   return &_weight;      
438 }
439
440 bool DynParaLoop::isMultiplicitySpecified(unsigned& value) const
441 {
442   return _nbOfBranches.isMultiplicitySpecified(value);
443 }
444
445 void DynParaLoop::forceMultiplicity(unsigned value)
446 {
447   _nbOfBranches.forceMultiplicity(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           if(*iter)
636             {
637               std::string rep=(*iter)->getErrorReport();
638               if(rep != "")
639                 {
640                   report=report+rep+"\n";
641                 }
642             }
643         }
644       for(vector<Node *>::iterator iter=_execFinalizeNodes.begin();iter!=_execFinalizeNodes.end();iter++)
645         {
646           std::string rep=(*iter)->getErrorReport();
647           if(rep != "")
648             {
649               report=report+rep+"\n";
650             }
651         }
652     }
653
654   report=report+"</error>";
655   return report;
656 }
657
658 void DynParaLoop::forwardExecStateToOriginalBody(Node *execNode)
659 {
660   unsigned int id;
661   Node * origNode = NULL;
662   switch (getIdentityOfNotifyerNode(execNode,id))
663     {
664     case INIT_NODE:
665     {
666       origNode = _initNode;
667       break;
668     }
669     case WORK_NODE:
670     {
671       origNode = _node;
672       break;
673     }
674     case FINALIZE_NODE:
675     {
676       origNode = _finalizeNode;
677       break;
678     }
679     default:
680       YASSERT(false)
681     }
682
683   YASSERT(origNode != NULL)
684   origNode->setState(execNode->getState());
685   origNode->setErrorDetails(execNode->getErrorDetails());
686
687   ComposedNode* compNode = dynamic_cast<ComposedNode*>(origNode);
688   ComposedNode* compNodeExe = dynamic_cast<ComposedNode*>(execNode);
689   if (compNode && compNodeExe)
690     {
691       list<Node *> aChldn = compNodeExe->getAllRecursiveConstituents();
692       list<Node *>::iterator iter=aChldn.begin();
693       for(;iter!=aChldn.end();iter++)
694         {
695           Node* node=compNode->getChildByName(compNodeExe->getChildName(*iter));
696           node->setState((*iter)->getState());
697           node->setErrorDetails((*iter)->getErrorDetails());
698         }
699     }
700 }
701
702 //! Method used to notify the node that a child node has failed
703 /*!
704  * Update the current state and return the change state
705  *
706  *  \param node : the child node that has failed
707  *  \return the state change
708  */
709 YACS::Event DynParaLoop::updateStateOnFailedEventFrom(Node *node, const Executor *execInst)
710 {
711   DEBTRACE("DynParaLoop::updateStateOnFailedEventFrom " << node->getName());
712   setState(YACS::FAILED);
713   forwardExecStateToOriginalBody(node);
714   unsigned int id;
715   switch (getIdentityOfNotifyerNode(node,id))
716     {
717     case INIT_NODE:
718     {
719       _node->setState(YACS::FAILED);
720       if (_finalizeNode != NULL) _finalizeNode->setState(YACS::FAILED);
721       break;
722     }
723     case WORK_NODE:
724     {
725       if (_finalizeNode != NULL) _finalizeNode->setState(YACS::FAILED);
726       break;
727     }
728     }
729   return YACS::ABORT;
730 }
731
732 //! Clone nodes and make their placement consistent with the placement of the original ones.
733 /*!
734  *  For instance, if two original nodes are placed on a component comp1 in a container cont1
735  *  and a third one is placed on a component comp2 in the container cont1, the clones of the two
736  *  first nodes will be placed on a component comp3 in a container cont2 and the third clone
737  *  will be placed on a component comp4 in the container cont2.
738  */
739 vector<Node *> DynParaLoop::cloneAndPlaceNodesCoherently(const vector<Node *> & origNodes)
740 {
741   DEBTRACE("Begin cloneAndPlaceNodesCoherently")
742   vector<Node *> clones;
743   DeploymentTree treeToDup;
744   vector<list<ElementaryNode *> > origElemNodeList;
745   for (int i=0 ; i<origNodes.size() ; i++)
746     {
747       DEBTRACE("Cloning node " << i)
748       if (origNodes[i] == NULL)
749         {
750           DEBTRACE("Cloning node " << i << ", NULL" )
751           clones.push_back(NULL);
752           origElemNodeList.push_back(list<ElementaryNode *>());
753         }
754       else
755         {
756           DEBTRACE("Cloning node " << i << "," << origNodes[i]->getName())
757           clones.push_back(origNodes[i]->simpleClone(this, false));
758           list<ElementaryNode *> tasks = origNodes[i]->getRecursiveConstituents();
759           origElemNodeList.push_back(tasks);
760           for (list< ElementaryNode *>::iterator iter=tasks.begin() ; iter!=tasks.end() ; iter++)
761             treeToDup.appendTask(*iter, (*iter)->getDynClonerIfExists(this));
762         }
763     }
764   
765   // Build the links between clones.
766   // Only the links starting from initNode are possible.
767   if(_initNode)
768   {
769     std::vector< std::pair<OutPort *, InPort *> > outLinks = _initNode->getSetOfLinksLeavingCurrentScope();
770     std::vector< std::pair<OutPort *, InPort *> >::const_iterator it;
771     for(it=outLinks.begin(); it!=outLinks.end(); it++)
772     {
773       OutPort *startPort = it->first;
774       InPort *endPort = it->second;
775       Node* destNode = isInMyDescendance(endPort->getNode());
776       if(destNode == _node)
777         edAddLink(clones[0]->getOutPort(startPort->getName()),
778                   clones[1]->getInPort(endPort->getName()));
779       if(destNode == _finalizeNode)
780         edAddLink(clones[0]->getOutPort(startPort->getName()),
781                   clones[2]->getInPort(endPort->getName()));
782     }
783   }
784
785   DEBTRACE("Placing nodes...")
786   vector<Container *> conts=treeToDup.getAllContainers();
787
788   //iterate on all containers
789   for(vector<Container *>::iterator iterCt=conts.begin();iterCt!=conts.end();iterCt++)
790     {
791       DEBTRACE("Container " << ((*iterCt)?(*iterCt)->getName():"NULL"))
792       vector<ComponentInstance *> comps=treeToDup.getComponentsLinkedToContainer(*iterCt);
793       Container *contCloned=0;
794       if((*iterCt))
795         contCloned=(*iterCt)->clone();
796
797       //iterate on all component instances linked to the container
798       for(vector<ComponentInstance *>::iterator iterCp=comps.begin();iterCp!=comps.end();iterCp++)
799         {
800           DEBTRACE("Component " << (*iterCp)->getCompoName())
801           vector<Task *> tasks=treeToDup.getTasksLinkedToComponent(*iterCp);
802           ComponentInstance *curCloned=(*iterCp)->clone();
803           DEBTRACE("Assign container " << (*iterCp)->getCompoName())
804           curCloned->setContainer(contCloned);
805           for(vector<Task *>::iterator iterT=tasks.begin();iterT!=tasks.end();iterT++)
806             {
807               DEBTRACE("Task " << ((ElementaryNode *)(*iterT))->getName())
808               int i = 0;
809               ElementaryNode * origElemNode = NULL;
810               for (i=0 ; i<origNodes.size() ; i++)
811                 if (origNodes[i] != NULL)
812                   {
813                     DEBTRACE("Looking in original node " << i)
814                     list<ElementaryNode *>::iterator res=find(origElemNodeList[i].begin(),
815                                                               origElemNodeList[i].end(),
816                                                               (ElementaryNode *)(*iterT));
817                     if (res != origElemNodeList[i].end()) {
818                       origElemNode = *res;
819                       break;
820                     }
821                   }
822
823               YASSERT(origElemNode != NULL)
824               DEBTRACE("Found task in node " << i)
825               ServiceNode * nodeC = NULL;
826               if (origNodes[i] == origElemNode)
827                 nodeC = (ServiceNode *)clones[i];
828               else
829                 {
830                   string childName = ((ComposedNode *)origNodes[i])->getChildName(origElemNode);
831                   nodeC = (ServiceNode *)clones[i]->getChildByName(childName);
832                 }
833               DEBTRACE("Assign component: " << (*iterCp)->getCompoName() << "," << nodeC->getName())
834               nodeC->setComponent(curCloned);
835             }
836           curCloned->decrRef();
837         }
838
839       // iterate on all tasks linked to the container
840       vector<Task *> tasks=treeToDup.getTasksLinkedToContainer(*iterCt);
841       for(vector<Task *>::iterator iterT=tasks.begin();iterT!=tasks.end();iterT++)
842         {
843           DEBTRACE("Task " << ((ElementaryNode *)(*iterT))->getName())
844           int i = 0;
845           ElementaryNode * origElemNode = NULL;
846           for (i=0 ; i<origNodes.size() ; i++)
847             if (origNodes[i] != NULL)
848               {
849                 DEBTRACE("Looking in original node " << i)
850                 list<ElementaryNode *>::iterator res=find(origElemNodeList[i].begin(),
851                                                           origElemNodeList[i].end(),
852                                                           (ElementaryNode *)(*iterT));
853                 if (res != origElemNodeList[i].end()) 
854                   {
855                     origElemNode = *res;
856                     break;
857                   }
858               }
859           YASSERT(origElemNode != NULL)
860           DEBTRACE("Found task in node " << i)
861           InlineFuncNode * nodeC = NULL;
862           if (origNodes[i] == origElemNode)
863             {
864               nodeC = (InlineFuncNode *)clones[i];
865             }
866           else
867             {
868               string childName = ((ComposedNode *)origNodes[i])->getChildName(origElemNode);
869               nodeC = (InlineFuncNode *)clones[i]->getChildByName(childName);
870             }
871           DEBTRACE("Assign container " << nodeC->getName() << "," << contCloned->getName())
872           nodeC->setContainer(contCloned);
873         }
874
875       // ended with current container
876       if(contCloned)
877         contCloned->decrRef();
878     }
879
880   DEBTRACE("End cloneAndPlaceNodesCoherently")
881   return clones;
882 }
883
884 void DynParaLoop::accept(Visitor *visitor)
885 {
886   visitor->visitDynParaLoop(this);
887 }
888
889 Node * DynParaLoop::getInitNode()
890 {
891   return _initNode;
892 }
893
894 Node * DynParaLoop::getExecNode()
895 {
896   return _node;
897 }
898
899 Node * DynParaLoop::getFinalizeNode()
900 {
901   return _finalizeNode;
902 }
903
904 int DynParaLoop::getMaxLevelOfParallelism() const
905 {
906   return _nbOfBranches.getIntValue() * _node->getMaxLevelOfParallelism();
907 }
908
909 void DynParaLoop::partitionRegardingDPL(const PartDefinition *pd, std::map<ComposedNode *, YACS::BASES::AutoRefCnt<PartDefinition> >& zeMap)
910 {
911   YACS::BASES::AutoRefCnt<PartDefinition> pd2(pd->copy());
912   zeMap[this]=pd2;
913   if(_node)
914     _node->partitionRegardingDPL(pd,zeMap);
915 }
916
917 void DynParaLoop::shutdown(int level)
918 {
919   if(level==0)return;
920   if(!_node) return;
921
922   std::vector<Node *>::iterator iter;
923   for (iter=_execNodes.begin() ; iter!=_execNodes.end() ; iter++)
924     (*iter)->shutdown(level);
925   for (iter=_execInitNodes.begin() ; iter!=_execInitNodes.end() ; iter++)
926     (*iter)->shutdown(level);
927   for (iter=_execFinalizeNodes.begin() ; iter!=_execFinalizeNodes.end() ; iter++)
928     (*iter)->shutdown(level);
929 }