Salome HOME
152b578f1c620d9dafb9698bbc1789373a84ae51
[modules/yacs.git] / src / engine / OptimizerLoop.cxx
1 // Copyright (C) 2006-2012  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "OptimizerLoop.hxx"
21 #include "OutputPort.hxx"
22 #include "Visitor.hxx"
23
24 #include <iostream>
25
26 //#define _DEVDEBUG_
27 #include "YacsTrace.hxx"
28
29 using namespace YACS::ENGINE;
30 using namespace std;
31
32 const char FakeNodeForOptimizerLoop::NAME[]="thisIsAFakeNode";
33
34 const int OptimizerLoop::NOT_RUNNING_BRANCH_ID=-1973012217;
35 const int OptimizerLoop::NOT_INITIALIZED_BRANCH_ID=-1973;
36
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";
40
41
42 FakeNodeForOptimizerLoop::FakeNodeForOptimizerLoop(OptimizerLoop *loop, bool normal, std::string message)
43   : ElementaryNode(NAME), _loop(loop), _normal(normal), _message(message)
44 {
45   _state=YACS::TOACTIVATE;
46   _father=_loop->getFather();
47 }
48
49 FakeNodeForOptimizerLoop::FakeNodeForOptimizerLoop(const FakeNodeForOptimizerLoop& other)
50   : ElementaryNode(other), _loop(0), _normal(other._normal), _message(other._message)
51
52 }
53
54 Node *FakeNodeForOptimizerLoop::simpleClone(ComposedNode *father, bool editionOnly) const
55 {
56   return new FakeNodeForOptimizerLoop(*this);
57 }
58
59 void FakeNodeForOptimizerLoop::exForwardFailed()
60 {
61   _loop->exForwardFailed();
62 }
63
64 void FakeNodeForOptimizerLoop::exForwardFinished()
65 {
66   _loop->exForwardFinished();
67 }
68
69 void FakeNodeForOptimizerLoop::execute()
70 {
71   DEBTRACE("FakeNodeForOptimizerLoop::execute: " << _message)
72   if (!_normal) {
73     _loop->_errorDetails = _message;
74     throw Exception(_message);
75   }
76   else
77   {
78     _loop->_algoResultPort.put(_loop->_alg->getAlgoResultProxy());
79   }
80 }
81
82 void FakeNodeForOptimizerLoop::aborted()
83 {
84   _loop->setState(YACS::ERROR);
85 }
86
87 void FakeNodeForOptimizerLoop::finished()
88 {
89   _loop->setState(YACS::DONE);
90 }
91
92 /*! \class YACS::ENGINE::OptimizerLoop
93  *  \brief class to build optimization loops
94  *
95  * \ingroup ComposedNodes
96  */
97
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)
106 {
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 
109   if(initAlgo)
110     setAlgorithm(algLibWthOutExt,symbolNameToOptimizerAlgBaseInstanceFactory, procForTypes);
111 }
112
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)
118 {
119   //Don't call setAlgorithm here because it will be called several times if the class is derived. Call it in simpleClone for cloning
120 }
121
122 OptimizerLoop::~OptimizerLoop()
123 {
124   if(_alg)
125     _alg->decrRef();
126   cleanDynGraph();
127   cleanInterceptors();
128   delete _loader;
129   delete _nodeForSpecialCases;
130 }
131
132 Node *OptimizerLoop::simpleClone(ComposedNode *father, bool editionOnly) const
133 {
134   OptimizerLoop* ol=new OptimizerLoop(*this,father,editionOnly);
135   // TODO: Remove this const_cast (find a better design to get the type codes from the original node)
136   Proc * procForTypes = ol->getProc();
137   if (procForTypes == NULL) {
138     const Proc * origProc = getProc();
139     procForTypes = const_cast<Proc *>(origProc);
140   }
141   ol->setAlgorithm(_alglib, _symbol, false, procForTypes);
142   return ol;
143 }
144
145 void OptimizerLoop::init(bool start)
146 {
147   DynParaLoop::init(start);
148   _algoInitPort.exInit(start);
149   _retPortForOutPool.exInit(start);
150   _algoResultPort.exInit();
151   _convergenceReachedWithOtherCalc=false;
152   cleanDynGraph();
153   cleanInterceptors();
154 }
155
156 void OptimizerLoop::exUpdateState()
157 {
158   if(_state == YACS::DISABLED)
159     return;
160   delete _nodeForSpecialCases;
161   _nodeForSpecialCases = NULL;
162   try
163     {
164       if(_inGate.exIsReady())
165         {
166           setState(YACS::TOACTIVATE);
167           // Force termination in case the previous algorithm did not finish properly (manual stop)
168           _alg->finishProxy();
169           _myPool.destroyAll();
170
171           // Initialize and launch the algorithm
172           _alg->initializeProxy(_algoInitPort.getValue());
173           _alg->startProxy();
174           if (_alg->hasError()) {
175             string error = _alg->getError();
176             _alg->finishProxy();
177             throw Exception(error);
178           }
179
180           //internal graph update
181           int i;
182           int nbOfBr=_nbOfBranches.getIntValue();
183           if(nbOfBr==0)
184             {
185               // A number of branches of 0 is acceptable if there are no output ports
186               // leaving OptimizerLoop
187               bool normal = getAllOutPortsLeavingCurrentScope().empty();
188               _nodeForSpecialCases = new FakeNodeForOptimizerLoop(this, normal,
189                   "OptimizerLoop has no branch to run the internal node(s)");
190               return;
191             }
192           _execNodes.resize(nbOfBr);
193           _execIds.resize(nbOfBr);
194           if(_initNode)
195             {
196               _execInitNodes.resize(nbOfBr);
197               _initNodeUpdated.resize(nbOfBr);
198               for(i=0;i<nbOfBr;i++)
199                 _initNodeUpdated[i]=false;
200             }
201           _initializingCounter = 0;
202           if (_finalizeNode)
203             _execFinalizeNodes.resize(nbOfBr);
204           vector<Node *> origNodes;
205           origNodes.push_back(_initNode);
206           origNodes.push_back(_node);
207           origNodes.push_back(_finalizeNode);
208           for(i=0;i<nbOfBr;i++)
209             {
210               _execIds[i]=NOT_INITIALIZED_BRANCH_ID;
211               vector<Node *> clonedNodes = cloneAndPlaceNodesCoherently(origNodes);
212               if(_initNode)
213                 _execInitNodes[i] = clonedNodes[0];
214               _execNodes[i] = clonedNodes[1];
215               if(_finalizeNode)
216                 _execFinalizeNodes[i] = clonedNodes[2];
217               prepareInputsFromOutOfScope(i);
218             }
219           initInterceptors(nbOfBr);
220           int id;
221           unsigned char priority;
222           Any *val=_myPool.getNextSampleWithHighestPriority(id,priority);
223           if(!val)
224             {
225               // It is acceptable to have no sample to launch if there are no output ports
226               // leaving OptimizerLoop
227               std::set<OutPort *> setOutPort = getAllOutPortsLeavingCurrentScope();
228               // Special in the special
229               // We do not check algoResult
230               setOutPort.erase(&_algoResultPort);
231               bool normal = setOutPort.empty();
232               _nodeForSpecialCases = new FakeNodeForOptimizerLoop(this, normal,
233                   string("The algorithm of OptimizerLoop with name ") + _name +
234                   " returns no sample to launch");
235               return;
236             }
237           launchMaxOfSamples(true);
238         }
239     }
240   catch (const exception & e)
241     {
242       _nodeForSpecialCases = new FakeNodeForOptimizerLoop(this, false,
243           string("An error happened in the control algorithm of OptimizerLoop \"") + _name +
244           "\": " + e.what());
245     }
246 }
247
248 int OptimizerLoop::getNumberOfInputPorts() const
249 {
250   return DynParaLoop::getNumberOfInputPorts()+2;
251 }
252
253 InputPort *OptimizerLoop::getInputPort(const std::string& name) const throw(YACS::Exception)
254 {
255   if (name == NAME_OF_ALGO_INIT_PORT)
256     return (InputPort *)&_algoInitPort;
257   else if (name == NAME_OF_OUT_POOL_INPUT)
258     return (InputPort *)&_retPortForOutPool;
259   else
260     return DynParaLoop::getInputPort(name);
261 }
262
263 std::list<InputPort *> OptimizerLoop::getSetOfInputPort() const
264 {
265   list<InputPort *> ret=DynParaLoop::getSetOfInputPort();
266   ret.push_back((InputPort *)&_algoInitPort);
267   ret.push_back((InputPort *)&_retPortForOutPool);
268   return ret;
269 }
270
271 std::list<InputPort *> OptimizerLoop::getLocalInputPorts() const
272 {
273   list<InputPort *> ret=DynParaLoop::getLocalInputPorts();
274   ret.push_back((InputPort *)&_algoInitPort);
275   ret.push_back((InputPort *)&_retPortForOutPool);
276   return ret;
277 }
278
279 void OptimizerLoop::selectRunnableTasks(std::vector<Task *>& tasks)
280 {
281 }
282
283 void OptimizerLoop::getReadyTasks(std::vector<Task *>& tasks)
284 {
285   if(!_node)
286     return;
287   if(_state==YACS::TOACTIVATE || _state==YACS::ACTIVATED)
288     {
289       if(_nodeForSpecialCases)
290         {
291           _nodeForSpecialCases->getReadyTasks(tasks);
292           return ;
293         }
294       vector<Node *>::iterator iter;
295       for (iter=_execNodes.begin() ; iter!=_execNodes.end() ; iter++)
296         (*iter)->getReadyTasks(tasks);
297       for (iter=_execInitNodes.begin() ; iter!=_execInitNodes.end() ; iter++)
298         (*iter)->getReadyTasks(tasks);
299       for (iter=_execFinalizeNodes.begin() ; iter!=_execFinalizeNodes.end() ; iter++)
300         (*iter)->getReadyTasks(tasks);
301     }
302 }
303
304 YACS::Event OptimizerLoop::updateStateOnFinishedEventFrom(Node *node)
305 {
306   if (getState() == YACS::FAILED)
307     {
308       // This happens when a valid computation on a branch finishes after an error on another branch.
309       // In this case we just ignore the new result because the algorithm has already been terminated.
310       return YACS::NOEVENT;
311     }
312   unsigned int id;
313   switch(getIdentityOfNotifyerNode(node,id))
314     {
315     case INIT_NODE:
316     {
317       _execNodes[id]->exUpdateState();
318       _nbOfEltConsumed++;
319       _initializingCounter--;
320       if (_initializingCounter == 0) _initNode->setState(DONE);
321       break;
322     }
323     case WORK_NODE:
324     {
325       if(_convergenceReachedWithOtherCalc)
326         { //This case happens when alg has reached its convergence whereas other calculations still compute
327           _execIds[id]=NOT_RUNNING_BRANCH_ID;
328           if(!isFullyLazy())
329             return YACS::NOEVENT;
330           else
331             return finalize();
332         }
333       _myPool.putOutSampleAt(_execIds[id],_interceptorsForOutPool[id]->getValue());
334       _myPool.setCurrentId(_execIds[id]);
335       _alg->takeDecisionProxy();
336       if (_alg->hasError()) {
337         _errorDetails = string("An error happened in the control algorithm of optimizer loop: ") +
338                         _alg->getError();
339         _alg->finishProxy();
340         setState(YACS::FAILED);
341         return YACS::ABORT;
342       }
343
344       _myPool.destroyCurrentCase();
345       if(_myPool.empty())
346         {
347           pushValueOutOfScopeForCase(id);
348           _execIds[id]=NOT_RUNNING_BRANCH_ID;
349           if(!isFullyLazy())
350             {// This case happens when the hand is returned to continue, whereas some other are working in parallel for nothing.
351               _convergenceReachedWithOtherCalc=true;
352               return YACS::NOEVENT;
353             }
354           return finalize();
355         }
356       _execIds[id]=NOT_RUNNING_BRANCH_ID;
357       int newId;
358       unsigned char priority;
359       Any *val=_myPool.getNextSampleWithHighestPriority(newId, priority);
360       if(!val)
361         {
362           bool isFinished=true;
363           for(int i=0;i<_execIds.size() && isFinished;i++)
364             isFinished=(_execIds[i]==NOT_RUNNING_BRANCH_ID || _execIds[i]==NOT_INITIALIZED_BRANCH_ID);
365           if(isFinished)
366             {
367               std::cerr <<"OptimizerLoop::updateStateOnFinishedEventFrom: Alg has not inserted more cases whereas last element has been calculated !" << std::endl;
368               setState(YACS::ERROR);
369               exForwardFailed();
370               _alg->finishProxy();
371               return YACS::FINISH;
372             }
373           return YACS::NOEVENT;
374         }
375       launchMaxOfSamples(false);
376       break;
377     }
378     case FINALIZE_NODE:
379     {
380       _unfinishedCounter--;
381       if (_unfinishedCounter == 0)
382         {
383           _finalizeNode->setState(YACS::DONE);
384           setState(YACS::DONE);
385           return YACS::FINISH;
386         }
387       else
388         return YACS::NOEVENT;
389       break;
390     }
391     default:
392       YASSERT(false);
393     }
394   return YACS::NOEVENT;
395 }
396
397 YACS::Event OptimizerLoop::finalize()
398 {
399   //update internal node (definition node) state
400   if (_node)
401     {
402       _node->setState(YACS::DONE);
403       ComposedNode* compNode = dynamic_cast<ComposedNode*>(_node);
404       if (compNode)
405         {
406           std::list<Node *> aChldn = compNode->getAllRecursiveConstituents();
407           std::list<Node *>::iterator iter=aChldn.begin();
408           for(;iter!=aChldn.end();iter++)
409             (*iter)->setState(YACS::DONE);
410         }
411     }
412   _alg->finishProxy();
413   _algoResultPort.put(_alg->getAlgoResultProxy());
414   if (_finalizeNode == NULL)
415     {
416       // No finalize node, we just finish OptimizerLoop at the end of exec nodes execution
417       setState(YACS::DONE);
418       return YACS::FINISH;
419     }
420   else
421     {
422       // Run the finalize nodes, the OptimizerLoop will be done only when they all finish
423       _unfinishedCounter = 0;  // This counter indicates how many branches are not finished
424       for (int i=0 ; i<_nbOfBranches.getIntValue() ; i++)
425         if (_execIds[i] == NOT_RUNNING_BRANCH_ID)
426           {
427             DEBTRACE("Launching finalize node for branch " << i)
428             _execFinalizeNodes[i]->exUpdateState();
429             _unfinishedCounter++;
430           }
431         else
432           // There should not be any running branch at this point
433           YASSERT(_execIds[i] == NOT_INITIALIZED_BRANCH_ID)
434       return YACS::NOEVENT;
435     }
436 }
437
438 //! Method used to notify the node that a child node has failed
439 /*!
440  * Notify the slave thread of the error, update the current state and
441  * return the change state
442  *
443  *  \param node : the child node that has failed
444  *  \return the state change
445  */
446 YACS::Event OptimizerLoop::updateStateOnFailedEventFrom(Node *node)
447 {
448   DEBTRACE("OptimizerLoop::updateStateOnFailedEventFrom " << node->getName());
449   _alg->setError(string("Error during the execution of YACS node ") + node->getName() +
450                  ": " + node->getErrorReport());
451   _alg->finishProxy();
452   _myPool.destroyAll();
453   DEBTRACE("OptimizerLoop::updateStateOnFailedEventFrom: returned from error notification.");
454   return DynParaLoop::updateStateOnFailedEventFrom(node);
455 }
456
457 void OptimizerLoop::checkNoCyclePassingThrough(Node *node) throw(YACS::Exception)
458 {
459 }
460
461 void OptimizerLoop::buildDelegateOf(InPort * & port, OutPort *initialStart, const std::list<ComposedNode *>& pointsOfView)
462 {
463   DynParaLoop::buildDelegateOf(port,initialStart,pointsOfView);
464   if(port==&_retPortForOutPool)
465     throw Exception("OptimizerLoop::buildDelegateOf : uncorrect OptimizerLoop link : out pool port must be linked within the scope of OptimizerLoop node it belongs to.");
466 }
467
468 void OptimizerLoop::buildDelegateOf(std::pair<OutPort *, OutPort *>& port, InPort *finalTarget, const std::list<ComposedNode *>& pointsOfView)
469 {
470   DynParaLoop::buildDelegateOf(port,finalTarget,pointsOfView);
471   string typeOfPortInstance=(port.first)->getNameOfTypeOfCurrentInstance();
472   if(typeOfPortInstance!=OutputPort::NAME)
473     throw Exception("OptimizerLoop::buildDelegateOf : not implemented for DS because not specified ");
474 }
475
476 void OptimizerLoop::checkControlDependancy(OutPort *start, InPort *end, bool cross,
477                                            std::map < ComposedNode *,  std::list < OutPort * >, SortHierarc >& fw,
478                                            std::vector<OutPort *>& fwCross,
479                                            std::map< ComposedNode *, std::list < OutPort *>, SortHierarc >& bw,
480                                            LinkInfo& info) const
481 {
482   if(end==&_retPortForOutPool)
483     fw[(ComposedNode *)this].push_back(start);
484   else
485     DynParaLoop::checkControlDependancy(start,end,cross,fw,fwCross,bw,info);
486 }
487
488 void OptimizerLoop::checkCFLinks(const std::list<OutPort *>& starts, InputPort *end, unsigned char& alreadyFed, bool direction, LinkInfo& info) const
489 {
490   if(end==&_retPortForOutPool)
491     solveObviousOrDelegateCFLinks(starts,end,alreadyFed,direction,info);
492   else
493     DynParaLoop::checkCFLinks(starts,end,alreadyFed,direction,info);
494 }
495
496 void OptimizerLoop::cleanInterceptors()
497 {
498   // At this point all garanties taken let's clean all.
499   map<InputPort *,vector<InputPort *> >::iterator iter=_interceptors.begin();
500   for(;iter!=_interceptors.end();iter++)
501     for(vector<InputPort *>::iterator iter2=(*iter).second.begin();iter2!=(*iter).second.end();iter2++)
502       delete (*iter2);
503   _interceptors.clear();
504   for(vector<AnyInputPort *>::iterator iter3=_interceptorsForOutPool.begin();iter3!=_interceptorsForOutPool.end();iter3++)
505     delete (*iter3);
506   _interceptorsForOutPool.clear();
507 }
508
509 void OptimizerLoop::launchMaxOfSamples(bool first)
510 {
511   int id;
512   unsigned char priority;
513   Any *val;
514   unsigned i;
515   for (val = _myPool.getNextSampleWithHighestPriority(id, priority);
516        !isFullyBusy(i) && val;
517        val = _myPool.getNextSampleWithHighestPriority(id, priority))
518     {
519       if(_execIds[i] == NOT_INITIALIZED_BRANCH_ID)
520         first=true; // node is not initialized (first pass)
521       else
522         first=false; // node is initialized (second pass)
523       _execIds[i]=id;
524       _myPool.markIdAsInUse(id);
525       if(_initNode && !_initNodeUpdated[i])
526         {
527           putValueOnBranch(val,i,first);
528           _execInitNodes[i]->exUpdateState();
529           _initNodeUpdated[i]=true;
530           _initializingCounter++;
531         }
532       else
533         {
534           if(!first)
535             _execNodes[i]->init(first);
536           putValueOnBranch(val,i,first);
537           _execNodes[i]->exUpdateState();
538           _nbOfEltConsumed++;
539         }
540     }
541 }
542
543 bool OptimizerLoop::isFullyLazy() const
544 {
545   bool isLazy=true;
546   for(unsigned i=0;i<_execIds.size() && isLazy;i++)
547     isLazy=(_execIds[i]==NOT_RUNNING_BRANCH_ID || _execIds[i]==NOT_INITIALIZED_BRANCH_ID);
548   return isLazy;
549 }
550
551 /*!
552  * Returns if a dynamic branch is available.
553  * \param branchId Out param. Only usable if returned value is equal to \b false.
554  */
555 bool OptimizerLoop::isFullyBusy(unsigned& branchId) const
556 {
557   bool isFinished=true;
558   unsigned i;
559   for(i=0;i<_execIds.size() && isFinished;i++)
560     isFinished=(_execIds[i]!=NOT_RUNNING_BRANCH_ID && _execIds[i]!=NOT_INITIALIZED_BRANCH_ID);
561   if(!isFinished)
562     branchId=i-1;
563   return isFinished;
564 }
565
566 /*!
567  * Perform initialization of interceptors. \b WARNING _execNodes have to be created before.
568  */
569 void OptimizerLoop::initInterceptors(unsigned nbOfBr)
570 {
571   //For all classical outputports leaving 'this'
572   set<OutPort *> portsToIntercept=getAllOutPortsLeavingCurrentScope();
573   portsToIntercept.erase(&_algoResultPort);
574   for(set<OutPort *>::iterator iter=portsToIntercept.begin();iter!=portsToIntercept.end();iter++)
575     {
576       OutputPort *portC=(OutputPort *)(*iter);//Warrantied by OptimizerLoop::buildDelegateOf
577       const set<InputPort *>& links=portC->getSetOfPhyLinks();
578       for(set<InputPort *>::const_iterator iter2=links.begin();iter2!=links.end();iter2++)
579         {
580 #ifdef NOCOVARIANT
581           InputPort *reprCur=dynamic_cast<InputPort *>((*iter2)->getPublicRepresentant());
582 #else
583           InputPort *reprCur=(*iter2)->getPublicRepresentant();
584 #endif
585           if(!isInMyDescendance(reprCur->getNode()))
586             {//here we've got an out of scope link : Let's intercept it
587               if(_interceptors.find(reprCur)==_interceptors.end())
588                 {
589                   _interceptors[reprCur].resize(nbOfBr);
590                   for(unsigned i=0;i<nbOfBr;i++)
591                     {
592                       OutputPort *portExecC=(OutputPort *)_execNodes[i]->getOutputPort(_node->getOutPortName(portC));
593                       InputPort *clone=reprCur->clone(0);
594                       _interceptors[reprCur][i]=clone;
595                       portExecC->edAddInputPort(clone);
596                     }
597                 }
598               else
599                 {
600                   for(unsigned i=0;i<nbOfBr;i++)
601                     {
602                       OutputPort *portExecC=(OutputPort *)_execNodes[i]->getOutputPort(_node->getOutPortName(portC));
603                       portExecC->edAddInputPort(_interceptors[reprCur][i]);
604                     }
605                 }
606             }
607         }
608     }
609   // For out pool
610   _interceptorsForOutPool.resize(nbOfBr);
611   set< OutPort * > links=_retPortForOutPool.edSetOutPort();
612   for(unsigned i=0;i<nbOfBr;i++)
613     _interceptorsForOutPool[i]=(AnyInputPort *)_retPortForOutPool.clone(this);
614   for(set<OutPort *>::iterator iter2=links.begin();iter2!=links.end();iter2++)
615     for(unsigned j=0;j<nbOfBr;j++)
616       {
617         OutPort *portExec;
618         Node *whatType=isInMyDescendance((*iter2)->getNode());
619         if(whatType==_node)
620           {
621             portExec=_execNodes[j]->getOutPort(_node->getOutPortName(*iter2));
622             portExec->addInPort(_interceptorsForOutPool[j]);
623           }
624         else if(whatType==_initNode && whatType!=0)//This case should never happend. Useless !
625           {
626             portExec=_execInitNodes[j]->getOutPort(_node->getOutPortName(*iter2));
627             portExec->addInPort(_interceptorsForOutPool[j]);
628           }
629       }
630 }
631
632 /*!
633  * Typically called when _alg has decided that convergence has been reached. In this case the links leaving the current scope are activated and filled
634  * with value of the branch specified by 'branchId' that is the branch in which the convergence has been reached.
635  */
636 void OptimizerLoop::pushValueOutOfScopeForCase(unsigned branchId)
637 {
638   map<InputPort *, std::vector<InputPort *> >::iterator iter;
639   for(iter=_interceptors.begin();iter!=_interceptors.end();iter++)
640     (*iter).first->put((*iter).second[branchId]->get());
641 }
642
643 void OptimizerLoop::accept(Visitor *visitor)
644 {
645   visitor->visitOptimizerLoop(this);
646 }
647
648 //! Set the algorithm library name and factory name (symbol in library) to create the algorithm and change it if the node is not connected
649 /*!
650  *   throw an exception if the node is connected
651  */
652 void OptimizerLoop::setAlgorithm(const std::string& alglib, const std::string& symbol,
653                                  bool checkLinks, Proc * procForTypes)
654 {
655   if(checkLinks)
656     {
657       if (_splittedPort.edGetNumberOfOutLinks() != 0 ||
658           _retPortForOutPool.edGetNumberOfLinks() != 0 ||
659           _algoInitPort.edGetNumberOfLinks() != 0 ||
660           _algoResultPort.edGetNumberOfOutLinks() != 0)
661         throw Exception("The OptimizerLoop node must be disconnected before setting the algorithm");
662     }
663
664   _symbol = symbol;
665   _alglib = alglib;
666
667   if (_alg) {
668     _alg->decrRef();
669     _alg = NULL;
670   }
671
672   loadAlgorithm();
673
674   if(_alg)
675     {
676       _alg->setProc((procForTypes == NULL) ? getProc() : procForTypes);
677
678       // Delete the values in the input ports if they were initialized
679       _retPortForOutPool.put((Any *)NULL);
680       _algoInitPort.put((Any *)NULL);
681
682       // Change the type of the ports
683       _splittedPort.edSetType(checkTypeCode(_alg->getTCForInProxy(), NAME_OF_SPLITTED_SEQ_OUT));
684       _retPortForOutPool.edSetType(checkTypeCode(_alg->getTCForOutProxy(), NAME_OF_OUT_POOL_INPUT));
685       _algoInitPort.edSetType(checkTypeCode(_alg->getTCForAlgoInitProxy(), NAME_OF_ALGO_INIT_PORT));
686       _algoResultPort.edSetType(checkTypeCode(_alg->getTCForAlgoResultProxy(), NAME_OF_ALGO_RESULT_PORT));
687     }
688
689   modified();
690 }
691
692 TypeCode * OptimizerLoop::checkTypeCode(TypeCode * tc, const char * portName)
693 {
694   if (tc == NULL) {
695     ostringstream errorMsg;
696     errorMsg << "The algorithm specified for OptimizerLoop node \"" << getName() <<
697                 "\" provided an invalid type for port \"" << portName << "\"";
698     throw Exception(errorMsg.str());
699   }
700   return tc;
701 }
702
703 //! Load the algorithm from the dynamic library
704 /*!
705  *
706  */
707 void OptimizerLoop::loadAlgorithm()
708 {
709   YASSERT(_alg == NULL)
710
711   if (_loader != NULL) {
712     delete _loader;
713     _loader = NULL;
714   }
715   _loader = new YACS::BASES::DynLibLoader(_alglib);
716   OptimizerAlgBaseFactory algFactory = NULL;
717
718   if (_alglib != "" && _symbol != "")
719     {
720       try
721         {
722           _errorDetails = "";
723           algFactory = (OptimizerAlgBaseFactory)_loader->getHandleOnSymbolWithName(_symbol);
724         }
725       catch (YACS::Exception& e)
726         {
727           _errorDetails = e.what();
728           modified();
729           throw;
730         }
731     }
732
733   if (algFactory != NULL)
734     _alg = algFactory(&_myPool);
735 }
736
737 //! Return the name of the algorithm library
738 /*!
739  *
740  */
741 std::string OptimizerLoop::getAlgLib() const
742 {
743   return _alglib;
744 }
745
746 //! Check validity for the node.
747 /*!
748  *  Throw an exception if the node is not valid
749  */
750 void OptimizerLoop::checkBasicConsistency() const throw(YACS::Exception)
751 {
752   DEBTRACE("OptimizerLoop::checkBasicConsistency");
753   if (_alglib == "")
754     throw Exception("No library specified for the OptimizerLoop control algorithm");
755   if (_symbol == "")
756     throw Exception("No symbol specified for the OptimizerLoop control algorithm");
757   if(_alg == NULL)
758     throw YACS::Exception("Problem during library loading: "+_errorDetails);
759
760   DynParaLoop::checkBasicConsistency();
761 }
762
763 int OptimizerLoop::getNumberOfOutputPorts() const
764 {
765   return DynParaLoop::getNumberOfOutputPorts() + 1;
766 }
767
768 std::list<OutputPort *> OptimizerLoop::getSetOfOutputPort() const
769 {
770   list<OutputPort *> ret = DynParaLoop::getSetOfOutputPort();
771   ret.push_back((OutputPort *)&_algoResultPort);
772   return ret;
773 }
774
775 std::list<OutputPort *> OptimizerLoop::getLocalOutputPorts() const
776 {
777   list<OutputPort *> ret = DynParaLoop::getLocalOutputPorts();
778   ret.push_front((OutputPort *)&_algoResultPort);
779   return ret;
780 }
781
782 OutPort * OptimizerLoop::getOutPort(const std::string& name) const throw(YACS::Exception)
783 {
784   return (name == NAME_OF_ALGO_RESULT_PORT) ? (OutPort *)&_algoResultPort :
785                                               DynParaLoop::getOutPort(name);
786 }
787
788
789 OutputPort * OptimizerLoop::getOutputPort(const std::string& name) const throw(YACS::Exception)
790 {
791   return (name == NAME_OF_ALGO_RESULT_PORT) ? (OutputPort *)&_algoResultPort :
792                                               DynParaLoop::getOutputPort(name);
793 }