1 # Copyright (C) 2005 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License.
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 # Lesser General Public License for more details.
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 # Author : Francis KLOSS, OCC
37 # import NETGENPlugin module if possible
55 # MirrorType enumeration
56 POINT = SMESH_MeshEditor.POINT
57 AXIS = SMESH_MeshEditor.AXIS
58 PLANE = SMESH_MeshEditor.PLANE
60 # Smooth_Method enumeration
61 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
62 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
64 # Fineness enumeration(for NETGEN)
76 smesh = salome.lcc.FindOrLoadComponent("FactoryServer", "SMESH")
77 smesh.SetCurrentStudy(salome.myStudy)
83 ior = salome.orb.object_to_string(obj)
84 sobj = salome.myStudy.FindObjectIOR(ior)
88 attr = sobj.FindAttribute("AttributeName")[1]
91 ## Sets name to object
92 def SetName(obj, name):
93 ior = salome.orb.object_to_string(obj)
94 sobj = salome.myStudy.FindObjectIOR(ior)
96 attr = sobj.FindAttribute("AttributeName")[1]
99 ## Returns long value from enumeration
100 # Uses for SMESH.FunctorType enumeration
101 def EnumToLong(theItem):
104 ## Get PointStruct from vertex
105 # @param theVertex is GEOM object(vertex)
106 # @return SMESH.PointStruct
107 def GetPointStruct(theVertex):
108 [x, y, z] = geompy.PointCoordinates(theVertex)
109 return PointStruct(x,y,z)
111 ## Get DirStruct from vector
112 # @param theVector is GEOM object(vector)
113 # @return SMESH.DirStruct
114 def GetDirStruct(theVector):
115 vertices = geompy.SubShapeAll( theVector, geompy.ShapeType["VERTEX"] )
116 if(len(vertices) != 2):
117 print "Error: vector object is incorrect."
119 p1 = geompy.PointCoordinates(vertices[0])
120 p2 = geompy.PointCoordinates(vertices[1])
121 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
125 ## Get AxisStruct from object
126 # @param theObj is GEOM object(line or plane)
127 # @return SMESH.AxisStruct
128 def GetAxisStruct(theObj):
129 edges = geompy.SubShapeAll( theObj, geompy.ShapeType["EDGE"] )
131 vertex1, vertex2 = geompy.SubShapeAll( edges[0], geompy.ShapeType["VERTEX"] )
132 vertex3, vertex4 = geompy.SubShapeAll( edges[1], geompy.ShapeType["VERTEX"] )
133 vertex1 = geompy.PointCoordinates(vertex1)
134 vertex2 = geompy.PointCoordinates(vertex2)
135 vertex3 = geompy.PointCoordinates(vertex3)
136 vertex4 = geompy.PointCoordinates(vertex4)
137 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
138 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
139 normal = [ v1[1]*v2[2]-v2[1]*v1[2], v1[2]*v2[0]-v2[2]*v1[0], v1[0]*v2[1]-v2[0]*v1[1] ]
140 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
142 elif len(edges) == 1:
143 vertex1, vertex2 = geompy.SubShapeAll( edges[0], geompy.ShapeType["VERTEX"] )
144 p1 = geompy.PointCoordinates( vertex1 )
145 p2 = geompy.PointCoordinates( vertex2 )
146 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
150 # From SMESH_Gen interface:
151 # ------------------------
153 ## Set the current mode
154 def SetEmbeddedMode( theMode ):
155 smesh.SetEmbeddedMode(theMode)
157 ## Get the current mode
158 def IsEmbeddedMode():
159 return smesh.IsEmbeddedMode()
161 ## Set the current study
162 def SetCurrentStudy( theStudy ):
163 smesh.SetCurrentStudy(theStudy)
165 ## Get the current study
166 def GetCurrentStudy():
167 return smesh.GetCurrentStudy()
169 ## Create Mesh object importing data from given UNV file
170 # @return an instance of Mesh class
171 def CreateMeshesFromUNV( theFileName ):
172 aSmeshMesh = smesh.CreateMeshesFromUNV(theFileName)
173 aMesh = Mesh(aSmeshMesh)
176 ## Create Mesh object(s) importing data from given MED file
177 # @return a list of Mesh class instances
178 def CreateMeshesFromMED( theFileName ):
179 aSmeshMeshes, aStatus = smesh.CreateMeshesFromMED(theFileName)
181 for iMesh in range(len(aSmeshMeshes)) :
182 aMesh = Mesh(aSmeshMeshes[iMesh])
183 aMeshes.append(aMesh)
184 return aMeshes, aStatus
186 ## Create Mesh object importing data from given STL file
187 # @return an instance of Mesh class
188 def CreateMeshesFromSTL( theFileName ):
189 aSmeshMesh = smesh.CreateMeshesFromSTL(theFileName)
190 aMesh = Mesh(aSmeshMesh)
193 ## From SMESH_Gen interface
194 def GetSubShapesId( theMainObject, theListOfSubObjects ):
195 return smesh.GetSubShapesId(theMainObject, theListOfSubObjects)
197 ## From SMESH_Gen interface. Creates pattern
199 return smesh.GetPattern()
203 # Filtering. Auxiliary functions:
204 # ------------------------------
206 ## Creates an empty criterion
207 # @return SMESH.Filter.Criterion
208 def GetEmptyCriterion():
209 Type = EnumToLong(FT_Undefined)
210 Compare = EnumToLong(FT_Undefined)
214 UnaryOp = EnumToLong(FT_Undefined)
215 BinaryOp = EnumToLong(FT_Undefined)
218 Precision = -1 ##@1e-07
219 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
220 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
222 ## Creates a criterion by given parameters
223 # @param elementType is the type of elements(NODE, EDGE, FACE, VOLUME)
224 # @param CritType is type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
225 # @param Compare belong to {FT_LessThan, FT_MoreThan, FT_EqualTo}
226 # @param Treshold is threshold value (range of ids as string, shape, numeric)
227 # @param UnaryOp is FT_LogicalNOT or FT_Undefined
228 # @param BinaryOp is binary logical operation FT_LogicalAND, FT_LogicalOR or
229 # FT_Undefined(must be for the last criterion in criteria)
230 # @return SMESH.Filter.Criterion
231 def GetCriterion(elementType,
233 Compare = FT_EqualTo,
235 UnaryOp=FT_Undefined,
236 BinaryOp=FT_Undefined):
237 aCriterion = GetEmptyCriterion()
238 aCriterion.TypeOfElement = elementType
239 aCriterion.Type = EnumToLong(CritType)
243 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
244 aCriterion.Compare = EnumToLong(Compare)
245 elif Compare == "=" or Compare == "==":
246 aCriterion.Compare = EnumToLong(FT_EqualTo)
248 aCriterion.Compare = EnumToLong(FT_LessThan)
250 aCriterion.Compare = EnumToLong(FT_MoreThan)
252 aCriterion.Compare = EnumToLong(FT_EqualTo)
255 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
256 FT_BelongToCylinder, FT_LyingOnGeom]:
258 if isinstance(aTreshold, geompy.GEOM._objref_GEOM_Object):
259 aCriterion.ThresholdStr = GetName(aTreshold)
260 aCriterion.ThresholdID = salome.ObjectToID(aTreshold)
262 print "Error: Treshold should be a shape."
264 elif CritType == FT_RangeOfIds:
266 if isinstance(aTreshold, str):
267 aCriterion.ThresholdStr = aTreshold
269 print "Error: Treshold should be a string."
271 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_BadOrientedVolume]:
272 # Here we don't need treshold
273 if aTreshold == FT_LogicalNOT:
274 aCriterion.UnaryOp = EnumToLong(FT_LogicalNOT)
275 elif aTreshold in [FT_LogicalAND, FT_LogicalOR]:
276 aCriterion.BinaryOp = aTreshold
280 aTreshold = float(aTreshold)
281 aCriterion.Threshold = aTreshold
283 print "Error: Treshold should be a number."
286 if Treshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
287 aCriterion.UnaryOp = EnumToLong(FT_LogicalNOT)
289 if Treshold in [FT_LogicalAND, FT_LogicalOR]:
290 aCriterion.BinaryOp = EnumToLong(Treshold)
292 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
293 aCriterion.BinaryOp = EnumToLong(UnaryOp)
295 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
296 aCriterion.BinaryOp = EnumToLong(BinaryOp)
300 ## Creates filter by given parameters of criterion
301 # @param elementType is the type of elements in the group
302 # @param CritType is type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
303 # @param Compare belong to {FT_LessThan, FT_MoreThan, FT_EqualTo}
304 # @param Treshold is threshold value (range of id ids as string, shape, numeric)
305 # @param UnaryOp is FT_LogicalNOT or FT_Undefined
306 # @return SMESH_Filter
307 def GetFilter(elementType,
308 CritType=FT_Undefined,
311 UnaryOp=FT_Undefined):
312 aCriterion = GetCriterion(elementType, CritType, Compare, Treshold, UnaryOp, FT_Undefined)
313 aFilterMgr = smesh.CreateFilterManager()
314 aFilter = aFilterMgr.CreateFilter()
316 aCriteria.append(aCriterion)
317 aFilter.SetCriteria(aCriteria)
320 ## Creates numerical functor by its type
321 # @param theCrierion is FT_...; functor type
322 # @return SMESH_NumericalFunctor
323 def GetFunctor(theCriterion):
324 aFilterMgr = smesh.CreateFilterManager()
325 if theCriterion == FT_AspectRatio:
326 return aFilterMgr.CreateAspectRatio()
327 elif theCriterion == FT_AspectRatio3D:
328 return aFilterMgr.CreateAspectRatio3D()
329 elif theCriterion == FT_Warping:
330 return aFilterMgr.CreateWarping()
331 elif theCriterion == FT_MinimumAngle:
332 return aFilterMgr.CreateMinimumAngle()
333 elif theCriterion == FT_Taper:
334 return aFilterMgr.CreateTaper()
335 elif theCriterion == FT_Skew:
336 return aFilterMgr.CreateSkew()
337 elif theCriterion == FT_Area:
338 return aFilterMgr.CreateArea()
339 elif theCriterion == FT_Volume3D:
340 return aFilterMgr.CreateVolume3D()
341 elif theCriterion == FT_MultiConnection:
342 return aFilterMgr.CreateMultiConnection()
343 elif theCriterion == FT_MultiConnection2D:
344 return aFilterMgr.CreateMultiConnection2D()
345 elif theCriterion == FT_Length:
346 return aFilterMgr.CreateLength()
347 elif theCriterion == FT_Length2D:
348 return aFilterMgr.CreateLength2D()
350 print "Error: given parameter is not numerucal functor type."
353 ## Print error message if a hypothesis was not assigned.
354 def TreatHypoStatus(status, hypName, geomName, isAlgo):
356 hypType = "algorithm"
358 hypType = "hypothesis"
360 if status == HYP_UNKNOWN_FATAL :
361 reason = "for unknown reason"
362 elif status == HYP_INCOMPATIBLE :
363 reason = "this hypothesis mismatches algorithm"
364 elif status == HYP_NOTCONFORM :
365 reason = "not conform mesh would be built"
366 elif status == HYP_ALREADY_EXIST :
367 reason = hypType + " of the same dimension already assigned to this shape"
368 elif status == HYP_BAD_DIM :
369 reason = hypType + " mismatches shape"
370 elif status == HYP_CONCURENT :
371 reason = "there are concurrent hypotheses on sub-shapes"
372 elif status == HYP_BAD_SUBSHAPE :
373 reason = "shape is neither the main one, nor its subshape, nor a valid group"
374 elif status == HYP_BAD_GEOMETRY:
375 reason = "geometry mismatches algorithm's expectation"
376 elif status == HYP_HIDDEN_ALGO:
377 reason = "it is hidden by an algorithm of upper dimension generating all-dimensions elements"
378 elif status == HYP_HIDING_ALGO:
379 reason = "it hides algorithm(s) of lower dimension by generating all-dimensions elements"
382 hypName = '"' + hypName + '"'
383 geomName= '"' + geomName+ '"'
384 if status < HYP_UNKNOWN_FATAL:
385 print hypName, "was assigned to", geomName,"but", reason
387 print hypName, "was not assigned to",geomName,":", reason
392 ## Mother class to define algorithm, recommended to don't use directly.
395 class Mesh_Algorithm:
396 # @class Mesh_Algorithm
397 # @brief Class Mesh_Algorithm
404 ## If the algorithm is global, return 0; \n
405 # else return the submesh associated to this algorithm.
406 def GetSubMesh(self):
409 ## Return the wrapped mesher.
410 def GetAlgorithm(self):
413 ## Get list of hypothesis that can be used with this algorithm
414 def GetCompatibleHypothesis(self):
417 list = self.algo.GetCompatibleHypothesis()
425 def SetName(self, name):
426 SetName(self.algo, name)
430 return self.algo.GetId()
433 def Create(self, mesh, geom, hypo, so="libStdMeshersEngine.so"):
435 raise RuntimeError, "Attemp to create " + hypo + " algoritm on None shape"
440 name = GetName(piece)
445 name = geompy.SubShapeName(geom, piece)
446 geompy.addToStudyInFather(piece, geom, name)
447 self.subm = mesh.mesh.GetSubMesh(geom, hypo)
449 self.algo = smesh.CreateHypothesis(hypo, so)
450 SetName(self.algo, name + "/" + hypo)
451 status = mesh.mesh.AddHypothesis(self.geom, self.algo)
452 TreatHypoStatus( status, hypo, name, 1 )
455 def Hypothesis(self, hyp, args=[], so="libStdMeshersEngine.so"):
456 hypo = smesh.CreateHypothesis(hyp, so)
462 a = a + s + str(args[i])
465 name = GetName(self.geom)
466 SetName(hypo, name + "/" + hyp + a)
467 status = self.mesh.mesh.AddHypothesis(self.geom, hypo)
468 TreatHypoStatus( status, hyp, name, 0 )
472 # Public class: Mesh_Segment
473 # --------------------------
475 ## Class to define a segment 1D algorithm for discretization
478 class Mesh_Segment(Mesh_Algorithm):
480 ## Private constructor.
481 def __init__(self, mesh, geom=0):
482 self.Create(mesh, geom, "Regular_1D")
484 ## Define "LocalLength" hypothesis to cut an edge in several segments with the same length
485 # @param l for the length of segments that cut an edge
486 def LocalLength(self, l):
487 hyp = self.Hypothesis("LocalLength", [l])
491 ## Define "NumberOfSegments" hypothesis to cut an edge in several fixed number of segments
492 # @param n for the number of segments that cut an edge
493 # @param s for the scale factor (optional)
494 def NumberOfSegments(self, n, s=[]):
496 hyp = self.Hypothesis("NumberOfSegments", [n])
498 hyp = self.Hypothesis("NumberOfSegments", [n,s])
499 hyp.SetDistrType( 1 )
500 hyp.SetScaleFactor(s)
501 hyp.SetNumberOfSegments(n)
504 ## Define "Arithmetic1D" hypothesis to cut an edge in several segments with arithmetic length increasing
505 # @param start for the length of the first segment
506 # @param end for the length of the last segment
507 def Arithmetic1D(self, start, end):
508 hyp = self.Hypothesis("Arithmetic1D", [start, end])
509 hyp.SetLength(start, 1)
510 hyp.SetLength(end , 0)
513 ## Define "StartEndLength" hypothesis to cut an edge in several segments with geometric length increasing
514 # @param start for the length of the first segment
515 # @param end for the length of the last segment
516 def StartEndLength(self, start, end):
517 hyp = self.Hypothesis("StartEndLength", [start, end])
518 hyp.SetLength(start, 1)
519 hyp.SetLength(end , 0)
522 ## Define "Deflection1D" hypothesis
523 # @param d for the deflection
524 def Deflection1D(self, d):
525 hyp = self.Hypothesis("Deflection1D", [d])
529 ## Define "Propagation" hypothesis that propagate all other hypothesis on all others edges that are in
530 # the opposite side in the case of quadrangular faces
531 def Propagation(self):
532 return self.Hypothesis("Propagation")
534 ## Define "AutomaticLength" hypothesis
535 # @param fineness for the fineness [0-1]
536 def AutomaticLength(self, fineness=0):
537 hyp = self.Hypothesis("AutomaticLength")
538 hyp.SetFineness( fineness )
541 ## Define "SegmentLengthAroundVertex" hypothesis
542 # @param length for the segment length
543 # @param vertex for the length localization: vertex index [0,1] | verext object
544 def LengthNearVertex(self, length, vertex=0):
546 store_geom = self.geom
548 if type(vertex) is types.IntType:
549 vertex = geompy.SubShapeAllSorted(self.geom,geompy.ShapeType["VERTEX"])[vertex]
553 hyp = self.Hypothesis("SegmentAroundVertex_0D")
554 hyp = self.Hypothesis("SegmentLengthAroundVertex")
555 self.geom = store_geom
556 hyp.SetLength( length )
559 ## Define "QuadraticMesh" hypothesis, forcing construction of quadratic edges.
560 # If the 2D mesher sees that all boundary edges are quadratic ones,
561 # it generates quadratic faces, else it generates linear faces using
562 # medium nodes as if they were vertex ones.
563 # The 3D mesher generates quadratic volumes only if all boundary faces
564 # are quadratic ones, else it fails.
565 def QuadraticMesh(self):
566 hyp = self.Hypothesis("QuadraticMesh")
569 # Public class: Mesh_CompositeSegment
570 # --------------------------
572 ## Class to define a segment 1D algorithm for discretization
575 class Mesh_CompositeSegment(Mesh_Segment):
577 ## Private constructor.
578 def __init__(self, mesh, geom=0):
579 self.Create(mesh, geom, "CompositeSegment_1D")
582 # Public class: Mesh_Segment_Python
583 # ---------------------------------
585 ## Class to define a segment 1D algorithm for discretization with python function
588 class Mesh_Segment_Python(Mesh_Segment):
590 ## Private constructor.
591 def __init__(self, mesh, geom=0):
592 import Python1dPlugin
593 self.Create(mesh, geom, "Python_1D", "libPython1dEngine.so")
595 ## Define "PythonSplit1D" hypothesis based on the Erwan Adam patch, awaiting equivalent SALOME functionality
596 # @param n for the number of segments that cut an edge
597 # @param func for the python function that calculate the length of all segments
598 def PythonSplit1D(self, n, func):
599 hyp = self.Hypothesis("PythonSplit1D", [n], "libPython1dEngine.so")
600 hyp.SetNumberOfSegments(n)
601 hyp.SetPythonLog10RatioFunction(func)
604 # Public class: Mesh_Triangle
605 # ---------------------------
607 ## Class to define a triangle 2D algorithm
610 class Mesh_Triangle(Mesh_Algorithm):
615 ## Private constructor.
616 def __init__(self, mesh, algoType, geom=0):
617 if algoType == MEFISTO:
618 self.Create(mesh, geom, "MEFISTO_2D")
619 elif algoType == NETGEN:
621 print "Warning: NETGENPlugin module has not been imported."
622 self.Create(mesh, geom, "NETGEN_2D", "libNETGENEngine.so")
623 self.algoType = algoType
625 ## Define "MaxElementArea" hypothesis to give the maximun area of each triangles
626 # @param area for the maximum area of each triangles
627 def MaxElementArea(self, area):
628 if self.algoType == MEFISTO:
629 hyp = self.Hypothesis("MaxElementArea", [area])
630 hyp.SetMaxElementArea(area)
632 elif self.algoType == NETGEN:
633 print "Netgen 1D-2D algo doesn't support this hypothesis"
636 ## Define "LengthFromEdges" hypothesis to build triangles based on the length of the edges taken from the wire
637 def LengthFromEdges(self):
638 if self.algoType == MEFISTO:
639 hyp = self.Hypothesis("LengthFromEdges")
641 elif self.algoType == NETGEN:
642 print "Netgen 1D-2D algo doesn't support this hypothesis"
645 ## Define "Netgen 2D Parameters" hypothesis
646 def Parameters(self):
647 if self.algoType == NETGEN:
648 self.params = self.Hypothesis("NETGEN_Parameters_2D", [], "libNETGENEngine.so")
650 elif self.algoType == MEFISTO:
651 print "Mefisto algo doesn't support this hypothesis"
655 def SetMaxSize(self, theSize):
658 self.params.SetMaxSize(theSize)
660 ## Set SecondOrder flag
661 def SetSecondOrder(seld, theVal):
664 self.params.SetSecondOrder(theVal)
667 def SetOptimize(self, theVal):
670 self.params.SetOptimize(theVal)
673 # @param theFineness is:
674 # VeryCoarse, Coarse, Moderate, Fine, VeryFine or Custom
675 def SetFineness(self, theFineness):
678 self.params.SetFineness(theFineness)
681 def SetGrowthRate(self, theRate):
684 self.params.SetGrowthRate(theRate)
687 def SetNbSegPerEdge(self, theVal):
690 self.params.SetNbSegPerEdge(theVal)
692 ## Set NbSegPerRadius
693 def SetNbSegPerRadius(self, theVal):
696 self.params.SetNbSegPerRadius(theVal)
698 ## Set QuadAllowed flag
699 def SetQuadAllowed(self, toAllow):
702 self.params.SetQuadAllowed(toAllow)
705 # Public class: Mesh_Quadrangle
706 # -----------------------------
708 ## Class to define a quadrangle 2D algorithm
711 class Mesh_Quadrangle(Mesh_Algorithm):
713 ## Private constructor.
714 def __init__(self, mesh, geom=0):
715 self.Create(mesh, geom, "Quadrangle_2D")
717 ## Define "QuadranglePreference" hypothesis, forcing construction
718 # of quadrangles if the number of nodes on opposite edges is not the same
719 # in the case where the global number of nodes on edges is even
720 def QuadranglePreference(self):
721 hyp = self.Hypothesis("QuadranglePreference")
724 # Public class: Mesh_Tetrahedron
725 # ------------------------------
727 ## Class to define a tetrahedron 3D algorithm
730 class Mesh_Tetrahedron(Mesh_Algorithm):
735 ## Private constructor.
736 def __init__(self, mesh, algoType, geom=0):
737 if algoType == NETGEN:
738 self.Create(mesh, geom, "NETGEN_3D", "libNETGENEngine.so")
739 elif algoType == GHS3D:
741 self.Create(mesh, geom, "GHS3D_3D" , "libGHS3DEngine.so")
742 elif algoType == FULL_NETGEN:
744 print "Warning: NETGENPlugin module has not been imported."
745 self.Create(mesh, geom, "NETGEN_2D3D", "libNETGENEngine.so")
746 self.algoType = algoType
748 ## Define "MaxElementVolume" hypothesis to give the maximun volume of each tetrahedral
749 # @param vol for the maximum volume of each tetrahedral
750 def MaxElementVolume(self, vol):
751 hyp = self.Hypothesis("MaxElementVolume", [vol])
752 hyp.SetMaxElementVolume(vol)
755 ## Define "Netgen 3D Parameters" hypothesis
756 def Parameters(self):
757 if (self.algoType == FULL_NETGEN):
758 self.params = self.Hypothesis("NETGEN_Parameters", [], "libNETGENEngine.so")
761 print "Algo doesn't support this hypothesis"
765 def SetMaxSize(self, theSize):
768 self.params.SetMaxSize(theSize)
770 ## Set SecondOrder flag
771 def SetSecondOrder(self, theVal):
774 self.params.SetSecondOrder(theVal)
777 def SetOptimize(self, theVal):
780 self.params.SetOptimize(theVal)
783 # @param theFineness is:
784 # VeryCoarse, Coarse, Moderate, Fine, VeryFine or Custom
785 def SetFineness(self, theFineness):
788 self.params.SetFineness(theFineness)
791 def SetGrowthRate(self, theRate):
794 self.params.SetGrowthRate(theRate)
797 def SetNbSegPerEdge(self, theVal):
800 self.params.SetNbSegPerEdge(theVal)
802 ## Set NbSegPerRadius
803 def SetNbSegPerRadius(self, theVal):
806 self.params.SetNbSegPerRadius(theVal)
808 # Public class: Mesh_Hexahedron
809 # ------------------------------
811 ## Class to define a hexahedron 3D algorithm
814 class Mesh_Hexahedron(Mesh_Algorithm):
816 ## Private constructor.
817 def __init__(self, mesh, geom=0):
818 self.Create(mesh, geom, "Hexa_3D")
820 # Deprecated, only for compatibility!
821 # Public class: Mesh_Netgen
822 # ------------------------------
824 ## Class to define a NETGEN-based 2D or 3D algorithm
825 # that need no discrete boundary (i.e. independent)
827 # This class is deprecated, only for compatibility!
830 class Mesh_Netgen(Mesh_Algorithm):
834 ## Private constructor.
835 def __init__(self, mesh, is3D, geom=0):
837 print "Warning: NETGENPlugin module has not been imported."
841 self.Create(mesh, geom, "NETGEN_2D3D", "libNETGENEngine.so")
843 self.Create(mesh, geom, "NETGEN_2D", "libNETGENEngine.so")
845 ## Define hypothesis containing parameters of the algorithm
846 def Parameters(self):
848 hyp = self.Hypothesis("NETGEN_Parameters", [], "libNETGENEngine.so")
850 hyp = self.Hypothesis("NETGEN_Parameters_2D", [], "libNETGENEngine.so")
853 # Public class: Mesh_Projection1D
854 # ------------------------------
856 ## Class to define a projection 1D algorithm
859 class Mesh_Projection1D(Mesh_Algorithm):
861 ## Private constructor.
862 def __init__(self, mesh, geom=0):
863 self.Create(mesh, geom, "Projection_1D")
865 ## Define "Source Edge" hypothesis, specifying a meshed edge to
866 # take a mesh pattern from, and optionally association of vertices
867 # between the source edge and a target one (where a hipothesis is assigned to)
868 # @param edge to take nodes distribution from
869 # @param mesh to take nodes distribution from (optional)
870 # @param srcV is vertex of \a edge to associate with \a tgtV (optional)
871 # @param tgtV is vertex of \a the edge where the algorithm is assigned,
872 # to associate with \a srcV (optional)
873 def SourceEdge(self, edge, mesh=None, srcV=None, tgtV=None):
874 hyp = self.Hypothesis("ProjectionSource1D")
875 hyp.SetSourceEdge( edge )
876 if not mesh is None and isinstance(mesh, Mesh):
877 mesh = mesh.GetMesh()
878 hyp.SetSourceMesh( mesh )
879 hyp.SetVertexAssociation( srcV, tgtV )
883 # Public class: Mesh_Projection2D
884 # ------------------------------
886 ## Class to define a projection 2D algorithm
889 class Mesh_Projection2D(Mesh_Algorithm):
891 ## Private constructor.
892 def __init__(self, mesh, geom=0):
893 self.Create(mesh, geom, "Projection_2D")
895 ## Define "Source Face" hypothesis, specifying a meshed face to
896 # take a mesh pattern from, and optionally association of vertices
897 # between the source face and a target one (where a hipothesis is assigned to)
898 # @param face to take mesh pattern from
899 # @param mesh to take mesh pattern from (optional)
900 # @param srcV1 is vertex of \a face to associate with \a tgtV1 (optional)
901 # @param tgtV1 is vertex of \a the face where the algorithm is assigned,
902 # to associate with \a srcV1 (optional)
903 # @param srcV2 is vertex of \a face to associate with \a tgtV1 (optional)
904 # @param tgtV2 is vertex of \a the face where the algorithm is assigned,
905 # to associate with \a srcV2 (optional)
907 # Note: association vertices must belong to one edge of a face
908 def SourceFace(self, face, mesh=None, srcV1=None, tgtV1=None, srcV2=None, tgtV2=None):
909 hyp = self.Hypothesis("ProjectionSource2D")
910 hyp.SetSourceFace( face )
911 if not mesh is None and isinstance(mesh, Mesh):
912 mesh = mesh.GetMesh()
913 hyp.SetSourceMesh( mesh )
914 hyp.SetVertexAssociation( srcV1, srcV2, tgtV1, tgtV2 )
917 # Public class: Mesh_Projection3D
918 # ------------------------------
920 ## Class to define a projection 3D algorithm
923 class Mesh_Projection3D(Mesh_Algorithm):
925 ## Private constructor.
926 def __init__(self, mesh, geom=0):
927 self.Create(mesh, geom, "Projection_3D")
929 ## Define "Source Shape 3D" hypothesis, specifying a meshed solid to
930 # take a mesh pattern from, and optionally association of vertices
931 # between the source solid and a target one (where a hipothesis is assigned to)
932 # @param solid to take mesh pattern from
933 # @param mesh to take mesh pattern from (optional)
934 # @param srcV1 is vertex of \a solid to associate with \a tgtV1 (optional)
935 # @param tgtV1 is vertex of \a the solid where the algorithm is assigned,
936 # to associate with \a srcV1 (optional)
937 # @param srcV2 is vertex of \a solid to associate with \a tgtV1 (optional)
938 # @param tgtV2 is vertex of \a the solid where the algorithm is assigned,
939 # to associate with \a srcV2 (optional)
941 # Note: association vertices must belong to one edge of a solid
942 def SourceShape3D(self, solid, mesh=0, srcV1=0, tgtV1=0, srcV2=0, tgtV2=0):
943 hyp = self.Hypothesis("ProjectionSource3D")
944 hyp.SetSource3DShape( solid )
945 if not mesh is None and isinstance(mesh, Mesh):
946 mesh = mesh.GetMesh()
947 hyp.SetSourceMesh( mesh )
948 hyp.SetVertexAssociation( srcV1, srcV2, tgtV1, tgtV2 )
952 # Public class: Mesh_Prism
953 # ------------------------
955 ## Class to define a 3D extrusion algorithm
958 class Mesh_Prism3D(Mesh_Algorithm):
960 ## Private constructor.
961 def __init__(self, mesh, geom=0):
962 self.Create(mesh, geom, "Prism_3D")
964 # Public class: Mesh_RadialPrism
965 # -------------------------------
967 ## Class to define a Radial Prism 3D algorithm
970 class Mesh_RadialPrism3D(Mesh_Algorithm):
972 ## Private constructor.
973 def __init__(self, mesh, geom=0):
974 self.Create(mesh, geom, "RadialPrism_3D")
975 self.distribHyp = self.Hypothesis( "LayerDistribution" )
978 ## Return 3D hypothesis holding the 1D one
979 def Get3DHypothesis(self):
980 return self.distribHyp
982 ## Private method creating 1D hypothes and storing it in the LayerDistribution
983 # hypothes. Returns the created hypothes
984 def OwnHypothesis(self, hypType, args=[], so="libStdMeshersEngine.so"):
985 if not self.nbLayers is None:
986 self.mesh.GetMesh().RemoveHypothesis( self.geom, self.nbLayers )
987 self.mesh.GetMesh().AddHypothesis( self.geom, self.distribHyp )
988 study = GetCurrentStudy() # prevent publishing of own 1D hypothesis
989 hyp = smesh.CreateHypothesis(hypType, so)
990 SetCurrentStudy( study ) # anable publishing
991 self.distribHyp.SetLayerDistribution( hyp )
994 ## Define "NumberOfLayers" hypothesis, specifying a number of layers of
995 # prisms to build between the inner and outer shells
996 def NumberOfLayers(self, n ):
997 self.mesh.GetMesh().RemoveHypothesis( self.geom, self.distribHyp )
998 self.nbLayers = self.Hypothesis("NumberOfLayers")
999 self.nbLayers.SetNumberOfLayers( n )
1000 return self.nbLayers
1002 ## Define "LocalLength" hypothesis, specifying segment length
1003 # to build between the inner and outer shells
1004 # @param l for the length of segments
1005 def LocalLength(self, l):
1006 hyp = self.OwnHypothesis("LocalLength", [l])
1010 ## Define "NumberOfSegments" hypothesis, specifying a number of layers of
1011 # prisms to build between the inner and outer shells
1012 # @param n for the number of segments
1013 # @param s for the scale factor (optional)
1014 def NumberOfSegments(self, n, s=[]):
1016 hyp = self.OwnHypothesis("NumberOfSegments", [n])
1018 hyp = self.OwnHypothesis("NumberOfSegments", [n,s])
1019 hyp.SetDistrType( 1 )
1020 hyp.SetScaleFactor(s)
1021 hyp.SetNumberOfSegments(n)
1024 ## Define "Arithmetic1D" hypothesis, specifying distribution of segments
1025 # to build between the inner and outer shells as arithmetic length increasing
1026 # @param start for the length of the first segment
1027 # @param end for the length of the last segment
1028 def Arithmetic1D(self, start, end):
1029 hyp = self.OwnHypothesis("Arithmetic1D", [start, end])
1030 hyp.SetLength(start, 1)
1031 hyp.SetLength(end , 0)
1034 ## Define "StartEndLength" hypothesis, specifying distribution of segments
1035 # to build between the inner and outer shells as geometric length increasing
1036 # @param start for the length of the first segment
1037 # @param end for the length of the last segment
1038 def StartEndLength(self, start, end):
1039 hyp = self.OwnHypothesis("StartEndLength", [start, end])
1040 hyp.SetLength(start, 1)
1041 hyp.SetLength(end , 0)
1044 ## Define "AutomaticLength" hypothesis, specifying number of segments
1045 # to build between the inner and outer shells
1046 # @param fineness for the fineness [0-1]
1047 def AutomaticLength(self, fineness=0):
1048 hyp = self.OwnHypothesis("AutomaticLength")
1049 hyp.SetFineness( fineness )
1053 # Public class: Mesh
1054 # ==================
1056 ## Class to define a mesh
1058 # The class contains mesh shape, SMESH_Mesh, SMESH_MeshEditor
1068 # Creates mesh on the shape \a geom(or the empty mesh if geom equal to 0),
1069 # sets GUI name of this mesh to \a name.
1070 # @param obj Shape to be meshed or SMESH_Mesh object
1071 # @param name Study name of the mesh
1072 def __init__(self, obj=0, name=0):
1076 if isinstance(obj, geompy.GEOM._objref_GEOM_Object):
1078 self.mesh = smesh.CreateMesh(self.geom)
1079 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1082 self.mesh = smesh.CreateEmptyMesh()
1084 SetName(self.mesh, name)
1086 SetName(self.mesh, GetName(obj))
1088 self.editor = self.mesh.GetMeshEditor()
1090 ## Method that inits the Mesh object from SMESH_Mesh interface
1091 # @param theMesh is SMESH_Mesh object
1092 def SetMesh(self, theMesh):
1094 self.geom = self.mesh.GetShapeToMesh()
1096 ## Method that returns the mesh
1097 # @return SMESH_Mesh object
1103 name = GetName(self.GetMesh())
1107 def SetName(self, name):
1108 SetName(self.GetMesh(), name)
1110 ## Get the subMesh object associated to a subShape. The subMesh object
1111 # gives access to nodes and elements IDs.
1112 # \n SubMesh will be used instead of SubShape in a next idl version to
1113 # adress a specific subMesh...
1114 def GetSubMesh(self, theSubObject, name):
1115 submesh = self.mesh.GetSubMesh(theSubObject, name)
1118 ## Method that returns the shape associated to the mesh
1119 # @return GEOM_Object
1123 ## Method that associates given shape to the mesh(entails the mesh recreation)
1124 # @param geom shape to be meshed(GEOM_Object)
1125 def SetShape(self, geom):
1126 self.mesh = smesh.CreateMesh(geom)
1128 ## Return true if hypotheses are defined well
1129 # @param theMesh is an instance of Mesh class
1130 # @param theSubObject subshape of a mesh shape
1131 def IsReadyToCompute(self, theSubObject):
1132 return smesh.IsReadyToCompute(self.mesh, theSubObject)
1134 ## Return errors of hypotheses definintion
1135 # error list is empty if everything is OK
1136 # @param theMesh is an instance of Mesh class
1137 # @param theSubObject subshape of a mesh shape
1138 # @return a list of errors
1139 def GetAlgoState(self, theSubObject):
1140 return smesh.GetAlgoState(self.mesh, theSubObject)
1142 ## Return geometrical object the given element is built on.
1143 # The returned geometrical object, if not nil, is either found in the
1144 # study or is published by this method with the given name
1145 # @param theMesh is an instance of Mesh class
1146 # @param theElementID an id of the mesh element
1147 # @param theGeomName user defined name of geometrical object
1148 # @return GEOM::GEOM_Object instance
1149 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1150 return smesh.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1152 ## Returns mesh dimension depending on shape one
1153 def MeshDimension(self):
1154 shells = geompy.SubShapeAllIDs( self.geom, geompy.ShapeType["SHELL"] )
1155 if len( shells ) > 0 :
1157 elif geompy.NumberOfFaces( self.geom ) > 0 :
1159 elif geompy.NumberOfEdges( self.geom ) > 0 :
1165 ## Creates a segment discretization 1D algorithm.
1166 # If the optional \a algo parameter is not sets, this algorithm is REGULAR.
1167 # If the optional \a geom parameter is not sets, this algorithm is global.
1168 # \n Otherwise, this algorithm define a submesh based on \a geom subshape.
1169 # @param algo values are smesh.REGULAR or smesh.PYTHON for discretization via python function
1170 # @param geom If defined, subshape to be meshed
1171 def Segment(self, algo=REGULAR, geom=0):
1172 ## if Segment(geom) is called by mistake
1173 if ( isinstance( algo, geompy.GEOM._objref_GEOM_Object)):
1174 algo, geom = geom, algo
1177 return Mesh_Segment(self, geom)
1178 elif algo == PYTHON:
1179 return Mesh_Segment_Python(self, geom)
1180 elif algo == COMPOSITE:
1181 return Mesh_CompositeSegment(self, geom)
1183 return Mesh_Segment(self, geom)
1185 ## Creates a triangle 2D algorithm for faces.
1186 # If the optional \a geom parameter is not sets, this algorithm is global.
1187 # \n Otherwise, this algorithm define a submesh based on \a geom subshape.
1188 # @param algo values are: smesh.MEFISTO or smesh.NETGEN
1189 # @param geom If defined, subshape to be meshed
1190 def Triangle(self, algo=MEFISTO, geom=0):
1191 ## if Triangle(geom) is called by mistake
1192 if ( isinstance( algo, geompy.GEOM._objref_GEOM_Object)):
1196 return Mesh_Triangle(self, algo, geom)
1198 ## Creates a quadrangle 2D algorithm for faces.
1199 # If the optional \a geom parameter is not sets, this algorithm is global.
1200 # \n Otherwise, this algorithm define a submesh based on \a geom subshape.
1201 # @param geom If defined, subshape to be meshed
1202 def Quadrangle(self, geom=0):
1203 return Mesh_Quadrangle(self, geom)
1205 ## Creates a tetrahedron 3D algorithm for solids.
1206 # The parameter \a algo permits to choice the algorithm: NETGEN or GHS3D
1207 # If the optional \a geom parameter is not sets, this algorithm is global.
1208 # \n Otherwise, this algorithm define a submesh based on \a geom subshape.
1209 # @param algo values are: smesh.NETGEN, smesh.GHS3D, smesh.FULL_NETGEN
1210 # @param geom If defined, subshape to be meshed
1211 def Tetrahedron(self, algo=NETGEN, geom=0):
1212 ## if Tetrahedron(geom) is called by mistake
1213 if ( isinstance( algo, geompy.GEOM._objref_GEOM_Object)):
1214 algo, geom = geom, algo
1216 return Mesh_Tetrahedron(self, algo, geom)
1218 ## Creates a hexahedron 3D algorithm for solids.
1219 # If the optional \a geom parameter is not sets, this algorithm is global.
1220 # \n Otherwise, this algorithm define a submesh based on \a geom subshape.
1221 # @param geom If defined, subshape to be meshed
1222 def Hexahedron(self, geom=0):
1223 return Mesh_Hexahedron(self, geom)
1225 ## Deprecated, only for compatibility!
1226 def Netgen(self, is3D, geom=0):
1227 return Mesh_Netgen(self, is3D, geom)
1229 ## Creates a projection 1D algorithm for edges.
1230 # If the optional \a geom parameter is not sets, this algorithm is global.
1231 # Otherwise, this algorithm define a submesh based on \a geom subshape.
1232 # @param geom If defined, subshape to be meshed
1233 def Projection1D(self, geom=0):
1234 return Mesh_Projection1D(self, geom)
1236 ## Creates a projection 2D algorithm for faces.
1237 # If the optional \a geom parameter is not sets, this algorithm is global.
1238 # Otherwise, this algorithm define a submesh based on \a geom subshape.
1239 # @param geom If defined, subshape to be meshed
1240 def Projection2D(self, geom=0):
1241 return Mesh_Projection2D(self, geom)
1243 ## Creates a projection 3D algorithm for solids.
1244 # If the optional \a geom parameter is not sets, this algorithm is global.
1245 # Otherwise, this algorithm define a submesh based on \a geom subshape.
1246 # @param geom If defined, subshape to be meshed
1247 def Projection3D(self, geom=0):
1248 return Mesh_Projection3D(self, geom)
1250 ## Creates a 3D extrusion (Prism 3D) or RadialPrism 3D algorithm for solids.
1251 # If the optional \a geom parameter is not sets, this algorithm is global.
1252 # Otherwise, this algorithm define a submesh based on \a geom subshape.
1253 # @param geom If defined, subshape to be meshed
1254 def Prism(self, geom=0):
1258 nbSolids = len( geompy.SubShapeAll( shape, geompy.ShapeType["SOLID"] ))
1259 nbShells = len( geompy.SubShapeAll( shape, geompy.ShapeType["SHELL"] ))
1260 if nbSolids == 0 or nbSolids == nbShells:
1261 return Mesh_Prism3D(self, geom)
1262 return Mesh_RadialPrism3D(self, geom)
1264 ## Compute the mesh and return the status of the computation
1265 def Compute(self, geom=0):
1266 if geom == 0 or not isinstance(geom, geompy.GEOM._objref_GEOM_Object):
1268 print "Compute impossible: mesh is not constructed on geom shape."
1272 ok = smesh.Compute(self.mesh, geom)
1274 errors = smesh.GetAlgoState( self.mesh, geom )
1277 if err.isGlobalAlgo:
1282 dim = str(err.algoDim)
1283 if err.name == MISSING_ALGO:
1284 reason = glob + dim + "D algorithm is missing"
1285 elif err.name == MISSING_HYPO:
1286 name = '"' + err.algoName + '"'
1287 reason = glob + dim + "D algorithm " + name + " misses " + dim + "D hypothesis"
1288 elif err.name == NOT_CONFORM_MESH:
1289 reason = "Global \"Not Conform mesh allowed\" hypothesis is missing"
1290 elif err.name == BAD_PARAM_VALUE:
1291 name = '"' + err.algoName + '"'
1292 reason = "Hypothesis of" + glob + dim + "D algorithm " + name +\
1293 " has a bad parameter value"
1295 reason = "For unknown reason."+\
1296 " Revise Mesh.Compute() implementation in smesh.py!"
1298 if allReasons != "":
1301 allReasons += reason
1303 if allReasons != "":
1304 print '"' + GetName(self.mesh) + '"',"not computed:"
1308 if salome.sg.hasDesktop():
1309 smeshgui = salome.ImportComponentGUI("SMESH")
1310 smeshgui.Init(salome.myStudyId)
1311 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok )
1312 salome.sg.updateObjBrowser(1)
1316 ## Compute tetrahedral mesh using AutomaticLength + MEFISTO + NETGEN
1317 # The parameter \a fineness [0,-1] defines mesh fineness
1318 def AutomaticTetrahedralization(self, fineness=0):
1319 dim = self.MeshDimension()
1321 self.RemoveGlobalHypotheses()
1322 self.Segment().AutomaticLength(fineness)
1324 self.Triangle().LengthFromEdges()
1327 self.Tetrahedron(NETGEN)
1329 return self.Compute()
1331 ## Compute hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1332 # The parameter \a fineness [0,-1] defines mesh fineness
1333 def AutomaticHexahedralization(self, fineness=0):
1334 dim = self.MeshDimension()
1336 self.RemoveGlobalHypotheses()
1337 self.Segment().AutomaticLength(fineness)
1344 return self.Compute()
1346 ## Assign hypothesis
1347 # @param hyp is a hypothesis to assign
1348 # @param geom is subhape of mesh geometry
1349 def AddHypothesis(self, hyp, geom=0 ):
1350 if isinstance( hyp, Mesh_Algorithm ):
1351 hyp = hyp.GetAlgorithm()
1356 status = self.mesh.AddHypothesis(geom, hyp)
1357 isAlgo = ( hyp._narrow( SMESH.SMESH_Algo ) is not None )
1358 TreatHypoStatus( status, GetName( hyp ), GetName( geom ), isAlgo )
1361 ## Get the list of hypothesis added on a geom
1362 # @param geom is subhape of mesh geometry
1363 def GetHypothesisList(self, geom):
1364 return self.mesh.GetHypothesisList( geom )
1366 ## Removes all global hypotheses
1367 def RemoveGlobalHypotheses(self):
1368 current_hyps = self.mesh.GetHypothesisList( self.geom )
1369 for hyp in current_hyps:
1370 self.mesh.RemoveHypothesis( self.geom, hyp )
1374 ## Create a mesh group based on geometric object \a grp
1375 # and give a \a name, \n if this parameter is not defined
1376 # the name is the same as the geometric group name \n
1377 # Note: Works like GroupOnGeom().
1378 # @param grp is a geometric group, a vertex, an edge, a face or a solid
1379 # @param name is the name of the mesh group
1380 # @return SMESH_GroupOnGeom
1381 def Group(self, grp, name=""):
1382 return self.GroupOnGeom(grp, name)
1384 ## Deprecated, only for compatibility! Please, use ExportMED() method instead.
1385 # Export the mesh in a file with the MED format and choice the \a version of MED format
1386 # @param f is the file name
1387 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1388 def ExportToMED(self, f, version, opt=0):
1389 self.mesh.ExportToMED(f, opt, version)
1391 ## Export the mesh in a file with the MED format
1392 # @param f is the file name
1393 # @param auto_groups boolean parameter for creating/not creating
1394 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1395 # the typical use is auto_groups=false.
1396 # @param version MED format version(MED_V2_1 or MED_V2_2)
1397 def ExportMED(self, f, auto_groups=0, version=MED_V2_2):
1398 self.mesh.ExportToMED(f, auto_groups, version)
1400 ## Export the mesh in a file with the DAT format
1401 # @param f is the file name
1402 def ExportDAT(self, f):
1403 self.mesh.ExportDAT(f)
1405 ## Export the mesh in a file with the UNV format
1406 # @param f is the file name
1407 def ExportUNV(self, f):
1408 self.mesh.ExportUNV(f)
1410 ## Export the mesh in a file with the STL format
1411 # @param f is the file name
1412 # @param ascii defined the kind of file contents
1413 def ExportSTL(self, f, ascii=1):
1414 self.mesh.ExportSTL(f, ascii)
1417 # Operations with groups:
1418 # ----------------------
1420 ## Creates an empty mesh group
1421 # @param elementType is the type of elements in the group
1422 # @param name is the name of the mesh group
1423 # @return SMESH_Group
1424 def CreateEmptyGroup(self, elementType, name):
1425 return self.mesh.CreateGroup(elementType, name)
1427 ## Creates a mesh group based on geometric object \a grp
1428 # and give a \a name, \n if this parameter is not defined
1429 # the name is the same as the geometric group name
1430 # @param grp is a geometric group, a vertex, an edge, a face or a solid
1431 # @param name is the name of the mesh group
1432 # @return SMESH_GroupOnGeom
1433 def GroupOnGeom(self, grp, name="", type=None):
1435 name = grp.GetName()
1438 tgeo = str(grp.GetShapeType())
1439 if tgeo == "VERTEX":
1441 elif tgeo == "EDGE":
1443 elif tgeo == "FACE":
1445 elif tgeo == "SOLID":
1447 elif tgeo == "SHELL":
1449 elif tgeo == "COMPOUND":
1450 if len( geompy.GetObjectIDs( grp )) == 0:
1451 print "Mesh.Group: empty geometric group", GetName( grp )
1453 tgeo = geompy.GetType(grp)
1454 if tgeo == geompy.ShapeType["VERTEX"]:
1456 elif tgeo == geompy.ShapeType["EDGE"]:
1458 elif tgeo == geompy.ShapeType["FACE"]:
1460 elif tgeo == geompy.ShapeType["SOLID"]:
1464 print "Mesh.Group: bad first argument: expected a group, a vertex, an edge, a face or a solid"
1467 return self.mesh.CreateGroupFromGEOM(type, name, grp)
1469 ## Create a mesh group by the given ids of elements
1470 # @param groupName is the name of the mesh group
1471 # @param elementType is the type of elements in the group
1472 # @param elemIDs is the list of ids
1473 # @return SMESH_Group
1474 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1475 group = self.mesh.CreateGroup(elementType, groupName)
1479 ## Create a mesh group by the given conditions
1480 # @param groupName is the name of the mesh group
1481 # @param elementType is the type of elements in the group
1482 # @param CritType is type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1483 # @param Compare belong to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1484 # @param Treshold is threshold value (range of id ids as string, shape, numeric)
1485 # @param UnaryOp is FT_LogicalNOT or FT_Undefined
1486 # @return SMESH_Group
1490 CritType=FT_Undefined,
1493 UnaryOp=FT_Undefined):
1494 aCriterion = GetCriterion(elementType, CritType, Compare, Treshold, UnaryOp, FT_Undefined)
1495 group = self.MakeGroupByCriterion(groupName, aCriterion)
1498 ## Create a mesh group by the given criterion
1499 # @param groupName is the name of the mesh group
1500 # @param Criterion is the instance of Criterion class
1501 # @return SMESH_Group
1502 def MakeGroupByCriterion(self, groupName, Criterion):
1503 aFilterMgr = smesh.CreateFilterManager()
1504 aFilter = aFilterMgr.CreateFilter()
1506 aCriteria.append(Criterion)
1507 aFilter.SetCriteria(aCriteria)
1508 group = self.MakeGroupByFilter(groupName, aFilter)
1511 ## Create a mesh group by the given criteria(list of criterions)
1512 # @param groupName is the name of the mesh group
1513 # @param Criteria is the list of criterions
1514 # @return SMESH_Group
1515 def MakeGroupByCriteria(self, groupName, theCriteria):
1516 aFilterMgr = smesh.CreateFilterManager()
1517 aFilter = aFilterMgr.CreateFilter()
1518 aFilter.SetCriteria(theCriteria)
1519 group = self.MakeGroupByFilter(groupName, aFilter)
1522 ## Create a mesh group by the given filter
1523 # @param groupName is the name of the mesh group
1524 # @param Criterion is the instance of Filter class
1525 # @return SMESH_Group
1526 def MakeGroupByFilter(self, groupName, theFilter):
1527 anIds = theFilter.GetElementsId(self.mesh)
1528 anElemType = theFilter.GetElementType()
1529 group = self.MakeGroupByIds(groupName, anElemType, anIds)
1532 ## Pass mesh elements through the given filter and return ids
1533 # @param theFilter is SMESH_Filter
1534 # @return list of ids
1535 def GetIdsFromFilter(self, theFilter):
1536 return theFilter.GetElementsId(self.mesh)
1538 ## Verify whether 2D mesh element has free edges(edges connected to one face only)\n
1539 # Returns list of special structures(borders).
1540 # @return list of SMESH.FreeEdges.Border structure: edge id and two its nodes ids.
1541 def GetFreeBorders(self):
1542 aFilterMgr = smesh.CreateFilterManager()
1543 aPredicate = aFilterMgr.CreateFreeEdges()
1544 aPredicate.SetMesh(self.mesh)
1545 aBorders = aPredicate.GetBorders()
1549 def RemoveGroup(self, group):
1550 self.mesh.RemoveGroup(group)
1552 ## Remove group with its contents
1553 def RemoveGroupWithContents(self, group):
1554 self.mesh.RemoveGroupWithContents(group)
1556 ## Get the list of groups existing in the mesh
1557 def GetGroups(self):
1558 return self.mesh.GetGroups()
1560 ## Get the list of names of groups existing in the mesh
1561 def GetGroupNames(self):
1562 groups = self.GetGroups()
1564 for group in groups:
1565 names.append(group.GetName())
1568 ## Union of two groups
1569 # New group is created. All mesh elements that are
1570 # present in initial groups are added to the new one
1571 def UnionGroups(self, group1, group2, name):
1572 return self.mesh.UnionGroups(group1, group2, name)
1574 ## Intersection of two groups
1575 # New group is created. All mesh elements that are
1576 # present in both initial groups are added to the new one.
1577 def IntersectGroups(self, group1, group2, name):
1578 return self.mesh.IntersectGroups(group1, group2, name)
1580 ## Cut of two groups
1581 # New group is created. All mesh elements that are present in
1582 # main group but do not present in tool group are added to the new one
1583 def CutGroups(self, mainGroup, toolGroup, name):
1584 return self.mesh.CutGroups(mainGroup, toolGroup, name)
1587 # Get some info about mesh:
1588 # ------------------------
1590 ## Get the log of nodes and elements added or removed since previous
1592 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
1593 # @return list of log_block structures:
1598 def GetLog(self, clearAfterGet):
1599 return self.mesh.GetLog(clearAfterGet)
1601 ## Clear the log of nodes and elements added or removed since previous
1602 # clear. Must be used immediately after GetLog if clearAfterGet is false.
1604 self.mesh.ClearLog()
1606 ## Get the internal Id
1608 return self.mesh.GetId()
1611 def GetStudyId(self):
1612 return self.mesh.GetStudyId()
1614 ## Check group names for duplications.
1615 # Consider maximum group name length stored in MED file.
1616 def HasDuplicatedGroupNamesMED(self):
1617 return self.mesh.GetStudyId()
1619 ## Obtain instance of SMESH_MeshEditor
1620 def GetMeshEditor(self):
1621 return self.mesh.GetMeshEditor()
1624 def GetMEDMesh(self):
1625 return self.mesh.GetMEDMesh()
1628 # Get informations about mesh contents:
1629 # ------------------------------------
1631 ## Returns number of nodes in mesh
1633 return self.mesh.NbNodes()
1635 ## Returns number of elements in mesh
1636 def NbElements(self):
1637 return self.mesh.NbElements()
1639 ## Returns number of edges in mesh
1641 return self.mesh.NbEdges()
1643 ## Returns number of edges with given order in mesh
1644 # @param elementOrder is order of elements:
1645 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1646 def NbEdgesOfOrder(self, elementOrder):
1647 return self.mesh.NbEdgesOfOrder(elementOrder)
1649 ## Returns number of faces in mesh
1651 return self.mesh.NbFaces()
1653 ## Returns number of faces with given order in mesh
1654 # @param elementOrder is order of elements:
1655 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1656 def NbFacesOfOrder(self, elementOrder):
1657 return self.mesh.NbFacesOfOrder(elementOrder)
1659 ## Returns number of triangles in mesh
1660 def NbTriangles(self):
1661 return self.mesh.NbTriangles()
1663 ## Returns number of triangles with given order in mesh
1664 # @param elementOrder is order of elements:
1665 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1666 def NbTrianglesOfOrder(self, elementOrder):
1667 return self.mesh.NbTrianglesOfOrder(elementOrder)
1669 ## Returns number of quadrangles in mesh
1670 def NbQuadrangles(self):
1671 return self.mesh.NbQuadrangles()
1673 ## Returns number of quadrangles with given order in mesh
1674 # @param elementOrder is order of elements:
1675 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1676 def NbQuadranglesOfOrder(self, elementOrder):
1677 return self.mesh.NbQuadranglesOfOrder(elementOrder)
1679 ## Returns number of polygons in mesh
1680 def NbPolygons(self):
1681 return self.mesh.NbPolygons()
1683 ## Returns number of volumes in mesh
1684 def NbVolumes(self):
1685 return self.mesh.NbVolumes()
1687 ## Returns number of volumes with given order in mesh
1688 # @param elementOrder is order of elements:
1689 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1690 def NbVolumesOfOrder(self, elementOrder):
1691 return self.mesh.NbVolumesOfOrder(elementOrder)
1693 ## Returns number of tetrahedrons in mesh
1695 return self.mesh.NbTetras()
1697 ## Returns number of tetrahedrons with given order in mesh
1698 # @param elementOrder is order of elements:
1699 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1700 def NbTetrasOfOrder(self, elementOrder):
1701 return self.mesh.NbTetrasOfOrder(elementOrder)
1703 ## Returns number of hexahedrons in mesh
1705 return self.mesh.NbHexas()
1707 ## Returns number of hexahedrons with given order in mesh
1708 # @param elementOrder is order of elements:
1709 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1710 def NbHexasOfOrder(self, elementOrder):
1711 return self.mesh.NbHexasOfOrder(elementOrder)
1713 ## Returns number of pyramids in mesh
1714 def NbPyramids(self):
1715 return self.mesh.NbPyramids()
1717 ## Returns number of pyramids with given order in mesh
1718 # @param elementOrder is order of elements:
1719 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1720 def NbPyramidsOfOrder(self, elementOrder):
1721 return self.mesh.NbPyramidsOfOrder(elementOrder)
1723 ## Returns number of prisms in mesh
1725 return self.mesh.NbPrisms()
1727 ## Returns number of prisms with given order in mesh
1728 # @param elementOrder is order of elements:
1729 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1730 def NbPrismsOfOrder(self, elementOrder):
1731 return self.mesh.NbPrismsOfOrder(elementOrder)
1733 ## Returns number of polyhedrons in mesh
1734 def NbPolyhedrons(self):
1735 return self.mesh.NbPolyhedrons()
1737 ## Returns number of submeshes in mesh
1738 def NbSubMesh(self):
1739 return self.mesh.NbSubMesh()
1741 ## Returns list of mesh elements ids
1742 def GetElementsId(self):
1743 return self.mesh.GetElementsId()
1745 ## Returns list of ids of mesh elements with given type
1746 # @param elementType is required type of elements
1747 def GetElementsByType(self, elementType):
1748 return self.mesh.GetElementsByType(elementType)
1750 ## Returns list of mesh nodes ids
1751 def GetNodesId(self):
1752 return self.mesh.GetNodesId()
1754 # Get informations about mesh elements:
1755 # ------------------------------------
1757 ## Returns type of mesh element
1758 def GetElementType(self, id, iselem):
1759 return self.mesh.GetElementType(id, iselem)
1761 ## Returns list of submesh elements ids
1762 # @param shapeID is geom object(subshape) IOR
1763 def GetSubMeshElementsId(self, shapeID):
1764 return self.mesh.GetSubMeshElementsId(shapeID)
1766 ## Returns list of submesh nodes ids
1767 # @param shapeID is geom object(subshape) IOR
1768 def GetSubMeshNodesId(self, shapeID, all):
1769 return self.mesh.GetSubMeshNodesId(shapeID, all)
1771 ## Returns list of ids of submesh elements with given type
1772 # @param shapeID is geom object(subshape) IOR
1773 def GetSubMeshElementType(self, shapeID):
1774 return self.mesh.GetSubMeshElementType(shapeID)
1776 ## Get mesh description
1778 return self.mesh.Dump()
1781 # Get information about nodes and elements of mesh by its ids:
1782 # -----------------------------------------------------------
1784 ## Get XYZ coordinates of node as list of double
1785 # \n If there is not node for given ID - returns empty list
1786 def GetNodeXYZ(self, id):
1787 return self.mesh.GetNodeXYZ(id)
1789 ## For given node returns list of IDs of inverse elements
1790 # \n If there is not node for given ID - returns empty list
1791 def GetNodeInverseElements(self, id):
1792 return self.mesh.GetNodeInverseElements(id)
1794 ## If given element is node returns IDs of shape from position
1795 # \n If there is not node for given ID - returns -1
1796 def GetShapeID(self, id):
1797 return self.mesh.GetShapeID(id)
1799 ## For given element returns ID of result shape after
1800 # FindShape() from SMESH_MeshEditor
1801 # \n If there is not element for given ID - returns -1
1802 def GetShapeIDForElem(id):
1803 return self.mesh.GetShapeIDForElem(id)
1805 ## Returns number of nodes for given element
1806 # \n If there is not element for given ID - returns -1
1807 def GetElemNbNodes(self, id):
1808 return self.mesh.GetElemNbNodes(id)
1810 ## Returns ID of node by given index for given element
1811 # \n If there is not element for given ID - returns -1
1812 # \n If there is not node for given index - returns -2
1813 def GetElemNode(self, id, index):
1814 return self.mesh.GetElemNode(id, index)
1816 ## Returns true if given node is medium node
1817 # in given quadratic element
1818 def IsMediumNode(self, elementID, nodeID):
1819 return self.mesh.IsMediumNode(elementID, nodeID)
1821 ## Returns true if given node is medium node
1822 # in one of quadratic elements
1823 def IsMediumNodeOfAnyElem(self, nodeID, elementType):
1824 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
1826 ## Returns number of edges for given element
1827 def ElemNbEdges(self, id):
1828 return self.mesh.ElemNbEdges(id)
1830 ## Returns number of faces for given element
1831 def ElemNbFaces(self, id):
1832 return self.mesh.ElemNbFaces(id)
1834 ## Returns true if given element is polygon
1835 def IsPoly(self, id):
1836 return self.mesh.IsPoly(id)
1838 ## Returns true if given element is quadratic
1839 def IsQuadratic(self, id):
1840 return self.mesh.IsQuadratic(id)
1842 ## Returns XYZ coordinates of bary center for given element
1844 # \n If there is not element for given ID - returns empty list
1845 def BaryCenter(self, id):
1846 return self.mesh.BaryCenter(id)
1849 # Mesh edition (SMESH_MeshEditor functionality):
1850 # ---------------------------------------------
1852 ## Removes elements from mesh by ids
1853 # @param IDsOfElements is list of ids of elements to remove
1854 def RemoveElements(self, IDsOfElements):
1855 return self.editor.RemoveElements(IDsOfElements)
1857 ## Removes nodes from mesh by ids
1858 # @param IDsOfNodes is list of ids of nodes to remove
1859 def RemoveNodes(self, IDsOfNodes):
1860 return self.editor.RemoveNodes(IDsOfNodes)
1862 ## Add node to mesh by coordinates
1863 def AddNode(self, x, y, z):
1864 return self.editor.AddNode( x, y, z)
1867 ## Create edge both similar and quadratic (this is determed
1868 # by number of given nodes).
1869 # @param IdsOfNodes List of node IDs for creation of element.
1870 # Needed order of nodes in this list corresponds to description
1871 # of MED. \n This description is located by the following link:
1872 # http://www.salome-platform.org/salome2/web_med_internet/logiciels/medV2.2.2_doc_html/html/modele_de_donnees.html#3.
1873 def AddEdge(self, IDsOfNodes):
1874 return self.editor.AddEdge(IDsOfNodes)
1876 ## Create face both similar and quadratic (this is determed
1877 # by number of given nodes).
1878 # @param IdsOfNodes List of node IDs for creation of element.
1879 # Needed order of nodes in this list corresponds to description
1880 # of MED. \n This description is located by the following link:
1881 # http://www.salome-platform.org/salome2/web_med_internet/logiciels/medV2.2.2_doc_html/html/modele_de_donnees.html#3.
1882 def AddFace(self, IDsOfNodes):
1883 return self.editor.AddFace(IDsOfNodes)
1885 ## Add polygonal face to mesh by list of nodes ids
1886 def AddPolygonalFace(self, IdsOfNodes):
1887 return self.editor.AddPolygonalFace(IdsOfNodes)
1889 ## Create volume both similar and quadratic (this is determed
1890 # by number of given nodes).
1891 # @param IdsOfNodes List of node IDs for creation of element.
1892 # Needed order of nodes in this list corresponds to description
1893 # of MED. \n This description is located by the following link:
1894 # http://www.salome-platform.org/salome2/web_med_internet/logiciels/medV2.2.2_doc_html/html/modele_de_donnees.html#3.
1895 def AddVolume(self, IDsOfNodes):
1896 return self.editor.AddVolume(IDsOfNodes)
1898 ## Create volume of many faces, giving nodes for each face.
1899 # @param IdsOfNodes List of node IDs for volume creation face by face.
1900 # @param Quantities List of integer values, Quantities[i]
1901 # gives quantity of nodes in face number i.
1902 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
1903 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
1905 ## Create volume of many faces, giving IDs of existing faces.
1906 # @param IdsOfFaces List of face IDs for volume creation.
1908 # Note: The created volume will refer only to nodes
1909 # of the given faces, not to the faces itself.
1910 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
1911 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
1913 ## Move node with given id
1914 # @param NodeID id of the node
1915 # @param x new X coordinate
1916 # @param y new Y coordinate
1917 # @param z new Z coordinate
1918 def MoveNode(self, NodeID, x, y, z):
1919 return self.editor.MoveNode(NodeID, x, y, z)
1921 ## Find a node closest to a point
1922 # @param x X coordinate of a point
1923 # @param y Y coordinate of a point
1924 # @param z Z coordinate of a point
1925 # @return id of a node
1926 def FindNodeClosestTo(self, x, y, z):
1927 preview = self.mesh.GetMeshEditPreviewer()
1928 return preview.MoveClosestNodeToPoint(x, y, z, -1)
1930 ## Find a node closest to a point and move it to a point location
1931 # @param x X coordinate of a point
1932 # @param y Y coordinate of a point
1933 # @param z Z coordinate of a point
1934 # @return id of a moved node
1935 def MeshToPassThroughAPoint(self, x, y, z):
1936 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
1938 ## Replace two neighbour triangles sharing Node1-Node2 link
1939 # with ones built on the same 4 nodes but having other common link.
1940 # @param NodeID1 first node id
1941 # @param NodeID2 second node id
1942 # @return false if proper faces not found
1943 def InverseDiag(self, NodeID1, NodeID2):
1944 return self.editor.InverseDiag(NodeID1, NodeID2)
1946 ## Replace two neighbour triangles sharing Node1-Node2 link
1947 # with a quadrangle built on the same 4 nodes.
1948 # @param NodeID1 first node id
1949 # @param NodeID2 second node id
1950 # @return false if proper faces not found
1951 def DeleteDiag(self, NodeID1, NodeID2):
1952 return self.editor.DeleteDiag(NodeID1, NodeID2)
1954 ## Reorient elements by ids
1955 # @param IDsOfElements if undefined reorient all mesh elements
1956 def Reorient(self, IDsOfElements=None):
1957 if IDsOfElements == None:
1958 IDsOfElements = self.GetElementsId()
1959 return self.editor.Reorient(IDsOfElements)
1961 ## Reorient all elements of the object
1962 # @param theObject is mesh, submesh or group
1963 def ReorientObject(self, theObject):
1964 return self.editor.ReorientObject(theObject)
1966 ## Fuse neighbour triangles into quadrangles.
1967 # @param IDsOfElements The triangles to be fused,
1968 # @param theCriterion is FT_...; used to choose a neighbour to fuse with.
1969 # @param MaxAngle is a max angle between element normals at which fusion
1970 # is still performed; theMaxAngle is mesured in radians.
1971 # @return TRUE in case of success, FALSE otherwise.
1972 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
1973 if IDsOfElements == []:
1974 IDsOfElements = self.GetElementsId()
1975 return self.editor.TriToQuad(IDsOfElements, GetFunctor(theCriterion), MaxAngle)
1977 ## Fuse neighbour triangles of the object into quadrangles
1978 # @param theObject is mesh, submesh or group
1979 # @param theCriterion is FT_...; used to choose a neighbour to fuse with.
1980 # @param MaxAngle is a max angle between element normals at which fusion
1981 # is still performed; theMaxAngle is mesured in radians.
1982 # @return TRUE in case of success, FALSE otherwise.
1983 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
1984 return self.editor.TriToQuadObject(theObject, GetFunctor(theCriterion), MaxAngle)
1986 ## Split quadrangles into triangles.
1987 # @param IDsOfElements the faces to be splitted.
1988 # @param theCriterion is FT_...; used to choose a diagonal for splitting.
1989 # @param @return TRUE in case of success, FALSE otherwise.
1990 def QuadToTri (self, IDsOfElements, theCriterion):
1991 if IDsOfElements == []:
1992 IDsOfElements = self.GetElementsId()
1993 return self.editor.QuadToTri(IDsOfElements, GetFunctor(theCriterion))
1995 ## Split quadrangles into triangles.
1996 # @param theObject object to taking list of elements from, is mesh, submesh or group
1997 # @param theCriterion is FT_...; used to choose a diagonal for splitting.
1998 def QuadToTriObject (self, theObject, theCriterion):
1999 return self.editor.QuadToTriObject(theObject, GetFunctor(theCriterion))
2001 ## Split quadrangles into triangles.
2002 # @param theElems The faces to be splitted
2003 # @param the13Diag is used to choose a diagonal for splitting.
2004 # @return TRUE in case of success, FALSE otherwise.
2005 def SplitQuad (self, IDsOfElements, Diag13):
2006 if IDsOfElements == []:
2007 IDsOfElements = self.GetElementsId()
2008 return self.editor.SplitQuad(IDsOfElements, Diag13)
2010 ## Split quadrangles into triangles.
2011 # @param theObject is object to taking list of elements from, is mesh, submesh or group
2012 def SplitQuadObject (self, theObject, Diag13):
2013 return self.editor.SplitQuadObject(theObject, Diag13)
2015 ## Find better splitting of the given quadrangle.
2016 # @param IDOfQuad ID of the quadrangle to be splitted.
2017 # @param theCriterion is FT_...; a criterion to choose a diagonal for splitting.
2018 # @return 1 if 1-3 diagonal is better, 2 if 2-4
2019 # diagonal is better, 0 if error occurs.
2020 def BestSplit (self, IDOfQuad, theCriterion):
2021 return self.editor.BestSplit(IDOfQuad, GetFunctor(theCriterion))
2023 ## Split quafrangle faces near triangular facets of volumes
2025 def SplitQuadsNearTriangularFacets(self):
2026 faces_array = self.GetElementsByType(SMESH.FACE)
2027 for face_id in faces_array:
2028 if self.GetElemNbNodes(face_id) == 4: # quadrangle
2029 quad_nodes = self.mesh.GetElemNodes(face_id)
2030 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
2031 isVolumeFound = False
2032 for node1_elem in node1_elems:
2033 if not isVolumeFound:
2034 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
2035 nb_nodes = self.GetElemNbNodes(node1_elem)
2036 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
2037 volume_elem = node1_elem
2038 volume_nodes = self.mesh.GetElemNodes(volume_elem)
2039 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
2040 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
2041 isVolumeFound = True
2042 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
2043 self.SplitQuad([face_id], False) # diagonal 2-4
2044 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
2045 isVolumeFound = True
2046 self.SplitQuad([face_id], True) # diagonal 1-3
2047 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
2048 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
2049 isVolumeFound = True
2050 self.SplitQuad([face_id], True) # diagonal 1-3
2052 ## @brief Split hexahedrons into tetrahedrons.
2054 # Use pattern mapping functionality for splitting.
2055 # @param theObject object to take list of hexahedrons from; is mesh, submesh or group.
2056 # @param theNode000,theNode001 is in range [0,7]; give an orientation of the
2057 # pattern relatively each hexahedron: the (0,0,0) key-point of pattern
2058 # will be mapped into <theNode000>-th node of each volume, the (0,0,1)
2059 # key-point will be mapped into <theNode001>-th node of each volume.
2060 # The (0,0,0) key-point of used pattern corresponds to not split corner.
2061 # @param @return TRUE in case of success, FALSE otherwise.
2062 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
2063 # Pattern: 5.---------.6
2068 # (0,0,1) 4.---------.7 * |
2075 # (0,0,0) 0.---------.3
2076 pattern_tetra = "!!! Nb of points: \n 8 \n\
2086 !!! Indices of points of 6 tetras: \n\
2094 pattern = GetPattern()
2095 isDone = pattern.LoadFromFile(pattern_tetra)
2097 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
2100 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
2101 isDone = pattern.MakeMesh(self.mesh, False, False)
2102 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
2104 # split quafrangle faces near triangular facets of volumes
2105 self.SplitQuadsNearTriangularFacets()
2109 ## @brief Split hexahedrons into prisms.
2111 # Use pattern mapping functionality for splitting.
2112 # @param theObject object to take list of hexahedrons from; is mesh, submesh or group.
2113 # @param theNode000,theNode001 is in range [0,7]; give an orientation of the
2114 # pattern relatively each hexahedron: the (0,0,0) key-point of pattern
2115 # will be mapped into <theNode000>-th node of each volume, the (0,0,1)
2116 # key-point will be mapped into <theNode001>-th node of each volume.
2117 # The edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
2118 # @param @return TRUE in case of success, FALSE otherwise.
2119 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
2120 # Pattern: 5.---------.6
2125 # (0,0,1) 4.---------.7 |
2132 # (0,0,0) 0.---------.3
2133 pattern_prism = "!!! Nb of points: \n 8 \n\
2143 !!! Indices of points of 2 prisms: \n\
2147 pattern = GetPattern()
2148 isDone = pattern.LoadFromFile(pattern_prism)
2150 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
2153 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
2154 isDone = pattern.MakeMesh(self.mesh, False, False)
2155 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
2157 # split quafrangle faces near triangular facets of volumes
2158 self.SplitQuadsNearTriangularFacets()
2163 # @param IDsOfElements list if ids of elements to smooth
2164 # @param IDsOfFixedNodes list of ids of fixed nodes.
2165 # Note that nodes built on edges and boundary nodes are always fixed.
2166 # @param MaxNbOfIterations maximum number of iterations
2167 # @param MaxAspectRatio varies in range [1.0, inf]
2168 # @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
2169 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
2170 MaxNbOfIterations, MaxAspectRatio, Method):
2171 if IDsOfElements == []:
2172 IDsOfElements = self.GetElementsId()
2173 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
2174 MaxNbOfIterations, MaxAspectRatio, Method)
2176 ## Smooth elements belong to given object
2177 # @param theObject object to smooth
2178 # @param IDsOfFixedNodes list of ids of fixed nodes.
2179 # Note that nodes built on edges and boundary nodes are always fixed.
2180 # @param MaxNbOfIterations maximum number of iterations
2181 # @param MaxAspectRatio varies in range [1.0, inf]
2182 # @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
2183 def SmoothObject(self, theObject, IDsOfFixedNodes,
2184 MaxNbOfIterations, MaxxAspectRatio, Method):
2185 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
2186 MaxNbOfIterations, MaxxAspectRatio, Method)
2188 ## Parametric smooth the given elements
2189 # @param IDsOfElements list if ids of elements to smooth
2190 # @param IDsOfFixedNodes list of ids of fixed nodes.
2191 # Note that nodes built on edges and boundary nodes are always fixed.
2192 # @param MaxNbOfIterations maximum number of iterations
2193 # @param MaxAspectRatio varies in range [1.0, inf]
2194 # @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
2195 def SmoothParametric(IDsOfElements, IDsOfFixedNodes,
2196 MaxNbOfIterations, MaxAspectRatio, Method):
2197 if IDsOfElements == []:
2198 IDsOfElements = self.GetElementsId()
2199 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
2200 MaxNbOfIterations, MaxAspectRatio, Method)
2202 ## Parametric smooth elements belong to given object
2203 # @param theObject object to smooth
2204 # @param IDsOfFixedNodes list of ids of fixed nodes.
2205 # Note that nodes built on edges and boundary nodes are always fixed.
2206 # @param MaxNbOfIterations maximum number of iterations
2207 # @param MaxAspectRatio varies in range [1.0, inf]
2208 # @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
2209 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
2210 MaxNbOfIterations, MaxAspectRatio, Method):
2211 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
2212 MaxNbOfIterations, MaxAspectRatio, Method)
2214 ## Converts all mesh to quadratic one, deletes old elements, replacing
2215 # them with quadratic ones with the same id.
2216 def ConvertToQuadratic(self, theForce3d):
2217 self.editor.ConvertToQuadratic(theForce3d)
2219 ## Converts all mesh from quadratic to ordinary ones,
2220 # deletes old quadratic elements, \n replacing
2221 # them with ordinary mesh elements with the same id.
2222 def ConvertFromQuadratic(self):
2223 return self.editor.ConvertFromQuadratic()
2225 ## Renumber mesh nodes
2226 def RenumberNodes(self):
2227 self.editor.RenumberNodes()
2229 ## Renumber mesh elements
2230 def RenumberElements(self):
2231 self.editor.RenumberElements()
2233 ## Generate new elements by rotation of the elements around the axis
2234 # @param IDsOfElements list of ids of elements to sweep
2235 # @param Axix axis of rotation, AxisStruct or line(geom object)
2236 # @param AngleInRadians angle of Rotation
2237 # @param NbOfSteps number of steps
2238 # @param Tolerance tolerance
2239 def RotationSweep(self, IDsOfElements, Axix, AngleInRadians, NbOfSteps, Tolerance):
2240 if IDsOfElements == []:
2241 IDsOfElements = self.GetElementsId()
2242 if ( isinstance( Axix, geompy.GEOM._objref_GEOM_Object)):
2243 Axix = GetAxisStruct(Axix)
2244 self.editor.RotationSweep(IDsOfElements, Axix, AngleInRadians, NbOfSteps, Tolerance)
2246 ## Generate new elements by rotation of the elements of object around the axis
2247 # @param theObject object wich elements should be sweeped
2248 # @param Axix axis of rotation, AxisStruct or line(geom object)
2249 # @param AngleInRadians angle of Rotation
2250 # @param NbOfSteps number of steps
2251 # @param Tolerance tolerance
2252 def RotationSweepObject(self, theObject, Axix, AngleInRadians, NbOfSteps, Tolerance):
2253 if ( isinstance( Axix, geompy.GEOM._objref_GEOM_Object)):
2254 Axix = GetAxisStruct(Axix)
2255 self.editor.RotationSweepObject(theObject, Axix, AngleInRadians, NbOfSteps, Tolerance)
2257 ## Generate new elements by extrusion of the elements with given ids
2258 # @param IDsOfElements list of elements ids for extrusion
2259 # @param StepVector vector, defining the direction and value of extrusion
2260 # @param NbOfSteps the number of steps
2261 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps):
2262 if IDsOfElements == []:
2263 IDsOfElements = self.GetElementsId()
2264 if ( isinstance( StepVector, geompy.GEOM._objref_GEOM_Object)):
2265 StepVector = GetDirStruct(StepVector)
2266 self.editor.ExtrusionSweep(IDsOfElements, StepVector, NbOfSteps)
2268 ## Generate new elements by extrusion of the elements with given ids
2269 # @param IDsOfElements is ids of elements
2270 # @param StepVector vector, defining the direction and value of extrusion
2271 # @param NbOfSteps the number of steps
2272 # @param ExtrFlags set flags for performing extrusion
2273 # @param SewTolerance uses for comparing locations of nodes if flag
2274 # EXTRUSION_FLAG_SEW is set
2275 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps, ExtrFlags, SewTolerance):
2276 if ( isinstance( StepVector, geompy.GEOM._objref_GEOM_Object)):
2277 StepVector = GetDirStruct(StepVector)
2278 self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps, ExtrFlags, SewTolerance)
2280 ## Generate new elements by extrusion of the elements belong to object
2281 # @param theObject object wich elements should be processed
2282 # @param StepVector vector, defining the direction and value of extrusion
2283 # @param NbOfSteps the number of steps
2284 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps):
2285 if ( isinstance( StepVector, geompy.GEOM._objref_GEOM_Object)):
2286 StepVector = GetDirStruct(StepVector)
2287 self.editor.ExtrusionSweepObject(theObject, StepVector, NbOfSteps)
2289 ## Generate new elements by extrusion of the elements belong to object
2290 # @param theObject object wich elements should be processed
2291 # @param StepVector vector, defining the direction and value of extrusion
2292 # @param NbOfSteps the number of steps
2293 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps):
2294 if ( isinstance( StepVector, geompy.GEOM._objref_GEOM_Object)):
2295 StepVector = GetDirStruct(StepVector)
2296 self.editor.ExtrusionSweepObject1D(theObject, StepVector, NbOfSteps)
2298 ## Generate new elements by extrusion of the elements belong to object
2299 # @param theObject object wich elements should be processed
2300 # @param StepVector vector, defining the direction and value of extrusion
2301 # @param NbOfSteps the number of steps
2302 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps):
2303 if ( isinstance( StepVector, geompy.GEOM._objref_GEOM_Object)):
2304 StepVector = GetDirStruct(StepVector)
2305 self.editor.ExtrusionSweepObject2D(theObject, StepVector, NbOfSteps)
2307 ## Generate new elements by extrusion of the given elements
2308 # A path of extrusion must be a meshed edge.
2309 # @param IDsOfElements is ids of elements
2310 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
2311 # @param PathShape is shape(edge); as the mesh can be complex, the edge is used to define the sub-mesh for the path
2312 # @param NodeStart the first or the last node on the edge. It is used to define the direction of extrusion
2313 # @param HasAngles allows the shape to be rotated around the path to get the resulting mesh in a helical fashion
2314 # @param Angles list of angles
2315 # @param HasRefPoint allows to use base point
2316 # @param RefPoint point around which the shape is rotated(the mass center of the shape by default).
2317 # User can specify any point as the Base Point and the shape will be rotated with respect to this point.
2318 # @param LinearVariation makes compute rotation angles as linear variation of given Angles along path steps
2319 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
2320 HasAngles, Angles, HasRefPoint, RefPoint, LinearVariation=False):
2321 if IDsOfElements == []:
2322 IDsOfElements = self.GetElementsId()
2323 if ( isinstance( RefPoint, geompy.GEOM._objref_GEOM_Object)):
2324 RefPoint = GetPointStruct(RefPoint)
2326 return self.editor.ExtrusionAlongPath(IDsOfElements, PathMesh.GetMesh(), PathShape, NodeStart,
2327 HasAngles, Angles, HasRefPoint, RefPoint)
2329 ## Generate new elements by extrusion of the elements belong to object
2330 # A path of extrusion must be a meshed edge.
2331 # @param IDsOfElements is ids of elements
2332 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
2333 # @param PathShape is shape(edge); as the mesh can be complex, the edge is used to define the sub-mesh for the path
2334 # @param NodeStart the first or the last node on the edge. It is used to define the direction of extrusion
2335 # @param HasAngles allows the shape to be rotated around the path to get the resulting mesh in a helical fashion
2336 # @param Angles list of angles
2337 # @param HasRefPoint allows to use base point
2338 # @param RefPoint point around which the shape is rotated(the mass center of the shape by default).
2339 # User can specify any point as the Base Point and the shape will be rotated with respect to this point.
2340 # @param LinearVariation makes compute rotation angles as linear variation of given Angles along path steps
2341 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
2342 HasAngles, Angles, HasRefPoint, RefPoint, LinearVariation=False):
2343 if ( isinstance( RefPoint, geompy.GEOM._objref_GEOM_Object)):
2344 RefPoint = GetPointStruct(RefPoint)
2345 return self.editor.ExtrusionAlongPathObject(theObject, PathMesh.GetMesh(), PathShape, NodeStart,
2346 HasAngles, Angles, HasRefPoint, RefPoint, LinearVariation)
2348 ## Symmetrical copy of mesh elements
2349 # @param IDsOfElements list of elements ids
2350 # @param Mirror is AxisStruct or geom object(point, line, plane)
2351 # @param theMirrorType is POINT, AXIS or PLANE
2352 # If the Mirror is geom object this parameter is unnecessary
2353 # @param Copy allows to copy element(Copy is 1) or to replace with its mirroring(Copy is 0)
2354 def Mirror(self, IDsOfElements, Mirror, theMirrorType, Copy=0):
2355 if IDsOfElements == []:
2356 IDsOfElements = self.GetElementsId()
2357 if ( isinstance( Mirror, geompy.GEOM._objref_GEOM_Object)):
2358 Mirror = GetAxisStruct(Mirror)
2359 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
2361 ## Symmetrical copy of object
2362 # @param theObject mesh, submesh or group
2363 # @param Mirror is AxisStruct or geom object(point, line, plane)
2364 # @param theMirrorType is POINT, AXIS or PLANE
2365 # If the Mirror is geom object this parameter is unnecessary
2366 # @param Copy allows to copy element(Copy is 1) or to replace with its mirroring(Copy is 0)
2367 def MirrorObject (self, theObject, Mirror, theMirrorType, Copy=0):
2368 if ( isinstance( Mirror, geompy.GEOM._objref_GEOM_Object)):
2369 Mirror = GetAxisStruct(Mirror)
2370 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
2372 ## Translates the elements
2373 # @param IDsOfElements list of elements ids
2374 # @param Vector direction of translation(DirStruct or vector)
2375 # @param Copy allows to copy the translated elements
2376 def Translate(self, IDsOfElements, Vector, Copy):
2377 if IDsOfElements == []:
2378 IDsOfElements = self.GetElementsId()
2379 if ( isinstance( Vector, geompy.GEOM._objref_GEOM_Object)):
2380 Vector = GetDirStruct(Vector)
2381 self.editor.Translate(IDsOfElements, Vector, Copy)
2383 ## Translates the object
2384 # @param theObject object to translate(mesh, submesh, or group)
2385 # @param Vector direction of translation(DirStruct or geom vector)
2386 # @param Copy allows to copy the translated elements
2387 def TranslateObject(self, theObject, Vector, Copy):
2388 if ( isinstance( Vector, geompy.GEOM._objref_GEOM_Object)):
2389 Vector = GetDirStruct(Vector)
2390 self.editor.TranslateObject(theObject, Vector, Copy)
2392 ## Rotates the elements
2393 # @param IDsOfElements list of elements ids
2394 # @param Axis axis of rotation(AxisStruct or geom line)
2395 # @param AngleInRadians angle of rotation(in radians)
2396 # @param Copy allows to copy the rotated elements
2397 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy):
2398 if IDsOfElements == []:
2399 IDsOfElements = self.GetElementsId()
2400 if ( isinstance( Axis, geompy.GEOM._objref_GEOM_Object)):
2401 Axis = GetAxisStruct(Axis)
2402 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
2404 ## Rotates the object
2405 # @param theObject object to rotate(mesh, submesh, or group)
2406 # @param Axis axis of rotation(AxisStruct or geom line)
2407 # @param AngleInRadians angle of rotation(in radians)
2408 # @param Copy allows to copy the rotated elements
2409 def RotateObject (self, theObject, Axis, AngleInRadians, Copy):
2410 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
2412 ## Find group of nodes close to each other within Tolerance.
2413 # @param Tolerance tolerance value
2414 # @param list of group of nodes
2415 def FindCoincidentNodes (self, Tolerance):
2416 return self.editor.FindCoincidentNodes(Tolerance)
2418 ## Find group of nodes close to each other within Tolerance.
2419 # @param Tolerance tolerance value
2420 # @param SubMeshOrGroup SubMesh or Group
2421 # @param list of group of nodes
2422 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance):
2423 return self.editor.FindCoincidentNodesOnPart(SubMeshOrGroup, Tolerance)
2426 # @param list of group of nodes
2427 def MergeNodes (self, GroupsOfNodes):
2428 self.editor.MergeNodes(GroupsOfNodes)
2430 ## Remove all but one of elements built on the same nodes.
2431 def MergeEqualElements(self):
2432 self.editor.MergeEqualElements()
2435 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
2436 FirstNodeID2, SecondNodeID2, LastNodeID2,
2437 CreatePolygons, CreatePolyedrs):
2438 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
2439 FirstNodeID2, SecondNodeID2, LastNodeID2,
2440 CreatePolygons, CreatePolyedrs)
2442 ## Sew conform free borders
2443 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
2444 FirstNodeID2, SecondNodeID2):
2445 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
2446 FirstNodeID2, SecondNodeID2)
2448 ## Sew border to side
2449 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
2450 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
2451 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
2452 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
2454 ## Sew two sides of a mesh. Nodes belonging to Side1 are
2455 # merged with nodes of elements of Side2.
2456 # Number of elements in theSide1 and in theSide2 must be
2457 # equal and they should have similar node connectivity.
2458 # The nodes to merge should belong to sides borders and
2459 # the first node should be linked to the second.
2460 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
2461 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
2462 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
2463 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
2464 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
2465 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
2467 ## Set new nodes for given element.
2468 # @param ide the element id
2469 # @param newIDs nodes ids
2470 # @return If number of nodes is not corresponded to type of element - returns false
2471 def ChangeElemNodes(self, ide, newIDs):
2472 return self.editor.ChangeElemNodes(ide, newIDs)
2474 ## If during last operation of MeshEditor some nodes were
2475 # created this method returns list of it's IDs, \n
2476 # if new nodes not created - returns empty list
2477 def GetLastCreatedNodes(self):
2478 return self.editor.GetLastCreatedNodes()
2480 ## If during last operation of MeshEditor some elements were
2481 # created this method returns list of it's IDs, \n
2482 # if new elements not creared - returns empty list
2483 def GetLastCreatedElems(self):
2484 return self.editor.GetLastCreatedElems()