Salome HOME
675bbad0399d31175987ea4d845d0281bb42148a
[modules/smesh.git] / src / StdMeshers / StdMeshers_NumberOfSegments.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 //  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 //  commented by mpa for IPAL 52986
190 //  if ( fabs(scaleFactor - 1.0) < PRECISION )
191 //    _distrType = DT_Regular;
192
193   if ( fabs(_scaleFactor - scaleFactor) > PRECISION )
194   {
195     _scaleFactor = scaleFactor;
196     NotifySubMeshesHypothesisModification();
197   }
198 }
199
200 //================================================================================
201 /*!
202  *
203  */
204 //================================================================================
205
206 double StdMeshers_NumberOfSegments::GetScaleFactor() const
207   throw(SALOME_Exception)
208 {
209   if (_distrType != DT_Scale)
210     throw SALOME_Exception(LOCALIZED("not a scale distribution"));
211   return _scaleFactor;
212 }
213
214 //================================================================================
215 /*!
216  *
217  */
218 //================================================================================
219
220 void StdMeshers_NumberOfSegments::SetTableFunction(const vector<double>& table)
221   throw(SALOME_Exception)
222 {
223   if (_distrType != DT_TabFunc)
224     _distrType = DT_TabFunc;
225   //throw SALOME_Exception(LOCALIZED("not a table function distribution"));
226   if ( (table.size() % 2) != 0 )
227     throw SALOME_Exception(LOCALIZED("odd size of vector of table function"));
228
229   double prev = -PRECISION;
230   bool isSame = table.size() == _table.size();
231
232   bool pos = false;
233   for ( size_t i = 0; i < table.size() / 2; i++ )
234   {
235     double par = table[i*2];
236     double val = table[i*2+1];
237     if( _convMode==0 )
238     {
239       try {
240 #ifdef NO_CAS_CATCH
241         OCC_CATCH_SIGNALS;
242 #endif
243         val = pow( 10.0, val );
244       }
245       catch(Standard_Failure) {
246         Handle(Standard_Failure) aFail = Standard_Failure::Caught();
247         throw SALOME_Exception( LOCALIZED( "invalid value"));
248         return;
249       }
250     }
251     else if( _convMode==1 && val<0.0 )
252       val = 0.0;
253
254     if ( par < 0 || par > 1)
255       throw SALOME_Exception(LOCALIZED("parameter of table function is out of range [0,1]"));
256     if ( fabs(par-prev) < PRECISION )
257       throw SALOME_Exception(LOCALIZED("two parameters are the same"));
258     if ( val < 0 )
259       throw SALOME_Exception(LOCALIZED("value of table function is not positive"));
260     if( val > PRECISION )
261       pos = true;
262     if (isSame)
263     {
264       double oldpar = _table[i*2];
265       double oldval = _table[i*2+1];
266       if ( fabs(par - oldpar) > PRECISION || fabs(val - oldval) > PRECISION )
267         isSame = false;
268     }
269     prev = par;
270   }
271
272   if( !pos )
273     throw SALOME_Exception(LOCALIZED("value of table function is not positive"));
274
275   if ( pos && !isSame )
276   {
277     _table = table;
278     NotifySubMeshesHypothesisModification();
279   }
280 }
281
282 //================================================================================
283 /*!
284  *
285  */
286 //================================================================================
287
288 const vector<double>& StdMeshers_NumberOfSegments::GetTableFunction() const
289   throw(SALOME_Exception)
290 {
291   if (_distrType != DT_TabFunc)
292     throw SALOME_Exception(LOCALIZED("not a table function distribution"));
293   return _table;
294 }
295
296 //================================================================================
297 /*! check if only 't' is unknown variable in expression
298  */
299 //================================================================================
300 bool isCorrectArg( const Handle( Expr_GeneralExpression )& expr )
301 {
302   Handle( Expr_NamedUnknown ) sub = Handle( Expr_NamedUnknown )::DownCast( expr );
303   if( !sub.IsNull() )
304     return sub->GetName()=="t";
305
306   bool res = true;
307   for( int i=1, n=expr->NbSubExpressions(); i<=n && res; i++ )
308   {
309     Handle( Expr_GeneralExpression ) sub = expr->SubExpression( i );
310     Handle( Expr_NamedUnknown ) name = Handle( Expr_NamedUnknown )::DownCast( sub );
311     if( !name.IsNull() )
312     {
313       if( name->GetName()!="t" )
314         res = false;
315     }
316     else
317       res = isCorrectArg( sub );
318   }
319   return res;
320 }
321
322 //================================================================================
323 /*! this function parses the expression 'str' in order to check if syntax is correct
324  *  ( result in 'syntax' ) and if only 't' is unknown variable in expression ( result in 'args' )
325  */
326 //================================================================================
327 bool process( const TCollection_AsciiString& str, int convMode,
328               bool& syntax, bool& args,
329               bool& non_neg, bool& non_zero,
330               bool& singulars, double& sing_point )
331 {
332   Kernel_Utils::Localizer loc;
333
334   bool parsed_ok = true;
335   Handle( ExprIntrp_GenExp ) myExpr;
336   try {
337 #ifdef NO_CAS_CATCH
338     OCC_CATCH_SIGNALS;
339 #endif
340     myExpr = ExprIntrp_GenExp::Create();
341     myExpr->Process( str.ToCString() );
342   } catch(Standard_Failure) {
343     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
344     parsed_ok = false;
345   }
346
347   syntax = false;
348   args = false;
349   if( parsed_ok && myExpr->IsDone() )
350   {
351     syntax = true;
352     args = isCorrectArg( myExpr->Expression() );
353   }
354
355   bool res = parsed_ok && syntax && args;
356   if( !res )
357     myExpr.Nullify();
358
359   non_neg = true;
360   singulars = false;
361   non_zero = false;
362
363   if( res )
364   {
365     FunctionExpr f( str.ToCString(), convMode );
366     const int max = 500;
367     for( int i=0; i<=max; i++ )
368     {
369       double t = double(i)/double(max), val;
370       if( !f.value( t, val ) )
371       {
372         sing_point = t;
373         singulars = true;
374         break;
375       }
376       if( val<0 )
377       {
378         non_neg = false;
379         break;
380       }
381       if( val>PRECISION )
382         non_zero = true;
383     }
384   }
385
386   return res && non_neg && non_zero && ( !singulars );
387 }
388
389 //================================================================================
390 /*!
391  * 
392  */
393 //================================================================================
394
395 void StdMeshers_NumberOfSegments::SetExpressionFunction(const char* expr)
396   throw(SALOME_Exception)
397 {
398   if (_distrType != DT_ExprFunc)
399     _distrType = DT_ExprFunc;
400
401   string func = CheckExpressionFunction( expr, _convMode );
402   if( _func != func )
403   {
404     _func = func;
405     NotifySubMeshesHypothesisModification();
406   }
407 }
408
409 //=======================================================================
410 //function : CheckExpressionFunction
411 //purpose  : Checks validity of  the expression of the function f(t), e.g. "sin(t)".
412 //           In case of validity returns a cleaned expression
413 //=======================================================================
414
415 std::string
416 StdMeshers_NumberOfSegments::CheckExpressionFunction( const std::string& expr,
417                                                       const int          convMode)
418     throw (SALOME_Exception)
419 {
420   // remove white spaces
421   TCollection_AsciiString str((Standard_CString)expr.c_str());
422   str.RemoveAll(' ');
423   str.RemoveAll('\t');
424   str.RemoveAll('\r');
425   str.RemoveAll('\n');
426
427   bool syntax, args, non_neg, singulars, non_zero;
428   double sing_point;
429   bool res = process( str, convMode, syntax, args, non_neg, non_zero, singulars, sing_point );
430   if( !res )
431   {
432     if( !syntax )
433       throw SALOME_Exception(SMESH_Comment("invalid expression syntax: ") << str );
434     if( !args )
435       throw SALOME_Exception(LOCALIZED("only 't' may be used as function argument"));
436     if( !non_neg )
437       throw SALOME_Exception(LOCALIZED("only non-negative function can be used"));
438     if( singulars )
439     {
440       char buf[1024];
441       sprintf( buf, "Function has singular point in %.3f", sing_point );
442       throw SALOME_Exception( buf );
443     }
444     if( !non_zero )
445       throw SALOME_Exception(LOCALIZED("f(t)=0 cannot be used"));
446   }
447  
448   return str.ToCString();
449 }
450
451 //================================================================================
452 /*!
453  * 
454  */
455 //================================================================================
456
457 const char* StdMeshers_NumberOfSegments::GetExpressionFunction() const
458   throw(SALOME_Exception)
459 {
460   if (_distrType != DT_ExprFunc)
461     throw SALOME_Exception(LOCALIZED("not an expression function distribution"));
462   return _func.c_str();
463 }
464
465 //================================================================================
466 /*!
467  * 
468  */
469 //================================================================================
470
471 void StdMeshers_NumberOfSegments::SetConversionMode( int conv )
472   throw(SALOME_Exception)
473 {
474 //   if (_distrType != DT_TabFunc && _distrType != DT_ExprFunc)
475 //     throw SALOME_Exception(LOCALIZED("not a functional distribution"));
476
477   if( conv != _convMode )
478   {
479     _convMode = conv;
480     NotifySubMeshesHypothesisModification();
481   }
482 }
483
484 //================================================================================
485 /*!
486  * 
487  */
488 //================================================================================
489
490 int StdMeshers_NumberOfSegments::ConversionMode() const
491   throw(SALOME_Exception)
492 {
493 //   if (_distrType != DT_TabFunc && _distrType != DT_ExprFunc)
494 //     throw SALOME_Exception(LOCALIZED("not a functional distribution"));
495   return _convMode;
496 }
497
498 //=============================================================================
499 /*!
500  *  
501  */
502 //=============================================================================
503
504 ostream & StdMeshers_NumberOfSegments::SaveTo(ostream & save)
505 {
506   int listSize = _edgeIDs.size();
507   save << _numberOfSegments << " " << (int)_distrType;
508   switch (_distrType)
509   {
510   case DT_Scale:
511     save << " " << _scaleFactor;
512     break;
513   case DT_TabFunc:
514     save << " " << _table.size();
515     for ( size_t i = 0; i < _table.size(); i++ )
516       save << " " << _table[i];
517     break;
518   case DT_ExprFunc:
519     save << " " << _func;
520     break;
521   case DT_Regular:
522   default:
523     break;
524   }
525
526   if (_distrType == DT_TabFunc || _distrType == DT_ExprFunc)
527     save << " " << _convMode;
528
529   if ( _distrType != DT_Regular && listSize > 0 ) {
530     save << " " << listSize;
531     for ( int i = 0; i < listSize; i++ )
532       save << " " << _edgeIDs[i];
533     save << " " << _objEntry;
534   }
535   
536   return save;
537 }
538
539 //=============================================================================
540 /*!
541  *  
542  */
543 //=============================================================================
544
545 istream & StdMeshers_NumberOfSegments::LoadFrom(istream & load)
546 {
547   bool isOK = true;
548   int a;
549
550   // read number of segments
551   isOK = static_cast<bool>(load >> a);
552   if (isOK)
553     _numberOfSegments = a;
554   else
555     load.clear(ios::badbit | load.rdstate());
556
557   // read second stored value. It can be two variants here:
558   // 1. If the hypothesis is stored in old format (nb.segments and scale factor),
559   //    we wait here the scale factor, which is double.
560   // 2. If the hypothesis is stored in new format
561   //    (nb.segments, distr.type, some other params.),
562   //    we wait here the ditribution type, which is integer
563   double scale_factor;
564   isOK = static_cast<bool>(load >> scale_factor);
565   a = (int)scale_factor;
566
567   // try to interprete ditribution type,
568   // supposing that this hypothesis was written in the new format
569   if (isOK)
570   {
571     if (a < DT_Regular || a > DT_ExprFunc)
572       _distrType = DT_Regular;
573     else
574       _distrType = (DistrType) a;
575   }
576   else
577     load.clear(ios::badbit | load.rdstate());
578
579   // parameters of distribution
580   double b;
581   switch (_distrType)
582   {
583   case DT_Scale:
584     {
585       isOK = static_cast<bool>(load >> b);
586       if (isOK)
587         _scaleFactor = b;
588       else
589       {
590         load.clear(ios::badbit | load.rdstate());
591         // this can mean, that the hypothesis is stored in old format
592         _distrType = DT_Regular;
593         _scaleFactor = scale_factor;
594       }
595     }
596     break;
597   case DT_TabFunc:
598     {
599       isOK = static_cast<bool>(load >> a);
600       if (isOK)
601       {
602         _table.resize(a, 0.);
603         for ( size_t i=0; i < _table.size(); i++ )
604         {
605           isOK = static_cast<bool>(load >> b);
606           if (isOK)
607             _table[i] = b;
608           else
609             load.clear(ios::badbit | load.rdstate());
610         }
611       }
612       else
613       {
614         load.clear(ios::badbit | load.rdstate());
615         // this can mean, that the hypothesis is stored in old format
616         _distrType = DT_Regular;
617         _scaleFactor = scale_factor;
618       }
619     }
620     break;
621   case DT_ExprFunc:
622     {
623       string str;
624       isOK = static_cast<bool>(load >> str);
625       if (isOK)
626         _func = str;
627       else
628       {
629         load.clear(ios::badbit | load.rdstate());
630         // this can mean, that the hypothesis is stored in old format
631         _distrType = DT_Regular;
632         _scaleFactor = scale_factor;
633       }
634     }
635     break;
636   case DT_Regular:
637   default:
638     break;
639   }
640
641   if (_distrType == DT_TabFunc || _distrType == DT_ExprFunc)
642   {
643     isOK = static_cast<bool>(load >> a);
644     if (isOK)
645       _convMode = a;
646     else
647       load.clear(ios::badbit | load.rdstate());
648   }
649
650   // load reversed edges IDs
651   int intVal;
652   isOK = static_cast<bool>(load >> intVal);
653   if ( isOK && _distrType != DT_Regular && intVal > 0 ) {
654     _edgeIDs.reserve( intVal );
655     for ( size_t i = 0; i < _edgeIDs.capacity() && isOK; i++) {
656       isOK = static_cast<bool>(load >> intVal);
657       if ( isOK ) _edgeIDs.push_back( intVal );
658     }
659     isOK = static_cast<bool>(load >> _objEntry);
660   }
661
662   return load;
663 }
664
665 //=============================================================================
666 /*!
667  *
668  */
669 //=============================================================================
670
671 ostream & operator <<(ostream & save, StdMeshers_NumberOfSegments & hyp)
672 {
673   return hyp.SaveTo( save );
674 }
675
676 //=============================================================================
677 /*!
678  *  
679  */
680 //=============================================================================
681
682 istream & operator >>(istream & load, StdMeshers_NumberOfSegments & hyp)
683 {
684   return hyp.LoadFrom( load );
685 }
686
687 //================================================================================
688 /*!
689  * \brief Initialize number of segments by the mesh built on the geometry
690  * \param theMesh - the built mesh
691  * \param theShape - the geometry of interest
692  * \retval bool - true if parameter values have been successfully defined
693  */
694 //================================================================================
695
696 bool StdMeshers_NumberOfSegments::SetParametersByMesh(const SMESH_Mesh*   theMesh,
697                                                       const TopoDS_Shape& theShape)
698 {
699   if ( !theMesh || theShape.IsNull() )
700     return false;
701
702   _numberOfSegments = 0;
703   _distrType = DT_Regular;
704
705   int nbEdges = 0;
706   TopTools_IndexedMapOfShape edgeMap;
707   TopExp::MapShapes( theShape, TopAbs_EDGE, edgeMap );
708   SMESHDS_Mesh* aMeshDS = const_cast< SMESH_Mesh* >( theMesh )->GetMeshDS();
709   for ( int i = 1; i <= edgeMap.Extent(); ++i )
710   {
711     // get current segment length
712     SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edgeMap( i ));
713     if ( eSubMesh && eSubMesh->NbElements())
714       _numberOfSegments += eSubMesh->NbElements();
715
716     ++nbEdges;
717   }
718   if ( nbEdges )
719     _numberOfSegments /= nbEdges;
720
721   if (_numberOfSegments == 0) _numberOfSegments = 1;
722
723   return nbEdges;
724 }
725 //================================================================================
726 /*!
727  * \brief Initialize my parameter values by default parameters.
728  *  \retval bool - true if parameter values have been successfully defined
729  */
730 //================================================================================
731
732 bool StdMeshers_NumberOfSegments::SetParametersByDefaults(const TDefaults&  dflts,
733                                                           const SMESH_Mesh* /*theMesh*/)
734 {
735   return (_numberOfSegments = dflts._nbSegments );
736 }
737
738 //=============================================================================
739 /*!
740  *  
741  */
742 //=============================================================================
743
744 void StdMeshers_NumberOfSegments::SetReversedEdges( std::vector<int>& ids )
745 {
746   if ( ids != _edgeIDs ) {
747     _edgeIDs = ids;
748
749     NotifySubMeshesHypothesisModification();
750   }
751 }
752