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