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 InterceptorInputPort::InterceptorInputPort(const std::string& name, Node *node, TypeCode* type):AnyInputPort(name,node,type),
53 DataPort(name,node,type),Port(node),
58 InterceptorInputPort::InterceptorInputPort(const InterceptorInputPort& other, Node *newHelder):AnyInputPort(other,newHelder),DataPort(other,newHelder),
59 Port(other,newHelder),
64 void InterceptorInputPort::getAllRepresentants(std::set<InPort *>& repr) const
66 set<InPort *> ports=_repr->edSetInPort();
67 for(set<InPort *>::iterator iter=ports.begin();iter!=ports.end();iter++)
68 (*iter)->getAllRepresentants(repr);
71 InputPort *InterceptorInputPort::clone(Node *newHelder) const
73 return new InterceptorInputPort(*this,newHelder);
76 void InterceptorInputPort::setRepr(AnySplitOutputPort *repr)
81 bool AnySplitOutputPort::decrRef()
86 void AnySplitOutputPort::incrRef() const
91 AnySplitOutputPort::AnySplitOutputPort(const std::string& name, Node *node, TypeCode *type):OutputPort(name,node,type),
92 DataPort(name,node,type),Port(node),
93 _repr(0),_intercptr(0),_cnt(1)
97 AnySplitOutputPort::AnySplitOutputPort(const AnySplitOutputPort& other, Node *newHelder):OutputPort(other,newHelder),
98 DataPort(other,newHelder),
99 Port(other,newHelder),
100 _repr(0),_intercptr(0),_cnt(1)
104 bool AnySplitOutputPort::addInPort(InPort *inPort) throw(YACS::Exception)
106 bool ret=OutputPort::addInPort(inPort);
108 _repr->addInPort(_intercptr);
112 void AnySplitOutputPort::getAllRepresented(std::set<OutPort *>& represented) const
115 OutPort::getAllRepresented(represented);
117 _repr->getAllRepresented(represented);
120 int AnySplitOutputPort::removeInPort(InPort *inPort, bool forward) throw(YACS::Exception)
122 bool ret=OutputPort::removeInPort(inPort,forward);
124 if(_setOfInputPort.empty())
125 _repr->removeInPort(_intercptr,forward);
129 void AnySplitOutputPort::addRepr(OutPort *repr, InterceptorInputPort *intercptr)
132 _intercptr=intercptr;
135 OutputPort *AnySplitOutputPort::clone(Node *newHelder) const
137 return new AnySplitOutputPort(*this,newHelder);
140 SeqAnyInputPort::SeqAnyInputPort(const std::string& name, Node *node, TypeCodeSeq* type):AnyInputPort(name,node,type),DataPort(name,node,type),Port(node)
145 SeqAnyInputPort::SeqAnyInputPort(const SeqAnyInputPort& other, Node *newHelder):AnyInputPort(other,newHelder),DataPort(other,newHelder),Port(other,newHelder)
149 InputPort *SeqAnyInputPort::clone(Node *newHelder) const
151 return new SeqAnyInputPort(*this,newHelder);
154 unsigned SeqAnyInputPort::getNumberOfElements() const
156 const SequenceAny * valCsted=(const SequenceAny *) _value;
157 if (valCsted) return valCsted->size();
161 Any *SeqAnyInputPort::getValueAtRank(int i) const
163 const SequenceAny * valCsted=(const SequenceAny *) _value;
164 AnyPtr ret=(*valCsted)[i];
169 std::string SeqAnyInputPort::dump()
171 stringstream xmldump;
172 int nbElem = getNumberOfElements();
173 xmldump << "<value><array><data>" << endl;
174 for (int i = 0; i < nbElem; i++)
176 Any *val = getValueAtRank(i);
177 switch (val->getType()->kind())
180 xmldump << "<value><double>" << setprecision(16) << val->getDoubleValue() << "</double></value>" << endl;
183 xmldump << "<value><int>" << val->getIntValue() << "</int></value>" << endl;
186 xmldump << "<value><boolean>" << val->getBoolValue() << "</boolean></value>" << endl;
189 xmldump << "<value><string>" << val->getStringValue() << "</string></value>" << endl;
192 xmldump << "<value><objref>" << val->getStringValue() << "</objref></value>" << endl;
195 xmldump << "<value><error> NO_SERIALISATION_AVAILABLE </error></value>" << endl;
199 xmldump << "</data></array></value>" << endl;
200 return xmldump.str();
203 SplitterNode::SplitterNode(const std::string& name, TypeCode *typeOfData,
204 ForEachLoop *father):ElementaryNode(name),
205 _dataPortToDispatch(NAME_OF_SEQUENCE_INPUT,
206 this,(TypeCodeSeq *)TypeCode::sequenceTc("","",typeOfData))
211 SplitterNode::SplitterNode(const SplitterNode& other, ForEachLoop *father):ElementaryNode(other,father),
212 _dataPortToDispatch(other._dataPortToDispatch,this)
216 InputPort *SplitterNode::getInputPort(const std::string& name) const throw(YACS::Exception)
218 if(name==NAME_OF_SEQUENCE_INPUT)
219 return (InputPort *)&_dataPortToDispatch;
221 return ElementaryNode::getInputPort(name);
224 Node *SplitterNode::simpleClone(ComposedNode *father, bool editionOnly) const
226 return new SplitterNode(*this,(ForEachLoop *)father);
229 unsigned SplitterNode::getNumberOfElements() const
231 return _dataPortToDispatch.getNumberOfElements();
234 void SplitterNode::execute()
236 //Nothing : should never been called elsewhere big problem...
239 void SplitterNode::init(bool start)
241 ElementaryNode::init(start);
242 _dataPortToDispatch.exInit(start);
245 void SplitterNode::putSplittedValueOnRankTo(int rankInSeq, int branch, bool first)
247 Any *valueToDispatch=_dataPortToDispatch.getValueAtRank(rankInSeq);
248 ForEachLoop *fatherTyped=(ForEachLoop *)_father;
249 fatherTyped->putValueOnBranch(valueToDispatch,branch,first);
250 valueToDispatch->decrRef();
253 FakeNodeForForEachLoop::FakeNodeForForEachLoop(ForEachLoop *loop, bool normalFinish):ElementaryNode(NAME),
255 _normalFinish(normalFinish)
257 _state=YACS::TOACTIVATE;
258 _father=_loop->getFather();
261 FakeNodeForForEachLoop::FakeNodeForForEachLoop(const FakeNodeForForEachLoop& other):ElementaryNode(other),_loop(0),
266 Node *FakeNodeForForEachLoop::simpleClone(ComposedNode *father, bool editionOnly) const
268 return new FakeNodeForForEachLoop(*this);
271 void FakeNodeForForEachLoop::exForwardFailed()
273 _loop->exForwardFailed();
276 void FakeNodeForForEachLoop::exForwardFinished()
278 _loop->exForwardFinished();
281 void FakeNodeForForEachLoop::execute()
284 throw Exception("");//only to trigger ABORT on Executor
286 _loop->pushAllSequenceValues();
289 void FakeNodeForForEachLoop::aborted()
291 _loop->setState(YACS::ERROR);
294 void FakeNodeForForEachLoop::finished()
296 _loop->setState(YACS::DONE);
299 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)
301 std::size_t sz(_passedIds.size()),sz1(passedOutputs.size()),sz2(nameOfOutputs.size());
303 throw YACS::Exception("ForEachLoopPassedData::ForEachLoopPassedData : nameOfOutputs and passedOutputs must have the same size !");
304 for(std::vector<SequenceAny *>::iterator it=_passedOutputs.begin();it!=_passedOutputs.end();it++)
306 const SequenceAny *elt(*it);
308 if(sz!=(std::size_t)elt->size())
309 throw YACS::Exception("ForEachLoopPassedData::ForEachLoopPassedData : incoherent input of passed data !");
311 for(std::vector<SequenceAny *>::iterator it=_passedOutputs.begin();it!=_passedOutputs.end();it++)
313 SequenceAny *elt(*it);
319 ForEachLoopPassedData::~ForEachLoopPassedData()
321 for(std::vector<SequenceAny *>::iterator it=_passedOutputs.begin();it!=_passedOutputs.end();it++)
323 SequenceAny *elt(*it);
329 void ForEachLoopPassedData::init()
334 void ForEachLoopPassedData::checkCompatibilyWithNb(int nbOfElts) const
337 throw YACS::Exception("ForEachLoopPassedData::checkCompatibilyWithNb : nb of elts is expected to be > 0 !");
338 std::size_t sizeExp(_passedIds.size()),nbOfElts2(nbOfElts);
339 if(nbOfElts2<sizeExp)
340 throw YACS::Exception("ForEachLoopPassedData::checkCompatibilyWithNb : Invalid nb of elemts in input seq regarding passed data set !");
341 for(std::vector<unsigned int>::const_iterator it=_passedIds.begin();it!=_passedIds.end();it++)
344 throw YACS::Exception("ForEachLoopPassedData::checkCompatibilyWithNb : Invalid nb of elemts in input seq regarding passed data set 2 !");
346 _flagsIds.resize(nbOfElts);
347 std::fill(_flagsIds.begin(),_flagsIds.end(),false);
348 for(std::vector<unsigned int>::const_iterator it=_passedIds.begin();it!=_passedIds.end();it++)
356 std::ostringstream oss; oss << "ForEachLoopPassedData::checkCompatibilyWithNb : id " << *it << " in list of ids appears more than once !";
357 throw YACS::Exception(oss.str());
362 std::ostringstream oss; oss << "ForEachLoopPassedData::checkCompatibilyWithNb : Presence of id " << *it << " in list of ids ! Must be in [0," << nbOfElts << ") !";
363 throw YACS::Exception(oss.str());
368 void ForEachLoopPassedData::checkLevel2(const std::vector<AnyInputPort *>& ports) const
370 std::size_t sz(_nameOfOutputs.size());
372 throw YACS::Exception("ForEachLoopPassedData::checkLevel2 : mismatch of size of vectors !");
373 for(std::size_t i=0;i<sz;i++)
375 AnyInputPort *elt(ports[i]);
377 throw YACS::Exception("ForEachLoopPassedData::checkLevel2 : presence of null instance !");
378 if(_nameOfOutputs[i]!=elt->getName())
380 std::ostringstream oss; oss << "ForEachLoopPassedData::checkLevel2 : At pos #" << i << " the name is not OK !";
381 throw YACS::Exception(oss.str());
387 * 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.
389 int ForEachLoopPassedData::toAbsId(int localId) const
392 throw YACS::Exception("ForEachLoopPassedData::toAbsId : local pos must be >= 0 !");
393 int ret(0),curLocId(0);
394 for(std::vector<bool>::const_iterator it=_flagsIds.begin();it!=_flagsIds.end();it++,ret++)
398 if(localId==curLocId)
403 throw YACS::Exception("ForEachLoopPassedData::toAbsId : not referenced Id !");
407 * Equivalent to toAbsId except that only ON are considered here.
409 int ForEachLoopPassedData::toAbsIdNot(int localId) const
412 throw YACS::Exception("ForEachLoopPassedData::toAbsIdNot : local pos must be >= 0 !");
413 int ret(0),curLocId(0);
414 for(std::vector<bool>::const_iterator it=_flagsIds.begin();it!=_flagsIds.end();it++,ret++)
416 if(*it)//<- diff is here !
418 if(localId==curLocId)
423 throw YACS::Exception("ForEachLoopPassedData::toAbsIdNot : not referenced Id !");
426 int ForEachLoopPassedData::getNumberOfElementsToDo() const
428 std::size_t nbAllElts(_flagsIds.size());
429 std::size_t ret(nbAllElts-_passedIds.size());
433 void ForEachLoopPassedData::assignAlreadyDone(const std::vector<SequenceAny *>& execVals) const
435 std::size_t sz(execVals.size());
436 if(_passedOutputs.size()!=sz)
437 throw YACS::Exception("ForEachLoopPassedData::assignedAlreadyDone : mismatch of size of vectors !");
438 for(std::size_t i=0;i<sz;i++)
440 SequenceAny *elt(_passedOutputs[i]);
441 SequenceAny *eltDestination(execVals[i]);
443 throw YACS::Exception("ForEachLoopPassedData::assignedAlreadyDone : presence of null elt !");
444 unsigned int szOfElt(elt->size());
445 for(unsigned int j=0;j<szOfElt;j++)
447 AnyPtr elt1((*elt)[j]);
448 int jAbs(toAbsIdNot(j));
449 eltDestination->setEltAtRank(jAbs,elt1);
454 ForEachLoop::ForEachLoop(const std::string& name, TypeCode *typeOfDataSplitted):DynParaLoop(name,typeOfDataSplitted),
455 _splitterNode(NAME_OF_SPLITTERNODE,typeOfDataSplitted,this),
456 _execCurrentId(0),_nodeForSpecialCases(0),_currentIndex(0),_passedData(0)
460 ForEachLoop::ForEachLoop(const ForEachLoop& other, ComposedNode *father, bool editionOnly):DynParaLoop(other,father,editionOnly),
461 _splitterNode(other._splitterNode,this),
462 _execCurrentId(0),_nodeForSpecialCases(0),_currentIndex(0),_passedData(0)
466 for(vector<AnySplitOutputPort *>::const_iterator iter2=other._outGoingPorts.begin();iter2!=other._outGoingPorts.end();iter2++,i++)
468 AnySplitOutputPort *temp=new AnySplitOutputPort(*(*iter2),this);
469 InterceptorInputPort *interc=new InterceptorInputPort(*other._intecptrsForOutGoingPorts[i],this);
470 temp->addRepr(getOutPort(other.getOutPortName((*iter2)->getRepr())),interc);
471 interc->setRepr(temp);
472 _outGoingPorts.push_back(temp);
473 _intecptrsForOutGoingPorts.push_back(interc);
477 Node *ForEachLoop::simpleClone(ComposedNode *father, bool editionOnly) const
479 return new ForEachLoop(*this,father,editionOnly);
482 ForEachLoop::~ForEachLoop()
485 for(vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();iter!=_outGoingPorts.end();iter++)
487 for(vector<InterceptorInputPort *>::iterator iter2=_intecptrsForOutGoingPorts.begin();iter2!=_intecptrsForOutGoingPorts.end();iter2++)
492 void ForEachLoop::init(bool start)
494 DynParaLoop::init(start);
495 _splitterNode.init(start);
504 void ForEachLoop::exUpdateState()
506 DEBTRACE("ForEachLoop::exUpdateState");
507 if(_state == YACS::DISABLED)
509 if(_state == YACS::DONE)
511 if(_inGate.exIsReady())
513 //internal graph update
515 int nbOfBr(_nbOfBranches.getIntValue()),nbOfElts(_splitterNode.getNumberOfElements()),nbOfEltsDone(0);
518 _passedData->checkCompatibilyWithNb(nbOfElts);
519 nbOfEltsDone=_passedData->getNumberOfEltsAlreadyDone();
521 int nbOfEltsToDo(nbOfElts-nbOfEltsDone);
523 DEBTRACE("nbOfElts=" << nbOfElts);
524 DEBTRACE("nbOfBr=" << nbOfBr);
528 prepareSequenceValues(0);
529 delete _nodeForSpecialCases;
530 _nodeForSpecialCases=new FakeNodeForForEachLoop(this,true);
531 setState(YACS::ACTIVATED);
536 delete _nodeForSpecialCases;
537 _nodeForSpecialCases=new FakeNodeForForEachLoop(this,getAllOutPortsLeavingCurrentScope().empty());
538 setState(YACS::ACTIVATED);
541 if(nbOfBr>nbOfEltsToDo)
543 _execNodes.resize(nbOfBr);
544 _execIds.resize(nbOfBr);
545 _execOutGoingPorts.resize(nbOfBr);
546 prepareSequenceValues(nbOfElts);
548 _execInitNodes.resize(nbOfBr);
549 _initializingCounter = 0;
551 _execFinalizeNodes.resize(nbOfBr);
553 vector<Node *> origNodes;
554 origNodes.push_back(_initNode);
555 origNodes.push_back(_node);
556 origNodes.push_back(_finalizeNode);
558 //Conversion exceptions can be thrown by createOutputOutOfScopeInterceptors
559 //so catch them to control errors
562 for(i=0;i<nbOfBr;i++)
564 DEBTRACE( "-------------- 2" );
565 vector<Node *> clonedNodes = cloneAndPlaceNodesCoherently(origNodes);
567 _execInitNodes[i] = clonedNodes[0];
568 _execNodes[i] = clonedNodes[1];
570 _execFinalizeNodes[i] = clonedNodes[2];
571 DEBTRACE( "-------------- 4" );
572 prepareInputsFromOutOfScope(i);
573 DEBTRACE( "-------------- 5" );
574 createOutputOutOfScopeInterceptors(i);
575 DEBTRACE( "-------------- 6" );
577 for(i=0;i<nbOfBr;i++)
579 DEBTRACE( "-------------- 1 " << i << " " << _execCurrentId);
580 _execIds[i]=_execCurrentId;
581 int posInAbs(_execCurrentId);
583 posInAbs=_passedData->toAbsId(_execCurrentId);
584 _splitterNode.putSplittedValueOnRankTo(posInAbs,i,true);
586 DEBTRACE( "-------------- 7" );
590 _passedData->checkLevel2(_execOutGoingPorts[0]);
591 _passedData->assignAlreadyDone(_execVals);
594 catch(YACS::Exception& ex)
596 //ForEachLoop must be put in error and the exception rethrown to notify the caller
597 DEBTRACE( "ForEachLoop::exUpdateState: " << ex.what() );
598 setState(YACS::ERROR);
603 setState(YACS::ACTIVATED); // move the calling of setState method there for adding observers for clone nodes in GUI part
606 for(i=0;i<nbOfBr;i++)
609 _execInitNodes[i]->exUpdateState();
610 _initializingCounter++;
615 _execNodes[i]->exUpdateState();
618 forwardExecStateToOriginalBody(_execNodes[nbOfBr-1]);
622 void ForEachLoop::exUpdateProgress()
624 // emit notification to all observers registered with the dispatcher on any change of the node's state
625 sendEvent("progress");
628 void ForEachLoop::getReadyTasks(std::vector<Task *>& tasks)
632 if(_state==YACS::TOACTIVATE) setState(YACS::ACTIVATED);
633 if(_state==YACS::TOACTIVATE || _state==YACS::ACTIVATED)
635 if(_nodeForSpecialCases)
637 _nodeForSpecialCases->getReadyTasks(tasks);
640 vector<Node *>::iterator iter;
641 for (iter=_execNodes.begin() ; iter!=_execNodes.end() ; iter++)
642 (*iter)->getReadyTasks(tasks);
643 for (iter=_execInitNodes.begin() ; iter!=_execInitNodes.end() ; iter++)
644 (*iter)->getReadyTasks(tasks);
645 for (iter=_execFinalizeNodes.begin() ; iter!=_execFinalizeNodes.end() ; iter++)
646 (*iter)->getReadyTasks(tasks);
650 int ForEachLoop::getNumberOfInputPorts() const
652 return DynParaLoop::getNumberOfInputPorts()+1;
655 void ForEachLoop::checkNoCyclePassingThrough(Node *node) throw(YACS::Exception)
660 void ForEachLoop::selectRunnableTasks(std::vector<Task *>& tasks)
664 std::list<InputPort *> ForEachLoop::getSetOfInputPort() const
666 list<InputPort *> ret=DynParaLoop::getSetOfInputPort();
667 ret.push_back((InputPort *)&_splitterNode._dataPortToDispatch);
671 std::list<InputPort *> ForEachLoop::getLocalInputPorts() const
673 list<InputPort *> ret=DynParaLoop::getLocalInputPorts();
674 ret.push_back((InputPort *)&_splitterNode._dataPortToDispatch);
678 InputPort *ForEachLoop::getInputPort(const std::string& name) const throw(YACS::Exception)
680 if(name==SplitterNode::NAME_OF_SEQUENCE_INPUT)
681 return (InputPort *)&_splitterNode._dataPortToDispatch;
683 return DynParaLoop::getInputPort(name);
686 OutputPort *ForEachLoop::getOutputPort(const std::string& name) const throw(YACS::Exception)
688 for(vector<AnySplitOutputPort *>::const_iterator iter=_outGoingPorts.begin();iter!=_outGoingPorts.end();iter++)
690 if(name==(*iter)->getName())
691 return (OutputPort *)(*iter);
693 return DynParaLoop::getOutputPort(name);
696 OutPort *ForEachLoop::getOutPort(const std::string& name) const throw(YACS::Exception)
698 for(vector<AnySplitOutputPort *>::const_iterator iter=_outGoingPorts.begin();iter!=_outGoingPorts.end();iter++)
700 if(name==(*iter)->getName())
701 return (OutPort *)(*iter);
703 return DynParaLoop::getOutPort(name);
706 Node *ForEachLoop::getChildByShortName(const std::string& name) const throw(YACS::Exception)
708 if(name==NAME_OF_SPLITTERNODE)
709 return (Node *)&_splitterNode;
711 return DynParaLoop::getChildByShortName(name);
714 //! Method used to notify the node that a child node has finished
716 * Update the current state and return the change state
718 * \param node : the child node that has finished
719 * \return the state change
721 YACS::Event ForEachLoop::updateStateOnFinishedEventFrom(Node *node)
723 DEBTRACE("updateStateOnFinishedEventFrom " << node->getName() << " " << node->getState());
725 switch(getIdentityOfNotifyerNode(node,id))
728 return updateStateForInitNodeOnFinishedEventFrom(node,id);
730 return updateStateForWorkNodeOnFinishedEventFrom(node,id,true);
732 return updateStateForFinalizeNodeOnFinishedEventFrom(node,id);
736 return YACS::NOEVENT;
739 YACS::Event ForEachLoop::updateStateForInitNodeOnFinishedEventFrom(Node *node, unsigned int id)
741 _execNodes[id]->exUpdateState();
743 _initializingCounter--;
744 if (_initializingCounter == 0)
745 _initNode->setState(DONE);
746 return YACS::NOEVENT;
750 * \param [in] isNormalFinish - if true
752 YACS::Event ForEachLoop::updateStateForWorkNodeOnFinishedEventFrom(Node *node, unsigned int id, bool isNormalFinish)
758 int globalId(_execIds[id]);
760 globalId=_passedData->toAbsId(globalId);
761 storeOutValsInSeqForOutOfScopeUse(globalId,id);
764 if(_execCurrentId==getFinishedId())
765 {//No more elements of _dataPortToDispatch to treat
766 _execIds[id]=NOT_RUNNING_BRANCH_ID;
767 //analyzing if some samples are still on treatment on other branches.
768 bool isFinished(true);
769 for(int i=0;i<_execIds.size() && isFinished;i++)
770 isFinished=(_execIds[i]==NOT_RUNNING_BRANCH_ID);
775 if(_failedCounter!=0)
776 {// case of keepgoing mode + a failed
777 std::ostringstream oss; oss << "Keep Going mode activated and some errors (" << _failedCounter << ")reported !";
778 DEBTRACE("ForEachLoop::updateStateOnFinishedEventFrom : "<< oss.str());
779 setState(YACS::FAILED);
782 pushAllSequenceValues();
786 _node->setState(YACS::DONE);
788 ComposedNode* compNode = dynamic_cast<ComposedNode*>(_node);
791 std::list<Node *> aChldn = compNode->getAllRecursiveConstituents();
792 std::list<Node *>::iterator iter=aChldn.begin();
793 for(;iter!=aChldn.end();iter++)
794 (*iter)->setState(YACS::DONE);
798 if (_finalizeNode == NULL)
800 // No finalize node, we just finish the loop at the end of exec nodes execution
801 setState(YACS::DONE);
806 // Run the finalize nodes, the loop will be done only when they all finish
807 _unfinishedCounter = 0; // This counter indicates how many branches are not finished
808 for (int i=0 ; i<_execIds.size() ; i++)
810 YASSERT(_execIds[i] == NOT_RUNNING_BRANCH_ID);
811 DEBTRACE("Launching finalize node for branch " << i);
812 _execFinalizeNodes[i]->exUpdateState();
813 _unfinishedCounter++;
815 return YACS::NOEVENT;
818 catch(YACS::Exception& ex)
820 DEBTRACE("ForEachLoop::updateStateOnFinishedEventFrom: "<<ex.what());
821 //no way to push results : put following nodes in FAILED state
822 //TODO could be more fine grain : put only concerned nodes in FAILED state
824 setState(YACS::ERROR);
829 else if(_state == YACS::ACTIVATED)
830 {//more elements to do and loop still activated
831 _execIds[id]=_execCurrentId;
833 int posInAbs(_execCurrentId);
835 posInAbs=_passedData->toAbsId(_execCurrentId);
836 _splitterNode.putSplittedValueOnRankTo(posInAbs,id,false);
838 node->exUpdateState();
839 forwardExecStateToOriginalBody(node);
843 {//elements to process and loop no more activated
844 DEBTRACE("foreach loop state " << _state);
846 return YACS::NOEVENT;
849 YACS::Event ForEachLoop::updateStateForFinalizeNodeOnFinishedEventFrom(Node *node, unsigned int id)
851 DEBTRACE("Finalize node finished on branch " << id);
852 _unfinishedCounter--;
855 DEBTRACE(_unfinishedCounter << " finalize nodes still running");
856 if (_unfinishedCounter == 0)
858 _finalizeNode->setState(YACS::DONE);
859 setState(YACS::DONE);
863 return YACS::NOEVENT;
866 YACS::Event ForEachLoop::updateStateOnFailedEventFrom(Node *node, const Executor *execInst)
869 DynParaLoop::TypeOfNode ton(getIdentityOfNotifyerNode(node,id));
870 if(ton!=WORK_NODE || !execInst->getKeepGoingProperty())
871 return DynParaLoop::updateStateOnFailedEventFrom(node,execInst);
875 return updateStateForWorkNodeOnFinishedEventFrom(node,id,false);
879 void ForEachLoop::buildDelegateOf(std::pair<OutPort *, OutPort *>& port, InPort *finalTarget, const std::list<ComposedNode *>& pointsOfView)
881 DynParaLoop::buildDelegateOf(port,finalTarget,pointsOfView);
882 string typeOfPortInstance=(port.first)->getNameOfTypeOfCurrentInstance();
883 if(typeOfPortInstance==OutputPort::NAME)
885 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
887 for(;iter!=_outGoingPorts.end();iter++,i++)
888 if((*iter)->getRepr()==port.first || *iter==port.first)
890 if(iter!=_outGoingPorts.end())
892 if(*iter!=port.first)
895 (*iter)->addRepr(port.first,_intecptrsForOutGoingPorts[i]);
901 TypeCodeSeq *newTc=(TypeCodeSeq *)TypeCode::sequenceTc("","",port.first->edGetType());
902 // The out going ports belong to the ForEachLoop, whereas
903 // the delegated port belongs to a node child of the ForEachLoop.
904 // The name of the delegated port contains dots (bloc.node.outport),
905 // whereas the name of the out going port shouldn't do.
906 std::string outputPortName = getPortName(port.first);
907 std::replace_if (outputPortName.begin(), outputPortName.end(),
908 std::bind1st(std::equal_to<char>(), '.'), '_');
909 outputPortName += "_interceptor";
910 AnySplitOutputPort *newPort=new AnySplitOutputPort(outputPortName,this,newTc);
911 InterceptorInputPort *intercptor=new InterceptorInputPort(outputPortName + "_in",this,port.first->edGetType());
912 intercptor->setRepr(newPort);
914 newPort->addRepr(port.first,intercptor);
915 _outGoingPorts.push_back(newPort);
916 _intecptrsForOutGoingPorts.push_back(intercptor);
921 throw Exception("ForEachLoop::buildDelegateOf : not implemented for DS because not specified");
924 void ForEachLoop::getDelegateOf(std::pair<OutPort *, OutPort *>& port, InPort *finalTarget, const std::list<ComposedNode *>& pointsOfView) throw(YACS::Exception)
926 string typeOfPortInstance=(port.first)->getNameOfTypeOfCurrentInstance();
927 if(typeOfPortInstance==OutputPort::NAME)
929 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
930 for(;iter!=_outGoingPorts.end();iter++)
931 if((*iter)->getRepr()==port.first)
933 if(iter==_outGoingPorts.end())
935 string what("ForEachLoop::getDelegateOf : Port with name "); what+=port.first->getName(); what+=" not exported by ForEachLoop "; what+=_name;
936 throw Exception(what);
942 throw Exception("ForEachLoop::getDelegateOf : not implemented because not specified");
945 void ForEachLoop::releaseDelegateOf(OutPort *portDwn, OutPort *portUp, InPort *finalTarget, const std::list<ComposedNode *>& pointsOfView) throw(YACS::Exception)
947 string typeOfPortInstance=portDwn->getNameOfTypeOfCurrentInstance();
948 if(typeOfPortInstance==OutputPort::NAME)
950 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
951 vector<InterceptorInputPort *>::iterator iter2=_intecptrsForOutGoingPorts.begin();
952 for(;iter!=_outGoingPorts.end();iter++,iter2++)
953 if((*iter)->getRepr()==portDwn)
955 //ASSERT(portUp==*iter.second)
956 if((*iter)->decrRef())
958 AnySplitOutputPort *p=*iter;
959 _outGoingPorts.erase(iter);
961 InterceptorInputPort *ip=*iter2;
962 _intecptrsForOutGoingPorts.erase(iter2);
968 OutPort *ForEachLoop::getDynOutPortByAbsName(int branchNb, const std::string& name)
970 string portName, nodeName;
971 splitNamesBySep(name,Node::SEP_CHAR_IN_PORT,nodeName,portName,false);
972 Node *staticChild = getChildByName(nodeName);
973 return _execNodes[branchNb]->getOutPort(portName);//It's impossible(garanteed by YACS::ENGINE::ForEachLoop::buildDelegateOf)
974 //that a link starting from _initNode goes out of scope of 'this'.
977 void ForEachLoop::cleanDynGraph()
979 DynParaLoop::cleanDynGraph();
980 for(vector< SequenceAny *>::iterator iter3=_execVals.begin();iter3!=_execVals.end();iter3++)
983 for(vector< vector<AnyInputPort *> >::iterator iter4=_execOutGoingPorts.begin();iter4!=_execOutGoingPorts.end();iter4++)
984 for(vector<AnyInputPort *>::iterator iter5=(*iter4).begin();iter5!=(*iter4).end();iter5++)
986 _execOutGoingPorts.clear();
989 void ForEachLoop::storeOutValsInSeqForOutOfScopeUse(int rank, int branchNb)
991 vector<AnyInputPort *>::iterator iter;
993 for(iter=_execOutGoingPorts[branchNb].begin();iter!=_execOutGoingPorts[branchNb].end();iter++,i++)
995 Any *val=(Any *)(*iter)->getValue();
996 _execVals[i]->setEltAtRank(rank,val);
1000 int ForEachLoop::getFinishedId()
1003 return _splitterNode.getNumberOfElements();
1005 return _passedData->getNumberOfElementsToDo();
1008 void ForEachLoop::prepareSequenceValues(int sizeOfSamples)
1010 _execVals.resize(_outGoingPorts.size());
1011 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
1012 for(int i=0;iter!=_outGoingPorts.end();iter++,i++)
1013 _execVals[i]=SequenceAny::New((*iter)->edGetType()->contentType(),sizeOfSamples);
1016 void ForEachLoop::pushAllSequenceValues()
1018 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
1020 for(;iter!=_outGoingPorts.end();iter++,i++)
1021 (*iter)->put((const void *)_execVals[i]);
1024 void ForEachLoop::createOutputOutOfScopeInterceptors(int branchNb)
1026 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
1028 for(;iter!=_outGoingPorts.end();iter++,i++)
1030 DEBTRACE( (*iter)->getName() << " " << (*iter)->edGetType()->kind() );
1031 //AnyInputPort *interceptor=new AnyInputPort((*iter)->getName(),this,(*iter)->edGetType());
1032 OutPort *portOut=getDynOutPortByAbsName(branchNb,getOutPortName(((*iter)->getRepr())));
1033 DEBTRACE( portOut->getName() );
1034 AnyInputPort *interceptor=new AnyInputPort((*iter)->getName(),this,portOut->edGetType());
1035 portOut->addInPort(interceptor);
1036 _execOutGoingPorts[branchNb].push_back(interceptor);
1040 void ForEachLoop::checkLinkPossibility(OutPort *start, const std::list<ComposedNode *>& pointsOfViewStart,
1041 InPort *end, const std::list<ComposedNode *>& pointsOfViewEnd) throw(YACS::Exception)
1043 DynParaLoop::checkLinkPossibility(start, pointsOfViewStart, end, pointsOfViewEnd);
1044 if(end->getNode() == &_splitterNode)
1045 throw Exception("Illegal link within a foreach loop: \
1046 the 'SmplsCollection' port cannot be linked within the scope of the loop.");
1047 if(end == &_nbOfBranches)
1048 throw Exception("Illegal link within a foreach loop: \
1049 the 'nbBranches' port cannot be linked within the scope of the loop.");
1052 std::list<OutputPort *> ForEachLoop::getLocalOutputPorts() const
1054 list<OutputPort *> ret;
1055 ret.push_back(getOutputPort(NAME_OF_SPLITTED_SEQ_OUT));
1059 void ForEachLoop::accept(Visitor *visitor)
1061 visitor->visitForEachLoop(this);
1064 //! Dump the node state to a stream
1066 * \param os : the output stream
1068 void ForEachLoop::writeDot(std::ostream &os) const
1070 os << " subgraph cluster_" << getId() << " {\n" ;
1071 //only one node in a loop
1074 _node->writeDot(os);
1075 os << getId() << " -> " << _node->getId() << ";\n";
1078 os << getId() << "[fillcolor=\"" ;
1079 YACS::StatesForNode state=getEffectiveState();
1080 os << getColorState(state);
1081 os << "\" label=\"" << "Loop:" ;
1082 os << getName() <<"\"];\n";
1085 //! Reset the state of the node and its children depending on the parameter level
1086 void ForEachLoop::resetState(int level)
1089 DynParaLoop::resetState(level);
1091 //Note: cleanDynGraph is not a virtual method (must be called from ForEachLoop object)
1095 std::string ForEachLoop::getProgress() const
1097 int nbElems(getNbOfElementsToBeProcessed());
1098 std::stringstream aProgress;
1100 aProgress << _currentIndex << "/" << nbElems;
1103 return aProgress.str();
1106 //! Get the progress weight for all elementary nodes
1108 * Only elementary nodes have weight. For each node in the loop, the weight done is multiplied
1109 * by the number of elements done and the weight total by the number total of elements
1111 list<ProgressWeight> ForEachLoop::getProgressWeight() const
1113 list<ProgressWeight> ret;
1114 list<Node *> setOfNode=edGetDirectDescendants();
1115 int elemDone=getCurrentIndex();
1116 int elemTotal=getNbOfElementsToBeProcessed();
1117 for(list<Node *>::const_iterator iter=setOfNode.begin();iter!=setOfNode.end();iter++)
1119 list<ProgressWeight> myCurrentSet=(*iter)->getProgressWeight();
1120 for(list<ProgressWeight>::iterator iter=myCurrentSet.begin();iter!=myCurrentSet.end();iter++)
1122 (*iter).weightDone=((*iter).weightTotal) * elemDone;
1123 (*iter).weightTotal*=elemTotal;
1125 ret.insert(ret.end(),myCurrentSet.begin(),myCurrentSet.end());
1131 int ForEachLoop::getNbOfElementsToBeProcessed() const
1133 return _splitterNode.getNumberOfElements();
1137 * 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.
1138 * 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.
1139 * This method has one input \a execut and 3 outputs.
1141 * \param [in] execut - The single input is for threadsafety reasons because this method can be called safely during the execution of \a this.
1142 * \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.
1143 * All of the items in \a outputs have the same size.
1144 * \param [out] nameOfOutputs - The array with same size than \a outputs, that tells for each item in outputs the output port it refers to.
1145 * \return the list of ids among \c this->edGetSeqOfSamplesPort() that run successfully. The length of this returned array will be the length of all
1146 * SequenceAny objects contained in \a outputs.
1148 * \sa edGetSeqOfSamplesPort
1150 std::vector<unsigned int> ForEachLoop::getPassedResults(Executor *execut, std::vector<SequenceAny *>& outputs, std::vector<std::string>& nameOfOutputs) const
1152 YACS::BASES::AutoLocker<YACS::BASES::Mutex> alck(&(execut->getTheMutexForSchedulerUpdate()));
1153 if(_execVals.empty())
1154 return std::vector<unsigned int>();
1155 if(_execOutGoingPorts.empty())
1156 return std::vector<unsigned int>();
1157 std::size_t sz(_execVals.size()); outputs.resize(sz); nameOfOutputs.resize(sz);
1158 const std::vector<AnyInputPort *>& ports(_execOutGoingPorts[0]);
1159 for(std::size_t i=0;i<sz;i++)
1161 outputs[i]=_execVals[i]->removeUnsetItemsFromThis();
1162 nameOfOutputs[i]=ports[i]->getName();
1164 return _execVals[0]->getSetItems();
1168 * 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
1169 * getPassedResults method.
1171 void ForEachLoop::assignPassedResults(const std::vector<unsigned int>& passedIds, const std::vector<SequenceAny *>& passedOutputs, const std::vector<std::string>& nameOfOutputs)
1175 _passedData=new ForEachLoopPassedData(passedIds,passedOutputs,nameOfOutputs);