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