1 // Copyright (C) 2006-2019 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"
39 using namespace YACS::ENGINE;
42 /*! \class YACS::ENGINE::ForEachLoop
43 * \brief Loop node for parametric calculation
48 const char FakeNodeForForEachLoop::NAME[]="thisIsAFakeNode";
50 const char SplitterNode::NAME_OF_SEQUENCE_INPUT[]="SmplsCollection";
52 const char ForEachLoop::NAME_OF_SPLITTERNODE[]="splitter";
54 const int ForEachLoop::NOT_RUNNING_BRANCH_ID=-1;
56 const char ForEachLoop::INTERCEPTOR_STR[]="_interceptor";
58 InterceptorInputPort::InterceptorInputPort(const std::string& name, Node *node, TypeCode* type):AnyInputPort(name,node,type),
59 DataPort(name,node,type),Port(node),
64 InterceptorInputPort::InterceptorInputPort(const InterceptorInputPort& other, Node *newHelder):AnyInputPort(other,newHelder),DataPort(other,newHelder),
65 Port(other,newHelder),
70 void InterceptorInputPort::getAllRepresentants(std::set<InPort *>& repr) const
72 set<InPort *> ports=_repr->edSetInPort();
73 for(set<InPort *>::iterator iter=ports.begin();iter!=ports.end();iter++)
74 (*iter)->getAllRepresentants(repr);
77 InputPort *InterceptorInputPort::clone(Node *newHelder) const
79 return new InterceptorInputPort(*this,newHelder);
82 void InterceptorInputPort::setRepr(AnySplitOutputPort *repr)
87 bool AnySplitOutputPort::decrRef()
92 void AnySplitOutputPort::incrRef() const
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)
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)
110 bool AnySplitOutputPort::addInPort(InPort *inPort) throw(YACS::Exception)
112 bool ret=OutputPort::addInPort(inPort);
114 _repr->addInPort(_intercptr);
118 void AnySplitOutputPort::getAllRepresented(std::set<OutPort *>& represented) const
121 OutPort::getAllRepresented(represented);
123 _repr->getAllRepresented(represented);
126 int AnySplitOutputPort::removeInPort(InPort *inPort, bool forward) throw(YACS::Exception)
128 bool ret=OutputPort::removeInPort(inPort,forward);
130 if(_setOfInputPort.empty())
131 _repr->removeInPort(_intercptr,forward);
135 void AnySplitOutputPort::addRepr(OutPort *repr, InterceptorInputPort *intercptr)
138 _intercptr=intercptr;
141 OutputPort *AnySplitOutputPort::clone(Node *newHelder) const
143 return new AnySplitOutputPort(*this,newHelder);
146 SeqAnyInputPort::SeqAnyInputPort(const std::string& name, Node *node, TypeCodeSeq* type):AnyInputPort(name,node,type),DataPort(name,node,type),Port(node)
151 SeqAnyInputPort::SeqAnyInputPort(const SeqAnyInputPort& other, Node *newHelder):AnyInputPort(other,newHelder),DataPort(other,newHelder),Port(other,newHelder)
155 InputPort *SeqAnyInputPort::clone(Node *newHelder) const
157 return new SeqAnyInputPort(*this,newHelder);
160 unsigned SeqAnyInputPort::getNumberOfElements() const
162 const SequenceAny * valCsted=(const SequenceAny *) _value;
163 if (valCsted) return valCsted->size();
167 Any *SeqAnyInputPort::getValueAtRank(int i) const
169 const SequenceAny * valCsted=(const SequenceAny *) _value;
170 AnyPtr ret=(*valCsted)[i];
175 std::string SeqAnyInputPort::dump()
177 stringstream xmldump;
178 int nbElem = getNumberOfElements();
179 xmldump << "<value><array><data>" << endl;
180 for (int i = 0; i < nbElem; i++)
182 Any *val = getValueAtRank(i);
183 switch (((YACS::ENGINE::TypeCodeSeq *)edGetType())->contentType()->kind())
186 xmldump << "<value><double>" << setprecision(16) << val->getDoubleValue() << "</double></value>" << endl;
189 xmldump << "<value><int>" << val->getIntValue() << "</int></value>" << endl;
192 xmldump << "<value><boolean>" << val->getBoolValue() << "</boolean></value>" << endl;
195 xmldump << "<value><string>" << val->getStringValue() << "</string></value>" << endl;
198 xmldump << "<value><objref>" << ToBase64(val->getStringValue()) << "</objref></value>" << endl;
201 xmldump << "<value><error> NO_SERIALISATION_AVAILABLE </error></value>" << endl;
205 xmldump << "</data></array></value>" << endl;
206 return xmldump.str();
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))
217 SplitterNode::SplitterNode(const SplitterNode& other, ForEachLoop *father):ElementaryNode(other,father),
218 _dataPortToDispatch(other._dataPortToDispatch,this)
222 InputPort *SplitterNode::getInputPort(const std::string& name) const throw(YACS::Exception)
224 if(name==NAME_OF_SEQUENCE_INPUT)
225 return (InputPort *)&_dataPortToDispatch;
227 return ElementaryNode::getInputPort(name);
230 Node *SplitterNode::simpleClone(ComposedNode *father, bool editionOnly) const
232 return new SplitterNode(*this,(ForEachLoop *)father);
235 unsigned SplitterNode::getNumberOfElements() const
237 return _dataPortToDispatch.getNumberOfElements();
240 void SplitterNode::execute()
242 //Nothing : should never been called elsewhere big problem...
245 void SplitterNode::init(bool start)
247 ElementaryNode::init(start);
248 _dataPortToDispatch.exInit(start);
251 void SplitterNode::putSplittedValueOnRankTo(int rankInSeq, int branch, bool first)
253 Any *valueToDispatch=_dataPortToDispatch.getValueAtRank(rankInSeq);
254 ForEachLoop *fatherTyped=(ForEachLoop *)_father;
255 fatherTyped->putValueOnBranch(valueToDispatch,branch,first);
256 valueToDispatch->decrRef();
259 FakeNodeForForEachLoop::FakeNodeForForEachLoop(ForEachLoop *loop, bool normalFinish):ElementaryNode(NAME),
261 _normalFinish(normalFinish)
263 _state=YACS::TOACTIVATE;
264 _father=_loop->getFather();
267 FakeNodeForForEachLoop::FakeNodeForForEachLoop(const FakeNodeForForEachLoop& other):ElementaryNode(other),_loop(0),
272 Node *FakeNodeForForEachLoop::simpleClone(ComposedNode *father, bool editionOnly) const
274 return new FakeNodeForForEachLoop(*this);
277 void FakeNodeForForEachLoop::exForwardFailed()
279 _loop->exForwardFailed();
282 void FakeNodeForForEachLoop::exForwardFinished()
284 _loop->exForwardFinished();
287 void FakeNodeForForEachLoop::execute()
290 throw Exception("");//only to trigger ABORT on Executor
292 _loop->pushAllSequenceValues();
295 void FakeNodeForForEachLoop::aborted()
297 _loop->setState(YACS::ERROR);
300 void FakeNodeForForEachLoop::finished()
302 _loop->setState(YACS::DONE);
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)
307 std::size_t sz(_passedIds.size()),sz1(passedOutputs.size()),sz2(nameOfOutputs.size());
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++)
312 const SequenceAny *elt(*it);
314 if(sz!=(std::size_t)elt->size())
315 throw YACS::Exception("ForEachLoopPassedData::ForEachLoopPassedData : incoherent input of passed data !");
317 for(std::vector<SequenceAny *>::iterator it=_passedOutputs.begin();it!=_passedOutputs.end();it++)
319 SequenceAny *elt(*it);
325 ForEachLoopPassedData::ForEachLoopPassedData(const ForEachLoopPassedData& copy)
326 : _passedIds(copy._passedIds),
327 _passedOutputs(copy._passedOutputs),
328 _nameOfOutputs(copy._nameOfOutputs),
329 _flagsIds(copy._flagsIds)
333 ForEachLoopPassedData::~ForEachLoopPassedData()
335 for(std::vector<SequenceAny *>::iterator it=_passedOutputs.begin();it!=_passedOutputs.end();it++)
337 SequenceAny *elt(*it);
343 void ForEachLoopPassedData::init()
348 void ForEachLoopPassedData::checkCompatibilyWithNb(int nbOfElts) const
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++)
358 throw YACS::Exception("ForEachLoopPassedData::checkCompatibilyWithNb : Invalid nb of elemts in input seq regarding passed data set 2 !");
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++)
370 std::ostringstream oss; oss << "ForEachLoopPassedData::checkCompatibilyWithNb : id " << *it << " in list of ids appears more than once !";
371 throw YACS::Exception(oss.str());
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());
382 void ForEachLoopPassedData::checkLevel2(const std::vector<AnyInputPort *>& ports) const
384 std::size_t sz(_nameOfOutputs.size());
386 throw YACS::Exception("ForEachLoopPassedData::checkLevel2 : mismatch of size of vectors !");
387 for(std::size_t i=0;i<sz;i++)
389 AnyInputPort *elt(ports[i]);
391 throw YACS::Exception("ForEachLoopPassedData::checkLevel2 : presence of null instance !");
392 if(_nameOfOutputs[i]!=elt->getName())
394 std::ostringstream oss; oss << "ForEachLoopPassedData::checkLevel2 : At pos #" << i << " the name is not OK !";
395 throw YACS::Exception(oss.str());
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.
403 int ForEachLoopPassedData::toAbsId(int localId) const
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++)
412 if(localId==curLocId)
417 throw YACS::Exception("ForEachLoopPassedData::toAbsId : not referenced Id !");
421 * Equivalent to toAbsId except that only ON are considered here.
423 int ForEachLoopPassedData::toAbsIdNot(int localId) const
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++)
430 if(*it)//<- diff is here !
432 if(localId==curLocId)
437 throw YACS::Exception("ForEachLoopPassedData::toAbsIdNot : not referenced Id !");
440 int ForEachLoopPassedData::getNumberOfElementsToDo() const
442 std::size_t nbAllElts(_flagsIds.size());
443 std::size_t ret(nbAllElts-_passedIds.size());
447 void ForEachLoopPassedData::assignAlreadyDone(const std::vector<SequenceAny *>& execVals) const
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++)
454 SequenceAny *elt(_passedOutputs[i]);
455 SequenceAny *eltDestination(execVals[i]);
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++)
461 AnyPtr elt1((*elt)[j]);
462 int jAbs(toAbsIdNot(j));
463 eltDestination->setEltAtRank(jAbs,elt1);
468 ForEachLoop::ForEachLoop(const std::string& name, TypeCode *typeOfDataSplitted):DynParaLoop(name,typeOfDataSplitted,std::unique_ptr<NbBranchesAbstract>(new NbBranches(this))),
469 _splitterNode(NAME_OF_SPLITTERNODE,typeOfDataSplitted,this),
470 _execCurrentId(0),_nodeForSpecialCases(0),_currentIndex(0),_passedData(0)
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)
480 for(vector<AnySplitOutputPort *>::const_iterator iter2=other._outGoingPorts.begin();iter2!=other._outGoingPorts.end();iter2++,i++)
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);
491 Node *ForEachLoop::simpleClone(ComposedNode *father, bool editionOnly) const
493 return new ForEachLoop(*this,father,editionOnly);
496 ForEachLoop::~ForEachLoop()
499 for(vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();iter!=_outGoingPorts.end();iter++)
501 for(vector<InterceptorInputPort *>::iterator iter2=_intecptrsForOutGoingPorts.begin();iter2!=_intecptrsForOutGoingPorts.end();iter2++)
506 void ForEachLoop::init(bool start)
508 DynParaLoop::init(start);
509 _splitterNode.init(start);
518 void ForEachLoop::exUpdateState()
520 DEBTRACE("ForEachLoop::exUpdateState");
521 if(_state == YACS::DISABLED)
523 if(_state == YACS::DONE)
525 if(_inGate.exIsReady())
527 //internal graph update
529 int nbOfElts(_splitterNode.getNumberOfElements()),nbOfEltsDone(0);
530 int nbOfBr(_nbOfBranches->getNumberOfBranches(nbOfElts));
533 _passedData->checkCompatibilyWithNb(nbOfElts);
534 nbOfEltsDone=_passedData->getNumberOfEltsAlreadyDone();
536 int nbOfEltsToDo(nbOfElts-nbOfEltsDone);
538 DEBTRACE("nbOfElts=" << nbOfElts);
539 DEBTRACE("nbOfBr=" << nbOfBr);
543 prepareSequenceValues(0);
544 delete _nodeForSpecialCases;
545 _nodeForSpecialCases=new FakeNodeForForEachLoop(this,true);
546 setState(YACS::ACTIVATED);
551 delete _nodeForSpecialCases;
552 _nodeForSpecialCases=new FakeNodeForForEachLoop(this,getAllOutPortsLeavingCurrentScope().empty());
553 setState(YACS::ACTIVATED);
556 if(nbOfBr>nbOfEltsToDo)
558 _execNodes.resize(nbOfBr);
559 _execIds.resize(nbOfBr);
560 _execOutGoingPorts.resize(nbOfBr);
561 prepareSequenceValues(nbOfElts);
563 _execInitNodes.resize(nbOfBr);
564 _initializingCounter = 0;
566 _execFinalizeNodes.resize(nbOfBr);
568 vector<Node *> origNodes;
569 origNodes.push_back(_initNode);
570 origNodes.push_back(_node);
571 origNodes.push_back(_finalizeNode);
573 //Conversion exceptions can be thrown by createOutputOutOfScopeInterceptors
574 //so catch them to control errors
577 for(i=0;i<nbOfBr;i++)
579 DEBTRACE( "-------------- 2" );
580 vector<Node *> clonedNodes = cloneAndPlaceNodesCoherently(origNodes);
582 _execInitNodes[i] = clonedNodes[0];
583 _execNodes[i] = clonedNodes[1];
585 _execFinalizeNodes[i] = clonedNodes[2];
586 DEBTRACE( "-------------- 4" );
587 prepareInputsFromOutOfScope(i);
588 DEBTRACE( "-------------- 5" );
589 createOutputOutOfScopeInterceptors(i);
590 DEBTRACE( "-------------- 6" );
592 for(i=0;i<nbOfBr;i++)
594 DEBTRACE( "-------------- 1 " << i << " " << _execCurrentId);
595 _execIds[i]=_execCurrentId;
596 int posInAbs(_execCurrentId);
598 posInAbs=_passedData->toAbsId(_execCurrentId);
599 _splitterNode.putSplittedValueOnRankTo(posInAbs,i,true);
601 DEBTRACE( "-------------- 7" );
605 _passedData->checkLevel2(_execOutGoingPorts[0]);
606 _passedData->assignAlreadyDone(_execVals);
608 // clean inputs data coming from the outside in _node
609 set< InPort * > portsToSetVals=getAllInPortsComingFromOutsideOfCurrentScope();
610 for(auto iter : portsToSetVals)
612 InputPort *curPortCasted=(InputPort *) iter;//Cast granted by ForEachLoop::buildDelegateOf(InPort)
613 if(!curPortCasted->canSafelySqueezeMemory())// this can appear strange ! if not safelySqueeze -> release. Nevertheless it is true.
614 curPortCasted->releaseData(); // these input ports have been incremented with InputPort::put into DynParaLoop::prepareInputsFromOutOfScope. So they can be released now.
617 catch(YACS::Exception& ex)
619 //ForEachLoop must be put in error and the exception rethrown to notify the caller
620 DEBTRACE( "ForEachLoop::exUpdateState: " << ex.what() );
621 setState(YACS::ERROR);
622 setErrorDetails(ex.what());
627 setState(YACS::ACTIVATED); // move the calling of setState method there for adding observers for clone nodes in GUI part
630 for(i=0;i<nbOfBr;i++)
633 _execInitNodes[i]->exUpdateState();
634 _initializingCounter++;
639 _execNodes[i]->exUpdateState();
642 forwardExecStateToOriginalBody(_execNodes[nbOfBr-1]);
646 void ForEachLoop::exUpdateProgress()
648 // emit notification to all observers registered with the dispatcher on any change of the node's state
649 sendEvent("progress");
652 void ForEachLoop::getReadyTasks(std::vector<Task *>& tasks)
656 if(_state==YACS::TOACTIVATE) setState(YACS::ACTIVATED);
657 if(_state==YACS::TOACTIVATE || _state==YACS::ACTIVATED)
659 if(_nodeForSpecialCases)
661 _nodeForSpecialCases->getReadyTasks(tasks);
664 vector<Node *>::iterator iter;
665 for (iter=_execNodes.begin() ; iter!=_execNodes.end() ; iter++)
666 (*iter)->getReadyTasks(tasks);
667 for (iter=_execInitNodes.begin() ; iter!=_execInitNodes.end() ; iter++)
668 (*iter)->getReadyTasks(tasks);
669 for (iter=_execFinalizeNodes.begin() ; iter!=_execFinalizeNodes.end() ; iter++)
670 (*iter)->getReadyTasks(tasks);
674 int ForEachLoop::getNumberOfInputPorts() const
676 return DynParaLoop::getNumberOfInputPorts()+1;
679 void ForEachLoop::checkNoCyclePassingThrough(Node *node) throw(YACS::Exception)
684 void ForEachLoop::selectRunnableTasks(std::vector<Task *>& tasks)
688 std::list<InputPort *> ForEachLoop::getSetOfInputPort() const
690 list<InputPort *> ret=DynParaLoop::getSetOfInputPort();
691 ret.push_back((InputPort *)&_splitterNode._dataPortToDispatch);
695 std::list<InputPort *> ForEachLoop::getLocalInputPorts() const
697 list<InputPort *> ret=DynParaLoop::getLocalInputPorts();
698 ret.push_back((InputPort *)&_splitterNode._dataPortToDispatch);
702 InputPort *ForEachLoop::getInputPort(const std::string& name) const throw(YACS::Exception)
704 if(name==SplitterNode::NAME_OF_SEQUENCE_INPUT)
705 return (InputPort *)&_splitterNode._dataPortToDispatch;
707 return DynParaLoop::getInputPort(name);
710 OutputPort *ForEachLoop::getOutputPort(const std::string& name) const throw(YACS::Exception)
712 for(vector<AnySplitOutputPort *>::const_iterator iter=_outGoingPorts.begin();iter!=_outGoingPorts.end();iter++)
714 if(name==(*iter)->getName())
715 return (OutputPort *)(*iter);
717 return DynParaLoop::getOutputPort(name);
720 OutPort *ForEachLoop::getOutPort(const std::string& name) const throw(YACS::Exception)
722 for(vector<AnySplitOutputPort *>::const_iterator iter=_outGoingPorts.begin();iter!=_outGoingPorts.end();iter++)
724 if(name==(*iter)->getName())
725 return (OutPort *)(*iter);
727 return DynParaLoop::getOutPort(name);
730 Node *ForEachLoop::getChildByShortName(const std::string& name) const throw(YACS::Exception)
732 if(name==NAME_OF_SPLITTERNODE)
733 return (Node *)&_splitterNode;
735 return DynParaLoop::getChildByShortName(name);
738 //! Method used to notify the node that a child node has finished
740 * Update the current state and return the change state
742 * \param node : the child node that has finished
743 * \return the state change
745 YACS::Event ForEachLoop::updateStateOnFinishedEventFrom(Node *node)
747 DEBTRACE("updateStateOnFinishedEventFrom " << node->getName() << " " << node->getState());
749 switch(getIdentityOfNotifyerNode(node,id))
752 return updateStateForInitNodeOnFinishedEventFrom(node,id);
754 return updateStateForWorkNodeOnFinishedEventFrom(node,id,true);
756 return updateStateForFinalizeNodeOnFinishedEventFrom(node,id);
760 return YACS::NOEVENT;
763 YACS::Event ForEachLoop::updateStateForInitNodeOnFinishedEventFrom(Node *node, unsigned int id)
765 _execNodes[id]->exUpdateState();
767 _initializingCounter--;
769 if (_initializingCounter == 0)
770 _initNode->setState(DONE);
771 return YACS::NOEVENT;
775 * \param [in] isNormalFinish - if true
777 YACS::Event ForEachLoop::updateStateForWorkNodeOnFinishedEventFrom(Node *node, unsigned int id, bool isNormalFinish)
783 int globalId(_execIds[id]);
785 globalId=_passedData->toAbsId(globalId);
786 sendEvent2("progress_ok",&globalId);
787 storeOutValsInSeqForOutOfScopeUse(globalId,id);
791 int globalId(_execIds[id]);
793 globalId=_passedData->toAbsId(globalId);
794 sendEvent2("progress_ko",&globalId);
797 if(_execCurrentId==getFinishedId())
798 {//No more elements of _dataPortToDispatch to treat
799 _execIds[id]=NOT_RUNNING_BRANCH_ID;
800 //analyzing if some samples are still on treatment on other branches.
801 bool isFinished(true);
802 for(int i=0;i<_execIds.size() && isFinished;i++)
803 isFinished=(_execIds[i]==NOT_RUNNING_BRANCH_ID);
808 if(_failedCounter!=0)
809 {// case of keepgoing mode + a failed
810 std::ostringstream oss; oss << "Keep Going mode activated and some errors (" << _failedCounter << ")reported !";
811 DEBTRACE("ForEachLoop::updateStateOnFinishedEventFrom : "<< oss.str());
812 setState(YACS::FAILED);
815 pushAllSequenceValues();
819 _node->setState(YACS::DONE);
821 ComposedNode* compNode = dynamic_cast<ComposedNode*>(_node);
824 std::list<Node *> aChldn = compNode->getAllRecursiveConstituents();
825 std::list<Node *>::iterator iter=aChldn.begin();
826 for(;iter!=aChldn.end();iter++)
827 (*iter)->setState(YACS::DONE);
831 if (_finalizeNode == NULL)
833 // No finalize node, we just finish the loop at the end of exec nodes execution
834 setState(YACS::DONE);
839 // Run the finalize nodes, the loop will be done only when they all finish
840 _unfinishedCounter = 0; // This counter indicates how many branches are not finished
841 for (int i=0 ; i<_execIds.size() ; i++)
843 YASSERT(_execIds[i] == NOT_RUNNING_BRANCH_ID);
844 DEBTRACE("Launching finalize node for branch " << i);
845 _execFinalizeNodes[i]->exUpdateState();
846 _unfinishedCounter++;
848 return YACS::NOEVENT;
851 catch(YACS::Exception& ex)
853 DEBTRACE("ForEachLoop::updateStateOnFinishedEventFrom: "<<ex.what());
854 //no way to push results : put following nodes in FAILED state
855 //TODO could be more fine grain : put only concerned nodes in FAILED state
857 setState(YACS::ERROR);
862 else if(_state == YACS::ACTIVATED)
863 {//more elements to do and loop still activated
864 _execIds[id]=_execCurrentId;
865 int posInAbs(_execCurrentId);
867 posInAbs=_passedData->toAbsId(_execCurrentId);
868 _splitterNode.putSplittedValueOnRankTo(posInAbs,id,false);
869 //forwardExecStateToOriginalBody(node);
872 node->exUpdateState();
873 //forwardExecStateToOriginalBody(node);
877 {//elements to process and loop no more activated
878 DEBTRACE("foreach loop state " << _state);
880 return YACS::NOEVENT;
883 YACS::Event ForEachLoop::updateStateForFinalizeNodeOnFinishedEventFrom(Node *node, unsigned int id)
885 DEBTRACE("Finalize node finished on branch " << id);
886 _unfinishedCounter--;
889 DEBTRACE(_unfinishedCounter << " finalize nodes still running");
890 if (_unfinishedCounter == 0)
892 _finalizeNode->setState(YACS::DONE);
893 setState(YACS::DONE);
897 return YACS::NOEVENT;
900 YACS::Event ForEachLoop::updateStateOnFailedEventFrom(Node *node, const Executor *execInst)
903 DynParaLoop::TypeOfNode ton(getIdentityOfNotifyerNode(node,id));
904 // TODO: deal with keepgoing without the dependency to Executor
905 if(ton!=WORK_NODE || !execInst->getKeepGoingProperty())
906 return DynParaLoop::updateStateOnFailedEventFrom(node,execInst);
910 return updateStateForWorkNodeOnFinishedEventFrom(node,id,false);
914 void ForEachLoop::InterceptorizeNameOfPort(std::string& portName)
916 std::replace_if(portName.begin(), portName.end(), std::bind1st(std::equal_to<char>(), '.'), '_');
917 portName += INTERCEPTOR_STR;
920 void ForEachLoop::buildDelegateOf(std::pair<OutPort *, OutPort *>& port, InPort *finalTarget, const std::list<ComposedNode *>& pointsOfView)
922 DynParaLoop::buildDelegateOf(port,finalTarget,pointsOfView);
923 string typeOfPortInstance=(port.first)->getNameOfTypeOfCurrentInstance();
924 if(typeOfPortInstance==OutputPort::NAME)
926 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
928 for(;iter!=_outGoingPorts.end();iter++,i++)
929 if((*iter)->getRepr()==port.first || *iter==port.first)
931 if(iter!=_outGoingPorts.end())
933 if(*iter!=port.first)
936 (*iter)->addRepr(port.first,_intecptrsForOutGoingPorts[i]);
942 TypeCode *tcTrad((YACS::ENGINE::TypeCode*)finalTarget->edGetType()->subContentType(getFEDeltaBetween(port.first,finalTarget)));
943 TypeCodeSeq *newTc=(TypeCodeSeq *)TypeCode::sequenceTc("","",tcTrad);
944 // The out going ports belong to the ForEachLoop, whereas
945 // the delegated port belongs to a node child of the ForEachLoop.
946 // The name of the delegated port contains dots (bloc.node.outport),
947 // whereas the name of the out going port shouldn't do.
948 std::string outputPortName(getPortName(port.first));
949 InterceptorizeNameOfPort(outputPortName);
950 AnySplitOutputPort *newPort(new AnySplitOutputPort(outputPortName,this,newTc));
951 InterceptorInputPort *intercptor(new InterceptorInputPort(outputPortName + "_in",this,tcTrad));
952 intercptor->setRepr(newPort);
954 newPort->addRepr(port.first,intercptor);
955 _outGoingPorts.push_back(newPort);
956 _intecptrsForOutGoingPorts.push_back(intercptor);
961 throw Exception("ForEachLoop::buildDelegateOf : not implemented for DS because not specified");
964 void ForEachLoop::getDelegateOf(std::pair<OutPort *, OutPort *>& port, InPort *finalTarget, const std::list<ComposedNode *>& pointsOfView) throw(YACS::Exception)
966 string typeOfPortInstance=(port.first)->getNameOfTypeOfCurrentInstance();
967 if(typeOfPortInstance==OutputPort::NAME)
969 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
970 for(;iter!=_outGoingPorts.end();iter++)
971 if((*iter)->getRepr()==port.first)
973 if(iter==_outGoingPorts.end())
975 string what("ForEachLoop::getDelegateOf : Port with name "); what+=port.first->getName(); what+=" not exported by ForEachLoop "; what+=_name;
976 throw Exception(what);
982 throw Exception("ForEachLoop::getDelegateOf : not implemented because not specified");
985 void ForEachLoop::releaseDelegateOf(OutPort *portDwn, OutPort *portUp, InPort *finalTarget, const std::list<ComposedNode *>& pointsOfView) throw(YACS::Exception)
987 string typeOfPortInstance=portDwn->getNameOfTypeOfCurrentInstance();
988 if(typeOfPortInstance==OutputPort::NAME)
990 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
991 vector<InterceptorInputPort *>::iterator iter2=_intecptrsForOutGoingPorts.begin();
992 for(;iter!=_outGoingPorts.end();iter++,iter2++)
993 if((*iter)->getRepr()==portDwn)
995 //ASSERT(portUp==*iter.second)
996 if((*iter)->decrRef())
998 AnySplitOutputPort *p=*iter;
999 _outGoingPorts.erase(iter);
1001 InterceptorInputPort *ip=*iter2;
1002 _intecptrsForOutGoingPorts.erase(iter2);
1008 OutPort *ForEachLoop::getDynOutPortByAbsName(int branchNb, const std::string& name)
1010 string portName, nodeName;
1011 splitNamesBySep(name,Node::SEP_CHAR_IN_PORT,nodeName,portName,false);
1012 Node *staticChild = getChildByName(nodeName);
1013 return _execNodes[branchNb]->getOutPort(portName);//It's impossible(garanteed by YACS::ENGINE::ForEachLoop::buildDelegateOf)
1014 //that a link starting from _initNode goes out of scope of 'this'.
1017 void ForEachLoop::cleanDynGraph()
1019 DynParaLoop::cleanDynGraph();
1020 for(vector< SequenceAny *>::iterator iter3=_execVals.begin();iter3!=_execVals.end();iter3++)
1021 (*iter3)->decrRef();
1023 for(vector< vector<AnyInputPort *> >::iterator iter4=_execOutGoingPorts.begin();iter4!=_execOutGoingPorts.end();iter4++)
1024 for(vector<AnyInputPort *>::iterator iter5=(*iter4).begin();iter5!=(*iter4).end();iter5++)
1026 _execOutGoingPorts.clear();
1029 void ForEachLoop::storeOutValsInSeqForOutOfScopeUse(int rank, int branchNb)
1031 vector<AnyInputPort *>::iterator iter;
1033 for(iter=_execOutGoingPorts[branchNb].begin();iter!=_execOutGoingPorts[branchNb].end();iter++,i++)
1035 Any *val=(Any *)(*iter)->getValue();
1036 _execVals[i]->setEltAtRank(rank,val);
1040 int ForEachLoop::getFinishedId()
1043 return _splitterNode.getNumberOfElements();
1045 return _passedData->getNumberOfElementsToDo();
1048 void ForEachLoop::prepareSequenceValues(int sizeOfSamples)
1050 _execVals.resize(_outGoingPorts.size());
1051 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
1052 for(int i=0;iter!=_outGoingPorts.end();iter++,i++)
1053 _execVals[i]=SequenceAny::New((*iter)->edGetType()->contentType(),sizeOfSamples);
1056 void ForEachLoop::pushAllSequenceValues()
1058 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
1060 for(;iter!=_outGoingPorts.end();iter++,i++)
1061 (*iter)->put((const void *)_execVals[i]);
1064 void ForEachLoop::createOutputOutOfScopeInterceptors(int branchNb)
1066 vector<AnySplitOutputPort *>::iterator iter=_outGoingPorts.begin();
1068 for(;iter!=_outGoingPorts.end();iter++,i++)
1070 DEBTRACE( (*iter)->getName() << " " << (*iter)->edGetType()->kind() );
1071 //AnyInputPort *interceptor=new AnyInputPort((*iter)->getName(),this,(*iter)->edGetType());
1072 OutPort *portOut=getDynOutPortByAbsName(branchNb,getOutPortName(((*iter)->getRepr())));
1073 DEBTRACE( portOut->getName() );
1074 TypeCode *tc((TypeCode *)(*iter)->edGetType()->contentType());
1075 AnyInputPort *interceptor=new AnyInputPort((*iter)->getName(),this,tc);
1076 portOut->addInPort(interceptor);
1077 _execOutGoingPorts[branchNb].push_back(interceptor);
1081 void ForEachLoop::checkLinkPossibility(OutPort *start, const std::list<ComposedNode *>& pointsOfViewStart,
1082 InPort *end, const std::list<ComposedNode *>& pointsOfViewEnd) throw(YACS::Exception)
1084 DynParaLoop::checkLinkPossibility(start, pointsOfViewStart, end, pointsOfViewEnd);
1085 if(end->getNode() == &_splitterNode)
1086 throw Exception("Illegal link within a foreach loop: \
1087 the 'SmplsCollection' port cannot be linked within the scope of the loop.");
1088 if(end == _nbOfBranches->getPort())
1089 throw Exception("Illegal link within a foreach loop: \
1090 the 'nbBranches' port cannot be linked within the scope of the loop.");
1093 std::list<OutputPort *> ForEachLoop::getLocalOutputPorts() const
1095 list<OutputPort *> ret;
1096 ret.push_back(getOutputPort(NAME_OF_SPLITTED_SEQ_OUT));
1100 void ForEachLoop::accept(Visitor *visitor)
1102 visitor->visitForEachLoop(this);
1105 //! Dump the node state to a stream
1107 * \param os : the output stream
1109 void ForEachLoop::writeDot(std::ostream &os) const
1111 os << " subgraph cluster_" << getId() << " {\n" ;
1112 //only one node in a loop
1115 _node->writeDot(os);
1116 os << getId() << " -> " << _node->getId() << ";\n";
1119 os << getId() << "[fillcolor=\"" ;
1120 YACS::StatesForNode state=getEffectiveState();
1121 os << getColorState(state);
1122 os << "\" label=\"" << "Loop:" ;
1123 os << getName() <<"\"];\n";
1126 //! Reset the state of the node and its children depending on the parameter level
1127 void ForEachLoop::resetState(int level)
1130 DynParaLoop::resetState(level);
1135 std::string ForEachLoop::getProgress() const
1137 int nbElems(getNbOfElementsToBeProcessed());
1138 std::stringstream aProgress;
1140 aProgress << _currentIndex << "/" << nbElems;
1143 return aProgress.str();
1146 //! Get the progress weight for all elementary nodes
1148 * Only elementary nodes have weight. For each node in the loop, the weight done is multiplied
1149 * by the number of elements done and the weight total by the number total of elements
1151 list<ProgressWeight> ForEachLoop::getProgressWeight() const
1153 list<ProgressWeight> ret;
1154 list<Node *> setOfNode=edGetDirectDescendants();
1155 int elemDone=getCurrentIndex();
1156 int elemTotal=getNbOfElementsToBeProcessed();
1157 for(list<Node *>::const_iterator iter=setOfNode.begin();iter!=setOfNode.end();iter++)
1159 list<ProgressWeight> myCurrentSet=(*iter)->getProgressWeight();
1160 for(list<ProgressWeight>::iterator iter=myCurrentSet.begin();iter!=myCurrentSet.end();iter++)
1162 (*iter).weightDone=((*iter).weightTotal) * elemDone;
1163 (*iter).weightTotal*=elemTotal;
1165 ret.insert(ret.end(),myCurrentSet.begin(),myCurrentSet.end());
1170 int ForEachLoop::getNbOfElementsToBeProcessed() const
1172 int nbOfElems(_splitterNode.getNumberOfElements());
1173 int nbBranches = _nbOfBranches->getNumberOfBranches(nbOfElems);
1175 + (_initNode ? nbBranches:0)
1176 + (_finalizeNode ? nbBranches:0) ;
1180 * 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.
1181 * 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.
1182 * This method has one input \a execut and 3 outputs.
1184 * \param [in] execut - The single input is for threadsafety reasons because this method can be called safely during the execution of \a this.
1185 * \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.
1186 * All of the items in \a outputs have the same size.
1187 * \param [out] nameOfOutputs - The array with same size than \a outputs, that tells for each item in outputs the output port it refers to.
1188 * \return the list of ids among \c this->edGetSeqOfSamplesPort() that run successfully. The length of this returned array will be the length of all
1189 * SequenceAny objects contained in \a outputs.
1191 * \sa edGetSeqOfSamplesPort
1193 std::vector<unsigned int> ForEachLoop::getPassedResults(Executor *execut, std::vector<SequenceAny *>& outputs, std::vector<std::string>& nameOfOutputs) const
1195 YACS::BASES::AutoLocker<YACS::BASES::Mutex> alck(&(execut->getTheMutexForSchedulerUpdate()));
1196 if(_execVals.empty())
1197 return std::vector<unsigned int>();
1198 if(_execOutGoingPorts.empty())
1199 return std::vector<unsigned int>();
1200 std::size_t sz(_execVals.size());
1202 nameOfOutputs.resize(sz);
1203 const std::vector<AnyInputPort *>& ports(_execOutGoingPorts[0]);
1204 for(std::size_t i=0;i<sz;i++)
1206 outputs[i]=_execVals[i]->removeUnsetItemsFromThis();
1207 nameOfOutputs[i]=ports[i]->getName();
1209 return _execVals[0]->getSetItems();
1213 * 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
1214 * getPassedResults method.
1216 void ForEachLoop::assignPassedResults(const std::vector<unsigned int>& passedIds, const std::vector<SequenceAny *>& passedOutputs, const std::vector<std::string>& nameOfOutputs)
1220 _passedData=new ForEachLoopPassedData(passedIds,passedOutputs,nameOfOutputs);
1223 int ForEachLoop::getFEDeltaBetween(OutPort *start, InPort *end)
1225 Node *ns(start->getNode()),*ne(end->getNode());
1226 ComposedNode *co(getLowestCommonAncestor(ns,ne));
1231 ForEachLoop *isFE(dynamic_cast<ForEachLoop *>(work));
1234 work=work->getFather();
1236 if(dynamic_cast<AnySplitOutputPort *>(start))
1242 * This method is used to obtain the values already processed by the ForEachLoop.
1243 * A new ForEachLoopPassedData object is returned. You have to delete it.
1245 ForEachLoopPassedData* ForEachLoop::getProcessedData()const
1247 std::vector<SequenceAny *> outputs;
1248 std::vector<std::string> nameOfOutputs;
1249 if(_execVals.empty() || _execOutGoingPorts.empty())
1250 return new ForEachLoopPassedData(std::vector<unsigned int>(), outputs, nameOfOutputs);
1251 std::size_t sz(_execVals.size());
1253 nameOfOutputs.resize(sz);
1254 const std::vector<AnyInputPort *>& ports(_execOutGoingPorts[0]);
1255 for(std::size_t i=0;i<sz;i++)
1257 outputs[i]=_execVals[i]->removeUnsetItemsFromThis();
1258 nameOfOutputs[i]=ports[i]->getName();
1260 return new ForEachLoopPassedData(_execVals[0]->getSetItems(), outputs, nameOfOutputs);
1263 void ForEachLoop::setProcessedData(ForEachLoopPassedData* processedData)
1267 _passedData = processedData;
1271 * \param portName : "interceptorized" name of port.
1273 const YACS::ENGINE::TypeCode* ForEachLoop::getOutputPortType(const std::string& portName)const
1275 const YACS::ENGINE::TypeCode* ret=NULL;
1276 vector<AnySplitOutputPort *>::const_iterator it;
1277 for(it=_outGoingPorts.begin();it!=_outGoingPorts.end() && ret==NULL;it++)
1279 std::string originalPortName(getPortName(*it));
1280 //InterceptorizeNameOfPort(originalPortName);
1281 DEBTRACE("ForEachLoop::getOutputPortType compare " << portName << " == " << originalPortName);
1282 if(originalPortName == portName)
1284 ret = (*it)->edGetType()->contentType();