Salome HOME
Increment version: 8.5.0
[modules/smesh.git] / src / SMESHDS / SMESHDS_GroupOnFilter.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  File   : SMESHDS_GroupOnFilter.cxx
24 //  Module : SMESH
25 //
26 #include "SMESHDS_GroupOnFilter.hxx"
27
28 #include "SMDS_SetIterator.hxx"
29 #include "ObjectPool.hxx"
30 #include "SMESHDS_Mesh.hxx"
31
32 #include <numeric>
33 #include <limits>
34
35 #include <boost/make_shared.hpp>
36
37 using namespace std;
38
39 //#undef WITH_TBB
40
41 //=============================================================================
42 /*!
43  * Creates a group based on thePredicate
44  */
45 //=============================================================================
46
47 SMESHDS_GroupOnFilter::SMESHDS_GroupOnFilter (const int                 theID,
48                                               const SMESHDS_Mesh*       theMesh,
49                                               const SMDSAbs_ElementType theType,
50                                               const SMESH_PredicatePtr& thePredicate)
51   : SMESHDS_GroupBase( theID, theMesh, theType ),
52     SMDS_ElementHolder( theMesh ),
53     myMeshInfo( SMDSEntity_Last, 0 ),
54     myMeshModifTime( 0 ),
55     myPredicateTic( 0 ),
56     myNbElemToSkip( 0 )
57 {
58   SetPredicate( thePredicate );
59 }
60
61 //================================================================================
62 /*!
63  * \brief Sets a new predicate
64  */
65 //================================================================================
66
67 void SMESHDS_GroupOnFilter::SetPredicate( const SMESH_PredicatePtr& thePredicate )
68 {
69   myPredicate = thePredicate;
70   ++myPredicateTic;
71   setChanged();
72   if ( myPredicate )
73     myPredicate->SetMesh( GetMesh() );
74 }
75
76 //================================================================================
77 /*!
78  * \brief Returns nb of elements
79  */
80 //================================================================================
81
82 int SMESHDS_GroupOnFilter::Extent() const
83 {
84   update();
85   return std::accumulate( myMeshInfo.begin(), myMeshInfo.end(), 0 );
86 }
87
88 //================================================================================
89 /*!
90  * \brief Checks emptyness
91  */
92 //================================================================================
93
94 bool SMESHDS_GroupOnFilter::IsEmpty()
95 {
96   if ( IsUpToDate() )
97   {
98     return ( Extent() == 0 );
99   }
100   else // not up-to-date
101   {
102     setChanged();
103     SMDS_ElemIteratorPtr okElemIt = GetElements();
104     if ( !okElemIt->more() )
105     {
106       // no satisfying elements
107       setChanged( false );
108     }
109     else
110     {
111       return false;
112     }
113   }
114   return true;
115 }
116
117 //================================================================================
118 /*!
119  * \brief Checks if the element belongs to the group
120  */
121 //================================================================================
122
123 bool SMESHDS_GroupOnFilter::Contains (const int theID)
124 {
125   return myPredicate && myPredicate->IsSatisfy( theID );
126 }
127
128 //================================================================================
129 /*!
130  * \brief Checks if the element belongs to the group
131  */
132 //================================================================================
133
134 bool SMESHDS_GroupOnFilter::Contains (const SMDS_MeshElement* elem)
135 {
136   return myPredicate && myPredicate->IsSatisfy( elem->GetID() );
137 }
138
139 //================================================================================
140 namespace // Iterator
141 {
142   struct TIterator : public SMDS_ElemIterator
143   {
144     SMESH_PredicatePtr                myPredicate;
145     SMDS_ElemIteratorPtr              myElemIt;
146     const SMDS_MeshElement*           myNextElem;
147     size_t                            myNbToFind, myNbFound, myTotalNb;
148     vector< const SMDS_MeshElement*>& myFoundElems;
149     bool &                            myFoundElemsOK;
150
151     TIterator( const SMESH_PredicatePtr&         filter,
152                SMDS_ElemIteratorPtr&             elems,
153                size_t                            nbToFind,
154                size_t                            totalNb,
155                vector< const SMDS_MeshElement*>& foundElems,
156                bool &                            foundElemsOK):
157       myPredicate( filter ),
158       myElemIt( elems ),
159       myNextElem( 0 ),
160       myNbToFind( nbToFind ),
161       myNbFound( 0 ),
162       myTotalNb( totalNb ),
163       myFoundElems( foundElems ),
164       myFoundElemsOK( foundElemsOK )
165     {
166       myFoundElemsOK = false;
167       next();
168     }
169     ~TIterator()
170     {
171       if ( !myFoundElemsOK )
172         clearVector( myFoundElems );
173     }
174     virtual bool more()
175     {
176       return myNextElem;
177     }
178     virtual const SMDS_MeshElement* next()
179     {
180       const SMDS_MeshElement* res = myNextElem;
181       myNbFound += bool( res );
182       myNextElem = 0;
183       if ( myNbFound < myNbToFind )
184       {
185         while ( myElemIt->more() && !myNextElem )
186         {
187           myNextElem = myElemIt->next();
188           if ( !myPredicate->IsSatisfy( myNextElem->GetID() ))
189             myNextElem = 0;
190         }
191         if ( myNextElem )
192           myFoundElems.push_back( myNextElem );
193         else
194           keepOrClearElemVec();
195       }
196       else
197       {
198         keepOrClearElemVec();
199       }
200       return res;
201     }
202     void keepOrClearElemVec()
203     {
204       if ( myNbFound == myTotalNb )
205       {
206         myFoundElemsOK = false; // all elems are OK, no need to keep them
207       }
208       else
209       {
210         // nb of bytes used for myFoundElems
211         size_t vecMemSize = myFoundElems.size() * sizeof( SMDS_MeshElement* ) / sizeof(char);
212         size_t aMB = 1024 * 1024;
213         if ( vecMemSize < aMB )
214         {
215           myFoundElemsOK = true; // < 1 MB - do not clear
216         }
217         else
218         {
219           int freeRamMB = SMDS_Mesh::CheckMemory( /*doNotRaise=*/true );
220           if ( freeRamMB < 0 )
221             myFoundElemsOK = true; // hope it's OK
222           else
223             myFoundElemsOK = ( freeRamMB * aMB > 10 * vecMemSize );
224         }
225       }
226       if ( !myFoundElemsOK )
227         clearVector( myFoundElems );
228     }
229   };
230
231   struct TEmptyIterator : public SMDS_ElemIterator
232   {
233     virtual bool more()                    { return false; }
234     virtual const SMDS_MeshElement* next() { return 0; }
235   };
236 }
237
238 //================================================================================
239 /*!
240  * \brief Return iterator on all elements
241  */
242 //================================================================================
243
244 SMDS_ElemIteratorPtr SMESHDS_GroupOnFilter::GetElements() const
245 {
246   size_t nbToFind = std::numeric_limits<size_t>::max();
247   size_t totalNb  = GetMesh()->GetMeshInfo().NbElements( GetType() );
248
249   SMDS_ElemIteratorPtr elemIt; // iterator on all elements to initialize TIterator
250   if ( myPredicate )
251   {
252     myPredicate->SetMesh( GetMesh() ); // hope myPredicate updates self here if necessary
253
254     if ( !IsUpToDate() )
255       updateParallel();
256
257     elemIt = GetMesh()->elementsIterator( GetType() );
258     if ( IsUpToDate() )
259     {
260       if ( myElementsOK )
261         return SMDS_ElemIteratorPtr( new SMDS_ElementVectorIterator( myElements.begin(),
262                                                                      myElements.end() ));
263       nbToFind = Extent();
264       if ( nbToFind == totalNb )
265         return elemIt; // all elements are OK
266       for ( size_t i = 0; i < myNbElemToSkip; ++i )
267         elemIt->next(); // skip w/o check
268     }
269   }
270   else
271   {
272     elemIt = SMDS_ElemIteratorPtr( new TEmptyIterator );
273   }
274
275   // the iterator fills myElements if all elements are checked
276   SMESHDS_GroupOnFilter* me = const_cast<SMESHDS_GroupOnFilter*>( this );
277   return SMDS_ElemIteratorPtr
278     ( new TIterator( myPredicate, elemIt, nbToFind, totalNb, me->myElements, me->myElementsOK ));
279 }
280
281 //================================================================================
282 /*!
283  * \brief Return info on sub-types of elements
284  */
285 //================================================================================
286
287 std::vector< int > SMESHDS_GroupOnFilter::GetMeshInfo() const
288 {
289   update();
290   return myMeshInfo;
291 }
292
293 //================================================================================
294 /*!
295  * \brief Fill ids of elements. And return their number.
296  *       \a ids must be pre-allocated using nb of elements of type == GetType()
297  */
298 //================================================================================
299
300 int SMESHDS_GroupOnFilter::getElementIds( void* ids, size_t idSize ) const
301 {
302   SMESHDS_GroupOnFilter* me = const_cast<SMESHDS_GroupOnFilter*>( this );
303
304   if ( !IsUpToDate() )
305     me->setChanged();
306     
307   char* curID = (char*) ids;
308   SMDS_ElemIteratorPtr elIt = GetElements();
309   if ( elIt->more() )
310   {
311     if ( IsUpToDate() )
312     {
313       for ( ; elIt->more(); curID += idSize )
314         (*(int*) curID) = elIt->next()->GetID();
315     }
316     else
317     {
318       // find out nb of elements to skip w/o check before the 1st OK element
319       const SMDS_MeshElement* firstOkElem = me->setNbElemToSkip( elIt );
320
321       me->myMeshInfo.assign( SMDSEntity_Last, 0 );
322       me->myMeshInfo[ firstOkElem->GetEntityType() ]++;
323
324       (*(int*) curID) = firstOkElem->GetID();
325       for ( curID += idSize; elIt->more(); curID += idSize )
326       {
327         const SMDS_MeshElement* e = elIt->next();
328         (*(int*) curID) = e->GetID();
329         me->myMeshInfo[ e->GetEntityType() ]++;
330       }
331     }
332   }
333   me->setChanged( false );
334
335   return ( curID - (char*)ids ) / idSize;
336 }
337
338 //================================================================================
339 /*!
340  * \brief Return a value allowing to find out if a group has changed or not
341  */
342 //================================================================================
343
344 int SMESHDS_GroupOnFilter::GetTic() const
345 {
346   return GetMesh()->GetMTime() * myPredicateTic;
347 }
348
349 //================================================================================
350 /*!
351  * \brief Return false if update() is needed
352  */
353 //================================================================================
354
355 bool SMESHDS_GroupOnFilter::IsUpToDate() const
356 {
357   return !( myMeshModifTime < GetMesh()->GetMTime() );
358 }
359
360 //================================================================================
361 /*!
362  * \brief Updates myElements if necessary
363  */
364 //================================================================================
365
366 void SMESHDS_GroupOnFilter::update() const
367 {
368   SMESHDS_GroupOnFilter* me = const_cast<SMESHDS_GroupOnFilter*>( this );
369   if ( !IsUpToDate() )
370   {
371     me->setChanged();
372     if ( !updateParallel() )
373     {
374       SMDS_ElemIteratorPtr elIt = GetElements();
375       if ( elIt->more() ) {
376         // find out nb of elements to skip w/o check before the 1st OK element
377         const SMDS_MeshElement* e = me->setNbElemToSkip( elIt );
378         ++me->myMeshInfo[ e->GetEntityType() ];
379         while ( elIt->more() )
380           ++me->myMeshInfo[ elIt->next()->GetEntityType() ];
381       }
382     }
383     me->setChanged( false );
384   }
385 }
386
387 //================================================================================
388 /*!
389  * \brief Updates myElements in parallel
390  */
391 //================================================================================
392 #ifdef WITH_TBB
393
394 #include <tbb/parallel_for.h>
395 #include "tbb/enumerable_thread_specific.h"
396
397 // a predicate per a thread
398 typedef tbb::enumerable_thread_specific<SMESH_PredicatePtr> TLocalPredicat;
399
400 struct IsSatisfyParallel
401 {
402   vector< char >&     myIsElemOK;
403   SMESH_PredicatePtr  myPredicate;
404   TLocalPredicat&     myLocalPredicates;
405   IsSatisfyParallel( SMESH_PredicatePtr mainPred, TLocalPredicat& locPred, vector< char >& isOk )
406     : myIsElemOK(isOk), myPredicate( mainPred ), myLocalPredicates( locPred )
407   {}
408   void operator() ( const tbb::blocked_range<size_t>& r ) const
409   {
410     SMESH_PredicatePtr& pred = myLocalPredicates.local();
411     if ( !pred )
412     {
413       if ( r.begin() == 0 )
414         pred = myPredicate;
415       else
416         pred.reset( myPredicate->clone() );
417     }
418     for ( size_t i = r.begin(); i != r.end(); ++i )
419       myIsElemOK[ i ] = char( pred->IsSatisfy( i ));
420   }
421 };
422
423 bool SMESHDS_GroupOnFilter::updateParallel() const
424 {
425   // if ( !getenv("updateParallel"))
426   //   return false;
427   size_t nbElemsOfType = GetMesh()->GetMeshInfo().NbElements( GetType() );
428   if ( nbElemsOfType == 0 )
429     return true;
430   if ( nbElemsOfType < 1000000 )
431     return false; // no sense in parallel work
432
433   SMDS_ElemIteratorPtr elemIt = GetMesh()->elementsIterator( GetType() );
434   const int minID = elemIt->next()->GetID();
435   myPredicate->IsSatisfy( minID ); // make myPredicate fully initialized for clone()
436   SMESH_PredicatePtr clone( myPredicate->clone() );
437   if ( !clone )
438     return false;
439
440   TLocalPredicat threadPredicates;
441   threadPredicates.local() = clone;
442
443   int maxID = ( GetType() == SMDSAbs_Node ) ? GetMesh()->MaxNodeID() : GetMesh()->MaxElementID();
444   vector< char > isElemOK( 1 + maxID );
445
446   tbb::parallel_for ( tbb::blocked_range<size_t>( 0, isElemOK.size() ),
447                       IsSatisfyParallel( myPredicate, threadPredicates, isElemOK ),
448                       tbb::simple_partitioner());
449
450   SMESHDS_GroupOnFilter* me = const_cast<SMESHDS_GroupOnFilter*>( this );
451
452   int nbOkElems = 0;
453   for ( size_t i = minID; i < isElemOK.size(); ++i )
454     nbOkElems += ( isElemOK[ i ]);
455   me->myElements.resize( nbOkElems );
456
457   const SMDS_MeshElement* e;
458   size_t iElem = 0;
459   if ( GetType() == SMDSAbs_Node )
460   {
461     for ( size_t i = minID; i < isElemOK.size(); ++i )
462       if (( isElemOK[ i ] ) &&
463           ( e = GetMesh()->FindNode( i )))
464       {
465         me->myElements[ iElem++ ] = e;
466       }
467     me->myMeshInfo[ SMDSEntity_Node ] = myElements.size();
468   }
469   else
470   {
471     for ( size_t i = minID; i < isElemOK.size(); ++i )
472       if (( isElemOK[ i ] ) &&
473           ( e = GetMesh()->FindElement( i )) &&
474           ( e->GetType() == GetType() ))
475       {
476         me->myElements[ iElem++ ] = e;
477         ++me->myMeshInfo[ e->GetEntityType() ];
478       }
479   }
480   me->myElementsOK = ( iElem < nbElemsOfType );
481   if ( !myElementsOK )
482     clearVector( me->myElements ); // all elements satisfy myPredicate
483   else
484     me->myElements.resize( iElem );
485
486   me->setChanged( false );
487   return true;
488 }
489 #else
490
491 bool SMESHDS_GroupOnFilter::updateParallel() const
492 {
493   return false;
494 }
495
496 #endif
497
498 //================================================================================
499 /*!
500  * \brief Sets myMeshModifTime and clear fields according to modification state
501  */
502 //================================================================================
503
504 void SMESHDS_GroupOnFilter::setChanged(bool changed)
505 {
506   myMeshModifTime = GetMesh()->GetMTime();
507   if ( changed && myMeshModifTime != 0 )
508     --myMeshModifTime;
509   if ( changed ) {
510     clearVector( myElements );
511     myElementsOK = false;
512     myNbElemToSkip = 0;
513     myMeshInfo.assign( SMDSEntity_Last, 0 );
514   }
515 }
516
517 //================================================================================
518 /*!
519  * \brief Sets myNbElemToSkip
520  *  \param okElemIt - iterator on OK elements
521  *  \retval const SMDS_MeshElement* - the first OK element
522  */
523 //================================================================================
524
525 const SMDS_MeshElement*
526 SMESHDS_GroupOnFilter::setNbElemToSkip( SMDS_ElemIteratorPtr& okElemIt )
527 {
528   // find out nb of elements to skip w/o check before the 1st OK element
529   const SMDS_MeshElement* firstOkElem = okElemIt->next();
530   if ( myNbElemToSkip == 0 )
531   {
532     SMDS_ElemIteratorPtr elemIt = GetMesh()->elementsIterator( GetType() );
533     myNbElemToSkip = 0;
534     while ( elemIt->next() != firstOkElem )
535       ++myNbElemToSkip;
536   }
537   return firstOkElem;
538 }
539
540 //================================================================================
541 /*!
542  * \brief Return elements before mesh compacting
543  */
544 //================================================================================
545
546 SMDS_ElemIteratorPtr SMESHDS_GroupOnFilter::getElements()
547 {
548   return boost::make_shared< SMDS_ElementVectorIterator >( myElements.begin(), myElements.end() );
549 }
550
551 //================================================================================
552 /*!
553  * \brief clear myElements before re-filling after mesh compacting
554  */
555 //================================================================================
556
557 void SMESHDS_GroupOnFilter::tmpClear()
558 {
559   std::vector< const SMDS_MeshElement*> newElems( myElements.size() );
560   myElements.swap( newElems );
561   myElements.clear();
562 }
563
564 //================================================================================
565 /*!
566  * \brief Re-fill myElements after mesh compacting
567  */
568 //================================================================================
569
570 void SMESHDS_GroupOnFilter::add( const SMDS_MeshElement* element )
571 {
572   myElements.push_back( element );
573 }