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