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