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 "OptimizerLoop.hxx"
21 #include "OutputPort.hxx"
22 #include "Visitor.hxx"
27 #include "YacsTrace.hxx"
29 using namespace YACS::ENGINE;
32 const char FakeNodeForOptimizerLoop::NAME[]="thisIsAFakeNode";
34 const int OptimizerLoop::NOT_RUNNING_BRANCH_ID=-1973012217;
35 const int OptimizerLoop::NOT_INITIALIZED_BRANCH_ID=-1973;
37 const char OptimizerLoop::NAME_OF_ALGO_INIT_PORT[] = "algoInit";
38 const char OptimizerLoop::NAME_OF_OUT_POOL_INPUT[] = "evalResults";
39 const char OptimizerLoop::NAME_OF_ALGO_RESULT_PORT[] = "algoResults";
42 FakeNodeForOptimizerLoop::FakeNodeForOptimizerLoop(OptimizerLoop *loop, bool normal, std::string message)
43 : ElementaryNode(NAME), _loop(loop), _normal(normal), _message(message)
45 _state=YACS::TOACTIVATE;
46 _father=_loop->getFather();
49 FakeNodeForOptimizerLoop::FakeNodeForOptimizerLoop(const FakeNodeForOptimizerLoop& other)
50 : ElementaryNode(other), _loop(0), _normal(other._normal), _message(other._message)
54 Node *FakeNodeForOptimizerLoop::simpleClone(ComposedNode *father, bool editionOnly) const
56 return new FakeNodeForOptimizerLoop(*this);
59 void FakeNodeForOptimizerLoop::exForwardFailed()
61 _loop->exForwardFailed();
64 void FakeNodeForOptimizerLoop::exForwardFinished()
66 _loop->exForwardFinished();
69 void FakeNodeForOptimizerLoop::execute()
71 DEBTRACE("FakeNodeForOptimizerLoop::execute: " << _message)
73 _loop->_errorDetails = _message;
74 throw Exception(_message);
78 _loop->_algoResultPort.put(_loop->_alg->getAlgoResultProxy());
82 void FakeNodeForOptimizerLoop::aborted()
84 _loop->setState(YACS::ERROR);
87 void FakeNodeForOptimizerLoop::finished()
89 _loop->setState(YACS::DONE);
92 /*! \class YACS::ENGINE::OptimizerLoop
93 * \brief class to build optimization loops
95 * \ingroup ComposedNodes
98 OptimizerLoop::OptimizerLoop(const std::string& name, const std::string& algLibWthOutExt,
99 const std::string& symbolNameToOptimizerAlgBaseInstanceFactory,
100 bool algInitOnFile,bool initAlgo, Proc * procForTypes):
101 DynParaLoop(name,Runtime::_tc_string),_algInitOnFile(algInitOnFile),_alglib(algLibWthOutExt),
102 _algoInitPort(NAME_OF_ALGO_INIT_PORT, this, Runtime::_tc_string, true),
103 _loader(NULL),_alg(0),_convergenceReachedWithOtherCalc(false),
104 _retPortForOutPool(NAME_OF_OUT_POOL_INPUT,this,Runtime::_tc_string),
105 _nodeForSpecialCases(0), _algoResultPort(NAME_OF_ALGO_RESULT_PORT, this, Runtime::_tc_string)
107 //We need this because calling a virtual method in a constructor does not call the most derived method but the method of the class
108 //A derived class must take care to manage that
110 setAlgorithm(algLibWthOutExt,symbolNameToOptimizerAlgBaseInstanceFactory, procForTypes);
113 OptimizerLoop::OptimizerLoop(const OptimizerLoop& other, ComposedNode *father, bool editionOnly):
114 DynParaLoop(other,father,editionOnly),_algInitOnFile(other._algInitOnFile),_alglib(other._alglib),
115 _convergenceReachedWithOtherCalc(false),_loader(NULL),_alg(0),_algoInitPort(other._algoInitPort,this),
116 _retPortForOutPool(other._retPortForOutPool,this),_nodeForSpecialCases(0),
117 _algoResultPort(other._algoResultPort, this)
119 //Don't call setAlgorithm here because it will be called several times if the class is derived. Call it in simpleClone for cloning
121 // Create the links to evalResults port
122 set<OutPort *> fromPortsToReproduce=other._retPortForOutPool.edSetOutPort();
123 for(set<OutPort *>::iterator iter=fromPortsToReproduce.begin();iter!=fromPortsToReproduce.end();iter++)
124 edAddLink(getOutPort(other.getPortName(*iter)),&_retPortForOutPool);
127 OptimizerLoop::~OptimizerLoop()
134 delete _nodeForSpecialCases;
137 Node *OptimizerLoop::simpleClone(ComposedNode *father, bool editionOnly) const
139 OptimizerLoop* ol=new OptimizerLoop(*this,father,editionOnly);
140 // TODO: Remove this const_cast (find a better design to get the type codes from the original node)
141 Proc * procForTypes = ol->getProc();
142 if (procForTypes == NULL) {
143 const Proc * origProc = getProc();
144 procForTypes = const_cast<Proc *>(origProc);
146 ol->setAlgorithm(_alglib, _symbol, false, procForTypes);
150 void OptimizerLoop::init(bool start)
152 DynParaLoop::init(start);
153 _algoInitPort.exInit(start);
154 _retPortForOutPool.exInit(start);
155 _algoResultPort.exInit();
156 _convergenceReachedWithOtherCalc=false;
161 void OptimizerLoop::exUpdateState()
163 if(_state == YACS::DISABLED)
165 delete _nodeForSpecialCases;
166 _nodeForSpecialCases = NULL;
169 if(_inGate.exIsReady())
171 setState(YACS::TOACTIVATE);
172 // Force termination in case the previous algorithm did not finish properly (manual stop)
174 _myPool.destroyAll();
176 // Initialize and launch the algorithm
177 _alg->initializeProxy(_algoInitPort.getValue());
178 if (_alg->hasError()) {
179 string error = _alg->getError();
181 throw Exception(error);
184 //internal graph update
186 int nbOfBr=_nbOfBranches.getIntValue();
187 _alg->setNbOfBranches(nbOfBr);
190 if (_alg->hasError()) {
191 string error = _alg->getError();
193 throw Exception(error);
198 // A number of branches of 0 is acceptable if there are no output ports
199 // leaving OptimizerLoop
200 bool normal = getAllOutPortsLeavingCurrentScope().empty();
201 _nodeForSpecialCases = new FakeNodeForOptimizerLoop(this, normal,
202 "OptimizerLoop has no branch to run the internal node(s)");
205 _execNodes.resize(nbOfBr);
206 _execIds.resize(nbOfBr);
209 _execInitNodes.resize(nbOfBr);
210 _initNodeUpdated.resize(nbOfBr);
211 for(i=0;i<nbOfBr;i++)
212 _initNodeUpdated[i]=false;
214 _initializingCounter = 0;
216 _execFinalizeNodes.resize(nbOfBr);
217 vector<Node *> origNodes;
218 origNodes.push_back(_initNode);
219 origNodes.push_back(_node);
220 origNodes.push_back(_finalizeNode);
221 for(i=0;i<nbOfBr;i++)
223 _execIds[i]=NOT_INITIALIZED_BRANCH_ID;
224 vector<Node *> clonedNodes = cloneAndPlaceNodesCoherently(origNodes);
226 _execInitNodes[i] = clonedNodes[0];
227 _execNodes[i] = clonedNodes[1];
229 _execFinalizeNodes[i] = clonedNodes[2];
230 prepareInputsFromOutOfScope(i);
232 initInterceptors(nbOfBr);
234 unsigned char priority;
235 Any *val=_myPool.getNextSampleWithHighestPriority(id,priority);
238 // It is acceptable to have no sample to launch if there are no output ports
239 // leaving OptimizerLoop
240 std::set<OutPort *> setOutPort = getAllOutPortsLeavingCurrentScope();
241 // Special in the special
242 // We do not check algoResult
243 setOutPort.erase(&_algoResultPort);
244 bool normal = setOutPort.empty();
245 _nodeForSpecialCases = new FakeNodeForOptimizerLoop(this, normal,
246 string("The algorithm of OptimizerLoop with name ") + _name +
247 " returns no sample to launch");
251 launchMaxOfSamples(true);
254 catch (const exception & e)
256 _nodeForSpecialCases = new FakeNodeForOptimizerLoop(this, false,
257 string("An error happened in the control algorithm of OptimizerLoop \"") + _name +
262 int OptimizerLoop::getNumberOfInputPorts() const
264 return DynParaLoop::getNumberOfInputPorts()+2;
267 InputPort *OptimizerLoop::getInputPort(const std::string& name) const throw(YACS::Exception)
269 if (name == NAME_OF_ALGO_INIT_PORT)
270 return (InputPort *)&_algoInitPort;
271 else if (name == NAME_OF_OUT_POOL_INPUT)
272 return (InputPort *)&_retPortForOutPool;
274 return DynParaLoop::getInputPort(name);
277 std::list<InputPort *> OptimizerLoop::getSetOfInputPort() const
279 list<InputPort *> ret=DynParaLoop::getSetOfInputPort();
280 ret.push_back((InputPort *)&_algoInitPort);
281 ret.push_back((InputPort *)&_retPortForOutPool);
285 std::list<InputPort *> OptimizerLoop::getLocalInputPorts() const
287 list<InputPort *> ret=DynParaLoop::getLocalInputPorts();
288 ret.push_back((InputPort *)&_algoInitPort);
289 ret.push_back((InputPort *)&_retPortForOutPool);
293 void OptimizerLoop::selectRunnableTasks(std::vector<Task *>& tasks)
297 void OptimizerLoop::getReadyTasks(std::vector<Task *>& tasks)
301 if(_state==YACS::TOACTIVATE || _state==YACS::ACTIVATED)
303 if(_nodeForSpecialCases)
305 _nodeForSpecialCases->getReadyTasks(tasks);
308 vector<Node *>::iterator iter;
309 for (iter=_execNodes.begin() ; iter!=_execNodes.end() ; iter++)
310 (*iter)->getReadyTasks(tasks);
311 for (iter=_execInitNodes.begin() ; iter!=_execInitNodes.end() ; iter++)
312 (*iter)->getReadyTasks(tasks);
313 for (iter=_execFinalizeNodes.begin() ; iter!=_execFinalizeNodes.end() ; iter++)
314 (*iter)->getReadyTasks(tasks);
318 YACS::Event OptimizerLoop::updateStateOnFinishedEventFrom(Node *node)
320 if (getState() == YACS::FAILED)
322 // This happens when a valid computation on a branch finishes after an error on another branch.
323 // In this case we just ignore the new result because the algorithm has already been terminated.
324 return YACS::NOEVENT;
327 switch(getIdentityOfNotifyerNode(node,id))
331 _execNodes[id]->exUpdateState();
333 _initializingCounter--;
334 if (_initializingCounter == 0) _initNode->setState(DONE);
339 if(_convergenceReachedWithOtherCalc)
340 { //This case happens when alg has reached its convergence whereas other calculations still compute
341 _execIds[id]=NOT_RUNNING_BRANCH_ID;
343 return YACS::NOEVENT;
347 _myPool.putOutSampleAt(_execIds[id],_interceptorsForOutPool[id]->getValue());
348 _myPool.setCurrentId(_execIds[id]);
349 _alg->takeDecisionProxy();
350 if (_alg->hasError()) {
351 _errorDetails = string("An error happened in the control algorithm of optimizer loop: ") +
354 setState(YACS::FAILED);
358 _myPool.destroyCurrentCase();
361 pushValueOutOfScopeForCase(id);
362 _execIds[id]=NOT_RUNNING_BRANCH_ID;
364 {// This case happens when the hand is returned to continue, whereas some other are working in parallel for nothing.
365 _convergenceReachedWithOtherCalc=true;
366 return YACS::NOEVENT;
370 _execIds[id]=NOT_RUNNING_BRANCH_ID;
372 unsigned char priority;
373 Any *val=_myPool.getNextSampleWithHighestPriority(newId, priority);
376 bool isFinished=true;
377 for(int i=0;i<_execIds.size() && isFinished;i++)
378 isFinished=(_execIds[i]==NOT_RUNNING_BRANCH_ID || _execIds[i]==NOT_INITIALIZED_BRANCH_ID);
381 std::cerr <<"OptimizerLoop::updateStateOnFinishedEventFrom: Alg has not inserted more cases whereas last element has been calculated !" << std::endl;
382 setState(YACS::ERROR);
387 return YACS::NOEVENT;
389 launchMaxOfSamples(false);
394 _unfinishedCounter--;
395 if (_unfinishedCounter == 0)
397 _finalizeNode->setState(YACS::DONE);
398 setState(YACS::DONE);
402 return YACS::NOEVENT;
408 return YACS::NOEVENT;
411 YACS::Event OptimizerLoop::finalize()
413 //update internal node (definition node) state
416 _node->setState(YACS::DONE);
417 ComposedNode* compNode = dynamic_cast<ComposedNode*>(_node);
420 std::list<Node *> aChldn = compNode->getAllRecursiveConstituents();
421 std::list<Node *>::iterator iter=aChldn.begin();
422 for(;iter!=aChldn.end();iter++)
423 (*iter)->setState(YACS::DONE);
426 _algoResultPort.put(_alg->getAlgoResultProxy());
428 if (_finalizeNode == NULL)
430 // No finalize node, we just finish OptimizerLoop at the end of exec nodes execution
431 setState(YACS::DONE);
436 // Run the finalize nodes, the OptimizerLoop will be done only when they all finish
437 _unfinishedCounter = 0; // This counter indicates how many branches are not finished
438 for (int i=0 ; i<_nbOfBranches.getIntValue() ; i++)
439 if (_execIds[i] == NOT_RUNNING_BRANCH_ID)
441 DEBTRACE("Launching finalize node for branch " << i)
442 _execFinalizeNodes[i]->exUpdateState();
443 _unfinishedCounter++;
446 // There should not be any running branch at this point
447 YASSERT(_execIds[i] == NOT_INITIALIZED_BRANCH_ID)
448 return YACS::NOEVENT;
452 //! Method used to notify the node that a child node has failed
454 * Notify the slave thread of the error, update the current state and
455 * return the change state
457 * \param node : the child node that has failed
458 * \return the state change
460 YACS::Event OptimizerLoop::updateStateOnFailedEventFrom(Node *node, const Executor *execInst)
462 DEBTRACE("OptimizerLoop::updateStateOnFailedEventFrom " << node->getName());
463 _alg->setError(string("Error during the execution of YACS node ") + node->getName() +
464 ": " + node->getErrorReport());
466 _myPool.destroyAll();
467 DEBTRACE("OptimizerLoop::updateStateOnFailedEventFrom: returned from error notification.");
468 return DynParaLoop::updateStateOnFailedEventFrom(node,execInst);
471 void OptimizerLoop::checkNoCyclePassingThrough(Node *node) throw(YACS::Exception)
475 void OptimizerLoop::buildDelegateOf(InPort * & port, OutPort *initialStart, const std::list<ComposedNode *>& pointsOfView)
477 DynParaLoop::buildDelegateOf(port,initialStart,pointsOfView);
478 if(port==&_retPortForOutPool)
480 std::string linkName("(");
481 linkName += initialStart->getName()+" to "+port->getName()+")";
482 throw Exception(std::string("Illegal OptimizerLoop link: \
483 The 'evalResults' port must be linked within the scope of the loop.")
488 void OptimizerLoop::buildDelegateOf(std::pair<OutPort *, OutPort *>& port, InPort *finalTarget, const std::list<ComposedNode *>& pointsOfView)
490 DynParaLoop::buildDelegateOf(port,finalTarget,pointsOfView);
491 if(port.first != &_algoResultPort)
493 std::string linkName("(");
494 linkName += port.first->getName()+" to "+finalTarget->getName()+")";
495 throw Exception(std::string("Illegal OptimizerLoop link: \
496 Only the algorithm result port can be linked to a port outside the scope of the loop.")
500 string typeOfPortInstance=(port.first)->getNameOfTypeOfCurrentInstance();
501 if(typeOfPortInstance!=OutputPort::NAME)
502 throw Exception("OptimizerLoop::buildDelegateOf : not implemented for DS because not specified ");
505 void OptimizerLoop::checkControlDependancy(OutPort *start, InPort *end, bool cross,
506 std::map < ComposedNode *, std::list < OutPort * >, SortHierarc >& fw,
507 std::vector<OutPort *>& fwCross,
508 std::map< ComposedNode *, std::list < OutPort *>, SortHierarc >& bw,
509 LinkInfo& info) const
511 if(end==&_retPortForOutPool)
512 fw[(ComposedNode *)this].push_back(start);
514 DynParaLoop::checkControlDependancy(start,end,cross,fw,fwCross,bw,info);
517 void OptimizerLoop::checkCFLinks(const std::list<OutPort *>& starts, InputPort *end, unsigned char& alreadyFed, bool direction, LinkInfo& info) const
519 if(end==&_retPortForOutPool)
520 solveObviousOrDelegateCFLinks(starts,end,alreadyFed,direction,info);
522 DynParaLoop::checkCFLinks(starts,end,alreadyFed,direction,info);
525 void OptimizerLoop::checkLinkPossibility(OutPort *start, const std::list<ComposedNode *>& pointsOfViewStart,
526 InPort *end, const std::list<ComposedNode *>& pointsOfViewEnd) throw(YACS::Exception)
528 DynParaLoop::checkLinkPossibility(start, pointsOfViewStart, end, pointsOfViewEnd);
529 std::string linkName("(");
530 linkName += start->getName()+" to "+end->getName()+")";
532 // Yes, it should be possible to link back the result port to any input port of the loop.
533 if(end == &_nbOfBranches || end == &_algoInitPort)
534 if(start != &_algoResultPort)
535 throw Exception(std::string("Illegal OptimizerLoop link.") + linkName);
539 if(start == &_algoResultPort)
540 throw Exception(std::string("Illegal OptimizerLoop link: \
541 The 'algoResult' port can't be linked within the scope of the loop.") + linkName);
543 if(end == &_retPortForOutPool && isInMyDescendance(start->getNode())!=_node)
544 throw Exception(std::string("Illegal OptimizerLoop link: \
545 The 'evalResults' port can only be linked to the working node.") + linkName);
548 void OptimizerLoop::cleanInterceptors()
550 // At this point all garanties taken let's clean all.
551 map<InputPort *,vector<InputPort *> >::iterator iter=_interceptors.begin();
552 for(;iter!=_interceptors.end();iter++)
553 for(vector<InputPort *>::iterator iter2=(*iter).second.begin();iter2!=(*iter).second.end();iter2++)
555 _interceptors.clear();
556 for(vector<AnyInputPort *>::iterator iter3=_interceptorsForOutPool.begin();iter3!=_interceptorsForOutPool.end();iter3++)
558 _interceptorsForOutPool.clear();
561 void OptimizerLoop::launchMaxOfSamples(bool first)
564 unsigned char priority;
567 for (val = _myPool.getNextSampleWithHighestPriority(id, priority);
568 !isFullyBusy(i) && val;
569 val = _myPool.getNextSampleWithHighestPriority(id, priority))
571 if(_execIds[i] == NOT_INITIALIZED_BRANCH_ID)
572 first=true; // node is not initialized (first pass)
574 first=false; // node is initialized (second pass)
576 _myPool.markIdAsInUse(id);
577 if(_initNode && !_initNodeUpdated[i])
579 putValueOnBranch(val,i,first);
580 _execInitNodes[i]->exUpdateState();
581 _initNodeUpdated[i]=true;
582 _initializingCounter++;
587 _execNodes[i]->init(first);
588 putValueOnBranch(val,i,first);
589 _execNodes[i]->exUpdateState();
595 bool OptimizerLoop::isFullyLazy() const
598 for(unsigned i=0;i<_execIds.size() && isLazy;i++)
599 isLazy=(_execIds[i]==NOT_RUNNING_BRANCH_ID || _execIds[i]==NOT_INITIALIZED_BRANCH_ID);
604 * Returns if a dynamic branch is available.
605 * \param branchId Out param. Only usable if returned value is equal to \b false.
607 bool OptimizerLoop::isFullyBusy(unsigned& branchId) const
609 bool isFinished=true;
611 for(i=0;i<_execIds.size() && isFinished;i++)
612 isFinished=(_execIds[i]!=NOT_RUNNING_BRANCH_ID && _execIds[i]!=NOT_INITIALIZED_BRANCH_ID);
619 * Perform initialization of interceptors. \b WARNING _execNodes have to be created before.
621 void OptimizerLoop::initInterceptors(unsigned nbOfBr)
623 //For all classical outputports leaving 'this'
624 set<OutPort *> portsToIntercept=getAllOutPortsLeavingCurrentScope();
625 portsToIntercept.erase(&_algoResultPort);
626 for(set<OutPort *>::iterator iter=portsToIntercept.begin();iter!=portsToIntercept.end();iter++)
628 OutputPort *portC=(OutputPort *)(*iter);//Warrantied by OptimizerLoop::buildDelegateOf
629 const set<InputPort *>& links=portC->getSetOfPhyLinks();
630 for(set<InputPort *>::const_iterator iter2=links.begin();iter2!=links.end();iter2++)
633 InputPort *reprCur=dynamic_cast<InputPort *>((*iter2)->getPublicRepresentant());
635 InputPort *reprCur=(*iter2)->getPublicRepresentant();
637 if(!isInMyDescendance(reprCur->getNode()))
638 {//here we've got an out of scope link : Let's intercept it
639 if(_interceptors.find(reprCur)==_interceptors.end())
641 _interceptors[reprCur].resize(nbOfBr);
642 for(unsigned i=0;i<nbOfBr;i++)
644 OutputPort *portExecC=(OutputPort *)_execNodes[i]->getOutputPort(_node->getOutPortName(portC));
645 InputPort *clone=reprCur->clone(0);
646 _interceptors[reprCur][i]=clone;
647 portExecC->edAddInputPort(clone);
652 for(unsigned i=0;i<nbOfBr;i++)
654 OutputPort *portExecC=(OutputPort *)_execNodes[i]->getOutputPort(_node->getOutPortName(portC));
655 portExecC->edAddInputPort(_interceptors[reprCur][i]);
662 _interceptorsForOutPool.resize(nbOfBr);
663 set< OutPort * > links=_retPortForOutPool.edSetOutPort();
664 for(unsigned i=0;i<nbOfBr;i++)
665 _interceptorsForOutPool[i]=(AnyInputPort *)_retPortForOutPool.clone(this);
666 for(set<OutPort *>::iterator iter2=links.begin();iter2!=links.end();iter2++)
667 for(unsigned j=0;j<nbOfBr;j++)
670 Node *whatType=isInMyDescendance((*iter2)->getNode());
673 portExec=_execNodes[j]->getOutPort(_node->getOutPortName(*iter2));
674 portExec->addInPort(_interceptorsForOutPool[j]);
676 else if(whatType==_initNode && whatType!=0)//This case should never happend. Useless !
678 portExec=_execInitNodes[j]->getOutPort(_node->getOutPortName(*iter2));
679 portExec->addInPort(_interceptorsForOutPool[j]);
685 * Typically called when _alg has decided that convergence has been reached. In this case the links leaving the current scope are activated and filled
686 * with value of the branch specified by 'branchId' that is the branch in which the convergence has been reached.
688 void OptimizerLoop::pushValueOutOfScopeForCase(unsigned branchId)
690 map<InputPort *, std::vector<InputPort *> >::iterator iter;
691 for(iter=_interceptors.begin();iter!=_interceptors.end();iter++)
692 (*iter).first->put((*iter).second[branchId]->get());
695 void OptimizerLoop::accept(Visitor *visitor)
697 visitor->visitOptimizerLoop(this);
700 //! Set the algorithm library name and factory name (symbol in library) to create the algorithm and change it if the node is not connected
702 * throw an exception if the node is connected
704 void OptimizerLoop::setAlgorithm(const std::string& alglib, const std::string& symbol,
705 bool checkLinks, Proc * procForTypes)
709 if (_splittedPort.edGetNumberOfOutLinks() != 0 ||
710 _retPortForOutPool.edGetNumberOfLinks() != 0 ||
711 _algoInitPort.edGetNumberOfLinks() != 0 ||
712 _algoResultPort.edGetNumberOfOutLinks() != 0)
713 throw Exception("The OptimizerLoop node must be disconnected before setting the algorithm");
728 _alg->setProc((procForTypes == NULL) ? getProc() : procForTypes);
730 // Delete the values in the input ports if they were initialized
731 _retPortForOutPool.put((Any *)NULL);
732 _algoInitPort.put((Any *)NULL);
734 // Change the type of the ports
735 _splittedPort.edSetType(checkTypeCode(_alg->getTCForInProxy(), NAME_OF_SPLITTED_SEQ_OUT));
736 _retPortForOutPool.edSetType(checkTypeCode(_alg->getTCForOutProxy(), NAME_OF_OUT_POOL_INPUT));
737 _algoInitPort.edSetType(checkTypeCode(_alg->getTCForAlgoInitProxy(), NAME_OF_ALGO_INIT_PORT));
738 _algoResultPort.edSetType(checkTypeCode(_alg->getTCForAlgoResultProxy(), NAME_OF_ALGO_RESULT_PORT));
744 TypeCode * OptimizerLoop::checkTypeCode(TypeCode * tc, const char * portName)
747 ostringstream errorMsg;
748 errorMsg << "The algorithm specified for OptimizerLoop node \"" << getName() <<
749 "\" provided an invalid type for port \"" << portName << "\"";
750 throw Exception(errorMsg.str());
755 //! Load the algorithm from the dynamic library
759 void OptimizerLoop::loadAlgorithm()
761 YASSERT(_alg == NULL)
763 if (_loader != NULL) {
767 _loader = new YACS::BASES::DynLibLoader(_alglib);
768 OptimizerAlgBaseFactory algFactory = NULL;
770 if (_alglib != "" && _symbol != "")
775 algFactory = (OptimizerAlgBaseFactory)_loader->getHandleOnSymbolWithName(_symbol);
777 catch (YACS::Exception& e)
779 _errorDetails = e.what();
785 if (algFactory != NULL)
786 _alg = algFactory(&_myPool);
789 //! Return the name of the algorithm library
793 std::string OptimizerLoop::getAlgLib() const
798 //! Check validity for the node.
800 * Throw an exception if the node is not valid
802 void OptimizerLoop::checkBasicConsistency() const throw(YACS::Exception)
804 DEBTRACE("OptimizerLoop::checkBasicConsistency");
806 throw Exception("No library specified for the OptimizerLoop control algorithm");
808 throw Exception("No symbol specified for the OptimizerLoop control algorithm");
810 throw YACS::Exception("Problem during library loading: "+_errorDetails);
812 DynParaLoop::checkBasicConsistency();
815 int OptimizerLoop::getNumberOfOutputPorts() const
817 return DynParaLoop::getNumberOfOutputPorts() + 1;
820 std::list<OutputPort *> OptimizerLoop::getSetOfOutputPort() const
822 list<OutputPort *> ret = DynParaLoop::getSetOfOutputPort();
823 ret.push_back((OutputPort *)&_algoResultPort);
827 std::list<OutputPort *> OptimizerLoop::getLocalOutputPorts() const
829 list<OutputPort *> ret = DynParaLoop::getLocalOutputPorts();
830 ret.push_front((OutputPort *)&_algoResultPort);
834 OutPort * OptimizerLoop::getOutPort(const std::string& name) const throw(YACS::Exception)
836 return (name == NAME_OF_ALGO_RESULT_PORT) ? (OutPort *)&_algoResultPort :
837 DynParaLoop::getOutPort(name);
841 OutputPort * OptimizerLoop::getOutputPort(const std::string& name) const throw(YACS::Exception)
843 return (name == NAME_OF_ALGO_RESULT_PORT) ? (OutputPort *)&_algoResultPort :
844 DynParaLoop::getOutputPort(name);