Salome HOME
IPAL53401: BelongToGeom is very long on multiple lines
[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 "SMESHDS_Mesh.hxx"
30
31 #include <numeric>
32 #include <limits>
33
34 using namespace std;
35
36 //#undef WITH_TBB
37
38 //=============================================================================
39 /*!
40  * Creates a group based on thePredicate
41  */
42 //=============================================================================
43
44 SMESHDS_GroupOnFilter::SMESHDS_GroupOnFilter (const int                 theID,
45                                               const SMESHDS_Mesh*       theMesh,
46                                               const SMDSAbs_ElementType theType,
47                                               const SMESH_PredicatePtr& thePredicate)
48   : SMESHDS_GroupBase(theID,theMesh,theType),
49     myMeshInfo( SMDSEntity_Last, 0 ),
50     myMeshModifTime(0),
51     myPredicateTic(0),
52     myNbElemToSkip(0)
53 {
54   SetPredicate( thePredicate );
55 }
56
57 //================================================================================
58 /*!
59  * \brief Sets a new predicate
60  */
61 //================================================================================
62
63 void SMESHDS_GroupOnFilter::SetPredicate( const SMESH_PredicatePtr& thePredicate )
64 {
65   myPredicate = thePredicate;
66   ++myPredicateTic;
67   setChanged();
68   if ( myPredicate )
69     myPredicate->SetMesh( GetMesh() );
70 }
71
72 //================================================================================
73 /*!
74  * \brief Returns nb of elements
75  */
76 //================================================================================
77
78 int SMESHDS_GroupOnFilter::Extent() const
79 {
80   update();
81   return std::accumulate( myMeshInfo.begin(), myMeshInfo.end(), 0 );
82 }
83
84 //================================================================================
85 /*!
86  * \brief Checks emptyness
87  */
88 //================================================================================
89
90 bool SMESHDS_GroupOnFilter::IsEmpty()
91 {
92   if ( IsUpToDate() )
93   {
94     return ( Extent() == 0 );
95   }
96   else // not up-to-date
97   {
98     setChanged();
99     SMDS_ElemIteratorPtr okElemIt = GetElements();
100     if ( !okElemIt->more() )
101     {
102       // no satisfying elements
103       setChanged( false );
104     }
105     else
106     {
107       return false;
108     }
109   }
110   return true;
111 }
112
113 //================================================================================
114 /*!
115  * \brief Checks if the element belongs to the group
116  */
117 //================================================================================
118
119 bool SMESHDS_GroupOnFilter::Contains (const int theID)
120 {
121   return myPredicate && myPredicate->IsSatisfy( theID );
122 }
123
124 //================================================================================
125 /*!
126  * \brief Checks if the element belongs to the group
127  */
128 //================================================================================
129
130 bool SMESHDS_GroupOnFilter::Contains (const SMDS_MeshElement* elem)
131 {
132   return myPredicate && myPredicate->IsSatisfy( elem->GetID() );
133 }
134
135 //================================================================================
136 namespace // Iterator
137 {
138   struct TIterator : public SMDS_ElemIterator
139   {
140     SMESH_PredicatePtr                myPredicate;
141     SMDS_ElemIteratorPtr              myElemIt;
142     const SMDS_MeshElement*           myNextElem;
143     size_t                            myNbToFind, myNbFound, myTotalNb;
144     vector< const SMDS_MeshElement*>& myFoundElems;
145     bool &                            myFoundElemsOK;
146
147     TIterator( const SMESH_PredicatePtr&         filter,
148                SMDS_ElemIteratorPtr&             elems,
149                size_t                            nbToFind,
150                size_t                            totalNb,
151                vector< const SMDS_MeshElement*>& foundElems,
152                bool &                            foundElemsOK):
153       myPredicate( filter ),
154       myElemIt( elems ),
155       myNextElem( 0 ),
156       myNbToFind( nbToFind ),
157       myNbFound( 0 ),
158       myTotalNb( totalNb ),
159       myFoundElems( foundElems ),
160       myFoundElemsOK( foundElemsOK )
161     {
162       myFoundElemsOK = false;
163       next();
164     }
165     ~TIterator()
166     {
167       if ( !myFoundElemsOK )
168         clearVector( myFoundElems );
169     }
170     virtual bool more()
171     {
172       return myNextElem;
173     }
174     virtual const SMDS_MeshElement* next()
175     {
176       const SMDS_MeshElement* res = myNextElem;
177       myNbFound += bool( res );
178       myNextElem = 0;
179       if ( myNbFound < myNbToFind )
180       {
181         while ( myElemIt->more() && !myNextElem )
182         {
183           myNextElem = myElemIt->next();
184           if ( !myPredicate->IsSatisfy( myNextElem->GetID() ))
185             myNextElem = 0;
186         }
187         if ( myNextElem )
188           myFoundElems.push_back( myNextElem );
189         else
190           keepOrClearElemVec();
191       }
192       else
193       {
194         keepOrClearElemVec();
195       }
196       return res;
197     }
198     void keepOrClearElemVec()
199     {
200       if ( myNbFound == myTotalNb )
201       {
202         myFoundElemsOK = false; // all elems are OK, no need to keep them
203       }
204       else
205       {
206         // nb of bytes used for myFoundElems
207         size_t vecMemSize = myFoundElems.size() * sizeof( SMDS_MeshElement* ) / sizeof(char);
208         size_t aMB = 1024 * 1024;
209         if ( vecMemSize < aMB )
210         {
211           myFoundElemsOK = true; // < 1 MB - do not clear
212         }
213         else
214         {
215           int freeRamMB = SMDS_Mesh::CheckMemory( /*doNotRaise=*/true );
216           if ( freeRamMB < 0 )
217             myFoundElemsOK = true; // hope it's OK
218           else
219             myFoundElemsOK = ( freeRamMB * aMB > 10 * vecMemSize );
220         }
221       }
222       if ( !myFoundElemsOK )
223         clearVector( myFoundElems );
224     }
225   };
226
227   struct TEmptyIterator : public SMDS_ElemIterator
228   {
229     virtual bool more()                    { return false; }
230     virtual const SMDS_MeshElement* next() { return 0; }
231   };
232 }
233
234 //================================================================================
235 /*!
236  * \brief Return iterator on all elements
237  */
238 //================================================================================
239
240 SMDS_ElemIteratorPtr SMESHDS_GroupOnFilter::GetElements() const
241 {
242   size_t nbToFind = std::numeric_limits<size_t>::max();
243   size_t totalNb  = GetMesh()->GetMeshInfo().NbElements( GetType() );
244
245   SMDS_ElemIteratorPtr elemIt; // iterator on all elements to initialize TIterator
246   if ( myPredicate )
247   {
248     myPredicate->SetMesh( GetMesh() ); // hope myPredicate updates self here if necessary
249
250     if ( !IsUpToDate() )
251       updateParallel();
252
253     elemIt = GetMesh()->elementsIterator( GetType() );
254     if ( IsUpToDate() )
255     {
256       if ( myElementsOK )
257         return SMDS_ElemIteratorPtr( new SMDS_ElementVectorIterator( myElements.begin(),
258                                                                      myElements.end() ));
259       nbToFind = Extent();
260       if ( nbToFind == totalNb )
261         return elemIt; // all elements are OK
262       for ( size_t i = 0; i < myNbElemToSkip; ++i )
263         elemIt->next(); // skip w/o check
264     }
265   }
266   else
267   {
268     elemIt = SMDS_ElemIteratorPtr( new TEmptyIterator );
269   }
270
271   // the iterator fills myElements if all elements are checked
272   SMESHDS_GroupOnFilter* me = const_cast<SMESHDS_GroupOnFilter*>( this );
273   return SMDS_ElemIteratorPtr
274     ( new TIterator( myPredicate, elemIt, nbToFind, totalNb, me->myElements, me->myElementsOK ));
275 }
276
277 //================================================================================
278 /*!
279  * \brief Return info on sub-types of elements
280  */
281 //================================================================================
282
283 std::vector< int > SMESHDS_GroupOnFilter::GetMeshInfo() const
284 {
285   update();
286   return myMeshInfo;
287 }
288
289 //================================================================================
290 /*!
291  * \brief Fill ids of elements. And return their number.
292  *       \a ids must be pre-allocated using nb of elements of type == GetType()
293  */
294 //================================================================================
295
296 int SMESHDS_GroupOnFilter::getElementIds( void* ids, size_t idSize ) const
297 {
298   SMESHDS_GroupOnFilter* me = const_cast<SMESHDS_GroupOnFilter*>( this );
299
300   if ( !IsUpToDate() )
301     me->setChanged();
302     
303   char* curID = (char*) ids;
304   SMDS_ElemIteratorPtr elIt = GetElements();
305   if ( elIt->more() )
306   {
307     if ( IsUpToDate() )
308     {
309       for ( ; elIt->more(); curID += idSize )
310         (*(int*) curID) = elIt->next()->GetID();
311     }
312     else
313     {
314       // find out nb of elements to skip w/o check before the 1st OK element
315       const SMDS_MeshElement* firstOkElem = me->setNbElemToSkip( elIt );
316
317       me->myMeshInfo.assign( SMDSEntity_Last, 0 );
318       me->myMeshInfo[ firstOkElem->GetEntityType() ]++;
319
320       (*(int*) curID) = firstOkElem->GetID();
321       for ( curID += idSize; elIt->more(); curID += idSize )
322       {
323         const SMDS_MeshElement* e = elIt->next();
324         (*(int*) curID) = e->GetID();
325         me->myMeshInfo[ e->GetEntityType() ]++;
326       }
327     }
328   }
329   me->setChanged( false );
330
331   return ( curID - (char*)ids ) / idSize;
332 }
333
334 //================================================================================
335 /*!
336  * \brief Return a value allowing to find out if a group has changed or not
337  */
338 //================================================================================
339
340 int SMESHDS_GroupOnFilter::GetTic() const
341 {
342   return GetMesh()->GetMTime() * myPredicateTic;
343 }
344
345 //================================================================================
346 /*!
347  * \brief Return false if update() is needed
348  */
349 //================================================================================
350
351 bool SMESHDS_GroupOnFilter::IsUpToDate() const
352 {
353   return !( myMeshModifTime < GetMesh()->GetMTime() );
354 }
355
356 //================================================================================
357 /*!
358  * \brief Updates myElements if necessary
359  */
360 //================================================================================
361
362 void SMESHDS_GroupOnFilter::update() const
363 {
364   SMESHDS_GroupOnFilter* me = const_cast<SMESHDS_GroupOnFilter*>( this );
365   if ( !IsUpToDate() )
366   {
367     me->setChanged();
368     if ( !updateParallel() )
369     {
370       SMDS_ElemIteratorPtr elIt = GetElements();
371       if ( elIt->more() ) {
372         // find out nb of elements to skip w/o check before the 1st OK element
373         const SMDS_MeshElement* e = me->setNbElemToSkip( elIt );
374         ++me->myMeshInfo[ e->GetEntityType() ];
375         while ( elIt->more() )
376           ++me->myMeshInfo[ elIt->next()->GetEntityType() ];
377       }
378     }
379     me->setChanged( false );
380   }
381 }
382
383 //================================================================================
384 /*!
385  * \brief Updates myElements in parallel
386  */
387 //================================================================================
388 #ifdef WITH_TBB
389
390 #include <tbb/parallel_for.h>
391 #include "tbb/enumerable_thread_specific.h"
392
393 // a predicate per a thread
394 typedef tbb::enumerable_thread_specific<SMESH_PredicatePtr> TLocalPredicat;
395
396 struct IsSatisfyParallel
397 {
398   vector< char >&     myIsElemOK;
399   SMESH_PredicatePtr  myPredicate;
400   TLocalPredicat&     myLocalPredicates;
401   IsSatisfyParallel( SMESH_PredicatePtr mainPred, TLocalPredicat& locPred, vector< char >& isOk )
402     : myIsElemOK(isOk), myPredicate( mainPred ), myLocalPredicates( locPred )
403   {}
404   void operator() ( const tbb::blocked_range<size_t>& r ) const
405   {
406     SMESH_PredicatePtr& pred = myLocalPredicates.local();
407     if ( !pred )
408     {
409       if ( r.begin() == 0 )
410         pred = myPredicate;
411       else
412         pred.reset( myPredicate->clone() );
413     }
414     for ( size_t i = r.begin(); i != r.end(); ++i )
415       myIsElemOK[ i ] = char( pred->IsSatisfy( i ));
416   }
417 };
418
419 bool SMESHDS_GroupOnFilter::updateParallel() const
420 {
421   // if ( !getenv("updateParallel"))
422   //   return false;
423   size_t nbElemsOfType = GetMesh()->GetMeshInfo().NbElements( GetType() );
424   if ( nbElemsOfType == 0 )
425     return true;
426   if ( nbElemsOfType < 1000000 )
427     return false; // no sense in parallel work
428
429   SMDS_ElemIteratorPtr elemIt = GetMesh()->elementsIterator( GetType() );
430   const int minID = elemIt->next()->GetID();
431   myPredicate->IsSatisfy( minID ); // make myPredicate fully initialized for clone()
432   SMESH_PredicatePtr clone( myPredicate->clone() );
433   if ( !clone )
434     return false;
435
436   TLocalPredicat threadPredicates;
437   threadPredicates.local() = clone;
438
439   int maxID = ( GetType() == SMDSAbs_Node ) ? GetMesh()->MaxNodeID() : GetMesh()->MaxElementID();
440   vector< char > isElemOK( 1 + maxID );
441
442   tbb::parallel_for ( tbb::blocked_range<size_t>( 0, isElemOK.size() ),
443                       IsSatisfyParallel( myPredicate, threadPredicates, isElemOK ),
444                       tbb::simple_partitioner());
445
446   SMESHDS_GroupOnFilter* me = const_cast<SMESHDS_GroupOnFilter*>( this );
447
448   int nbOkElems = 0;
449   for ( size_t i = minID; i < isElemOK.size(); ++i )
450     nbOkElems += ( isElemOK[ i ]);
451   me->myElements.resize( nbOkElems );
452
453   const SMDS_MeshElement* e;
454   size_t iElem = 0;
455   if ( GetType() == SMDSAbs_Node )
456   {
457     for ( size_t i = minID; i < isElemOK.size(); ++i )
458       if (( isElemOK[ i ] ) &&
459           ( e = GetMesh()->FindNode( i )))
460       {
461         me->myElements[ iElem++ ] = e;
462       }
463     me->myMeshInfo[ SMDSEntity_Node ] = myElements.size();
464   }
465   else
466   {
467     for ( size_t i = minID; i < isElemOK.size(); ++i )
468       if (( isElemOK[ i ] ) &&
469           ( e = GetMesh()->FindElement( i )) &&
470           ( e->GetType() == GetType() ))
471       {
472         me->myElements[ iElem++ ] = e;
473         ++me->myMeshInfo[ e->GetEntityType() ];
474       }
475   }
476   me->myElementsOK = ( iElem < nbElemsOfType );
477   if ( !myElementsOK )
478     clearVector( me->myElements ); // all elements satisfy myPredicate
479   else
480     me->myElements.resize( iElem );
481
482   me->setChanged( false );
483   return true;
484 }
485 #else
486
487 bool SMESHDS_GroupOnFilter::updateParallel() const
488 {
489   return false;
490 }
491
492 #endif
493
494 //================================================================================
495 /*!
496  * \brief Sets myMeshModifTime and clear fields according to modification state
497  */
498 //================================================================================
499
500 void SMESHDS_GroupOnFilter::setChanged(bool changed)
501 {
502   myMeshModifTime = GetMesh()->GetMTime();
503   if ( changed && myMeshModifTime != 0 )
504     --myMeshModifTime;
505   if ( changed ) {
506     clearVector( myElements );
507     myElementsOK = false;
508     myNbElemToSkip = 0;
509     myMeshInfo.assign( SMDSEntity_Last, 0 );
510   }
511 }
512
513 //================================================================================
514 /*!
515  * \brief Sets myNbElemToSkip
516  *  \param okElemIt - iterator on OK elements
517  *  \retval const SMDS_MeshElement* - the first OK element
518  */
519 //================================================================================
520
521 const SMDS_MeshElement*
522 SMESHDS_GroupOnFilter::setNbElemToSkip( SMDS_ElemIteratorPtr& okElemIt )
523 {
524   // find out nb of elements to skip w/o check before the 1st OK element
525   const SMDS_MeshElement* firstOkElem = okElemIt->next();
526   if ( myNbElemToSkip == 0 )
527   {
528     SMDS_ElemIteratorPtr elemIt = GetMesh()->elementsIterator( GetType() );
529     myNbElemToSkip = 0;
530     while ( elemIt->next() != firstOkElem )
531       ++myNbElemToSkip;
532   }
533   return firstOkElem;
534 }