1 // Copyright (C) 2006-2015 CEA/DEN, EDF R&D
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.
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.
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
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #include "ForEachLoop.hxx"
21 #include "TypeCode.hxx"
22 #include "Visitor.hxx"
23 #include "ComposedNode.hxx"
24 #include "Executor.hxx"
25 #include "AutoLocker.hxx"
30 #include <algorithm> // std::replace_if
33 #include "YacsTrace.hxx"
35 using namespace YACS::ENGINE;
38 /*! \class YACS::ENGINE::ForEachLoop
39 * \brief Loop node for parametric calculation
44 const char FakeNodeForForEachLoop::NAME[]="thisIsAFakeNode";
46 const char SplitterNode::NAME_OF_SEQUENCE_INPUT[]="SmplsCollection";
48 const char ForEachLoop::NAME_OF_SPLITTERNODE[]="splitter";
50 const int ForEachLoop::NOT_RUNNING_BRANCH_ID=-1;
52 const char ForEachLoop::INTERCEPTOR_STR[]="_interceptor";
54 InterceptorInputPort::InterceptorInputPort(const std::string& name, Node *node, TypeCode* type):AnyInputPort(name,node,type),
55 DataPort(name,node,type),Port(node),
60 InterceptorInputPort::InterceptorInputPort(const InterceptorInputPort& other, Node *newHelder):AnyInputPort(other,newHelder),DataPort(other,newHelder),
61 Port(other,newHelder),
66 void InterceptorInputPort::getAllRepresentants(std::set<InPort *>& repr) const
68 set<InPort *> ports=_repr->edSetInPort();
69 for(set<InPort *>::iterator iter=ports.begin();iter!=ports.end();iter++)
70 (*iter)->getAllRepresentants(repr);
73 InputPort *InterceptorInputPort::clone(Node *newHelder) const
75 return new InterceptorInputPort(*this,newHelder);
78 void InterceptorInputPort::setRepr(AnySplitOutputPort *repr)
83 bool AnySplitOutputPort::decrRef()
88 void AnySplitOutputPort::incrRef() const
93 AnySplitOutputPort::AnySplitOutputPort(const std::string& name, Node *node, TypeCode *type):OutputPort(name,node,type),
94 DataPort(name,node,type),Port(node),
95 _repr(0),_intercptr(0),_cnt(1)
99 AnySplitOutputPort::AnySplitOutputPort(const AnySplitOutputPort& other, Node *newHelder):OutputPort(other,newHelder),
100 DataPort(other,newHelder),
101 Port(other,newHelder),
102 _repr(0),_intercptr(0),_cnt(1)
106 bool AnySplitOutputPort::addInPort(InPort *inPort) throw(YACS::Exception)
108 bool ret=OutputPort::addInPort(inPort);
110 _repr->addInPort(_intercptr);
114 void AnySplitOutputPort::getAllRepresented(std::set<OutPort *>& represented) const
117 OutPort::getAllRepresented(represented);
119 _repr->getAllRepresented(represented);
122 int AnySplitOutputPort::removeInPort(InPort *inPort, bool forward) throw(YACS::Exception)
124 bool ret=OutputPort::removeInPort(inPort,forward);
126 if(_setOfInputPort.empty())
127 _repr->removeInPort(_intercptr,forward);
131 void AnySplitOutputPort::addRepr(OutPort *repr, InterceptorInputPort *intercptr)
134 _intercptr=intercptr;
137 OutputPort *AnySplitOutputPort::clone(Node *newHelder) const
139 return new AnySplitOutputPort(*this,newHelder);
142 SeqAnyInputPort::SeqAnyInputPort(const std::string& name, Node *node, TypeCodeSeq* type):AnyInputPort(name,node,type),DataPort(name,node,type),Port(node)
147 SeqAnyInputPort::SeqAnyInputPort(const SeqAnyInputPort& other, Node *newHelder):AnyInputPort(other,newHelder),DataPort(other,newHelder),Port(other,newHelder)
151 InputPort *SeqAnyInputPort::clone(Node *newHelder) const
153 return new SeqAnyInputPort(*this,newHelder);
156 unsigned SeqAnyInputPort::getNumberOfElements() const
158 const SequenceAny * valCsted=(const SequenceAny *) _value;
159 if (valCsted) return valCsted->size();
163 Any *SeqAnyInputPort::getValueAtRank(int i) const
165 const SequenceAny * valCsted=(const SequenceAny *) _value;
166 AnyPtr ret=(*valCsted)[i];
171 std::string SeqAnyInputPort::dump()
173 stringstream xmldump;
174 int nbElem = getNumberOfElements();
175 xmldump << "<value><array><data>" << endl;
176 for (int i = 0; i < nbElem; i++)
178 Any *val = getValueAtRank(i);
179 switch (val->getType()->kind())
182 xmldump << "<value><double>" << setprecision(16) << val->getDoubleValue() << "</double></value>" << endl;
185 xmldump << "<value><int>" << val->getIntValue() << "</int></value>" << endl;
188 xmldump << "<value><boolean>" << val->getBoolValue() << "</boolean></value>" << endl;
191 xmldump << "<value><string>" << val->getStringValue() << "</string></value>" << endl;
194 xmldump << "<value><objref>" << val->getStringValue() << "</objref></value>" << endl;
197 xmldump << "<value><error> NO_SERIALISATION_AVAILABLE </error></value>" << endl;
201 xmldump << "</data></array></value>" << endl;
202 return xmldump.str();
205 SplitterNode::SplitterNode(const std::string& name, TypeCode *typeOfData,
206 ForEachLoop *father):ElementaryNode(name),
207 _dataPortToDispatch(NAME_OF_SEQUENCE_INPUT,
208 this,(TypeCodeSeq *)TypeCode::sequenceTc("","",typeOfData))
213 SplitterNode::SplitterNode(const SplitterNode& other, ForEachLoop *father):ElementaryNode(other,father),
214 _dataPortToDispatch(other._dataPortToDispatch,this)
218 InputPort *SplitterNode::getInputPort(const std::string& name) const throw(YACS::Exception)
220 if(name==NAME_OF_SEQUENCE_INPUT)
221 return (InputPort *)&_dataPortToDispatch;
223 return ElementaryNode::getInputPort(name);
226 Node *SplitterNode::simpleClone(ComposedNode *father, bool editionOnly) const
228 return new SplitterNode(*this,(ForEachLoop *)father);
231 unsigned SplitterNode::getNumberOfElements() const
233 return _dataPortToDispatch.getNumberOfElements();
236 void SplitterNode::execute()
238 //Nothing : should never been called elsewhere big problem...
241 void SplitterNode::init(bool start)
243 ElementaryNode::init(start);
244 _dataPortToDispatch.exInit(start);
247 void SplitterNode::putSplittedValueOnRankTo(int rankInSeq, int branch, bool first)
249 Any *valueToDispatch=_dataPortToDispatch.getValueAtRank(rankInSeq);
250 ForEachLoop *fatherTyped=(ForEachLoop *)_father;
251 fatherTyped->putValueOnBranch(valueToDispatch,branch,first);
252 valueToDispatch->decrRef();
255 FakeNodeForForEachLoop::FakeNodeForForEachLoop(ForEachLoop *loop, bool normalFinish):ElementaryNode(NAME),
257 _normalFinish(normalFinish)
259 _state=YACS::TOACTIVATE;
260 _father=_loop->getFather();
263 FakeNodeForForEachLoop::FakeNodeForForEachLoop(const FakeNodeForForEachLoop& other):ElementaryNode(other),_loop(0),
268 Node *FakeNodeForForEachLoop::simpleClone(ComposedNode *father, bool editionOnly) const
270 return new FakeNodeForForEachLoop(*this);
273 void FakeNodeForForEachLoop::exForwardFailed()
275 _loop->exForwardFailed();
278 void FakeNodeForForEachLoop::exForwardFinished()
280 _loop->exForwardFinished();
283 void FakeNodeForForEachLoop::execute()
286 throw Exception("");//only to trigger ABORT on Executor
288 _loop->pushAllSequenceValues();
291 void FakeNodeForForEachLoop::aborted()
293 _loop->setState(YACS::ERROR);
296 void FakeNodeForForEachLoop::finished()
298 _loop->setState(YACS::DONE);
301 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)
303 std::size_t sz(_passedIds.size()),sz1(passedOutputs.size()),sz2(nameOfOutputs.size());
305 throw YACS::Exception("ForEachLoopPassedData::ForEachLoopPassedData : nameOfOutputs and passedOutputs must have the same size !");
306 for(std::vector<SequenceAny *>::iterator it=_passedOutputs.begin();it!=_passedOutputs.end();it++)
308 const SequenceAny *elt(*it);
310 if(sz!=(std::size_t)elt->size())
311 throw YACS::Exception("ForEachLoopPassedData::ForEachLoopPassedData : incoherent input of passed data !");
313 for(std::vector<SequenceAny *>::iterator it=_passedOutputs.begin();it!=_passedOutputs.end();it++)
315 SequenceAny *elt(*it);
321 ForEachLoopPassedData::~ForEachLoopPassedData()
323 for(std::vector<SequenceAny *>::iterator it=_passedOutputs.begin();it!=_passedOutputs.end();it++)
325 SequenceAny *elt(*it);
331 void ForEachLoopPassedData::init()
336 void ForEachLoopPassedData::checkCompatibilyWithNb(int nbOfElts) const
339 throw YACS::Exception("ForEachLoopPassedData::checkCompatibilyWithNb : nb of elts is expected to be > 0 !");
340 std::size_t sizeExp(_passedIds.size()),nbOfElts2(nbOfElts);
341 if(nbOfElts2<sizeExp)
342 throw YACS::Exception("ForEachLoopPassedData::checkCompatibilyWithNb : Invalid nb of elemts in input seq regarding passed data set !");
343 for(std::vector<unsigned int>::const_iterator it=_passedIds.begin();it!=_passedIds.end();it++)
346 throw YACS::Exception("ForEachLoopPassedData::checkCompatibilyWithNb : Invalid nb of elemts in input seq regarding passed data set 2 !");
348 _flagsIds.resize(nbOfElts);
349 std::fill(_flagsIds.begin(),_flagsIds.end(),false);
350 for(std::vector<unsigned int>::const_iterator it=_passedIds.begin();it!=_passedIds.end();it++)
358 std::ostringstream oss; oss << "ForEachLoopPassedData::checkCompatibilyWithNb : id " << *it << " in list of ids appears more than once !";
359 throw YACS::Exception(oss.str());
364 std::ostringstream oss; oss << "ForEachLoopPassedData::checkCompatibilyWithNb : Presence of id " << *it << " in list of ids ! Must be in [0," << nbOfElts << ") !";
365 throw YACS::Exception(oss.str());
370 void ForEachLoopPassedData::checkLevel2(const std::vector<AnyInputPort *>& ports) const
372 std::size_t sz(_nameOfOutputs.size());
374 throw YACS::Exception("ForEachLoopPassedData::checkLevel2 : mismatch of size of vectors !");
375 for(std::size_t i=0;i<sz;i++)
377 AnyInputPort *elt(ports[i]);
379 throw YACS::Exception("ForEachLoopPassedData::checkLevel2 : presence of null instance !");
380 if(_nameOfOutputs[i]!=elt->getName())
382 std::ostringstream oss; oss << "ForEachLoopPassedData::checkLevel2 : At pos #" << i << " the name is not OK !";
383 throw YACS::Exception(oss.str());
389 * 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.
391 int ForEachLoopPassedData::toAbsId(int localId) const
394 throw YACS::Exception("ForEachLoopPassedData::toAbsId : local pos must be >= 0 !");
395 int ret(0),curLocId(0);
396 for(std::vector<bool>::const_iterator it=_flagsIds.begin();it!=_flagsIds.end();it++,ret++)
400 if(localId==curLocId)
405 throw YACS::Exception("ForEachLoopPassedData::toAbsId : not referenced Id !");
409 * Equivalent to toAbsId except that only ON are considered here.
411 int ForEachLoopPassedData::toAbsIdNot(int localId) const
414 throw YACS::Exception("ForEachLoopPassedData::toAbsIdNot : local pos must be >= 0 !");
415 int ret(0),curLocId(0);
416 for(std::vector<bool>::const_iterator it=_flagsIds.begin();it!=_flagsIds.end();it++,ret++)
418 if(*it)//<- diff is here !
420 if(localId==curLocId)
425 throw YACS::Exception("ForEachLoopPassedData::toAbsIdNot : not referenced Id !");
428 int ForEachLoopPassedData::getNumberOfElementsToDo() const
430 std::size_t nbAllElts(_flagsIds.size());
431 std::size_t ret(nbAllElts-_passedIds.size());
435 void ForEachLoopPassedData::assignAlreadyDone(const std::vector<SequenceAny *>& execVals) const
437 std::size_t sz(execVals.size());
438 if(_passedOutputs.size()!=sz)
439 throw YACS::Exception("ForEachLoopPassedData::assignedAlreadyDone : mismatch of size of vectors !");
440 for(std::size_t i=0;i<sz;i++)
442 SequenceAny *elt(_passedOutputs[i]);
443 SequenceAny *eltDestination(execVals[i]);
445 throw YACS::Exception("ForEachLoopPassedData::assignedAlreadyDone : presence of null elt !");
446 unsigned int szOfElt(elt->size());
447 for(unsigned int j=0;j<szOfElt;j++)
449 AnyPtr elt1((*elt)[j]);
450 int jAbs(toAbsIdNot(j));
451 eltDestination->setEltAtRank(jAbs,elt1);
456 ForEachLoop::ForEachLoop(const std::string& name, TypeCode *typeOfDataSplitted):DynParaLoop(name,typeOfDataSplitted),
457 _splitterNode(NAME_OF_SPLITTERNODE,typeOfDataSplitted,this),
458 _execCurrentId(0),_nodeForSpecialCases(0),_currentIndex(0),_passedData(0)
462 ForEachLoop::ForEachLoop(const ForEachLoop& other, ComposedNode *father, bool editionOnly):DynParaLoop(other,father,editionOnly),
463 _splitterNode(other._splitterNode,this),
464 _execCurrentId(0),_nodeForSpecialCases(0),_currentIndex(0),_passedData(0)
468 for(vector<AnySplitOutputPort *>::const_iterator iter2=other._outGoingPorts.begin();iter2!=other._outGoingPorts.end();iter2++,i++)
470 AnySplitOutputPort *temp=new AnySplitOutputPort(*(*iter2),this);
471 InterceptorInputPort *interc=new InterceptorInputPort(*other._intecptrsForOutGoingPorts[i],this);
472 temp->addRepr(getOutPort(other.getOutPortName((*iter2)->getRepr())),interc);
473 interc->setRepr(temp);
474 _outGoingPorts.push_back(temp);
475 _intecptrsForOutGoingPorts.push_back(interc);
479 Node *ForEachLoop::simpleClone(ComposedNode *father, bool editionOnly) const
481 return new ForEachLoop(*this,father,editionOnly);
484 ForEachLoop::~ForEachLoop()
487 for(vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();iter!=_outGoingPorts.end();iter++)
489 for(vector<InterceptorInputPort *>::iterator iter2=_intecptrsForOutGoingPorts.begin();iter2!=_intecptrsForOutGoingPorts.end();iter2++)
494 void ForEachLoop::init(bool start)
496 DynParaLoop::init(start);
497 _splitterNode.init(start);
506 void ForEachLoop::exUpdateState()
508 DEBTRACE("ForEachLoop::exUpdateState");
509 if(_state == YACS::DISABLED)
511 if(_state == YACS::DONE)
513 if(_inGate.exIsReady())
515 //internal graph update
517 int nbOfBr(_nbOfBranches.getIntValue()),nbOfElts(_splitterNode.getNumberOfElements()),nbOfEltsDone(0);
520 _passedData->checkCompatibilyWithNb(nbOfElts);
521 nbOfEltsDone=_passedData->getNumberOfEltsAlreadyDone();
523 int nbOfEltsToDo(nbOfElts-nbOfEltsDone);
525 DEBTRACE("nbOfElts=" << nbOfElts);
526 DEBTRACE("nbOfBr=" << nbOfBr);
530 prepareSequenceValues(0);
531 delete _nodeForSpecialCases;
532 _nodeForSpecialCases=new FakeNodeForForEachLoop(this,true);
533 setState(YACS::ACTIVATED);
538 delete _nodeForSpecialCases;
539 _nodeForSpecialCases=new FakeNodeForForEachLoop(this,getAllOutPortsLeavingCurrentScope().empty());
540 setState(YACS::ACTIVATED);
543 if(nbOfBr>nbOfEltsToDo)
545 _execNodes.resize(nbOfBr);
546 _execIds.resize(nbOfBr);
547 _execOutGoingPorts.resize(nbOfBr);
548 prepareSequenceValues(nbOfElts);
550 _execInitNodes.resize(nbOfBr);
551 _initializingCounter = 0;
553 _execFinalizeNodes.resize(nbOfBr);
555 vector<Node *> origNodes;
556 origNodes.push_back(_initNode);
557 origNodes.push_back(_node);
558 origNodes.push_back(_finalizeNode);
560 //Conversion exceptions can be thrown by createOutputOutOfScopeInterceptors
561 //so catch them to control errors
564 for(i=0;i<nbOfBr;i++)
566 DEBTRACE( "-------------- 2" );
567 vector<Node *> clonedNodes = cloneAndPlaceNodesCoherently(origNodes);
569 _execInitNodes[i] = clonedNodes[0];
570 _execNodes[i] = clonedNodes[1];
572 _execFinalizeNodes[i] = clonedNodes[2];
573 DEBTRACE( "-------------- 4" );
574 prepareInputsFromOutOfScope(i);
575 DEBTRACE( "-------------- 5" );
576 createOutputOutOfScopeInterceptors(i);
577 DEBTRACE( "-------------- 6" );
579 for(i=0;i<nbOfBr;i++)
581 DEBTRACE( "-------------- 1 " << i << " " << _execCurrentId);
582 _execIds[i]=_execCurrentId;
583 int posInAbs(_execCurrentId);
585 posInAbs=_passedData->toAbsId(_execCurrentId);
586 _splitterNode.putSplittedValueOnRankTo(posInAbs,i,true);
588 DEBTRACE( "-------------- 7" );
592 _passedData->checkLevel2(_execOutGoingPorts[0]);
593 _passedData->assignAlreadyDone(_execVals);
596 catch(YACS::Exception& ex)
598 //ForEachLoop must be put in error and the exception rethrown to notify the caller
599 DEBTRACE( "ForEachLoop::exUpdateState: " << ex.what() );
600 setState(YACS::ERROR);
605 setState(YACS::ACTIVATED); // move the calling of setState method there for adding observers for clone nodes in GUI part
608 for(i=0;i<nbOfBr;i++)
611 _execInitNodes[i]->exUpdateState();
612 _initializingCounter++;
617 _execNodes[i]->exUpdateState();
620 forwardExecStateToOriginalBody(_execNodes[nbOfBr-1]);
624 void ForEachLoop::exUpdateProgress()
626 // emit notification to all observers registered with the dispatcher on any change of the node's state
627 sendEvent("progress");
630 void ForEachLoop::getReadyTasks(std::vector<Task *>& tasks)
634 if(_state==YACS::TOACTIVATE) setState(YACS::ACTIVATED);
635 if(_state==YACS::TOACTIVATE || _state==YACS::ACTIVATED)
637 if(_nodeForSpecialCases)
639 _nodeForSpecialCases->getReadyTasks(tasks);
642 vector<Node *>::iterator iter;
643 for (iter=_execNodes.begin() ; iter!=_execNodes.end() ; iter++)
644 (*iter)->getReadyTasks(tasks);
645 for (iter=_execInitNodes.begin() ; iter!=_execInitNodes.end() ; iter++)
646 (*iter)->getReadyTasks(tasks);
647 for (iter=_execFinalizeNodes.begin() ; iter!=_execFinalizeNodes.end() ; iter++)
648 (*iter)->getReadyTasks(tasks);
652 int ForEachLoop::getNumberOfInputPorts() const
654 return DynParaLoop::getNumberOfInputPorts()+1;
657 void ForEachLoop::checkNoCyclePassingThrough(Node *node) throw(YACS::Exception)
662 void ForEachLoop::selectRunnableTasks(std::vector<Task *>& tasks)
666 std::list<InputPort *> ForEachLoop::getSetOfInputPort() const
668 list<InputPort *> ret=DynParaLoop::getSetOfInputPort();
669 ret.push_back((InputPort *)&_splitterNode._dataPortToDispatch);
673 std::list<InputPort *> ForEachLoop::getLocalInputPorts() const
675 list<InputPort *> ret=DynParaLoop::getLocalInputPorts();
676 ret.push_back((InputPort *)&_splitterNode._dataPortToDispatch);
680 InputPort *ForEachLoop::getInputPort(const std::string& name) const throw(YACS::Exception)
682 if(name==SplitterNode::NAME_OF_SEQUENCE_INPUT)
683 return (InputPort *)&_splitterNode._dataPortToDispatch;
685 return DynParaLoop::getInputPort(name);
688 OutputPort *ForEachLoop::getOutputPort(const std::string& name) const throw(YACS::Exception)
690 for(vector<AnySplitOutputPort *>::const_iterator iter=_outGoingPorts.begin();iter!=_outGoingPorts.end();iter++)
692 if(name==(*iter)->getName())
693 return (OutputPort *)(*iter);
695 return DynParaLoop::getOutputPort(name);
698 OutPort *ForEachLoop::getOutPort(const std::string& name) const throw(YACS::Exception)
700 for(vector<AnySplitOutputPort *>::const_iterator iter=_outGoingPorts.begin();iter!=_outGoingPorts.end();iter++)
702 if(name==(*iter)->getName())
703 return (OutPort *)(*iter);
705 return DynParaLoop::getOutPort(name);
708 Node *ForEachLoop::getChildByShortName(const std::string& name) const throw(YACS::Exception)
710 if(name==NAME_OF_SPLITTERNODE)
711 return (Node *)&_splitterNode;
713 return DynParaLoop::getChildByShortName(name);
716 //! Method used to notify the node that a child node has finished
718 * Update the current state and return the change state
720 * \param node : the child node that has finished
721 * \return the state change
723 YACS::Event ForEachLoop::updateStateOnFinishedEventFrom(Node *node)
725 DEBTRACE("updateStateOnFinishedEventFrom " << node->getName() << " " << node->getState());
727 switch(getIdentityOfNotifyerNode(node,id))
730 return updateStateForInitNodeOnFinishedEventFrom(node,id);
732 return updateStateForWorkNodeOnFinishedEventFrom(node,id,true);
734 return updateStateForFinalizeNodeOnFinishedEventFrom(node,id);
738 return YACS::NOEVENT;
741 YACS::Event ForEachLoop::updateStateForInitNodeOnFinishedEventFrom(Node *node, unsigned int id)
743 _execNodes[id]->exUpdateState();
745 _initializingCounter--;
747 if (_initializingCounter == 0)
748 _initNode->setState(DONE);
749 return YACS::NOEVENT;
753 * \param [in] isNormalFinish - if true
755 YACS::Event ForEachLoop::updateStateForWorkNodeOnFinishedEventFrom(Node *node, unsigned int id, bool isNormalFinish)
761 int globalId(_execIds[id]);
763 globalId=_passedData->toAbsId(globalId);
764 storeOutValsInSeqForOutOfScopeUse(globalId,id);
767 if(_execCurrentId==getFinishedId())
768 {//No more elements of _dataPortToDispatch to treat
769 _execIds[id]=NOT_RUNNING_BRANCH_ID;
770 //analyzing if some samples are still on treatment on other branches.
771 bool isFinished(true);
772 for(int i=0;i<_execIds.size() && isFinished;i++)
773 isFinished=(_execIds[i]==NOT_RUNNING_BRANCH_ID);
778 if(_failedCounter!=0)
779 {// case of keepgoing mode + a failed
780 std::ostringstream oss; oss << "Keep Going mode activated and some errors (" << _failedCounter << ")reported !";
781 DEBTRACE("ForEachLoop::updateStateOnFinishedEventFrom : "<< oss.str());
782 setState(YACS::FAILED);
785 pushAllSequenceValues();
789 _node->setState(YACS::DONE);
791 ComposedNode* compNode = dynamic_cast<ComposedNode*>(_node);
794 std::list<Node *> aChldn = compNode->getAllRecursiveConstituents();
795 std::list<Node *>::iterator iter=aChldn.begin();
796 for(;iter!=aChldn.end();iter++)
797 (*iter)->setState(YACS::DONE);
801 if (_finalizeNode == NULL)
803 // No finalize node, we just finish the loop at the end of exec nodes execution
804 setState(YACS::DONE);
809 // Run the finalize nodes, the loop will be done only when they all finish
810 _unfinishedCounter = 0; // This counter indicates how many branches are not finished
811 for (int i=0 ; i<_execIds.size() ; i++)
813 YASSERT(_execIds[i] == NOT_RUNNING_BRANCH_ID);
814 DEBTRACE("Launching finalize node for branch " << i);
815 _execFinalizeNodes[i]->exUpdateState();
816 _unfinishedCounter++;
818 return YACS::NOEVENT;
821 catch(YACS::Exception& ex)
823 DEBTRACE("ForEachLoop::updateStateOnFinishedEventFrom: "<<ex.what());
824 //no way to push results : put following nodes in FAILED state
825 //TODO could be more fine grain : put only concerned nodes in FAILED state
827 setState(YACS::ERROR);
832 else if(_state == YACS::ACTIVATED)
833 {//more elements to do and loop still activated
834 _execIds[id]=_execCurrentId;
836 int posInAbs(_execCurrentId);
838 posInAbs=_passedData->toAbsId(_execCurrentId);
839 _splitterNode.putSplittedValueOnRankTo(posInAbs,id,false);
841 node->exUpdateState();
842 forwardExecStateToOriginalBody(node);
846 {//elements to process and loop no more activated
847 DEBTRACE("foreach loop state " << _state);
849 return YACS::NOEVENT;
852 YACS::Event ForEachLoop::updateStateForFinalizeNodeOnFinishedEventFrom(Node *node, unsigned int id)
854 DEBTRACE("Finalize node finished on branch " << id);
855 _unfinishedCounter--;
858 DEBTRACE(_unfinishedCounter << " finalize nodes still running");
859 if (_unfinishedCounter == 0)
861 _finalizeNode->setState(YACS::DONE);
862 setState(YACS::DONE);
866 return YACS::NOEVENT;
869 YACS::Event ForEachLoop::updateStateOnFailedEventFrom(Node *node, const Executor *execInst)
872 DynParaLoop::TypeOfNode ton(getIdentityOfNotifyerNode(node,id));
873 if(ton!=WORK_NODE || !execInst->getKeepGoingProperty())
874 return DynParaLoop::updateStateOnFailedEventFrom(node,execInst);
878 return updateStateForWorkNodeOnFinishedEventFrom(node,id,false);
882 void ForEachLoop::InterceptorizeNameOfPort(std::string& portName)
884 std::replace_if(portName.begin(), portName.end(), std::bind1st(std::equal_to<char>(), '.'), '_');
885 portName += INTERCEPTOR_STR;
888 void ForEachLoop::buildDelegateOf(std::pair<OutPort *, OutPort *>& port, InPort *finalTarget, const std::list<ComposedNode *>& pointsOfView)
890 DynParaLoop::buildDelegateOf(port,finalTarget,pointsOfView);
891 string typeOfPortInstance=(port.first)->getNameOfTypeOfCurrentInstance();
892 if(typeOfPortInstance==OutputPort::NAME)
894 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
896 for(;iter!=_outGoingPorts.end();iter++,i++)
897 if((*iter)->getRepr()==port.first || *iter==port.first)
899 if(iter!=_outGoingPorts.end())
901 if(*iter!=port.first)
904 (*iter)->addRepr(port.first,_intecptrsForOutGoingPorts[i]);
910 TypeCodeSeq *newTc=(TypeCodeSeq *)TypeCode::sequenceTc("","",port.first->edGetType());
911 // The out going ports belong to the ForEachLoop, whereas
912 // the delegated port belongs to a node child of the ForEachLoop.
913 // The name of the delegated port contains dots (bloc.node.outport),
914 // whereas the name of the out going port shouldn't do.
915 std::string outputPortName(getPortName(port.first));
916 InterceptorizeNameOfPort(outputPortName);
917 AnySplitOutputPort *newPort(new AnySplitOutputPort(outputPortName,this,newTc));
918 InterceptorInputPort *intercptor(new InterceptorInputPort(outputPortName + "_in",this,port.first->edGetType()));
919 intercptor->setRepr(newPort);
921 newPort->addRepr(port.first,intercptor);
922 _outGoingPorts.push_back(newPort);
923 _intecptrsForOutGoingPorts.push_back(intercptor);
928 throw Exception("ForEachLoop::buildDelegateOf : not implemented for DS because not specified");
931 void ForEachLoop::getDelegateOf(std::pair<OutPort *, OutPort *>& port, InPort *finalTarget, const std::list<ComposedNode *>& pointsOfView) throw(YACS::Exception)
933 string typeOfPortInstance=(port.first)->getNameOfTypeOfCurrentInstance();
934 if(typeOfPortInstance==OutputPort::NAME)
936 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
937 for(;iter!=_outGoingPorts.end();iter++)
938 if((*iter)->getRepr()==port.first)
940 if(iter==_outGoingPorts.end())
942 string what("ForEachLoop::getDelegateOf : Port with name "); what+=port.first->getName(); what+=" not exported by ForEachLoop "; what+=_name;
943 throw Exception(what);
949 throw Exception("ForEachLoop::getDelegateOf : not implemented because not specified");
952 void ForEachLoop::releaseDelegateOf(OutPort *portDwn, OutPort *portUp, InPort *finalTarget, const std::list<ComposedNode *>& pointsOfView) throw(YACS::Exception)
954 string typeOfPortInstance=portDwn->getNameOfTypeOfCurrentInstance();
955 if(typeOfPortInstance==OutputPort::NAME)
957 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
958 vector<InterceptorInputPort *>::iterator iter2=_intecptrsForOutGoingPorts.begin();
959 for(;iter!=_outGoingPorts.end();iter++,iter2++)
960 if((*iter)->getRepr()==portDwn)
962 //ASSERT(portUp==*iter.second)
963 if((*iter)->decrRef())
965 AnySplitOutputPort *p=*iter;
966 _outGoingPorts.erase(iter);
968 InterceptorInputPort *ip=*iter2;
969 _intecptrsForOutGoingPorts.erase(iter2);
975 OutPort *ForEachLoop::getDynOutPortByAbsName(int branchNb, const std::string& name)
977 string portName, nodeName;
978 splitNamesBySep(name,Node::SEP_CHAR_IN_PORT,nodeName,portName,false);
979 Node *staticChild = getChildByName(nodeName);
980 return _execNodes[branchNb]->getOutPort(portName);//It's impossible(garanteed by YACS::ENGINE::ForEachLoop::buildDelegateOf)
981 //that a link starting from _initNode goes out of scope of 'this'.
984 void ForEachLoop::cleanDynGraph()
986 DynParaLoop::cleanDynGraph();
987 for(vector< SequenceAny *>::iterator iter3=_execVals.begin();iter3!=_execVals.end();iter3++)
990 for(vector< vector<AnyInputPort *> >::iterator iter4=_execOutGoingPorts.begin();iter4!=_execOutGoingPorts.end();iter4++)
991 for(vector<AnyInputPort *>::iterator iter5=(*iter4).begin();iter5!=(*iter4).end();iter5++)
993 _execOutGoingPorts.clear();
996 void ForEachLoop::storeOutValsInSeqForOutOfScopeUse(int rank, int branchNb)
998 vector<AnyInputPort *>::iterator iter;
1000 for(iter=_execOutGoingPorts[branchNb].begin();iter!=_execOutGoingPorts[branchNb].end();iter++,i++)
1002 Any *val=(Any *)(*iter)->getValue();
1003 _execVals[i]->setEltAtRank(rank,val);
1007 int ForEachLoop::getFinishedId()
1010 return _splitterNode.getNumberOfElements();
1012 return _passedData->getNumberOfElementsToDo();
1015 void ForEachLoop::prepareSequenceValues(int sizeOfSamples)
1017 _execVals.resize(_outGoingPorts.size());
1018 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
1019 for(int i=0;iter!=_outGoingPorts.end();iter++,i++)
1020 _execVals[i]=SequenceAny::New((*iter)->edGetType()->contentType(),sizeOfSamples);
1023 void ForEachLoop::pushAllSequenceValues()
1025 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
1027 for(;iter!=_outGoingPorts.end();iter++,i++)
1028 (*iter)->put((const void *)_execVals[i]);
1031 void ForEachLoop::createOutputOutOfScopeInterceptors(int branchNb)
1033 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
1035 for(;iter!=_outGoingPorts.end();iter++,i++)
1037 DEBTRACE( (*iter)->getName() << " " << (*iter)->edGetType()->kind() );
1038 //AnyInputPort *interceptor=new AnyInputPort((*iter)->getName(),this,(*iter)->edGetType());
1039 OutPort *portOut=getDynOutPortByAbsName(branchNb,getOutPortName(((*iter)->getRepr())));
1040 DEBTRACE( portOut->getName() );
1041 AnyInputPort *interceptor=new AnyInputPort((*iter)->getName(),this,portOut->edGetType());
1042 portOut->addInPort(interceptor);
1043 _execOutGoingPorts[branchNb].push_back(interceptor);
1047 void ForEachLoop::checkLinkPossibility(OutPort *start, const std::list<ComposedNode *>& pointsOfViewStart,
1048 InPort *end, const std::list<ComposedNode *>& pointsOfViewEnd) throw(YACS::Exception)
1050 DynParaLoop::checkLinkPossibility(start, pointsOfViewStart, end, pointsOfViewEnd);
1051 if(end->getNode() == &_splitterNode)
1052 throw Exception("Illegal link within a foreach loop: \
1053 the 'SmplsCollection' port cannot be linked within the scope of the loop.");
1054 if(end == &_nbOfBranches)
1055 throw Exception("Illegal link within a foreach loop: \
1056 the 'nbBranches' port cannot be linked within the scope of the loop.");
1059 std::list<OutputPort *> ForEachLoop::getLocalOutputPorts() const
1061 list<OutputPort *> ret;
1062 ret.push_back(getOutputPort(NAME_OF_SPLITTED_SEQ_OUT));
1066 void ForEachLoop::accept(Visitor *visitor)
1068 visitor->visitForEachLoop(this);
1071 //! Dump the node state to a stream
1073 * \param os : the output stream
1075 void ForEachLoop::writeDot(std::ostream &os) const
1077 os << " subgraph cluster_" << getId() << " {\n" ;
1078 //only one node in a loop
1081 _node->writeDot(os);
1082 os << getId() << " -> " << _node->getId() << ";\n";
1085 os << getId() << "[fillcolor=\"" ;
1086 YACS::StatesForNode state=getEffectiveState();
1087 os << getColorState(state);
1088 os << "\" label=\"" << "Loop:" ;
1089 os << getName() <<"\"];\n";
1092 //! Reset the state of the node and its children depending on the parameter level
1093 void ForEachLoop::resetState(int level)
1096 DynParaLoop::resetState(level);
1098 //Note: cleanDynGraph is not a virtual method (must be called from ForEachLoop object)
1102 std::string ForEachLoop::getProgress() const
1104 int nbElems(getNbOfElementsToBeProcessed());
1105 std::stringstream aProgress;
1107 aProgress << _currentIndex << "/" << nbElems;
1110 return aProgress.str();
1113 //! Get the progress weight for all elementary nodes
1115 * Only elementary nodes have weight. For each node in the loop, the weight done is multiplied
1116 * by the number of elements done and the weight total by the number total of elements
1118 list<ProgressWeight> ForEachLoop::getProgressWeight() const
1120 list<ProgressWeight> ret;
1121 list<Node *> setOfNode=edGetDirectDescendants();
1122 int elemDone=getCurrentIndex();
1123 int elemTotal=getNbOfElementsToBeProcessed();
1124 for(list<Node *>::const_iterator iter=setOfNode.begin();iter!=setOfNode.end();iter++)
1126 list<ProgressWeight> myCurrentSet=(*iter)->getProgressWeight();
1127 for(list<ProgressWeight>::iterator iter=myCurrentSet.begin();iter!=myCurrentSet.end();iter++)
1129 (*iter).weightDone=((*iter).weightTotal) * elemDone;
1130 (*iter).weightTotal*=elemTotal;
1132 ret.insert(ret.end(),myCurrentSet.begin(),myCurrentSet.end());
1137 int ForEachLoop::getNbOfElementsToBeProcessed() const
1139 int nbBranches = _nbOfBranches.getIntValue();
1140 return _splitterNode.getNumberOfElements()
1141 + (_initNode ? nbBranches:0)
1142 + (_finalizeNode ? nbBranches:0) ;
1146 * 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.
1147 * 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.
1148 * This method has one input \a execut and 3 outputs.
1150 * \param [in] execut - The single input is for threadsafety reasons because this method can be called safely during the execution of \a this.
1151 * \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.
1152 * All of the items in \a outputs have the same size.
1153 * \param [out] nameOfOutputs - The array with same size than \a outputs, that tells for each item in outputs the output port it refers to.
1154 * \return the list of ids among \c this->edGetSeqOfSamplesPort() that run successfully. The length of this returned array will be the length of all
1155 * SequenceAny objects contained in \a outputs.
1157 * \sa edGetSeqOfSamplesPort
1159 std::vector<unsigned int> ForEachLoop::getPassedResults(Executor *execut, std::vector<SequenceAny *>& outputs, std::vector<std::string>& nameOfOutputs) const
1161 YACS::BASES::AutoLocker<YACS::BASES::Mutex> alck(&(execut->getTheMutexForSchedulerUpdate()));
1162 if(_execVals.empty())
1163 return std::vector<unsigned int>();
1164 if(_execOutGoingPorts.empty())
1165 return std::vector<unsigned int>();
1166 std::size_t sz(_execVals.size()); outputs.resize(sz); nameOfOutputs.resize(sz);
1167 const std::vector<AnyInputPort *>& ports(_execOutGoingPorts[0]);
1168 for(std::size_t i=0;i<sz;i++)
1170 outputs[i]=_execVals[i]->removeUnsetItemsFromThis();
1171 nameOfOutputs[i]=ports[i]->getName();
1173 return _execVals[0]->getSetItems();
1177 * 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
1178 * getPassedResults method.
1180 void ForEachLoop::assignPassedResults(const std::vector<unsigned int>& passedIds, const std::vector<SequenceAny *>& passedOutputs, const std::vector<std::string>& nameOfOutputs)
1184 _passedData=new ForEachLoopPassedData(passedIds,passedOutputs,nameOfOutputs);