Salome HOME
Copyright update 2022
[modules/smesh.git] / src / SMESHDS / SMESHDS_GroupOnFilter.cxx
1 // Copyright (C) 2007-2022  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 smIdType 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 smIdType 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     bool                              myFoundElemsChecked;
151
152     TIterator( const SMESH_PredicatePtr&         filter,
153                SMDS_ElemIteratorPtr&             elems,
154                size_t                            nbToFind,
155                size_t                            totalNb,
156                vector< const SMDS_MeshElement*>& foundElems,
157                bool &                            foundElemsOK):
158       myPredicate( filter ),
159       myElemIt( elems ),
160       myNextElem( 0 ),
161       myNbToFind( nbToFind ),
162       myNbFound( 0 ),
163       myTotalNb( totalNb ),
164       myFoundElems( foundElems ),
165       myFoundElemsOK( foundElemsOK ),
166       myFoundElemsChecked( false )
167     {
168       myFoundElemsOK = false;
169       next();
170     }
171     ~TIterator()
172     {
173       if ( !myFoundElemsChecked && !myFoundElemsOK )
174         clearVector( myFoundElems );
175     }
176     virtual bool more()
177     {
178       return myNextElem;
179     }
180     virtual const SMDS_MeshElement* next()
181     {
182       const SMDS_MeshElement* res = myNextElem;
183       myNbFound += bool( res );
184       myNextElem = 0;
185       if ( myNbFound < myNbToFind )
186       {
187         while ( myElemIt->more() && !myNextElem )
188         {
189           myNextElem = myElemIt->next();
190           if ( !myPredicate->IsSatisfy( myNextElem->GetID() ))
191             myNextElem = 0;
192         }
193         if ( myNextElem )
194           myFoundElems.push_back( myNextElem );
195         else
196           keepOrClearElemVec();
197       }
198       else
199       {
200         keepOrClearElemVec();
201       }
202       return res;
203     }
204     void keepOrClearElemVec()
205     {
206       if ( myNbFound == myTotalNb )
207       {
208         myFoundElemsOK = false; // all elems are OK, no need to keep them
209       }
210       else
211       {
212         // nb of bytes used for myFoundElems
213         size_t vecMemSize = myFoundElems.size() * sizeof( SMDS_MeshElement* ) / sizeof(char);
214         size_t aMB = 1024 * 1024;
215         if ( vecMemSize < aMB )
216         {
217           myFoundElemsOK = true; // < 1 MB - do not clear
218         }
219         else
220         {
221           int freeRamMB = SMDS_Mesh::CheckMemory( /*doNotRaise=*/true );
222           if ( freeRamMB < 0 )
223             myFoundElemsOK = true; // hope it's OK
224           else
225             myFoundElemsOK = ( freeRamMB * aMB > 10 * vecMemSize );
226         }
227       }
228       if ( !myFoundElemsOK )
229         clearVector( myFoundElems );
230
231       myFoundElemsChecked = true; // in destructor: not to clearVector() which may already die
232     }
233   };
234
235   struct TEmptyIterator : public SMDS_ElemIterator
236   {
237     virtual bool more()                    { return false; }
238     virtual const SMDS_MeshElement* next() { return 0; }
239   };
240 }
241
242 //================================================================================
243 /*!
244  * \brief Return iterator on all elements
245  */
246 //================================================================================
247
248 SMDS_ElemIteratorPtr SMESHDS_GroupOnFilter::GetElements() const
249 {
250   size_t nbToFind = std::numeric_limits<size_t>::max();
251   size_t totalNb  = GetMesh()->GetMeshInfo().NbElements( GetType() );
252
253   SMDS_ElemIteratorPtr elemIt; // iterator on all elements to initialize TIterator
254   if ( myPredicate )
255   {
256     myPredicate->SetMesh( GetMesh() ); // hope myPredicate updates self here if necessary
257
258     if ( !IsUpToDate() )
259       updateParallel();
260
261     elemIt = GetMesh()->elementsIterator( GetType() );
262     if ( IsUpToDate() )
263     {
264       if ( myElementsOK )
265         return SMDS_ElemIteratorPtr( new SMDS_ElementVectorIterator( myElements.begin(),
266                                                                      myElements.end() ));
267       nbToFind = Extent();
268       if ( nbToFind == totalNb )
269         return elemIt; // all elements are OK
270       for ( size_t i = 0; i < myNbElemToSkip; ++i )
271         elemIt->next(); // skip w/o check
272     }
273   }
274   else
275   {
276     elemIt = SMDS_ElemIteratorPtr( new TEmptyIterator );
277   }
278
279   // the iterator fills myElements if all elements are checked
280   SMESHDS_GroupOnFilter* me = const_cast<SMESHDS_GroupOnFilter*>( this );
281   return SMDS_ElemIteratorPtr
282     ( new TIterator( myPredicate, elemIt, nbToFind, totalNb, me->myElements, me->myElementsOK ));
283 }
284
285 //================================================================================
286 /*!
287  * \brief Return info on sub-types of elements
288  */
289 //================================================================================
290
291 std::vector< smIdType > SMESHDS_GroupOnFilter::GetMeshInfo() const
292 {
293   update();
294   return myMeshInfo;
295 }
296
297 //================================================================================
298 /*!
299  * \brief Fill ids of elements. And return their number.
300  *       \a ids must be pre-allocated using nb of elements of type == GetType()
301  */
302 //================================================================================
303
304 int SMESHDS_GroupOnFilter::getElementIds( void* ids, size_t idSize ) const
305 {
306   SMESHDS_GroupOnFilter* me = const_cast<SMESHDS_GroupOnFilter*>( this );
307
308   if ( !IsUpToDate() )
309     me->setChanged();
310     
311   char* curID = (char*) ids;
312   SMDS_ElemIteratorPtr elIt = GetElements();
313   if ( elIt->more() )
314   {
315     if ( IsUpToDate() )
316     {
317       for ( ; elIt->more(); curID += idSize )
318         (*(smIdType*) curID) = elIt->next()->GetID();
319     }
320     else
321     {
322       // find out nb of elements to skip w/o check before the 1st OK element
323       const SMDS_MeshElement* firstOkElem = me->setNbElemToSkip( elIt );
324
325       me->myMeshInfo.assign( SMDSEntity_Last, 0 );
326       me->myMeshInfo[ firstOkElem->GetEntityType() ]++;
327
328       (*(smIdType*) curID) = firstOkElem->GetID();
329       for ( curID += idSize; elIt->more(); curID += idSize )
330       {
331         const SMDS_MeshElement* e = elIt->next();
332         (*(smIdType*) curID) = e->GetID();
333         me->myMeshInfo[ e->GetEntityType() ]++;
334       }
335     }
336   }
337   me->setChanged( false );
338
339   return ( curID - (char*)ids ) / idSize;
340 }
341
342 //================================================================================
343 /*!
344  * \brief Return a value allowing to find out if a group has changed or not
345  */
346 //================================================================================
347
348 int SMESHDS_GroupOnFilter::GetTic() const
349 {
350   return GetMesh()->GetMTime() * myPredicateTic;
351 }
352
353 //================================================================================
354 /*!
355  * \brief Return false if update() is needed
356  */
357 //================================================================================
358
359 bool SMESHDS_GroupOnFilter::IsUpToDate() const
360 {
361   return !( myMeshModifTime < GetMesh()->GetMTime() );
362 }
363
364 //================================================================================
365 /*!
366  * \brief Updates myElements if necessary
367  */
368 //================================================================================
369
370 void SMESHDS_GroupOnFilter::update() const
371 {
372   SMESHDS_GroupOnFilter* me = const_cast<SMESHDS_GroupOnFilter*>( this );
373   if ( !IsUpToDate() )
374   {
375     me->setChanged();
376     if ( !updateParallel() )
377     {
378       SMDS_ElemIteratorPtr elIt = GetElements();
379       if ( elIt->more() ) {
380         // find out nb of elements to skip w/o check before the 1st OK element
381         const SMDS_MeshElement* e = me->setNbElemToSkip( elIt );
382         ++me->myMeshInfo[ e->GetEntityType() ];
383         while ( elIt->more() )
384           ++me->myMeshInfo[ elIt->next()->GetEntityType() ];
385       }
386     }
387     me->setChanged( false );
388   }
389 }
390
391 //================================================================================
392 /*!
393  * \brief Updates myElements in parallel
394  */
395 //================================================================================
396 #ifdef WITH_TBB
397
398 #ifdef WIN32
399 // See https://docs.microsoft.com/en-gb/cpp/porting/modifying-winver-and-win32-winnt?view=vs-2019
400 // Windows 10 = 0x0A00  
401 #define WINVER 0x0A00
402 #define _WIN32_WINNT 0x0A00
403
404 #endif
405
406 #include <tbb/parallel_for.h>
407 #include "tbb/enumerable_thread_specific.h"
408
409 // a predicate per a thread
410 typedef tbb::enumerable_thread_specific<SMESH_PredicatePtr> TLocalPredicat;
411
412 struct IsSatisfyParallel
413 {
414   vector< char >&     myIsElemOK;
415   SMESH_PredicatePtr  myPredicate;
416   TLocalPredicat&     myLocalPredicates;
417   IsSatisfyParallel( SMESH_PredicatePtr mainPred, TLocalPredicat& locPred, vector< char >& isOk )
418     : myIsElemOK(isOk), myPredicate( mainPred ), myLocalPredicates( locPred )
419   {}
420   void operator() ( const tbb::blocked_range<size_t>& r ) const
421   {
422     SMESH_PredicatePtr& pred = myLocalPredicates.local();
423     if ( !pred )
424     {
425       if ( r.begin() == 0 )
426         pred = myPredicate;
427       else
428         pred.reset( myPredicate->clone() );
429     }
430     for ( size_t i = r.begin(); i != r.end(); ++i )
431       myIsElemOK[ i ] = char( pred->IsSatisfy( i ));
432   }
433 };
434
435 bool SMESHDS_GroupOnFilter::updateParallel() const
436 {
437   // if ( !getenv("updateParallel"))
438   //   return false;
439   size_t nbElemsOfType = GetMesh()->GetMeshInfo().NbElements( GetType() );
440   if ( nbElemsOfType == 0 )
441     return true;
442   if ( nbElemsOfType < 1000000 )
443     return false; // no sense in parallel work
444
445   SMDS_ElemIteratorPtr elemIt = GetMesh()->elementsIterator( GetType() );
446   const smIdType minID = elemIt->next()->GetID();
447   myPredicate->IsSatisfy( minID ); // make myPredicate fully initialized for clone()
448   SMESH_PredicatePtr clone( myPredicate->clone() );
449   if ( !clone )
450     return false;
451
452   TLocalPredicat threadPredicates;
453   threadPredicates.local() = clone;
454
455   smIdType maxID = ( GetType() == SMDSAbs_Node ) ? GetMesh()->MaxNodeID() : GetMesh()->MaxElementID();
456   vector< char > isElemOK( 1 + maxID );
457
458   tbb::parallel_for ( tbb::blocked_range<size_t>( 0, isElemOK.size() ),
459                       IsSatisfyParallel( myPredicate, threadPredicates, isElemOK ),
460                       tbb::simple_partitioner());
461
462   SMESHDS_GroupOnFilter* me = const_cast<SMESHDS_GroupOnFilter*>( this );
463
464   int nbOkElems = 0;
465   for ( size_t i = minID; i < isElemOK.size(); ++i )
466     nbOkElems += ( isElemOK[ i ]);
467   me->myElements.resize( nbOkElems );
468
469   const SMDS_MeshElement* e;
470   size_t iElem = 0;
471   if ( GetType() == SMDSAbs_Node )
472   {
473     for ( size_t i = minID; i < isElemOK.size(); ++i )
474       if (( isElemOK[ i ] ) &&
475           ( e = GetMesh()->FindNode( i )))
476       {
477         me->myElements[ iElem++ ] = e;
478       }
479     me->myMeshInfo[ SMDSEntity_Node ] = myElements.size();
480   }
481   else
482   {
483     for ( size_t i = minID; i < isElemOK.size(); ++i )
484       if (( isElemOK[ i ] ) &&
485           ( e = GetMesh()->FindElement( i )) &&
486           ( e->GetType() == GetType() ))
487       {
488         me->myElements[ iElem++ ] = e;
489         ++me->myMeshInfo[ e->GetEntityType() ];
490       }
491   }
492   me->myElementsOK = ( iElem < nbElemsOfType );
493   if ( !myElementsOK )
494     clearVector( me->myElements ); // all elements satisfy myPredicate
495   else
496     me->myElements.resize( iElem );
497
498   me->setChanged( false );
499   return true;
500 }
501 #else
502
503 bool SMESHDS_GroupOnFilter::updateParallel() const
504 {
505   return false;
506 }
507
508 #endif
509
510 //================================================================================
511 /*!
512  * \brief Sets myMeshModifTime and clear fields according to modification state
513  */
514 //================================================================================
515
516 void SMESHDS_GroupOnFilter::setChanged(bool changed)
517 {
518   myMeshModifTime = GetMesh()->GetMTime();
519   if ( changed && myMeshModifTime != 0 )
520     --myMeshModifTime;
521   if ( changed ) {
522     clearVector( myElements );
523     myElementsOK = false;
524     myNbElemToSkip = 0;
525     myMeshInfo.assign( SMDSEntity_Last, 0 );
526   }
527 }
528
529 //================================================================================
530 /*!
531  * \brief Sets myNbElemToSkip
532  *  \param okElemIt - iterator on OK elements
533  *  \retval const SMDS_MeshElement* - the first OK element
534  */
535 //================================================================================
536
537 const SMDS_MeshElement*
538 SMESHDS_GroupOnFilter::setNbElemToSkip( SMDS_ElemIteratorPtr& okElemIt )
539 {
540   // find out nb of elements to skip w/o check before the 1st OK element
541   const SMDS_MeshElement* firstOkElem = okElemIt->next();
542   if ( myNbElemToSkip == 0 )
543   {
544     SMDS_ElemIteratorPtr elemIt = GetMesh()->elementsIterator( GetType() );
545     myNbElemToSkip = 0;
546     while ( elemIt->next() != firstOkElem )
547       ++myNbElemToSkip;
548   }
549   return firstOkElem;
550 }
551
552 //================================================================================
553 /*!
554  * \brief Return elements before mesh compacting
555  */
556 //================================================================================
557
558 SMDS_ElemIteratorPtr SMESHDS_GroupOnFilter::getElements()
559 {
560   return boost::make_shared< SMDS_ElementVectorIterator >( myElements.begin(), myElements.end() );
561 }
562
563 //================================================================================
564 /*!
565  * \brief clear myElements before re-filling after mesh compacting
566  */
567 //================================================================================
568
569 void SMESHDS_GroupOnFilter::tmpClear()
570 {
571   std::vector< const SMDS_MeshElement*> newElems( myElements.size() );
572   myElements.swap( newElems );
573   myElements.clear();
574 }
575
576 //================================================================================
577 /*!
578  * \brief Re-fill myElements after mesh compacting
579  */
580 //================================================================================
581
582 void SMESHDS_GroupOnFilter::add( const SMDS_MeshElement* element )
583 {
584   myElements.push_back( element );
585 }