Salome HOME
Merge from V5_1_3_BR branch (07/12/09)
[modules/smesh.git] / src / StdMeshers / StdMeshers_NumberOfSegments.cxx
1 //  Copyright (C) 2007-2008  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.
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 //  SMESH SMESH : implementaion of SMESH idl descriptions
23 //  File   : StdMeshers_NumberOfSegments.cxx
24 //           Moved here from SMESH_NumberOfSegments.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27 //
28 #include "StdMeshers_NumberOfSegments.hxx"
29
30 #include "StdMeshers_Distribution.hxx"
31 #include "SMESHDS_SubMesh.hxx"
32 #include "SMESH_Mesh.hxx"
33
34 #include <ExprIntrp_GenExp.hxx>
35 #include <Expr_Array1OfNamedUnknown.hxx>
36 #include <Expr_NamedUnknown.hxx>
37 #include <TColStd_Array1OfReal.hxx>
38 #include <TCollection_AsciiString.hxx>
39 #include <TopExp.hxx>
40 #include <TopTools_IndexedMapOfShape.hxx>
41
42 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
43 #define NO_CAS_CATCH
44 #endif
45
46 #include <Standard_Failure.hxx>
47
48 #ifdef NO_CAS_CATCH
49 #include <Standard_ErrorHandler.hxx>
50 #endif
51
52 #include <Basics_Utils.hxx>
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(15),//issue 19923
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   Kernel_Utils::Localizer loc;
327
328   bool parsed_ok = true;
329   Handle( ExprIntrp_GenExp ) myExpr;
330   try {
331 #ifdef NO_CAS_CATCH
332     OCC_CATCH_SIGNALS;
333 #endif
334     myExpr = ExprIntrp_GenExp::Create();
335     myExpr->Process( str.ToCString() );
336   } catch(Standard_Failure) {
337     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
338     parsed_ok = false;
339   }
340
341   syntax = false;
342   args = false;
343   if( parsed_ok && myExpr->IsDone() )
344   {
345     syntax = true;
346     args = isCorrectArg( myExpr->Expression() );
347   }
348
349   bool res = parsed_ok && syntax && args;
350   if( !res )
351     myExpr.Nullify();
352
353   non_neg = true;
354   singulars = false;
355   non_zero = false;
356
357   if( res )
358   {
359     FunctionExpr f( str.ToCString(), convMode );
360     const int max = 500;
361     for( int i=0; i<=max; i++ )
362     {
363       double t = double(i)/double(max), val;
364       if( !f.value( t, val ) )
365       {
366         sing_point = t;
367         singulars = true;
368         break;
369       }
370       if( val<0 )
371       {
372         non_neg = false;
373         break;
374       }
375       if( val>PRECISION )
376         non_zero = true;
377     }
378   }
379
380   return res && non_neg && non_zero && ( !singulars );
381 }
382
383 //================================================================================
384 /*!
385  * 
386  */
387 //================================================================================
388
389 void StdMeshers_NumberOfSegments::SetExpressionFunction(const char* expr)
390   throw(SALOME_Exception)
391 {
392   if (_distrType != DT_ExprFunc)
393     _distrType = DT_ExprFunc;
394     //throw SALOME_Exception(LOCALIZED("not an expression function distribution"));
395
396   // remove white spaces
397   TCollection_AsciiString str((Standard_CString)expr);
398   str.RemoveAll(' ');
399   str.RemoveAll('\t');
400   str.RemoveAll('\r');
401   str.RemoveAll('\n');
402
403   bool syntax, args, non_neg, singulars, non_zero;
404   double sing_point;
405   bool res = process( str, _convMode, syntax, args, non_neg, non_zero, singulars, sing_point );
406   if( !res )
407   {
408     if( !syntax )
409       throw SALOME_Exception(LOCALIZED("invalid expression syntax"));
410     if( !args )
411       throw SALOME_Exception(LOCALIZED("only 't' may be used as function argument"));
412     if( !non_neg )
413       throw SALOME_Exception(LOCALIZED("only non-negative function can be used as density"));
414     if( singulars )
415     {
416       char buf[1024];
417       sprintf( buf, "Function has singular point in %.3f", sing_point );
418       throw SALOME_Exception( buf );
419     }
420     if( !non_zero )
421       throw SALOME_Exception(LOCALIZED("f(t)=0 cannot be used as density"));
422
423     return;
424   }
425   
426   string func = expr;
427   if( _func != func )
428   {
429     _func = func;
430     NotifySubMeshesHypothesisModification();
431   }
432 }
433
434 //================================================================================
435 /*!
436  * 
437  */
438 //================================================================================
439
440 const char* StdMeshers_NumberOfSegments::GetExpressionFunction() const
441   throw(SALOME_Exception)
442 {
443   if (_distrType != DT_ExprFunc)
444     throw SALOME_Exception(LOCALIZED("not an expression function distribution"));
445   return _func.c_str();
446 }
447
448 //================================================================================
449 /*!
450  * 
451  */
452 //================================================================================
453
454 void StdMeshers_NumberOfSegments::SetConversionMode( int conv )
455   throw(SALOME_Exception)
456 {
457 //   if (_distrType != DT_TabFunc && _distrType != DT_ExprFunc)
458 //     throw SALOME_Exception(LOCALIZED("not a functional distribution"));
459
460   if( conv != _convMode )
461   {
462     _convMode = conv;
463     NotifySubMeshesHypothesisModification();
464   }
465 }
466
467 //================================================================================
468 /*!
469  * 
470  */
471 //================================================================================
472
473 int StdMeshers_NumberOfSegments::ConversionMode() const
474   throw(SALOME_Exception)
475 {
476 //   if (_distrType != DT_TabFunc && _distrType != DT_ExprFunc)
477 //     throw SALOME_Exception(LOCALIZED("not a functional distribution"));
478   return _convMode;
479 }
480
481 //=============================================================================
482 /*!
483  *  
484  */
485 //=============================================================================
486
487 ostream & StdMeshers_NumberOfSegments::SaveTo(ostream & save)
488 {
489   int listSize = _edgeIDs.size();
490   save << _numberOfSegments << " " << (int)_distrType;
491   switch (_distrType)
492   {
493   case DT_Scale:
494     save << " " << _scaleFactor;
495     break;
496   case DT_TabFunc:
497     int i;
498     save << " " << _table.size();
499     for (i=0; i < _table.size(); i++)
500       save << " " << _table[i];
501     break;
502   case DT_ExprFunc:
503     save << " " << _func;
504     break;
505   case DT_Regular:
506   default:
507     break;
508   }
509
510   if (_distrType == DT_TabFunc || _distrType == DT_ExprFunc)
511     save << " " << _convMode;
512
513   if ( _distrType != DT_Regular && listSize > 0 ) {
514     save << " " << listSize;
515     for ( int i = 0; i < listSize; i++ )
516       save << " " << _edgeIDs[i];
517     save << " " << _objEntry;
518   }
519   
520   return save;
521 }
522
523 //=============================================================================
524 /*!
525  *  
526  */
527 //=============================================================================
528
529 istream & StdMeshers_NumberOfSegments::LoadFrom(istream & load)
530 {
531   bool isOK = true;
532   int a;
533
534   // read number of segments
535   isOK = (load >> a);
536   if (isOK)
537     _numberOfSegments = a;
538   else
539     load.clear(ios::badbit | load.rdstate());
540
541   // read second stored value. It can be two variants here:
542   // 1. If the hypothesis is stored in old format (nb.segments and scale factor),
543   //    we wait here the scale factor, which is double.
544   // 2. If the hypothesis is stored in new format
545   //    (nb.segments, distr.type, some other params.),
546   //    we wait here the ditribution type, which is integer
547   double scale_factor;
548   isOK = (load >> scale_factor);
549   a = (int)scale_factor;
550
551   // try to interprete ditribution type,
552   // supposing that this hypothesis was written in the new format
553   if (isOK)
554   {
555     if (a < DT_Regular || a > DT_ExprFunc)
556       _distrType = DT_Regular;
557     else
558       _distrType = (DistrType) a;
559   }
560   else
561     load.clear(ios::badbit | load.rdstate());
562
563   // parameters of distribution
564   double b;
565   switch (_distrType)
566   {
567   case DT_Scale:
568     {
569       isOK = (load >> b);
570       if (isOK)
571         _scaleFactor = b;
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_TabFunc:
582     {
583       isOK = (load >> a);
584       if (isOK)
585       {
586         _table.resize(a, 0.);
587         int i;
588         for (i=0; i < _table.size(); i++)
589         {
590           isOK = (load >> b);
591           if (isOK)
592             _table[i] = b;
593           else
594             load.clear(ios::badbit | load.rdstate());
595         }
596       }
597       else
598       {
599         load.clear(ios::badbit | load.rdstate());
600         // this can mean, that the hypothesis is stored in old format
601         _distrType = DT_Regular;
602         _scaleFactor = scale_factor;
603       }
604     }
605     break;
606   case DT_ExprFunc:
607     {
608       string str;
609       isOK = (load >> str);
610       if (isOK)
611         _func = str;
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_Regular:
622   default:
623     break;
624   }
625
626   if (_distrType == DT_TabFunc || _distrType == DT_ExprFunc)
627   {
628     isOK = (load >> a);
629     if (isOK)
630       _convMode = a;
631     else
632       load.clear(ios::badbit | load.rdstate());
633   }
634
635   // load reversed edges IDs
636   int intVal;
637   isOK = (load >> intVal);
638   if ( isOK && _distrType != DT_Regular && intVal > 0 ) {
639     _edgeIDs.reserve( intVal );
640     for (int i = 0; i < _edgeIDs.capacity() && isOK; i++) {
641       isOK = (load >> intVal);
642       if ( isOK ) _edgeIDs.push_back( intVal );
643     }
644     isOK = (load >> _objEntry);
645   }
646
647   return load;
648 }
649
650 //=============================================================================
651 /*!
652  *  
653  */
654 //=============================================================================
655
656 ostream & operator <<(ostream & save, StdMeshers_NumberOfSegments & hyp)
657 {
658   return hyp.SaveTo( save );
659 }
660
661 //=============================================================================
662 /*!
663  *  
664  */
665 //=============================================================================
666
667 istream & operator >>(istream & load, StdMeshers_NumberOfSegments & hyp)
668 {
669   return hyp.LoadFrom( load );
670 }
671
672 //================================================================================
673 /*!
674  * \brief Initialize number of segments by the mesh built on the geometry
675  * \param theMesh - the built mesh
676  * \param theShape - the geometry of interest
677  * \retval bool - true if parameter values have been successfully defined
678  */
679 //================================================================================
680
681 bool StdMeshers_NumberOfSegments::SetParametersByMesh(const SMESH_Mesh*   theMesh,
682                                                       const TopoDS_Shape& theShape)
683 {
684   if ( !theMesh || theShape.IsNull() )
685     return false;
686
687   _numberOfSegments = 0;
688   _distrType = DT_Regular;
689
690   int nbEdges = 0;
691   TopTools_IndexedMapOfShape edgeMap;
692   TopExp::MapShapes( theShape, TopAbs_EDGE, edgeMap );
693   SMESHDS_Mesh* aMeshDS = const_cast< SMESH_Mesh* >( theMesh )->GetMeshDS();
694   for ( int i = 1; i <= edgeMap.Extent(); ++i )
695   {
696     // get current segment length
697     SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edgeMap( i ));
698     if ( eSubMesh && eSubMesh->NbElements())
699       _numberOfSegments += eSubMesh->NbElements();
700
701     ++nbEdges;
702   }
703   if ( nbEdges )
704     _numberOfSegments /= nbEdges;
705
706   if (_numberOfSegments == 0) _numberOfSegments = 1;
707
708   return nbEdges;
709 }
710 //================================================================================
711 /*!
712  * \brief Initialize my parameter values by default parameters.
713  *  \retval bool - true if parameter values have been successfully defined
714  */
715 //================================================================================
716
717 bool StdMeshers_NumberOfSegments::SetParametersByDefaults(const TDefaults&  dflts,
718                                                           const SMESH_Mesh* /*theMesh*/)
719 {
720   return (_numberOfSegments = dflts._nbSegments );
721 }
722
723 //=============================================================================
724 /*!
725  *  
726  */
727 //=============================================================================
728
729 void StdMeshers_NumberOfSegments::SetReversedEdges( std::vector<int>& ids )
730 {
731   if ( ids != _edgeIDs ) {
732     _edgeIDs = ids;
733
734     NotifySubMeshesHypothesisModification();
735   }
736 }
737