Salome HOME
23189: EDF 11603 - Dyssymetry in meshing
[modules/smesh.git] / src / StdMeshers / StdMeshers_NumberOfSegments.cxx
1 // Copyright (C) 2007-2015  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 //  SMESH SMESH : implementaion of SMESH idl descriptions
24 //  File   : StdMeshers_NumberOfSegments.cxx
25 //           Moved here from SMESH_NumberOfSegments.cxx
26 //  Author : Paul RASCLE, EDF
27 //  Module : SMESH
28 //
29 #include "StdMeshers_NumberOfSegments.hxx"
30
31 #include "StdMeshers_Distribution.hxx"
32 #include "SMESHDS_SubMesh.hxx"
33 #include "SMESH_Mesh.hxx"
34 #include "SMESH_Comment.hxx"
35
36 #include <ExprIntrp_GenExp.hxx>
37 #include <Expr_Array1OfNamedUnknown.hxx>
38 #include <Expr_NamedUnknown.hxx>
39 #include <TColStd_Array1OfReal.hxx>
40 #include <TCollection_AsciiString.hxx>
41 #include <TopExp.hxx>
42 #include <TopTools_IndexedMapOfShape.hxx>
43
44 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
45 #define NO_CAS_CATCH
46 #endif
47
48 #include <Standard_Failure.hxx>
49
50 #ifdef NO_CAS_CATCH
51 #include <Standard_ErrorHandler.hxx>
52 #endif
53
54 #include <Basics_Utils.hxx>
55
56 using namespace StdMeshers;
57 using namespace std;
58
59 const double PRECISION = 1e-7;
60
61 //=============================================================================
62 /*!
63  *  
64  */
65 //=============================================================================
66
67 StdMeshers_NumberOfSegments::StdMeshers_NumberOfSegments(int         hypId,
68                                                          int         studyId,
69                                                          SMESH_Gen * gen)
70   : SMESH_Hypothesis(hypId, studyId, gen),
71     _numberOfSegments(15),//issue 19923
72     _distrType(DT_Regular),
73     _scaleFactor(1.),
74     _convMode(1)  //cut negative by default
75 {
76   _name = "NumberOfSegments";
77   _param_algo_dim = 1;
78 }
79
80 //=============================================================================
81 /*!
82  *  
83  */
84 //=============================================================================
85
86 StdMeshers_NumberOfSegments::~StdMeshers_NumberOfSegments()
87 {
88 }
89
90 //=============================================================================
91 /*!
92  *  
93  */
94 //=============================================================================
95 const vector<double>&
96 StdMeshers_NumberOfSegments::BuildDistributionExpr( const char* expr,int nbSeg,int conv )
97   throw ( SALOME_Exception )
98 {
99   if( !buildDistribution( TCollection_AsciiString( ( Standard_CString )expr ), conv, 0.0, 1.0, nbSeg, _distr, 1E-4 ) )
100     _distr.resize( 0 );
101   return _distr;
102 }
103
104 const vector<double>&
105 StdMeshers_NumberOfSegments::BuildDistributionTab( const vector<double>& tab,
106                                                    int nbSeg,
107                                                    int conv )
108   throw ( SALOME_Exception )
109 {
110   if( !buildDistribution( tab, conv, 0.0, 1.0, nbSeg, _distr, 1E-4 ) )
111     _distr.resize( 0 );
112   return _distr;
113 }
114
115 //=============================================================================
116 /*!
117  *  
118  */
119 //=============================================================================
120
121 void StdMeshers_NumberOfSegments::SetNumberOfSegments(int segmentsNumber)
122 throw(SALOME_Exception)
123 {
124   int oldNumberOfSegments = _numberOfSegments;
125   if (segmentsNumber <= 0)
126     throw SALOME_Exception(LOCALIZED("number of segments must be positive"));
127   _numberOfSegments = segmentsNumber;
128
129   if (oldNumberOfSegments != _numberOfSegments)
130     NotifySubMeshesHypothesisModification();
131 }
132
133 //=============================================================================
134 /*!
135  *  
136  */
137 //=============================================================================
138
139 int StdMeshers_NumberOfSegments::GetNumberOfSegments() const
140 {
141   return _numberOfSegments;
142 }
143
144 //================================================================================
145 /*!
146  * 
147  */
148 //================================================================================
149
150 void StdMeshers_NumberOfSegments::SetDistrType(DistrType typ)
151   throw(SALOME_Exception)
152 {
153   if (typ < DT_Regular || typ > DT_ExprFunc)
154     throw SALOME_Exception(LOCALIZED("distribution type is out of range"));
155
156   if (typ != _distrType)
157   {
158     _distrType = typ;
159     NotifySubMeshesHypothesisModification();
160   }
161 }
162
163 //================================================================================
164 /*!
165  * 
166  */
167 //================================================================================
168
169 StdMeshers_NumberOfSegments::DistrType StdMeshers_NumberOfSegments::GetDistrType() const
170 {
171   return _distrType;
172 }
173
174 //================================================================================
175 /*!
176  * 
177  */
178 //================================================================================
179
180 void StdMeshers_NumberOfSegments::SetScaleFactor(double scaleFactor)
181   throw(SALOME_Exception)
182 {
183   if (scaleFactor < PRECISION)
184     throw SALOME_Exception(LOCALIZED("scale factor must be positive"));
185
186   if (_distrType != DT_Scale)
187     _distrType = DT_Scale;
188
189   if ( fabs(scaleFactor - 1.0) < PRECISION )
190     _distrType = DT_Regular;
191
192   if ( fabs(_scaleFactor - scaleFactor) > PRECISION )
193   {
194     _scaleFactor = scaleFactor;
195     NotifySubMeshesHypothesisModification();
196   }
197 }
198
199 //================================================================================
200 /*!
201  *
202  */
203 //================================================================================
204
205 double StdMeshers_NumberOfSegments::GetScaleFactor() const
206   throw(SALOME_Exception)
207 {
208   if (_distrType != DT_Scale)
209     throw SALOME_Exception(LOCALIZED("not a scale distribution"));
210   return _scaleFactor;
211 }
212
213 //================================================================================
214 /*!
215  *
216  */
217 //================================================================================
218
219 void StdMeshers_NumberOfSegments::SetTableFunction(const vector<double>& table)
220   throw(SALOME_Exception)
221 {
222   if (_distrType != DT_TabFunc)
223     _distrType = DT_TabFunc;
224   //throw SALOME_Exception(LOCALIZED("not a table function distribution"));
225   if ( (table.size() % 2) != 0 )
226     throw SALOME_Exception(LOCALIZED("odd size of vector of table function"));
227
228   double prev = -PRECISION;
229   bool isSame = table.size() == _table.size();
230
231   bool pos = false;
232   for ( size_t i = 0; i < table.size() / 2; i++ )
233   {
234     double par = table[i*2];
235     double val = table[i*2+1];
236     if( _convMode==0 )
237     {
238       try {
239 #ifdef NO_CAS_CATCH
240         OCC_CATCH_SIGNALS;
241 #endif
242         val = pow( 10.0, val );
243       }
244       catch(Standard_Failure) {
245         Handle(Standard_Failure) aFail = Standard_Failure::Caught();
246         throw SALOME_Exception( LOCALIZED( "invalid value"));
247         return;
248       }
249     }
250     else if( _convMode==1 && val<0.0 )
251       val = 0.0;
252
253     if ( par < 0 || par > 1)
254       throw SALOME_Exception(LOCALIZED("parameter of table function is out of range [0,1]"));
255     if ( fabs(par-prev) < PRECISION )
256       throw SALOME_Exception(LOCALIZED("two parameters are the same"));
257     if ( val < 0 )
258       throw SALOME_Exception(LOCALIZED("value of table function is not positive"));
259     if( val > PRECISION )
260       pos = true;
261     if (isSame)
262     {
263       double oldpar = _table[i*2];
264       double oldval = _table[i*2+1];
265       if ( fabs(par - oldpar) > PRECISION || fabs(val - oldval) > PRECISION )
266         isSame = false;
267     }
268     prev = par;
269   }
270
271   if( !pos )
272     throw SALOME_Exception(LOCALIZED("value of table function is not positive"));
273
274   if ( pos && !isSame )
275   {
276     _table = table;
277     NotifySubMeshesHypothesisModification();
278   }
279 }
280
281 //================================================================================
282 /*!
283  *
284  */
285 //================================================================================
286
287 const vector<double>& StdMeshers_NumberOfSegments::GetTableFunction() const
288   throw(SALOME_Exception)
289 {
290   if (_distrType != DT_TabFunc)
291     throw SALOME_Exception(LOCALIZED("not a table function distribution"));
292   return _table;
293 }
294
295 //================================================================================
296 /*! check if only 't' is unknown variable in expression
297  */
298 //================================================================================
299 bool isCorrectArg( const Handle( Expr_GeneralExpression )& expr )
300 {
301   Handle( Expr_NamedUnknown ) sub = Handle( Expr_NamedUnknown )::DownCast( expr );
302   if( !sub.IsNull() )
303     return sub->GetName()=="t";
304
305   bool res = true;
306   for( int i=1, n=expr->NbSubExpressions(); i<=n && res; i++ )
307   {
308     Handle( Expr_GeneralExpression ) sub = expr->SubExpression( i );
309     Handle( Expr_NamedUnknown ) name = Handle( Expr_NamedUnknown )::DownCast( sub );
310     if( !name.IsNull() )
311     {
312       if( name->GetName()!="t" )
313         res = false;
314     }
315     else
316       res = isCorrectArg( sub );
317   }
318   return res;
319 }
320
321 //================================================================================
322 /*! this function parses the expression 'str' in order to check if syntax is correct
323  *  ( result in 'syntax' ) and if only 't' is unknown variable in expression ( result in 'args' )
324  */
325 //================================================================================
326 bool process( const TCollection_AsciiString& str, int convMode,
327               bool& syntax, bool& args,
328               bool& non_neg, bool& non_zero,
329               bool& singulars, double& sing_point )
330 {
331   Kernel_Utils::Localizer loc;
332
333   bool parsed_ok = true;
334   Handle( ExprIntrp_GenExp ) myExpr;
335   try {
336 #ifdef NO_CAS_CATCH
337     OCC_CATCH_SIGNALS;
338 #endif
339     myExpr = ExprIntrp_GenExp::Create();
340     myExpr->Process( str.ToCString() );
341   } catch(Standard_Failure) {
342     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
343     parsed_ok = false;
344   }
345
346   syntax = false;
347   args = false;
348   if( parsed_ok && myExpr->IsDone() )
349   {
350     syntax = true;
351     args = isCorrectArg( myExpr->Expression() );
352   }
353
354   bool res = parsed_ok && syntax && args;
355   if( !res )
356     myExpr.Nullify();
357
358   non_neg = true;
359   singulars = false;
360   non_zero = false;
361
362   if( res )
363   {
364     FunctionExpr f( str.ToCString(), convMode );
365     const int max = 500;
366     for( int i=0; i<=max; i++ )
367     {
368       double t = double(i)/double(max), val;
369       if( !f.value( t, val ) )
370       {
371         sing_point = t;
372         singulars = true;
373         break;
374       }
375       if( val<0 )
376       {
377         non_neg = false;
378         break;
379       }
380       if( val>PRECISION )
381         non_zero = true;
382     }
383   }
384
385   return res && non_neg && non_zero && ( !singulars );
386 }
387
388 //================================================================================
389 /*!
390  * 
391  */
392 //================================================================================
393
394 void StdMeshers_NumberOfSegments::SetExpressionFunction(const char* expr)
395   throw(SALOME_Exception)
396 {
397   if (_distrType != DT_ExprFunc)
398     _distrType = DT_ExprFunc;
399
400   string func = CheckExpressionFunction( expr, _convMode );
401   if( _func != func )
402   {
403     _func = func;
404     NotifySubMeshesHypothesisModification();
405   }
406 }
407
408 //=======================================================================
409 //function : CheckExpressionFunction
410 //purpose  : Checks validity of  the expression of the function f(t), e.g. "sin(t)".
411 //           In case of validity returns a cleaned expression
412 //=======================================================================
413
414 std::string
415 StdMeshers_NumberOfSegments::CheckExpressionFunction( const std::string& expr,
416                                                       const int          convMode)
417     throw (SALOME_Exception)
418 {
419   // remove white spaces
420   TCollection_AsciiString str((Standard_CString)expr.c_str());
421   str.RemoveAll(' ');
422   str.RemoveAll('\t');
423   str.RemoveAll('\r');
424   str.RemoveAll('\n');
425
426   bool syntax, args, non_neg, singulars, non_zero;
427   double sing_point;
428   bool res = process( str, convMode, syntax, args, non_neg, non_zero, singulars, sing_point );
429   if( !res )
430   {
431     if( !syntax )
432       throw SALOME_Exception(SMESH_Comment("invalid expression syntax: ") << str );
433     if( !args )
434       throw SALOME_Exception(LOCALIZED("only 't' may be used as function argument"));
435     if( !non_neg )
436       throw SALOME_Exception(LOCALIZED("only non-negative function can be used"));
437     if( singulars )
438     {
439       char buf[1024];
440       sprintf( buf, "Function has singular point in %.3f", sing_point );
441       throw SALOME_Exception( buf );
442     }
443     if( !non_zero )
444       throw SALOME_Exception(LOCALIZED("f(t)=0 cannot be used"));
445   }
446  
447   return str.ToCString();
448 }
449
450 //================================================================================
451 /*!
452  * 
453  */
454 //================================================================================
455
456 const char* StdMeshers_NumberOfSegments::GetExpressionFunction() const
457   throw(SALOME_Exception)
458 {
459   if (_distrType != DT_ExprFunc)
460     throw SALOME_Exception(LOCALIZED("not an expression function distribution"));
461   return _func.c_str();
462 }
463
464 //================================================================================
465 /*!
466  * 
467  */
468 //================================================================================
469
470 void StdMeshers_NumberOfSegments::SetConversionMode( int conv )
471   throw(SALOME_Exception)
472 {
473 //   if (_distrType != DT_TabFunc && _distrType != DT_ExprFunc)
474 //     throw SALOME_Exception(LOCALIZED("not a functional distribution"));
475
476   if( conv != _convMode )
477   {
478     _convMode = conv;
479     NotifySubMeshesHypothesisModification();
480   }
481 }
482
483 //================================================================================
484 /*!
485  * 
486  */
487 //================================================================================
488
489 int StdMeshers_NumberOfSegments::ConversionMode() const
490   throw(SALOME_Exception)
491 {
492 //   if (_distrType != DT_TabFunc && _distrType != DT_ExprFunc)
493 //     throw SALOME_Exception(LOCALIZED("not a functional distribution"));
494   return _convMode;
495 }
496
497 //=============================================================================
498 /*!
499  *  
500  */
501 //=============================================================================
502
503 ostream & StdMeshers_NumberOfSegments::SaveTo(ostream & save)
504 {
505   int listSize = _edgeIDs.size();
506   save << _numberOfSegments << " " << (int)_distrType;
507   switch (_distrType)
508   {
509   case DT_Scale:
510     save << " " << _scaleFactor;
511     break;
512   case DT_TabFunc:
513     save << " " << _table.size();
514     for ( size_t i = 0; i < _table.size(); i++ )
515       save << " " << _table[i];
516     break;
517   case DT_ExprFunc:
518     save << " " << _func;
519     break;
520   case DT_Regular:
521   default:
522     break;
523   }
524
525   if (_distrType == DT_TabFunc || _distrType == DT_ExprFunc)
526     save << " " << _convMode;
527
528   if ( _distrType != DT_Regular && listSize > 0 ) {
529     save << " " << listSize;
530     for ( int i = 0; i < listSize; i++ )
531       save << " " << _edgeIDs[i];
532     save << " " << _objEntry;
533   }
534   
535   return save;
536 }
537
538 //=============================================================================
539 /*!
540  *  
541  */
542 //=============================================================================
543
544 istream & StdMeshers_NumberOfSegments::LoadFrom(istream & load)
545 {
546   bool isOK = true;
547   int a;
548
549   // read number of segments
550   isOK = (load >> a);
551   if (isOK)
552     _numberOfSegments = a;
553   else
554     load.clear(ios::badbit | load.rdstate());
555
556   // read second stored value. It can be two variants here:
557   // 1. If the hypothesis is stored in old format (nb.segments and scale factor),
558   //    we wait here the scale factor, which is double.
559   // 2. If the hypothesis is stored in new format
560   //    (nb.segments, distr.type, some other params.),
561   //    we wait here the ditribution type, which is integer
562   double scale_factor;
563   isOK = (load >> scale_factor);
564   a = (int)scale_factor;
565
566   // try to interprete ditribution type,
567   // supposing that this hypothesis was written in the new format
568   if (isOK)
569   {
570     if (a < DT_Regular || a > DT_ExprFunc)
571       _distrType = DT_Regular;
572     else
573       _distrType = (DistrType) a;
574   }
575   else
576     load.clear(ios::badbit | load.rdstate());
577
578   // parameters of distribution
579   double b;
580   switch (_distrType)
581   {
582   case DT_Scale:
583     {
584       isOK = (load >> b);
585       if (isOK)
586         _scaleFactor = b;
587       else
588       {
589         load.clear(ios::badbit | load.rdstate());
590         // this can mean, that the hypothesis is stored in old format
591         _distrType = DT_Regular;
592         _scaleFactor = scale_factor;
593       }
594     }
595     break;
596   case DT_TabFunc:
597     {
598       isOK = (load >> a);
599       if (isOK)
600       {
601         _table.resize(a, 0.);
602         for ( size_t i=0; i < _table.size(); i++ )
603         {
604           isOK = (load >> b);
605           if (isOK)
606             _table[i] = b;
607           else
608             load.clear(ios::badbit | load.rdstate());
609         }
610       }
611       else
612       {
613         load.clear(ios::badbit | load.rdstate());
614         // this can mean, that the hypothesis is stored in old format
615         _distrType = DT_Regular;
616         _scaleFactor = scale_factor;
617       }
618     }
619     break;
620   case DT_ExprFunc:
621     {
622       string str;
623       isOK = (load >> str);
624       if (isOK)
625         _func = str;
626       else
627       {
628         load.clear(ios::badbit | load.rdstate());
629         // this can mean, that the hypothesis is stored in old format
630         _distrType = DT_Regular;
631         _scaleFactor = scale_factor;
632       }
633     }
634     break;
635   case DT_Regular:
636   default:
637     break;
638   }
639
640   if (_distrType == DT_TabFunc || _distrType == DT_ExprFunc)
641   {
642     isOK = (load >> a);
643     if (isOK)
644       _convMode = a;
645     else
646       load.clear(ios::badbit | load.rdstate());
647   }
648
649   // load reversed edges IDs
650   int intVal;
651   isOK = (load >> intVal);
652   if ( isOK && _distrType != DT_Regular && intVal > 0 ) {
653     _edgeIDs.reserve( intVal );
654     for ( size_t i = 0; i < _edgeIDs.capacity() && isOK; i++) {
655       isOK = (load >> intVal);
656       if ( isOK ) _edgeIDs.push_back( intVal );
657     }
658     isOK = (load >> _objEntry);
659   }
660
661   return load;
662 }
663
664 //=============================================================================
665 /*!
666  *
667  */
668 //=============================================================================
669
670 ostream & operator <<(ostream & save, StdMeshers_NumberOfSegments & hyp)
671 {
672   return hyp.SaveTo( save );
673 }
674
675 //=============================================================================
676 /*!
677  *  
678  */
679 //=============================================================================
680
681 istream & operator >>(istream & load, StdMeshers_NumberOfSegments & hyp)
682 {
683   return hyp.LoadFrom( load );
684 }
685
686 //================================================================================
687 /*!
688  * \brief Initialize number of segments by the mesh built on the geometry
689  * \param theMesh - the built mesh
690  * \param theShape - the geometry of interest
691  * \retval bool - true if parameter values have been successfully defined
692  */
693 //================================================================================
694
695 bool StdMeshers_NumberOfSegments::SetParametersByMesh(const SMESH_Mesh*   theMesh,
696                                                       const TopoDS_Shape& theShape)
697 {
698   if ( !theMesh || theShape.IsNull() )
699     return false;
700
701   _numberOfSegments = 0;
702   _distrType = DT_Regular;
703
704   int nbEdges = 0;
705   TopTools_IndexedMapOfShape edgeMap;
706   TopExp::MapShapes( theShape, TopAbs_EDGE, edgeMap );
707   SMESHDS_Mesh* aMeshDS = const_cast< SMESH_Mesh* >( theMesh )->GetMeshDS();
708   for ( int i = 1; i <= edgeMap.Extent(); ++i )
709   {
710     // get current segment length
711     SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edgeMap( i ));
712     if ( eSubMesh && eSubMesh->NbElements())
713       _numberOfSegments += eSubMesh->NbElements();
714
715     ++nbEdges;
716   }
717   if ( nbEdges )
718     _numberOfSegments /= nbEdges;
719
720   if (_numberOfSegments == 0) _numberOfSegments = 1;
721
722   return nbEdges;
723 }
724 //================================================================================
725 /*!
726  * \brief Initialize my parameter values by default parameters.
727  *  \retval bool - true if parameter values have been successfully defined
728  */
729 //================================================================================
730
731 bool StdMeshers_NumberOfSegments::SetParametersByDefaults(const TDefaults&  dflts,
732                                                           const SMESH_Mesh* /*theMesh*/)
733 {
734   return (_numberOfSegments = dflts._nbSegments );
735 }
736
737 //=============================================================================
738 /*!
739  *  
740  */
741 //=============================================================================
742
743 void StdMeshers_NumberOfSegments::SetReversedEdges( std::vector<int>& ids )
744 {
745   if ( ids != _edgeIDs ) {
746     _edgeIDs = ids;
747
748     NotifySubMeshesHypothesisModification();
749   }
750 }
751