Salome HOME
Merge from V6_main_20120808 08Aug12
[modules/yacs.git] / src / engine / Bloc.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 "Bloc.hxx"
21 #include "LinkInfo.hxx"
22 #include "InputPort.hxx"
23 #include "InputDataStreamPort.hxx"
24 #include "OutputPort.hxx"
25 #include "OutputDataStreamPort.hxx"
26 #include "ElementaryNode.hxx"
27 #include "Visitor.hxx"
28
29 #include <iostream>
30
31 //#define _DEVDEBUG_
32 #include "YacsTrace.hxx"
33
34 using namespace YACS::ENGINE;
35 using namespace std;
36
37 /*! \class YACS::ENGINE::Bloc
38  *  \brief Composed node to group elementary and composed nodes
39  *
40  * \ingroup Nodes
41  */
42
43 Bloc::Bloc(const Bloc& other, ComposedNode *father, bool editionOnly):StaticDefinedComposedNode(other,father),_fwLinks(0),_bwLinks(0)
44 {
45   for(list<Node *>::const_iterator iter=other._setOfNode.begin();iter!=other._setOfNode.end();iter++)
46     _setOfNode.push_back((*iter)->simpleClone(this,editionOnly));
47
48   //CF Linking
49   vector< pair<OutGate *, InGate *> > cfLinksToReproduce=other.getSetOfInternalCFLinks();
50   vector< pair<OutGate *, InGate *> >::iterator iter1=cfLinksToReproduce.begin();
51   for(;iter1!=cfLinksToReproduce.end();iter1++)
52     edAddCFLink(getChildByName(other.getChildName((*iter1).first->getNode())),getChildByName(other.getChildName((*iter1).second->getNode())));
53
54   //Data + DataStream linking
55   vector< pair<OutPort *, InPort *> > linksToReproduce=other.getSetOfInternalLinks();
56   vector< pair<OutPort *, InPort *> >::iterator iter2=linksToReproduce.begin();
57   for(;iter2!=linksToReproduce.end();iter2++)
58     {
59       OutPort* pout = iter2->first;
60       InPort* pin = iter2->second;
61       edAddLink(getOutPort(other.getPortName(pout)),getInPort(other.getPortName(pin)));
62     }
63 }
64
65 //! Create a Bloc node with a given name
66 /*!
67  *   \param name : the given name
68  */
69 Bloc::Bloc(const std::string& name):StaticDefinedComposedNode(name),_fwLinks(0),_bwLinks(0)
70 {
71 }
72
73 Bloc::~Bloc()
74 {
75   for(list<Node *>::iterator iter=_setOfNode.begin();iter!=_setOfNode.end();iter++)
76     delete *iter;
77   delete _fwLinks;
78   delete _bwLinks;
79 }
80
81 //! Initialize the bloc
82 /*!
83  * \param start : a boolean flag indicating the kind of initialization
84  * If start is true, it's a complete initialization with reinitialization of port values
85  * If start is false, there is no initialization of port values
86  */
87 void Bloc::init(bool start)
88 {
89   Node::init(start);
90   for(list<Node *>::iterator iter=_setOfNode.begin();iter!=_setOfNode.end();iter++)
91     (*iter)->init(start);
92 }
93
94 //! Indicate if the bloc execution is finished
95 /*!
96  * The execution bloc is finished if all its child nodes
97  * are finished with or without error or if it is disabled (not to execute)
98  */
99 bool Bloc::isFinished()
100 {
101     if(_state==YACS::DONE)return true;
102     if(_state==YACS::ERROR)return true;
103     if(_state==YACS::FAILED)return true;
104     if(_state==YACS::DISABLED)return true;
105     return false;
106 }
107
108 int Bloc::getNumberOfCFLinks() const
109 {
110   int ret=0;
111   for(list<Node *>::const_iterator iter=_setOfNode.begin();iter!=_setOfNode.end();iter++)
112     ret+=(*iter)->getOutGate()->getNbOfInGatesConnected();
113   return ret;
114 }
115
116 Node *Bloc::simpleClone(ComposedNode *father, bool editionOnly) const
117 {
118   return new Bloc(*this,father,editionOnly);
119 }
120
121 //! Collect all nodes that are ready to execute
122 /*!
123  * \param tasks : vector of tasks to collect ready nodes
124  */
125 void Bloc::getReadyTasks(std::vector<Task *>& tasks)
126 {
127   /*
128    * ComposedNode state goes to ACTIVATED when one of its child has been ACTIVATED
129    * To change this uncomment the following line
130    * Then the father node will go to ACTIVATED state before its child node
131    */
132   if(_state==YACS::TOACTIVATE ) setState(YACS::ACTIVATED);
133   if(_state==YACS::TOACTIVATE || _state==YACS::ACTIVATED)
134     for(list<Node *>::iterator iter=_setOfNode.begin();iter!=_setOfNode.end();iter++)
135       (*iter)->getReadyTasks(tasks);
136 }
137
138 //! Update the bloc state
139 /*!
140  * Update the '_state' attribute.
141  * Typically called by 'this->_inGate' when 'this->_inGate' is ready. 
142  * Contrary to Node::exUpdateState no check done on inputs
143  * because internal linked DF inputports are not valid yet.
144  */
145 void Bloc::exUpdateState()
146 {
147   if(_state == YACS::DISABLED)return;
148   if(_state == YACS::DONE)return;
149   if(_inGate.exIsReady())
150     {
151       setState(YACS::ACTIVATED);
152       for(list<Node *>::iterator iter=_setOfNode.begin();iter!=_setOfNode.end();iter++)
153         if((*iter)->exIsControlReady())
154           (*iter)->exUpdateState();
155     }
156 }
157
158 //! Add a child node to the bloc
159 /*!
160  * \param node: the node to add to the bloc
161  * \return a boolean flag indicating if the node has been added
162  *
163  * If node is already a direct child of current bloc, do nothing.
164  * If node is a child of another bloc, throw exception.
165  * If node name already used in bloc, throw exception.
166  * Publish inputPorts in current bloc and ancestors.
167  */
168 bool Bloc::edAddChild(Node *node) throw(YACS::Exception)
169 {
170   if(isNodeAlreadyAggregated(node))
171     {
172       if(node->_father==this)
173         return false;
174       else
175         {
176           string what = "Bloc::edAddChild : node "; what += node->getName();
177           what += " is already grand children of node";
178           throw Exception(what);
179         }
180     }
181
182   if(node->_father)
183     {
184       string what = "Bloc::edAddChild: node is not orphan: "; what += node->getName();
185       throw Exception(what);
186     }
187   
188   checkNoCrossHierachyWith(node);
189
190   if(isNameAlreadyUsed(node->getName()))
191     {
192       string what("Bloc::edAddChild : name "); what+=node->getName(); 
193       what+=" already exists in the scope of "; what+=_name;
194       throw Exception(what);
195     }
196   
197   node->_father=this;
198   _setOfNode.push_back(node);
199   //should we also set _modified flag for node ??
200   ComposedNode *iter=node->_father;
201   //set the _modified flag so that latter on edUpdateState (eventually called by isValid) refresh state
202   //better call it at end
203   modified();
204   return true;
205 }
206
207 /**
208  * Remove 'node' from the set of direct children.
209  * @exception If 'node' is NOT the son of 'this'.
210  */
211
212 void Bloc::edRemoveChild(Node *node) throw(YACS::Exception)
213 {
214   StaticDefinedComposedNode::edRemoveChild(node);
215   list<Node *>::iterator iter=find(_setOfNode.begin(),_setOfNode.end(),node);
216   if(iter!=_setOfNode.end())
217     {
218       _setOfNode.erase(iter);
219       modified();
220     }
221 }
222
223 Node *Bloc::getChildByShortName(const std::string& name) const throw(YACS::Exception)
224 {
225   for (list<Node *>::const_iterator iter = _setOfNode.begin(); iter != _setOfNode.end(); iter++)
226     if ((*iter)->getName() == name)
227       return (*iter);
228   string what("node "); what+= name ; what+=" is not a child of Bloc "; what += getName();
229   throw Exception(what);
230 }
231
232 void Bloc::selectRunnableTasks(std::vector<Task *>& tasks)
233 {
234 }
235
236 bool Bloc::areAllSubNodesDone() const
237 {
238   for(list<Node *>::const_iterator iter=_setOfNode.begin();iter!=_setOfNode.end();iter++)
239     {
240       if((*iter)->_state == YACS::DONE)continue;
241       if((*iter)->_state == YACS::DISABLED)continue;
242       return false;
243     }
244   return true;
245 }
246
247 bool Bloc::areAllSubNodesFinished() const
248 {
249   for(list<Node *>::const_iterator iter=_setOfNode.begin();iter!=_setOfNode.end();iter++)
250     {
251       if((*iter)->_state == YACS::DONE)continue;
252       if((*iter)->_state == YACS::FAILED)continue;
253       if((*iter)->_state == YACS::DISABLED)continue;
254       if((*iter)->_state == YACS::ERROR)continue;
255       if((*iter)->_state == YACS::INTERNALERR)continue;
256       return false;
257     }
258   return true;
259 }
260
261 bool Bloc::isNameAlreadyUsed(const std::string& name) const
262 {
263   for(list<Node *>::const_iterator iter=_setOfNode.begin();iter!=_setOfNode.end();iter++)
264     if((*iter)->getName()==name)
265       return true;
266   return false;
267 }
268
269 bool insertNodeChildrenInSet(Node *node, std::set<Node *>& nodeSet)
270 {
271   bool verdict=true;
272   set<Node *> outNodes=node->getOutNodes();
273   for (set<Node *>::iterator iter=outNodes.begin();iter!=outNodes.end(); iter++)
274     {
275       verdict=(nodeSet.insert(*iter)).second;
276       if (verdict) verdict = insertNodeChildrenInSet((*iter),nodeSet);
277     }
278   return verdict;
279 }
280
281 /*!
282  * \note  Checks that in the forest from 'node' there are NO back-edges.
283  *        \b WARNING : When using this method 'node' has to be checked in order to be part of direct children of 'this'. 
284  *
285  */
286 void Bloc::checkNoCyclePassingThrough(Node *node) throw(YACS::Exception)
287 {
288   set<Node *> currentNodesToTest;
289   //don't insert node to test in set. 
290   //If it is present after insertion of connected nodes we have a loop
291   //collect all connected nodes
292   insertNodeChildrenInSet(node,currentNodesToTest);
293   //try to insert node
294   if(!(currentNodesToTest.insert(node)).second)
295     throw Exception("Cycle has been detected",1);
296 }
297
298 std::vector< std::pair<OutGate *, InGate *> > Bloc::getSetOfInternalCFLinks() const
299 {
300   vector< pair<OutGate *, InGate *> > ret;
301   for(list<Node *>::const_iterator iter=_setOfNode.begin();iter!=_setOfNode.end();iter++)
302     {
303       set<InGate *> outCFLinksOfCurNode=(*iter)->_outGate.edSetInGate();
304       for(set<InGate *>::iterator iter2=outCFLinksOfCurNode.begin();iter2!=outCFLinksOfCurNode.end();iter2++)
305         ret.push_back(pair<OutGate *, InGate *>(&(*iter)->_outGate,*iter2));
306     }
307   return ret;
308 }
309
310 /*!
311  *
312  * @note : Runtime called method. Indirectly called by StaticDefinedComposedNode::updateStateFrom which has dispatch to this method
313  *          'when event == FINISH'.
314  *          WARNING Precondition : '_state == Running' and 'node->_father==this'(garanteed by StaticDefinedComposedNode::notifyFrom)
315  *
316  * Calls the node's outgate OutGate::exNotifyDone if all nodes are not finished
317  */
318 YACS::Event Bloc::updateStateOnFinishedEventFrom(Node *node)
319 {
320   DEBTRACE("Bloc::updateStateOnFinishedEventFrom: " << node->getName());
321   //ASSERT(node->_father==this)
322   if(areAllSubNodesFinished())
323     {
324       setState(YACS::DONE);
325       if(!areAllSubNodesDone())
326         {
327           setState(YACS::FAILED);
328           return YACS::ABORT;
329         }
330       return YACS::FINISH;//notify to father node that 'this' has becomed finished.
331     }
332   //more job to do in 'this' bloc
333   //Conversion exceptions can be thrown so catch them to control errors
334   try
335     {
336       //notify the finished node to propagate to its following nodes
337       node->exForwardFinished();
338     }
339   catch(YACS::Exception& ex)
340     {
341       //The node has failed to propagate. It must be put in error
342       DEBTRACE("Bloc::updateStateOnFinishedEventFrom: " << ex.what());
343       // notify the node it has failed
344       node->exForwardFailed();
345       setState(YACS::FAILED);
346       return YACS::ABORT;
347     }
348   return YACS::NOEVENT;//no notification to father needed because from father point of view nothing happened.
349 }
350
351 //! Notify this bloc that a node has failed
352 /*!
353  * \param node : node that has emitted the event
354  * \return the event to notify to bloc's father
355  */
356 YACS::Event Bloc::updateStateOnFailedEventFrom(Node *node)
357 {
358   node->exForwardFailed();
359   if(areAllSubNodesFinished())
360     {
361       setState(YACS::DONE);
362       if(!areAllSubNodesDone()){
363           setState(YACS::FAILED);
364           return YACS::ABORT;
365       }
366       return YACS::FINISH;//notify to father node that 'this' has becomed finished.
367     }
368   return YACS::NOEVENT;
369 }
370
371 void Bloc::writeDot(std::ostream &os) const
372 {
373     os << "  subgraph cluster_" << getId() << "  {\n" ;
374     list<Node *>nodes=getChildren();
375     for(list<Node *>::const_iterator iter=nodes.begin();iter!=nodes.end();iter++)
376     {
377         (*iter)->writeDot(os);
378         string p=(*iter)->getId();
379         //not connected node
380         if((*iter)->_inGate._backLinks.size() == 0) os << getId() << " -> " << p << ";\n";
381         set<Node *>outnodes = (*iter)->getOutNodes();
382         for(set<Node *>::const_iterator itout=outnodes.begin();itout!=outnodes.end();itout++)
383         {
384             os << p << " -> " << (*itout)->getId() << ";\n";
385         }
386     }
387     os << "}\n" ;
388     os << getId() << "[fillcolor=\"" ;
389     YACS::StatesForNode state=getEffectiveState();
390     os << getColorState(state);
391     os << "\" label=\"" << "Bloc:" ;
392     os << getQualifiedName() <<"\"];\n";
393 }
394
395 void Bloc::accept(Visitor* visitor)
396 {
397   visitor->visitBloc(this);
398 }
399
400 /*!
401  * Updates mutable structures _fwLinks and _bwLinks with the result of computation (CPU consuming method).
402  * _fwLinks is a map with a Node* as key and a set<Node*> as value. The set gives
403  * all nodes that are forwardly connected to the key node 
404  * _bwLinks is a map for backward dependencies
405  * The method is : for all CF link (n1->n2) 
406  * add n2 and _fwLinks[n2] in forward dependencies of n1 and _bwLinks[n1]
407  * add n1 and _bwLinks[n1] in backward dependencies of n2 and _fwLinks[n2]
408  * For useless links
409  * If a node is already in a forward dependency when adding and the direct link
410  * already exists so it's a useless link (see the code !)
411  */
412 void Bloc::performCFComputations(LinkInfo& info) const
413 {
414   StaticDefinedComposedNode::performCFComputations(info);
415   delete _fwLinks;//Normally useless
416   delete _bwLinks;//Normally useless
417   _fwLinks=new map<Node *,set<Node *> >;
418   _bwLinks=new map<Node *,set<Node *> >;
419
420   //a set to store all CF links : used to find fastly if two nodes are connected
421   std::set< std::pair< Node*, Node* > > links;
422
423   for(list<Node *>::const_iterator iter=_setOfNode.begin();iter!=_setOfNode.end();iter++)
424     {
425       Node* n1=*iter;
426       std::set<InGate *> ingates=n1->getOutGate()->edSetInGate();
427       for(std::set<InGate *>::const_iterator it2=ingates.begin();it2!=ingates.end();it2++)
428         {
429           //CF link : n1 -> (*it2)->getNode()
430           Node* n2=(*it2)->getNode();
431           links.insert(std::pair< Node*, Node* >(n1,n2));
432           std::set<Node *> bwn1=(*_bwLinks)[n1];
433           std::set<Node *> fwn1=(*_fwLinks)[n1];
434           std::set<Node *> fwn2=(*_fwLinks)[n2];
435           std::set<Node *> bwn2=(*_bwLinks)[n2];
436           std::pair<std::set<Node*>::iterator,bool> ret;
437           for(std::set<Node *>::const_iterator iter2=bwn1.begin();iter2!=bwn1.end();iter2++)
438             {
439               for(std::set<Node *>::const_iterator it3=fwn2.begin();it3!=fwn2.end();it3++)
440                 {
441                   ret=(*_fwLinks)[*iter2].insert(*it3);
442                   if(ret.second==false)
443                     {
444                       //dependency already exists (*iter2) -> (*it3) : if a direct link exists it's a useless one
445                       if(links.find(std::pair< Node*, Node* >(*iter2,*it3)) != links.end())
446                         info.pushUselessCFLink(*iter2,*it3);
447                     }
448                 }
449               ret=(*_fwLinks)[*iter2].insert(n2);
450               if(ret.second==false)
451                 {
452                   //dependency already exists (*iter2) -> n2 : if a direct link exists it's a useless one
453                   if(links.find(std::pair< Node*, Node* >(*iter2,n2)) != links.end())
454                     info.pushUselessCFLink(*iter2,n2);
455                 }
456             }
457           for(std::set<Node *>::const_iterator it3=fwn2.begin();it3!=fwn2.end();it3++)
458             {
459               ret=(*_fwLinks)[n1].insert(*it3);
460               if(ret.second==false)
461                 {
462                   //dependency already exists n1 -> *it3 : if a direct link exists it's a useless one
463                   if(links.find(std::pair< Node*, Node* >(n1,*it3)) != links.end())
464                     info.pushUselessCFLink(n1,*it3);
465                 }
466             }
467           ret=(*_fwLinks)[n1].insert(n2);
468           if(ret.second==false)
469             {
470               //dependency already exists n1 -> n2 : it's a useless link
471               info.pushUselessCFLink(n1,n2);
472             }
473
474           for(std::set<Node *>::const_iterator iter2=fwn2.begin();iter2!=fwn2.end();iter2++)
475             {
476               (*_bwLinks)[*iter2].insert(bwn1.begin(),bwn1.end());
477               (*_bwLinks)[*iter2].insert(n1);
478             }
479           (*_bwLinks)[n2].insert(bwn1.begin(),bwn1.end());
480           (*_bwLinks)[n2].insert(n1);
481         }
482     }
483 }
484
485 void Bloc::destructCFComputations(LinkInfo& info) const
486 {
487   StaticDefinedComposedNode::destructCFComputations(info);
488   delete _fwLinks; _fwLinks=0;
489   delete _bwLinks; _bwLinks=0;
490 }
491
492 /*!
493  * \b WARNING \b Needs call of performCFComputations before beeing called.
494  *  Perform updates of containers regarding attributes of link 'start' -> 'end' and check the correct linking.
495  *  The output is in info struct.
496  *
497  * \param start : start port
498  * \param end : end port
499  * \param cross : 
500  * \param fw out parameter being append if start -> end link is a forward link \b without cross type DF/DS.
501  * \param fwCross out parameter being append if start -> end link is a forward link \b with cross type DF/DS.
502  * \param bw out parameter being append if start -> end link is a backward link.
503  * \param info out parameter being informed about eventual errors.
504  */
505 void Bloc::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
510 {
511   if(!cross)
512     {
513       Node *startN=isInMyDescendance(start->getNode());
514       Node *endN=isInMyDescendance(end->getNode());
515       if(startN==endN)
516         bw[(ComposedNode *)this].push_back(start);
517       else if(areLinked(startN,endN,true))
518         fw[(ComposedNode *)this].push_back(start);
519       else
520         if(areLinked(startN,endN,false))
521           bw[(ComposedNode *)this].push_back(start);
522         else
523           info.pushErrLink(start,end,E_UNPREDICTABLE_FED);
524     }
525   else//DFDS detected
526     if(arePossiblyRunnableAtSameTime(isInMyDescendance(start->getNode()),isInMyDescendance(end->getNode())))
527       fwCross.push_back(start);
528     else
529       info.pushErrLink(start,end,E_DS_LINK_UNESTABLISHABLE);
530 }
531
532 //! Check if two nodes are linked
533 /*!
534  * 'start' and 'end' \b must be direct son of 'this'.
535  * Typically used for data link.
536  * \param start : start node
537  * \param end : end node
538  * \param fw indicates if it is a forward link searched (true : default value) or a backward link serach.
539  * \return if true or false
540  */
541 bool Bloc::areLinked(Node *start, Node *end, bool fw) const
542 {
543   set<Node *>& nexts=fw ? (*_fwLinks)[start] : (*_bwLinks)[start];
544   return nexts.find(end)!=nexts.end();
545 }
546
547 //! Check if two nodes can run in parallel
548 /*!
549  * Typically used for stream link.
550  * 'start' and 'end' \b must be direct son of 'this'.
551  * \param start : start node
552  * \param end : end node
553  * \return true or false
554  */
555 bool Bloc::arePossiblyRunnableAtSameTime(Node *start, Node *end) const
556 {
557   set<Node *>& nexts=(*_fwLinks)[start];
558   set<Node *>& preds=(*_bwLinks)[start];
559   return nexts.find(end)==nexts.end() && preds.find(end)==preds.end();
560 }
561
562 //! Check control flow links
563 /*!
564  * \param starts If different of 0, must aggregate at leat \b 1 element.
565  * \param end : end port
566  * \param alreadyFed in/out parameter. Indicates if 'end' ports is already and surely set or fed by an another port.
567  * \param direction If true : forward direction else backward direction.
568  * \param info : collected information
569  */
570 void Bloc::checkCFLinks(const std::list<OutPort *>& starts, InputPort *end, unsigned char& alreadyFed, bool direction, LinkInfo& info) const
571 {
572   if(alreadyFed==FREE_ST || alreadyFed==FED_ST)
573     {
574       map<Node *,list <OutPort *> > classPerNodes;
575       for(list< OutPort *>::const_iterator iter1=starts.begin();iter1!=starts.end();iter1++)
576         classPerNodes[isInMyDescendance((*iter1)->getNode())].push_back(*iter1);
577       set<Node *> allNodes;
578       for(map<Node *,list <OutPort *> >::iterator iter2=classPerNodes.begin();iter2!=classPerNodes.end();iter2++)
579         allNodes.insert((*iter2).first);
580       vector<Node *> okAndUseless1,useless2;
581       seekOkAndUseless1(okAndUseless1,allNodes);
582       seekUseless2(useless2,allNodes);//after this point allNodes contains collapses
583       verdictForOkAndUseless1(classPerNodes,end,okAndUseless1,alreadyFed,direction,info);
584       verdictForCollapses(classPerNodes,end,allNodes,alreadyFed,direction,info);
585       verdictForOkAndUseless1(classPerNodes,end,useless2,alreadyFed,direction,info);
586     }
587   else if(alreadyFed==FED_DS_ST)
588     for(list< OutPort *>::const_iterator iter1=starts.begin();iter1!=starts.end();iter1++)
589       info.pushErrLink(*iter1,end,E_COLLAPSE_DFDS);
590 }
591
592 void Bloc::initComputation() const
593 {
594   for(list<Node *>::const_iterator iter=_setOfNode.begin();iter!=_setOfNode.end();iter++)
595     {
596       (*iter)->_colour=White;
597       (*iter)->getInGate()->exReset();
598       (*iter)->getOutGate()->exReset();
599     }
600 }
601
602 /*!
603  * Part of final step for CF graph anylizing. This is the part of non collapse nodes. 
604  * \param pool :
605  * \param end :
606  * \param candidates :
607  * \param alreadyFed in/out parameter. Indicates if 'end' ports is already and surely set or fed by an another port.
608  * \param direction
609  * \param info : collected information
610  */
611 void Bloc::verdictForOkAndUseless1(const std::map<Node *,std::list <OutPort *> >& pool, InputPort *end, 
612                                    const std::vector<Node *>& candidates, unsigned char& alreadyFed, 
613                                    bool direction, LinkInfo& info)
614 {
615   for(vector<Node *>::const_iterator iter=candidates.begin();iter!=candidates.end();iter++)
616     {
617       const list<OutPort *>& mySet=(*pool.find(*iter)).second;
618       if(mySet.size()==1)
619         {
620           if(alreadyFed==FREE_ST)
621             {
622               alreadyFed=FED_ST;//This the final choice. General case !
623               if(!direction)
624                 info.pushInfoLink(*(mySet.begin()),end,I_BACK);
625             }
626           else if(alreadyFed==FED_ST)
627               info.pushInfoLink(*(mySet.begin()),end,direction ? I_USELESS : I_BACK_USELESS);//Second or more turn in case of alreadyFed==FREE_ST before call of this method
628         }
629       else
630         {
631           if(dynamic_cast<ElementaryNode *>(*iter))
632             {
633               WarnReason reason;
634               if(alreadyFed==FREE_ST)
635                 reason=direction ? W_COLLAPSE_EL : W_BACK_COLLAPSE_EL;
636               else if(alreadyFed==FED_ST)
637                 reason=direction ? W_COLLAPSE_EL_AND_USELESS : W_BACK_COLLAPSE_EL_AND_USELESS;
638               for(list<OutPort *>::const_iterator iter2=mySet.begin();iter2!=mySet.end();iter2++)    
639                 info.pushWarnLink(*iter2,end,reason);
640             }
641           else
642             ((ComposedNode *)(*iter))->checkCFLinks(mySet,end,alreadyFed,direction,info);//Thanks to recursive model!
643         }
644     }
645 }
646
647 /*!
648  * Part of final step for CF graph anylizing. This is the part of collapses nodes. 
649  * \param pool :
650  * \param end :
651  * \param candidates :
652  * \param alreadyFed in/out parameter. Indicates if 'end' ports is already and surely set or fed by an another port.
653  * \param direction
654  * \param info : collected information
655  */
656 void Bloc::verdictForCollapses(const std::map<Node *,std::list <OutPort *> >& pool, InputPort *end, 
657                                const std::set<Node *>& candidates, unsigned char& alreadyFed, 
658                                bool direction, LinkInfo& info)
659 {
660   info.startCollapseTransac();
661   for(set<Node *>::const_iterator iter=candidates.begin();iter!=candidates.end();iter++)
662     {
663       const list<OutPort *>& mySet=(*pool.find(*iter)).second;
664       if(mySet.size()==1)
665         {
666           if(alreadyFed==FREE_ST)
667             info.pushWarnLink(*(mySet.begin()),end,direction ? W_COLLAPSE : W_BACK_COLLAPSE);
668           else if(alreadyFed==FED_ST)
669             info.pushWarnLink(*(mySet.begin()),end,direction ? W_COLLAPSE_AND_USELESS : W_BACK_COLLAPSE_EL_AND_USELESS);
670         }
671       else
672         {
673           if(dynamic_cast<ElementaryNode *>(*iter))
674             {
675               WarnReason reason;
676               if(alreadyFed==FREE_ST)
677                 reason=direction ? W_COLLAPSE_EL : W_BACK_COLLAPSE_EL;
678               else if(alreadyFed==FED_ST)
679                 reason=direction ? W_COLLAPSE_EL_AND_USELESS : W_BACK_COLLAPSE_EL_AND_USELESS;
680               for(list<OutPort *>::const_iterator iter2=mySet.begin();iter2!=mySet.end();iter2++)    
681                 info.pushWarnLink(*iter2,end,reason);
682             }
683           else
684             {
685               ((ComposedNode *)(*iter))->checkCFLinks(mySet,end,alreadyFed,direction,info);//Thanks to recursive model!
686               WarnReason reason;
687               if(alreadyFed==FREE_ST)
688                 reason=direction ? W_COLLAPSE : W_BACK_COLLAPSE;
689               else if(alreadyFed==FED_ST)
690                 reason=direction ? W_COLLAPSE_AND_USELESS : W_BACK_COLLAPSE_AND_USELESS;
691               for(list<OutPort *>::const_iterator iter2=mySet.begin();iter2!=mySet.end();iter2++)    
692                 info.pushWarnLink(*iter2,end,reason);
693             }
694         }
695     }
696   if(!candidates.empty())
697     if(alreadyFed==FREE_ST)
698       alreadyFed=FED_ST;
699   info.endCollapseTransac();
700 }
701
702 /*!
703  * \b WARNING use this method only after having called Bloc::performCFComputations method.
704  * \param okAndUseless1 out param contains at the end, the nodes without any collapse.
705  * \param allNodes in/out param. At the end, all the nodes in 'okAndUseless1' are deleted from 'allNodes'.
706  */
707 void Bloc::seekOkAndUseless1(std::vector<Node *>& okAndUseless1, std::set<Node *>& allNodes) const
708 {
709   set<Node *>::iterator iter=allNodes.begin();
710   while(iter!=allNodes.end())
711     {
712       set<Node *>& whereToFind=(*_bwLinks)[*iter];
713       std::set<Node *>::iterator iter2;
714       for(iter2=allNodes.begin();iter2!=allNodes.end();iter2++)
715         if((*iter)!=(*iter2))
716           if(whereToFind.find(*iter2)==whereToFind.end())
717             break;
718       if(iter2!=allNodes.end())
719         iter++;
720       else
721         {
722           okAndUseless1.push_back((*iter));
723           allNodes.erase(iter);
724           iter=allNodes.begin();
725         }
726     }
727 }
728
729 /*!
730  * \b WARNING use this method only after having called Bloc::performCFComputations method.
731  * For params see Bloc::seekOkAndUseless1.
732  */
733 void Bloc::seekUseless2(std::vector<Node *>& useless2, std::set<Node *>& allNodes) const
734 {
735   set<Node *>::iterator iter=allNodes.begin();
736   while(iter!=allNodes.end())
737     {
738       set<Node *>& whereToFind=(*_fwLinks)[*iter];
739       std::set<Node *>::iterator iter2;
740       for(iter2=allNodes.begin();iter2!=allNodes.end();iter2++)
741         if((*iter)!=(*iter2))
742           if(whereToFind.find(*iter2)==whereToFind.end())
743             break;
744       if(iter2!=allNodes.end())
745         {
746           iter++;
747         }
748       else
749         {
750           useless2.push_back((*iter));
751           allNodes.erase(iter);
752           iter=allNodes.begin();
753         }
754     }
755 }
756
757 /*! 
758  * Internal method : Given a succeful path : updates 'fastFinder'
759  */
760 void Bloc::updateWithNewFind(const std::vector<Node *>& path, std::map<Node *, std::set<Node *> >& fastFinder)
761 {
762   if(path.size()>=3)
763     {
764       vector<Node *>::const_iterator iter=path.begin(); iter++;
765       vector<Node *>::const_iterator iter2=path.end(); iter2-=1;
766       for(;iter!=iter2;iter++)
767         fastFinder[*iter].insert(*(iter+1));
768     }
769 }
770
771 /*! 
772  * Internal method : After all paths have been found, useless CF links are searched
773  */
774 void Bloc::findUselessLinksIn(const std::list< std::vector<Node *> >& res , LinkInfo& info)
775 {
776   unsigned maxSize=0;
777   list< vector<Node *> >::const_iterator whereToPeerAt;
778   for(list< vector<Node *> >::const_iterator iter=res.begin();iter!=res.end();iter++)
779     if((*iter).size()>maxSize)
780       {
781         maxSize=(*iter).size();
782         whereToPeerAt=iter;
783       }
784   //
785   if(maxSize>1)
786     {
787       vector<Node *>::const_iterator iter2=(*whereToPeerAt).begin();
788       map<Node *,bool>::iterator iter4;
789       set<Node *> searcher(iter2+1,(*whereToPeerAt).end());//to boost research
790       for(;iter2!=((*whereToPeerAt).end()-2);iter2++)
791         {
792           map<InGate *,bool>::iterator iter4;
793           map<InGate *,bool>& nexts=(*iter2)->getOutGate()->edMapInGate();
794           for(iter4=nexts.begin();iter4!=nexts.end();iter4++)
795             if((*iter4).first->getNode()!=*(iter2+1))
796               if(searcher.find((*iter4).first->getNode())!=searcher.end())
797                 info.pushUselessCFLink(*iter2,(*iter4).first->getNode());
798           searcher.erase(*iter2);
799         }
800     }
801 }