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