Salome HOME
Squeeze memory of process hosting YACS graph
[modules/yacs.git] / src / engine / ForEachLoop.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 "ForEachLoop.hxx"
21 #include "TypeCode.hxx"
22 #include "Visitor.hxx"
23 #include "ComposedNode.hxx"
24 #include "Executor.hxx"
25 #include "AutoLocker.hxx"
26
27 #include <iostream>
28 #include <iomanip>
29 #include <sstream>
30 #include <algorithm>    // std::replace_if
31
32 //#define _DEVDEBUG_
33 #include "YacsTrace.hxx"
34
35 #ifdef WIN32
36 #include <functional>
37 #endif
38
39 using namespace YACS::ENGINE;
40 using namespace std;
41
42 /*! \class YACS::ENGINE::ForEachLoop
43  *  \brief Loop node for parametric calculation
44  *
45  *  \ingroup Nodes
46  */
47
48 const char FakeNodeForForEachLoop::NAME[]="thisIsAFakeNode";
49
50 const char SplitterNode::NAME_OF_SEQUENCE_INPUT[]="SmplsCollection";
51
52 const char ForEachLoop::NAME_OF_SPLITTERNODE[]="splitter";
53
54 const int ForEachLoop::NOT_RUNNING_BRANCH_ID=-1;
55
56 const char ForEachLoop::INTERCEPTOR_STR[]="_interceptor";
57
58 InterceptorInputPort::InterceptorInputPort(const std::string& name, Node *node, TypeCode* type):AnyInputPort(name,node,type),
59                                                                                                 DataPort(name,node,type),Port(node),
60                                                                                                 _repr(0)
61 {
62 }
63
64 InterceptorInputPort::InterceptorInputPort(const  InterceptorInputPort& other, Node *newHelder):AnyInputPort(other,newHelder),DataPort(other,newHelder),
65                                                                                                 Port(other,newHelder),
66                                                                                                 _repr(0)
67 {
68 }
69
70 void InterceptorInputPort::getAllRepresentants(std::set<InPort *>& repr) const
71 {
72   set<InPort *> ports=_repr->edSetInPort();
73   for(set<InPort *>::iterator iter=ports.begin();iter!=ports.end();iter++)
74     (*iter)->getAllRepresentants(repr);
75 }
76
77 InputPort *InterceptorInputPort::clone(Node *newHelder) const
78 {
79   return new InterceptorInputPort(*this,newHelder);
80 }
81
82 void InterceptorInputPort::setRepr(AnySplitOutputPort *repr)
83 {
84   _repr=repr;
85 }
86
87 bool AnySplitOutputPort::decrRef()
88 {
89   return (--_cnt==0);
90 }
91
92 void AnySplitOutputPort::incrRef() const
93 {
94   _cnt++;
95 }
96
97 AnySplitOutputPort::AnySplitOutputPort(const std::string& name, Node *node, TypeCode *type):OutputPort(name,node,type),
98                                                                                             DataPort(name,node,type),Port(node),
99                                                                                             _repr(0),_intercptr(0),_cnt(1)
100 {
101 }
102
103 AnySplitOutputPort::AnySplitOutputPort(const AnySplitOutputPort& other, Node *newHelder):OutputPort(other,newHelder),
104                                                                                          DataPort(other,newHelder),
105                                                                                          Port(other,newHelder),
106                                                                                          _repr(0),_intercptr(0),_cnt(1)
107 {
108 }
109
110 bool AnySplitOutputPort::addInPort(InPort *inPort) throw(YACS::Exception)
111 {
112   bool ret=OutputPort::addInPort(inPort);
113   if(_repr)
114     _repr->addInPort(_intercptr);
115   return ret;
116 }
117
118 void AnySplitOutputPort::getAllRepresented(std::set<OutPort *>& represented) const
119 {
120   if(!_repr)
121     OutPort::getAllRepresented(represented);
122   else
123     _repr->getAllRepresented(represented);
124 }
125
126 int AnySplitOutputPort::removeInPort(InPort *inPort, bool forward) throw(YACS::Exception)
127 {
128   bool ret=OutputPort::removeInPort(inPort,forward);
129   if(_repr)
130     if(_setOfInputPort.empty())
131       _repr->removeInPort(_intercptr,forward);
132   return ret;
133 }
134
135 void AnySplitOutputPort::addRepr(OutPort *repr, InterceptorInputPort *intercptr)
136 {
137   _repr=repr;
138   _intercptr=intercptr;
139 }
140
141 OutputPort *AnySplitOutputPort::clone(Node *newHelder) const
142 {
143   return new AnySplitOutputPort(*this,newHelder);
144 }
145
146 SeqAnyInputPort::SeqAnyInputPort(const std::string& name, Node *node, TypeCodeSeq* type):AnyInputPort(name,node,type),DataPort(name,node,type),Port(node)
147 {
148   _type->decrRef();
149 }
150
151 SeqAnyInputPort::SeqAnyInputPort(const  SeqAnyInputPort& other, Node *newHelder):AnyInputPort(other,newHelder),DataPort(other,newHelder),Port(other,newHelder)
152 {
153 }
154
155 InputPort *SeqAnyInputPort::clone(Node *newHelder) const
156 {
157   return new SeqAnyInputPort(*this,newHelder);
158 }
159
160 unsigned SeqAnyInputPort::getNumberOfElements() const
161 {
162   const SequenceAny * valCsted=(const SequenceAny *) _value;
163   if (valCsted) return valCsted->size();
164   return 0;
165 }
166
167 Any *SeqAnyInputPort::getValueAtRank(int i) const
168 {
169   const SequenceAny * valCsted=(const SequenceAny *) _value;
170   AnyPtr ret=(*valCsted)[i];
171   ret->incrRef();
172   return ret;
173 }
174
175 std::string SeqAnyInputPort::dump()
176 {
177   stringstream xmldump;
178   int nbElem = getNumberOfElements();
179   xmldump << "<value><array><data>" << endl;
180   for (int i = 0; i < nbElem; i++)
181     {
182       Any *val = getValueAtRank(i);
183       switch (((YACS::ENGINE::TypeCodeSeq *)edGetType())->contentType()->kind())
184         {
185         case Double:
186           xmldump << "<value><double>" << setprecision(16) << val->getDoubleValue() << "</double></value>" << endl;
187           break;
188         case Int:
189           xmldump << "<value><int>" << val->getIntValue() << "</int></value>" << endl;
190           break;
191         case Bool:
192           xmldump << "<value><boolean>" << val->getBoolValue() << "</boolean></value>" << endl;
193           break;
194         case String:
195           xmldump << "<value><string>" << val->getStringValue() << "</string></value>" << endl;
196           break;
197         case Objref:
198           xmldump << "<value><objref>" << ToBase64(val->getStringValue()) << "</objref></value>" << endl;
199           break;
200         default:
201           xmldump << "<value><error> NO_SERIALISATION_AVAILABLE </error></value>" << endl;
202           break;
203         }
204     }
205   xmldump << "</data></array></value>" << endl;
206   return xmldump.str();
207 }
208
209 SplitterNode::SplitterNode(const std::string& name, TypeCode *typeOfData, 
210                            ForEachLoop *father):ElementaryNode(name),
211                                                 _dataPortToDispatch(NAME_OF_SEQUENCE_INPUT,
212                                                                     this,(TypeCodeSeq *)TypeCode::sequenceTc("","",typeOfData))
213 {
214   _father=father;
215 }
216
217 SplitterNode::SplitterNode(const SplitterNode& other, ForEachLoop *father):ElementaryNode(other,father),
218                                                                            _dataPortToDispatch(other._dataPortToDispatch,this)
219 {
220 }
221
222 InputPort *SplitterNode::getInputPort(const std::string& name) const throw(YACS::Exception)
223 {
224   if(name==NAME_OF_SEQUENCE_INPUT)
225     return (InputPort *)&_dataPortToDispatch;
226   else
227     return ElementaryNode::getInputPort(name);
228 }
229
230 Node *SplitterNode::simpleClone(ComposedNode *father, bool editionOnly) const
231 {
232   return new SplitterNode(*this,(ForEachLoop *)father);
233 }
234
235 unsigned SplitterNode::getNumberOfElements() const
236 {
237   return _dataPortToDispatch.getNumberOfElements();
238 }
239
240 void SplitterNode::execute()
241 {
242   //Nothing : should never been called elsewhere big problem...
243 }
244
245 void SplitterNode::init(bool start)
246 {
247   ElementaryNode::init(start);
248   _dataPortToDispatch.exInit(start);
249 }
250
251 void SplitterNode::putSplittedValueOnRankTo(int rankInSeq, int branch, bool first)
252 {
253   Any *valueToDispatch=_dataPortToDispatch.getValueAtRank(rankInSeq);
254   ForEachLoop *fatherTyped=(ForEachLoop *)_father;
255   fatherTyped->putValueOnBranch(valueToDispatch,branch,first);
256   valueToDispatch->decrRef();
257 }
258
259 FakeNodeForForEachLoop::FakeNodeForForEachLoop(ForEachLoop *loop, bool normalFinish):ElementaryNode(NAME),
260                                                                                      _loop(loop),
261                                                                                      _normalFinish(normalFinish)
262 {
263   _state=YACS::TOACTIVATE;
264   _father=_loop->getFather();
265 }
266
267 FakeNodeForForEachLoop::FakeNodeForForEachLoop(const FakeNodeForForEachLoop& other):ElementaryNode(other),_loop(0),
268                                                                                     _normalFinish(false)
269 {
270 }
271
272 Node *FakeNodeForForEachLoop::simpleClone(ComposedNode *father, bool editionOnly) const
273 {
274   return new FakeNodeForForEachLoop(*this);
275 }
276
277 void FakeNodeForForEachLoop::exForwardFailed()
278 {
279   _loop->exForwardFailed();
280 }
281
282 void FakeNodeForForEachLoop::exForwardFinished()
283
284   _loop->exForwardFinished();
285 }
286
287 void FakeNodeForForEachLoop::execute()
288 {
289   if(!_normalFinish)
290     throw Exception("");//only to trigger ABORT on Executor
291   else
292     _loop->pushAllSequenceValues();
293 }
294
295 void FakeNodeForForEachLoop::aborted()
296 {
297   _loop->setState(YACS::ERROR);
298 }
299
300 void FakeNodeForForEachLoop::finished()
301 {
302   _loop->setState(YACS::DONE);
303 }
304
305 ForEachLoopPassedData::ForEachLoopPassedData(const std::vector<unsigned int>& passedIds, const std::vector<SequenceAny *>& passedOutputs, const std::vector<std::string>& nameOfOutputs):_passedIds(passedIds),_passedOutputs(passedOutputs),_nameOfOutputs(nameOfOutputs)
306 {
307   std::size_t sz(_passedIds.size()),sz1(passedOutputs.size()),sz2(nameOfOutputs.size());
308   if(sz1!=sz2)
309     throw YACS::Exception("ForEachLoopPassedData::ForEachLoopPassedData : nameOfOutputs and passedOutputs must have the same size !");
310   for(std::vector<SequenceAny *>::iterator it=_passedOutputs.begin();it!=_passedOutputs.end();it++)
311     {
312       const SequenceAny *elt(*it);
313       if(elt)
314         if(sz!=(std::size_t)elt->size())
315           throw YACS::Exception("ForEachLoopPassedData::ForEachLoopPassedData : incoherent input of passed data !");
316     }
317   for(std::vector<SequenceAny *>::iterator it=_passedOutputs.begin();it!=_passedOutputs.end();it++)
318     {
319       SequenceAny *elt(*it);
320       if(elt)
321         elt->incrRef();
322     }
323 }
324
325 ForEachLoopPassedData::ForEachLoopPassedData(const ForEachLoopPassedData& copy)
326 : _passedIds(copy._passedIds),
327   _passedOutputs(copy._passedOutputs),
328   _nameOfOutputs(copy._nameOfOutputs),
329   _flagsIds(copy._flagsIds)
330 {
331 }
332
333 ForEachLoopPassedData::~ForEachLoopPassedData()
334 {
335   for(std::vector<SequenceAny *>::iterator it=_passedOutputs.begin();it!=_passedOutputs.end();it++)
336     {
337       SequenceAny *elt(*it);
338       if(elt)
339         elt->decrRef();
340     }
341 }
342
343 void ForEachLoopPassedData::init()
344 {
345   _flagsIds.clear();
346 }
347
348 void ForEachLoopPassedData::checkCompatibilyWithNb(int nbOfElts) const
349 {
350   if(nbOfElts<0)
351     throw YACS::Exception("ForEachLoopPassedData::checkCompatibilyWithNb : nb of elts is expected to be > 0 !");
352   std::size_t sizeExp(_passedIds.size()),nbOfElts2(nbOfElts);
353   if(nbOfElts2<sizeExp)
354     throw YACS::Exception("ForEachLoopPassedData::checkCompatibilyWithNb : Invalid nb of elemts in input seq regarding passed data set !");
355   for(std::vector<unsigned int>::const_iterator it=_passedIds.begin();it!=_passedIds.end();it++)
356     {
357       if((*it)>=nbOfElts2)
358         throw YACS::Exception("ForEachLoopPassedData::checkCompatibilyWithNb : Invalid nb of elemts in input seq regarding passed data set 2 !");
359     }
360   _flagsIds.resize(nbOfElts);
361   std::fill(_flagsIds.begin(),_flagsIds.end(),false);
362   for(std::vector<unsigned int>::const_iterator it=_passedIds.begin();it!=_passedIds.end();it++)
363     {
364       if(*it<nbOfElts)
365         {
366           if(!_flagsIds[*it])
367             _flagsIds[*it]=true;
368           else
369             {
370               std::ostringstream oss; oss << "ForEachLoopPassedData::checkCompatibilyWithNb : id " << *it << " in list of ids appears more than once !";
371               throw YACS::Exception(oss.str());
372             }
373         }
374       else
375         {
376           std::ostringstream oss; oss << "ForEachLoopPassedData::checkCompatibilyWithNb : Presence of id " << *it << " in list of ids ! Must be in [0," <<  nbOfElts << ") !";
377           throw YACS::Exception(oss.str());
378         }
379     }
380 }
381
382 void ForEachLoopPassedData::checkLevel2(const std::vector<AnyInputPort *>& ports) const
383 {
384   std::size_t sz(_nameOfOutputs.size());
385   if(sz!=ports.size())
386     throw YACS::Exception("ForEachLoopPassedData::checkLevel2 : mismatch of size of vectors !");
387   for(std::size_t i=0;i<sz;i++)
388     {
389       AnyInputPort *elt(ports[i]);
390       if(!elt)
391         throw YACS::Exception("ForEachLoopPassedData::checkLevel2 : presence of null instance !");
392       if(_nameOfOutputs[i]!=elt->getName())
393         {
394           std::ostringstream oss; oss << "ForEachLoopPassedData::checkLevel2 : At pos #" << i << " the name is not OK !";
395           throw YACS::Exception(oss.str());
396         }
397     }
398 }
399
400 /*!
401  * performs local to abs id. Input \a localId refers to an id in all jobs to perform. Returned id refers to pos in whole output sequences.
402  */
403 int ForEachLoopPassedData::toAbsId(int localId) const
404 {
405   if(localId<0)
406     throw YACS::Exception("ForEachLoopPassedData::toAbsId : local pos must be >= 0 !");
407   int ret(0),curLocId(0);
408   for(std::vector<bool>::const_iterator it=_flagsIds.begin();it!=_flagsIds.end();it++,ret++)
409     {
410       if(!*it)
411         {
412           if(localId==curLocId)
413             return ret;
414           curLocId++;
415         }
416     }
417   throw YACS::Exception("ForEachLoopPassedData::toAbsId : not referenced Id !");
418 }
419
420 /*!
421  * Equivalent to toAbsId except that only ON are considered here.
422  */
423 int ForEachLoopPassedData::toAbsIdNot(int localId) const
424 {
425   if(localId<0)
426     throw YACS::Exception("ForEachLoopPassedData::toAbsIdNot : local pos must be >= 0 !");
427   int ret(0),curLocId(0);
428   for(std::vector<bool>::const_iterator it=_flagsIds.begin();it!=_flagsIds.end();it++,ret++)
429     {
430       if(*it)//<- diff is here !
431         {
432           if(localId==curLocId)
433             return ret;
434           curLocId++;
435         }
436     }
437   throw YACS::Exception("ForEachLoopPassedData::toAbsIdNot : not referenced Id !");
438 }
439
440 int ForEachLoopPassedData::getNumberOfElementsToDo() const
441 {
442   std::size_t nbAllElts(_flagsIds.size());
443   std::size_t ret(nbAllElts-_passedIds.size());
444   return ret;
445 }
446
447 void ForEachLoopPassedData::assignAlreadyDone(const std::vector<SequenceAny *>& execVals) const
448 {
449   std::size_t sz(execVals.size());
450   if(_passedOutputs.size()!=sz)
451     throw YACS::Exception("ForEachLoopPassedData::assignedAlreadyDone : mismatch of size of vectors !");
452   for(std::size_t i=0;i<sz;i++)
453     {
454       SequenceAny *elt(_passedOutputs[i]);
455       SequenceAny *eltDestination(execVals[i]);
456       if(!elt)
457         throw YACS::Exception("ForEachLoopPassedData::assignedAlreadyDone : presence of null elt !");
458       unsigned int szOfElt(elt->size());
459       for(unsigned int j=0;j<szOfElt;j++)
460         {
461           AnyPtr elt1((*elt)[j]);
462           int jAbs(toAbsIdNot(j));
463           eltDestination->setEltAtRank(jAbs,elt1);
464         }
465     }
466 }
467
468 ForEachLoop::ForEachLoop(const std::string& name, TypeCode *typeOfDataSplitted):DynParaLoop(name,typeOfDataSplitted),
469                                                                                 _splitterNode(NAME_OF_SPLITTERNODE,typeOfDataSplitted,this),
470                                                                                 _execCurrentId(0),_nodeForSpecialCases(0),_currentIndex(0),_passedData(0)
471 {
472 }
473
474 ForEachLoop::ForEachLoop(const ForEachLoop& other, ComposedNode *father, bool editionOnly):DynParaLoop(other,father,editionOnly),
475                                                                                            _splitterNode(other._splitterNode,this),
476                                                                                            _execCurrentId(0),_nodeForSpecialCases(0),_currentIndex(0),_passedData(0)
477 {
478   int i=0;
479   if(!editionOnly)
480     for(vector<AnySplitOutputPort *>::const_iterator iter2=other._outGoingPorts.begin();iter2!=other._outGoingPorts.end();iter2++,i++)
481       {
482         AnySplitOutputPort *temp=new AnySplitOutputPort(*(*iter2),this);
483         InterceptorInputPort *interc=new InterceptorInputPort(*other._intecptrsForOutGoingPorts[i],this);
484         temp->addRepr(getOutPort(other.getOutPortName((*iter2)->getRepr())),interc);
485         interc->setRepr(temp);
486         _outGoingPorts.push_back(temp);
487         _intecptrsForOutGoingPorts.push_back(interc);
488       }
489 }
490
491 Node *ForEachLoop::simpleClone(ComposedNode *father, bool editionOnly) const
492 {
493   return new ForEachLoop(*this,father,editionOnly);
494 }
495
496 ForEachLoop::~ForEachLoop()
497 {
498   cleanDynGraph();
499   for(vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();iter!=_outGoingPorts.end();iter++)
500     delete *iter;
501   for(vector<InterceptorInputPort *>::iterator iter2=_intecptrsForOutGoingPorts.begin();iter2!=_intecptrsForOutGoingPorts.end();iter2++)
502     delete *iter2;
503   delete _passedData;
504 }
505
506 void ForEachLoop::init(bool start)
507 {
508   DynParaLoop::init(start);
509   _splitterNode.init(start);
510   _execCurrentId=0;
511   cleanDynGraph();
512   _currentIndex = 0;
513   exUpdateProgress();
514   if(_passedData)
515     _passedData->init();
516 }
517
518 void ForEachLoop::exUpdateState()
519 {
520   DEBTRACE("ForEachLoop::exUpdateState");
521   if(_state == YACS::DISABLED)
522     return;
523   if(_state == YACS::DONE)
524     return;
525   if(_inGate.exIsReady())
526     {
527       //internal graph update
528       int i;
529       int nbOfBr(_nbOfBranches.getIntValue()),nbOfElts(_splitterNode.getNumberOfElements()),nbOfEltsDone(0);
530       if(_passedData)
531         {
532           _passedData->checkCompatibilyWithNb(nbOfElts);
533           nbOfEltsDone=_passedData->getNumberOfEltsAlreadyDone();
534         }
535       int nbOfEltsToDo(nbOfElts-nbOfEltsDone);
536
537       DEBTRACE("nbOfElts=" << nbOfElts);
538       DEBTRACE("nbOfBr=" << nbOfBr);
539
540       if(nbOfEltsToDo==0)
541         {
542           prepareSequenceValues(0);
543           delete _nodeForSpecialCases;
544           _nodeForSpecialCases=new FakeNodeForForEachLoop(this,true);
545           setState(YACS::ACTIVATED);
546           return ;
547         }
548       if(nbOfBr<=0)
549         {
550           delete _nodeForSpecialCases;
551           _nodeForSpecialCases=new FakeNodeForForEachLoop(this,getAllOutPortsLeavingCurrentScope().empty());
552           setState(YACS::ACTIVATED);
553           return ;
554         }
555       if(nbOfBr>nbOfEltsToDo)
556         nbOfBr=nbOfEltsToDo;
557       _execNodes.resize(nbOfBr);
558       _execIds.resize(nbOfBr);
559       _execOutGoingPorts.resize(nbOfBr);
560       prepareSequenceValues(nbOfElts);
561       if(_initNode)
562         _execInitNodes.resize(nbOfBr);
563       _initializingCounter = 0;
564       if (_finalizeNode)
565         _execFinalizeNodes.resize(nbOfBr);
566
567       vector<Node *> origNodes;
568       origNodes.push_back(_initNode);
569       origNodes.push_back(_node);
570       origNodes.push_back(_finalizeNode);
571
572       //Conversion exceptions can be thrown by createOutputOutOfScopeInterceptors 
573       //so catch them to control errors
574       try
575         {
576           for(i=0;i<nbOfBr;i++)
577             {
578               DEBTRACE( "-------------- 2" );
579               vector<Node *> clonedNodes = cloneAndPlaceNodesCoherently(origNodes);
580               if(_initNode)
581                 _execInitNodes[i] = clonedNodes[0];
582               _execNodes[i] = clonedNodes[1];
583               if(_finalizeNode)
584                 _execFinalizeNodes[i] = clonedNodes[2];
585               DEBTRACE( "-------------- 4" );
586               prepareInputsFromOutOfScope(i);
587               DEBTRACE( "-------------- 5" );
588               createOutputOutOfScopeInterceptors(i);
589               DEBTRACE( "-------------- 6" );
590             }
591           for(i=0;i<nbOfBr;i++)
592             {
593               DEBTRACE( "-------------- 1 " << i << " " << _execCurrentId);
594               _execIds[i]=_execCurrentId;
595               int posInAbs(_execCurrentId);
596               if(_passedData)
597                 posInAbs=_passedData->toAbsId(_execCurrentId);
598               _splitterNode.putSplittedValueOnRankTo(posInAbs,i,true);
599               _execCurrentId++;
600               DEBTRACE( "-------------- 7" );
601             }
602           if(_passedData)
603             {
604               _passedData->checkLevel2(_execOutGoingPorts[0]);
605               _passedData->assignAlreadyDone(_execVals);
606             }
607           // clean inputs data coming from the outside in _node
608           set< InPort * > portsToSetVals=getAllInPortsComingFromOutsideOfCurrentScope();
609           for(auto iter : portsToSetVals)
610             {
611               InputPort *curPortCasted=(InputPort *) iter;//Cast granted by ForEachLoop::buildDelegateOf(InPort)
612               if(!curPortCasted->canSafelySqueezeMemory())// this can appear strange ! if not safelySqueeze -> release. Nevertheless it is true.
613                 curPortCasted->releaseData();             // these input ports have been incremented with InputPort::put into DynParaLoop::prepareInputsFromOutOfScope. So they can be released now.
614             }
615         }
616       catch(YACS::Exception& ex)
617         {
618           //ForEachLoop must be put in error and the exception rethrown to notify the caller
619           DEBTRACE( "ForEachLoop::exUpdateState: " << ex.what() );
620           setState(YACS::ERROR);
621           setErrorDetails(ex.what());
622           exForwardFailed();
623           throw;
624         }
625
626       setState(YACS::ACTIVATED); // move the calling of setState method there for adding observers for clone nodes in GUI part
627
628       //let's go
629       for(i=0;i<nbOfBr;i++)
630         if(_initNode)
631           {
632             _execInitNodes[i]->exUpdateState();
633             _initializingCounter++;
634           }
635         else
636           {
637             _nbOfEltConsumed++;
638             _execNodes[i]->exUpdateState();
639           }
640
641       forwardExecStateToOriginalBody(_execNodes[nbOfBr-1]);
642     }
643 }
644
645 void ForEachLoop::exUpdateProgress()
646 {
647   // emit notification to all observers registered with the dispatcher on any change of the node's state
648   sendEvent("progress");
649 }
650
651 void ForEachLoop::getReadyTasks(std::vector<Task *>& tasks)
652 {
653   if(!_node)
654     return;
655   if(_state==YACS::TOACTIVATE) setState(YACS::ACTIVATED);
656   if(_state==YACS::TOACTIVATE || _state==YACS::ACTIVATED)
657     {
658       if(_nodeForSpecialCases)
659         {
660           _nodeForSpecialCases->getReadyTasks(tasks);
661           return ;
662         }
663       vector<Node *>::iterator iter;
664       for (iter=_execNodes.begin() ; iter!=_execNodes.end() ; iter++)
665         (*iter)->getReadyTasks(tasks);
666       for (iter=_execInitNodes.begin() ; iter!=_execInitNodes.end() ; iter++)
667         (*iter)->getReadyTasks(tasks);
668       for (iter=_execFinalizeNodes.begin() ; iter!=_execFinalizeNodes.end() ; iter++)
669         (*iter)->getReadyTasks(tasks);
670     }
671 }
672
673 int ForEachLoop::getNumberOfInputPorts() const
674 {
675   return DynParaLoop::getNumberOfInputPorts()+1;
676 }
677
678 void ForEachLoop::checkNoCyclePassingThrough(Node *node) throw(YACS::Exception)
679 {
680   //TO DO
681 }
682
683 void ForEachLoop::selectRunnableTasks(std::vector<Task *>& tasks)
684 {
685 }
686
687 std::list<InputPort *> ForEachLoop::getSetOfInputPort() const
688 {
689   list<InputPort *> ret=DynParaLoop::getSetOfInputPort();
690   ret.push_back((InputPort *)&_splitterNode._dataPortToDispatch);
691   return ret;
692 }
693
694 std::list<InputPort *> ForEachLoop::getLocalInputPorts() const
695 {
696   list<InputPort *> ret=DynParaLoop::getLocalInputPorts();
697   ret.push_back((InputPort *)&_splitterNode._dataPortToDispatch);
698   return ret;
699 }
700
701 InputPort *ForEachLoop::getInputPort(const std::string& name) const throw(YACS::Exception)
702 {
703   if(name==SplitterNode::NAME_OF_SEQUENCE_INPUT)
704     return (InputPort *)&_splitterNode._dataPortToDispatch;
705   else
706     return DynParaLoop::getInputPort(name);
707 }
708
709 OutputPort *ForEachLoop::getOutputPort(const std::string& name) const throw(YACS::Exception)
710 {
711   for(vector<AnySplitOutputPort *>::const_iterator iter=_outGoingPorts.begin();iter!=_outGoingPorts.end();iter++)
712     {
713       if(name==(*iter)->getName())
714         return (OutputPort *)(*iter);
715     }
716   return DynParaLoop::getOutputPort(name);
717 }
718
719 OutPort *ForEachLoop::getOutPort(const std::string& name) const throw(YACS::Exception)
720 {
721   for(vector<AnySplitOutputPort *>::const_iterator iter=_outGoingPorts.begin();iter!=_outGoingPorts.end();iter++)
722     {
723       if(name==(*iter)->getName())
724         return (OutPort *)(*iter);
725     }
726   return DynParaLoop::getOutPort(name);
727 }
728
729 Node *ForEachLoop::getChildByShortName(const std::string& name) const throw(YACS::Exception)
730 {
731   if(name==NAME_OF_SPLITTERNODE)
732     return (Node *)&_splitterNode;
733   else
734     return DynParaLoop::getChildByShortName(name);
735 }
736
737 //! Method used to notify the node that a child node has finished
738 /*!
739  * Update the current state and return the change state
740  *
741  *  \param node : the child node that has finished
742  *  \return the state change
743  */
744 YACS::Event ForEachLoop::updateStateOnFinishedEventFrom(Node *node)
745 {
746   DEBTRACE("updateStateOnFinishedEventFrom " << node->getName() << " " << node->getState());
747   unsigned int id;
748   switch(getIdentityOfNotifyerNode(node,id))
749     {
750     case INIT_NODE:
751       return updateStateForInitNodeOnFinishedEventFrom(node,id);
752     case WORK_NODE:
753       return updateStateForWorkNodeOnFinishedEventFrom(node,id,true);
754     case FINALIZE_NODE:
755       return updateStateForFinalizeNodeOnFinishedEventFrom(node,id);
756     default:
757       YASSERT(false);
758     }
759   return YACS::NOEVENT;
760 }
761
762 YACS::Event ForEachLoop::updateStateForInitNodeOnFinishedEventFrom(Node *node, unsigned int id)
763 {
764   _execNodes[id]->exUpdateState();
765   _nbOfEltConsumed++;
766   _initializingCounter--;
767   _currentIndex++;
768   if (_initializingCounter == 0)
769     _initNode->setState(DONE);
770   return YACS::NOEVENT;
771 }
772
773 /*!
774  * \param [in] isNormalFinish - if true
775  */
776 YACS::Event ForEachLoop::updateStateForWorkNodeOnFinishedEventFrom(Node *node, unsigned int id, bool isNormalFinish)
777 {
778   _currentIndex++;
779   exUpdateProgress();
780   if(isNormalFinish)
781     {
782       int globalId(_execIds[id]);
783       if(_passedData)
784         globalId=_passedData->toAbsId(globalId);
785       sendEvent2("progress_ok",&globalId);
786       storeOutValsInSeqForOutOfScopeUse(globalId,id);
787     }
788   else
789     {
790       int globalId(_execIds[id]);
791       if(_passedData)
792         globalId=_passedData->toAbsId(globalId);
793       sendEvent2("progress_ko",&globalId);
794     }
795   //
796   if(_execCurrentId==getFinishedId())
797     {//No more elements of _dataPortToDispatch to treat
798       _execIds[id]=NOT_RUNNING_BRANCH_ID;
799       //analyzing if some samples are still on treatment on other branches.
800       bool isFinished(true);
801       for(int i=0;i<_execIds.size() && isFinished;i++)
802         isFinished=(_execIds[i]==NOT_RUNNING_BRANCH_ID);
803       if(isFinished)
804         {
805           try
806           {
807               if(_failedCounter!=0)
808                 {// case of keepgoing mode + a failed
809                   std::ostringstream oss; oss << "Keep Going mode activated and some errors (" << _failedCounter << ")reported !";
810                   DEBTRACE("ForEachLoop::updateStateOnFinishedEventFrom : "<< oss.str());
811                   setState(YACS::FAILED);
812                   return YACS::ABORT;
813                 }
814               pushAllSequenceValues();
815
816               if (_node)
817                 {
818                   _node->setState(YACS::DONE);
819
820                   ComposedNode* compNode = dynamic_cast<ComposedNode*>(_node);
821                   if (compNode)
822                     {
823                       std::list<Node *> aChldn = compNode->getAllRecursiveConstituents();
824                       std::list<Node *>::iterator iter=aChldn.begin();
825                       for(;iter!=aChldn.end();iter++)
826                         (*iter)->setState(YACS::DONE);
827                     }
828                 }
829
830               if (_finalizeNode == NULL)
831                 {
832                   // No finalize node, we just finish the loop at the end of exec nodes execution
833                   setState(YACS::DONE);
834                   return YACS::FINISH;
835                 }
836               else
837                 {
838                   // Run the finalize nodes, the loop will be done only when they all finish
839                   _unfinishedCounter = 0;  // This counter indicates how many branches are not finished
840                   for (int i=0 ; i<_execIds.size() ; i++)
841                     {
842                       YASSERT(_execIds[i] == NOT_RUNNING_BRANCH_ID);
843                       DEBTRACE("Launching finalize node for branch " << i);
844                       _execFinalizeNodes[i]->exUpdateState();
845                       _unfinishedCounter++;
846                     }
847                   return YACS::NOEVENT;
848                 }
849           }
850           catch(YACS::Exception& ex)
851           {
852               DEBTRACE("ForEachLoop::updateStateOnFinishedEventFrom: "<<ex.what());
853               //no way to push results : put following nodes in FAILED state
854               //TODO could be more fine grain : put only concerned nodes in FAILED state
855               exForwardFailed();
856               setState(YACS::ERROR);
857               return YACS::ABORT;
858           }
859         }
860     }
861   else if(_state == YACS::ACTIVATED)
862     {//more elements to do and loop still activated
863       _execIds[id]=_execCurrentId;
864       int posInAbs(_execCurrentId);
865       if(_passedData)
866         posInAbs=_passedData->toAbsId(_execCurrentId);
867       _splitterNode.putSplittedValueOnRankTo(posInAbs,id,false);
868       //forwardExecStateToOriginalBody(node);
869       node->init(false);
870       _execCurrentId++;
871       node->exUpdateState();
872       //forwardExecStateToOriginalBody(node);
873       _nbOfEltConsumed++;
874     }
875   else
876     {//elements to process and loop no more activated
877       DEBTRACE("foreach loop state " << _state);
878     }
879   return YACS::NOEVENT;
880 }
881
882 YACS::Event ForEachLoop::updateStateForFinalizeNodeOnFinishedEventFrom(Node *node, unsigned int id)
883 {
884   DEBTRACE("Finalize node finished on branch " << id);
885   _unfinishedCounter--;
886   _currentIndex++;
887   exUpdateProgress();
888   DEBTRACE(_unfinishedCounter << " finalize nodes still running");
889   if (_unfinishedCounter == 0)
890     {
891       _finalizeNode->setState(YACS::DONE);
892       setState(YACS::DONE);
893       return YACS::FINISH;
894     }
895   else
896     return YACS::NOEVENT;
897 }
898
899 YACS::Event ForEachLoop::updateStateOnFailedEventFrom(Node *node, const Executor *execInst)
900 {
901   unsigned int id;
902   DynParaLoop::TypeOfNode ton(getIdentityOfNotifyerNode(node,id));
903   // TODO: deal with keepgoing without the dependency to Executor
904   if(ton!=WORK_NODE || !execInst->getKeepGoingProperty())
905     return DynParaLoop::updateStateOnFailedEventFrom(node,execInst);
906   else
907     {
908       _failedCounter++;
909       return updateStateForWorkNodeOnFinishedEventFrom(node,id,false);
910     }
911 }
912
913 void ForEachLoop::InterceptorizeNameOfPort(std::string& portName)
914 {
915   std::replace_if(portName.begin(), portName.end(), std::bind1st(std::equal_to<char>(), '.'), '_');
916   portName += INTERCEPTOR_STR;
917 }
918
919 void ForEachLoop::buildDelegateOf(std::pair<OutPort *, OutPort *>& port, InPort *finalTarget, const std::list<ComposedNode *>& pointsOfView)
920 {
921   DynParaLoop::buildDelegateOf(port,finalTarget,pointsOfView);
922   string typeOfPortInstance=(port.first)->getNameOfTypeOfCurrentInstance();
923   if(typeOfPortInstance==OutputPort::NAME)
924     {
925       vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
926       int i=0;
927       for(;iter!=_outGoingPorts.end();iter++,i++)
928         if((*iter)->getRepr()==port.first || *iter==port.first)
929           break;
930       if(iter!=_outGoingPorts.end())
931         {
932           if(*iter!=port.first)
933             {
934               (*iter)->incrRef();
935               (*iter)->addRepr(port.first,_intecptrsForOutGoingPorts[i]);
936             }
937           port.first=*iter;
938         }
939       else
940         {
941           TypeCode *tcTrad((YACS::ENGINE::TypeCode*)finalTarget->edGetType()->subContentType(getFEDeltaBetween(port.first,finalTarget)));
942           TypeCodeSeq *newTc=(TypeCodeSeq *)TypeCode::sequenceTc("","",tcTrad);
943           // The out going ports belong to the ForEachLoop, whereas
944           // the delegated port belongs to a node child of the ForEachLoop.
945           // The name of the delegated port contains dots (bloc.node.outport),
946           // whereas the name of the out going port shouldn't do.
947           std::string outputPortName(getPortName(port.first));
948           InterceptorizeNameOfPort(outputPortName);
949           AnySplitOutputPort *newPort(new AnySplitOutputPort(outputPortName,this,newTc));
950           InterceptorInputPort *intercptor(new InterceptorInputPort(outputPortName + "_in",this,tcTrad));
951           intercptor->setRepr(newPort);
952           newTc->decrRef();
953           newPort->addRepr(port.first,intercptor);
954           _outGoingPorts.push_back(newPort);
955           _intecptrsForOutGoingPorts.push_back(intercptor);
956           port.first=newPort;
957         }
958     }
959   else
960     throw Exception("ForEachLoop::buildDelegateOf : not implemented for DS because not specified");
961 }
962
963 void ForEachLoop::getDelegateOf(std::pair<OutPort *, OutPort *>& port, InPort *finalTarget, const std::list<ComposedNode *>& pointsOfView) throw(YACS::Exception)
964 {
965   string typeOfPortInstance=(port.first)->getNameOfTypeOfCurrentInstance();
966   if(typeOfPortInstance==OutputPort::NAME)
967     {
968       vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
969       for(;iter!=_outGoingPorts.end();iter++)
970         if((*iter)->getRepr()==port.first)
971           break;
972       if(iter==_outGoingPorts.end())
973         {
974           string what("ForEachLoop::getDelegateOf : Port with name "); what+=port.first->getName(); what+=" not exported by ForEachLoop "; what+=_name; 
975           throw Exception(what);
976         }
977       else
978         port.first=(*iter);
979     }
980   else
981     throw Exception("ForEachLoop::getDelegateOf : not implemented because not specified");
982 }
983
984 void ForEachLoop::releaseDelegateOf(OutPort *portDwn, OutPort *portUp, InPort *finalTarget, const std::list<ComposedNode *>& pointsOfView) throw(YACS::Exception)
985 {
986   string typeOfPortInstance=portDwn->getNameOfTypeOfCurrentInstance();
987   if(typeOfPortInstance==OutputPort::NAME)
988     {
989       vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
990       vector<InterceptorInputPort *>::iterator iter2=_intecptrsForOutGoingPorts.begin();
991       for(;iter!=_outGoingPorts.end();iter++,iter2++)
992         if((*iter)->getRepr()==portDwn)
993           break;
994       //ASSERT(portUp==*iter.second)
995       if((*iter)->decrRef())
996         {
997           AnySplitOutputPort *p=*iter;
998           _outGoingPorts.erase(iter);
999           delete p;
1000           InterceptorInputPort *ip=*iter2;
1001           _intecptrsForOutGoingPorts.erase(iter2);
1002           delete ip;
1003         }
1004     }
1005 }
1006
1007 OutPort *ForEachLoop::getDynOutPortByAbsName(int branchNb, const std::string& name)
1008 {
1009   string portName, nodeName;
1010   splitNamesBySep(name,Node::SEP_CHAR_IN_PORT,nodeName,portName,false);
1011   Node *staticChild = getChildByName(nodeName);
1012   return _execNodes[branchNb]->getOutPort(portName);//It's impossible(garanteed by YACS::ENGINE::ForEachLoop::buildDelegateOf)
1013   //that a link starting from _initNode goes out of scope of 'this'.
1014 }
1015
1016 void ForEachLoop::cleanDynGraph()
1017 {
1018   DynParaLoop::cleanDynGraph();
1019   for(vector< SequenceAny *>::iterator iter3=_execVals.begin();iter3!=_execVals.end();iter3++)
1020     (*iter3)->decrRef();
1021   _execVals.clear();
1022   for(vector< vector<AnyInputPort *> >::iterator iter4=_execOutGoingPorts.begin();iter4!=_execOutGoingPorts.end();iter4++)
1023     for(vector<AnyInputPort *>::iterator iter5=(*iter4).begin();iter5!=(*iter4).end();iter5++)
1024       delete *iter5;
1025   _execOutGoingPorts.clear();
1026 }
1027
1028 void ForEachLoop::storeOutValsInSeqForOutOfScopeUse(int rank, int branchNb)
1029 {
1030   vector<AnyInputPort *>::iterator iter;
1031   int i=0;
1032   for(iter=_execOutGoingPorts[branchNb].begin();iter!=_execOutGoingPorts[branchNb].end();iter++,i++)
1033     {
1034       Any *val=(Any *)(*iter)->getValue();
1035       _execVals[i]->setEltAtRank(rank,val);
1036     }
1037 }
1038
1039 int ForEachLoop::getFinishedId()
1040 {
1041   if(!_passedData)
1042     return _splitterNode.getNumberOfElements();
1043   else
1044     return _passedData->getNumberOfElementsToDo();
1045 }
1046
1047 void ForEachLoop::prepareSequenceValues(int sizeOfSamples)
1048 {
1049   _execVals.resize(_outGoingPorts.size());
1050   vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
1051   for(int i=0;iter!=_outGoingPorts.end();iter++,i++)
1052     _execVals[i]=SequenceAny::New((*iter)->edGetType()->contentType(),sizeOfSamples);
1053 }
1054
1055 void ForEachLoop::pushAllSequenceValues()
1056 {
1057   vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
1058   int i=0;
1059   for(;iter!=_outGoingPorts.end();iter++,i++)
1060     (*iter)->put((const void *)_execVals[i]);
1061 }
1062
1063 void ForEachLoop::createOutputOutOfScopeInterceptors(int branchNb)
1064 {
1065   vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
1066   int i=0;
1067   for(;iter!=_outGoingPorts.end();iter++,i++)
1068     {
1069       DEBTRACE( (*iter)->getName() << " " << (*iter)->edGetType()->kind() );
1070       //AnyInputPort *interceptor=new AnyInputPort((*iter)->getName(),this,(*iter)->edGetType());
1071       OutPort *portOut=getDynOutPortByAbsName(branchNb,getOutPortName(((*iter)->getRepr())));
1072       DEBTRACE( portOut->getName() );
1073       TypeCode *tc((TypeCode *)(*iter)->edGetType()->contentType());
1074       AnyInputPort *interceptor=new AnyInputPort((*iter)->getName(),this,tc);
1075       portOut->addInPort(interceptor);
1076       _execOutGoingPorts[branchNb].push_back(interceptor);
1077     }
1078 }
1079
1080 void ForEachLoop::checkLinkPossibility(OutPort *start, const std::list<ComposedNode *>& pointsOfViewStart,
1081                                        InPort *end, const std::list<ComposedNode *>& pointsOfViewEnd) throw(YACS::Exception)
1082 {
1083   DynParaLoop::checkLinkPossibility(start, pointsOfViewStart, end, pointsOfViewEnd);
1084   if(end->getNode() == &_splitterNode)
1085     throw Exception("Illegal link within a foreach loop: \
1086 the 'SmplsCollection' port cannot be linked within the scope of the loop.");
1087   if(end == &_nbOfBranches)
1088     throw Exception("Illegal link within a foreach loop: \
1089 the 'nbBranches' port cannot be linked within the scope of the loop.");
1090 }
1091
1092 std::list<OutputPort *> ForEachLoop::getLocalOutputPorts() const
1093 {
1094   list<OutputPort *> ret;
1095   ret.push_back(getOutputPort(NAME_OF_SPLITTED_SEQ_OUT)); 
1096   return ret;
1097 }
1098
1099 void ForEachLoop::accept(Visitor *visitor)
1100 {
1101   visitor->visitForEachLoop(this);
1102 }
1103
1104 //! Dump the node state to a stream
1105 /*!
1106  * \param os : the output stream
1107  */
1108 void ForEachLoop::writeDot(std::ostream &os) const
1109 {
1110   os << "  subgraph cluster_" << getId() << "  {\n" ;
1111   //only one node in a loop
1112   if(_node)
1113     {
1114       _node->writeDot(os);
1115       os << getId() << " -> " << _node->getId() << ";\n";
1116     }
1117   os << "}\n" ;
1118   os << getId() << "[fillcolor=\"" ;
1119   YACS::StatesForNode state=getEffectiveState();
1120   os << getColorState(state);
1121   os << "\" label=\"" << "Loop:" ;
1122   os << getName() <<"\"];\n";
1123 }
1124
1125 //! Reset the state of the node and its children depending on the parameter level
1126 void ForEachLoop::resetState(int level)
1127 {
1128   if(level==0)return;
1129   DynParaLoop::resetState(level);
1130   _execCurrentId=0;
1131   cleanDynGraph();
1132 }
1133
1134 std::string ForEachLoop::getProgress() const
1135 {
1136   int nbElems(getNbOfElementsToBeProcessed());
1137   std::stringstream aProgress;
1138   if (nbElems > 0)
1139     aProgress << _currentIndex << "/" << nbElems;
1140   else
1141     aProgress << "0";
1142   return aProgress.str();
1143 }
1144
1145 //! Get the progress weight for all elementary nodes
1146 /*!
1147  * Only elementary nodes have weight. For each node in the loop, the weight done is multiplied
1148  * by the number of elements done and the weight total by the number total of elements
1149  */
1150 list<ProgressWeight> ForEachLoop::getProgressWeight() const
1151 {
1152   list<ProgressWeight> ret;
1153   list<Node *> setOfNode=edGetDirectDescendants();
1154   int elemDone=getCurrentIndex();
1155   int elemTotal=getNbOfElementsToBeProcessed();
1156   for(list<Node *>::const_iterator iter=setOfNode.begin();iter!=setOfNode.end();iter++)
1157     {
1158       list<ProgressWeight> myCurrentSet=(*iter)->getProgressWeight();
1159       for(list<ProgressWeight>::iterator iter=myCurrentSet.begin();iter!=myCurrentSet.end();iter++)
1160         {
1161           (*iter).weightDone=((*iter).weightTotal) * elemDone;
1162           (*iter).weightTotal*=elemTotal;
1163         }
1164       ret.insert(ret.end(),myCurrentSet.begin(),myCurrentSet.end());
1165     }
1166   return ret;
1167 }
1168
1169 int ForEachLoop::getNbOfElementsToBeProcessed() const
1170 {
1171   int nbBranches = _nbOfBranches.getIntValue();
1172   return _splitterNode.getNumberOfElements()
1173          + (_initNode ? nbBranches:0)
1174          + (_finalizeNode ? nbBranches:0) ;
1175 }
1176
1177 /*!
1178  * This method allows to retrieve the state of \a this during execution or after. This method works even if this is \b NOT complete, or during execution or after a failure in \a this.
1179  * The typical usage of this method is to retrieve the results of items that passed successfully to avoid to lose all of them if only one fails.
1180  * This method has one input \a execut and 3 outputs.
1181  *
1182  * \param [in] execut - The single input is for threadsafety reasons because this method can be called safely during the execution of \a this.
1183  * \param [out] outputs - For each output ports in \a this linked with nodes sharing the same father than \a this the passed results are stored.
1184  *                        All of the items in \a outputs have the same size.
1185  * \param [out] nameOfOutputs - The array with same size than \a outputs, that tells for each item in outputs the output port it refers to.
1186  * \return the list of ids among \c this->edGetSeqOfSamplesPort() that run successfully. The length of this returned array will be the length of all
1187  *         SequenceAny objects contained in \a outputs.
1188  *
1189  * \sa edGetSeqOfSamplesPort
1190  */
1191 std::vector<unsigned int> ForEachLoop::getPassedResults(Executor *execut, std::vector<SequenceAny *>& outputs, std::vector<std::string>& nameOfOutputs) const
1192 {
1193   YACS::BASES::AutoLocker<YACS::BASES::Mutex> alck(&(execut->getTheMutexForSchedulerUpdate()));
1194   if(_execVals.empty())
1195     return std::vector<unsigned int>();
1196   if(_execOutGoingPorts.empty())
1197     return std::vector<unsigned int>();
1198   std::size_t sz(_execVals.size());
1199   outputs.resize(sz);
1200   nameOfOutputs.resize(sz);
1201   const std::vector<AnyInputPort *>& ports(_execOutGoingPorts[0]);
1202   for(std::size_t i=0;i<sz;i++)
1203     {
1204       outputs[i]=_execVals[i]->removeUnsetItemsFromThis();
1205       nameOfOutputs[i]=ports[i]->getName();
1206     }
1207   return _execVals[0]->getSetItems();
1208 }
1209
1210 /*!
1211  * This method is typically useful for post-mortem relaunch to avoid to recompute already passed cases. This method takes in input exactly the parameters retrieved by
1212  * getPassedResults method.
1213  */
1214 void ForEachLoop::assignPassedResults(const std::vector<unsigned int>& passedIds, const std::vector<SequenceAny *>& passedOutputs, const std::vector<std::string>& nameOfOutputs)
1215 {
1216   delete _passedData;
1217   _failedCounter=0;
1218   _passedData=new ForEachLoopPassedData(passedIds,passedOutputs,nameOfOutputs);
1219 }
1220
1221 int ForEachLoop::getFEDeltaBetween(OutPort *start, InPort *end)
1222 {
1223   Node *ns(start->getNode()),*ne(end->getNode());
1224   ComposedNode *co(getLowestCommonAncestor(ns,ne));
1225   int ret(0);
1226   Node *work(ns);
1227   while(work!=co)
1228     {
1229       ForEachLoop *isFE(dynamic_cast<ForEachLoop *>(work));
1230       if(isFE)
1231         ret++;
1232       work=work->getFather();
1233     }
1234   if(dynamic_cast<AnySplitOutputPort *>(start))
1235     ret--;
1236   return ret;
1237 }
1238
1239 /*!
1240  * This method is used to obtain the values already processed by the ForEachLoop.
1241  * A new ForEachLoopPassedData object is returned. You have to delete it.
1242  */
1243 ForEachLoopPassedData* ForEachLoop::getProcessedData()const
1244 {
1245   std::vector<SequenceAny *> outputs;
1246   std::vector<std::string> nameOfOutputs;
1247   if(_execVals.empty() || _execOutGoingPorts.empty())
1248     return new ForEachLoopPassedData(std::vector<unsigned int>(), outputs, nameOfOutputs);
1249   std::size_t sz(_execVals.size());
1250   outputs.resize(sz);
1251   nameOfOutputs.resize(sz);
1252   const std::vector<AnyInputPort *>& ports(_execOutGoingPorts[0]);
1253   for(std::size_t i=0;i<sz;i++)
1254     {
1255       outputs[i]=_execVals[i]->removeUnsetItemsFromThis();
1256       nameOfOutputs[i]=ports[i]->getName();
1257     }
1258   return new ForEachLoopPassedData(_execVals[0]->getSetItems(), outputs, nameOfOutputs);
1259 }
1260
1261 void ForEachLoop::setProcessedData(ForEachLoopPassedData* processedData)
1262 {
1263   if(_passedData)
1264     delete _passedData;
1265   _passedData = processedData;
1266 }
1267
1268 /*!
1269  * \param portName : "interceptorized" name of port.
1270  */
1271 const YACS::ENGINE::TypeCode* ForEachLoop::getOutputPortType(const std::string& portName)const
1272 {
1273   const YACS::ENGINE::TypeCode* ret=NULL;
1274   vector<AnySplitOutputPort *>::const_iterator it;
1275   for(it=_outGoingPorts.begin();it!=_outGoingPorts.end() && ret==NULL;it++)
1276   {
1277     std::string originalPortName(getPortName(*it));
1278     //InterceptorizeNameOfPort(originalPortName);
1279     DEBTRACE("ForEachLoop::getOutputPortType compare " << portName << " == " << originalPortName);
1280     if(originalPortName == portName)
1281     {
1282       ret = (*it)->edGetType()->contentType();
1283     }
1284   }
1285   return ret;
1286 }