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