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 ## Private method. 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):
546 if type(vertex) is types.IntType:
547 vertex = geompy.SubShapeAllSorted(self.geom,geompy.ShapeType["VERTEX"])[vertex]
549 store_geom = self.geom
551 hyp = self.Hypothesis("SegmentLengthAroundVertex")
552 self.geom = store_geom
553 hyp.SetLength( length )
556 ## Define "QuadraticMesh" hypothesis, forcing construction of quadratic edges.
557 # If the 2D mesher sees that all boundary edges are quadratic ones,
558 # it generates quadratic faces, else it generates linear faces using
559 # medium nodes as if they were vertex ones.
560 # The 3D mesher generates quadratic volumes only if all boundary faces
561 # are quadratic ones, else it fails.
562 def QuadraticMesh(self):
563 hyp = self.Hypothesis("QuadraticMesh")
566 # Public class: Mesh_CompositeSegment
567 # --------------------------
569 ## Class to define a segment 1D algorithm for discretization
572 class Mesh_CompositeSegment(Mesh_Segment):
574 ## Private constructor.
575 def __init__(self, mesh, geom=0):
576 self.Create(mesh, geom, "CompositeSegment_1D")
579 # Public class: Mesh_Segment_Python
580 # ---------------------------------
582 ## Class to define a segment 1D algorithm for discretization with python function
585 class Mesh_Segment_Python(Mesh_Segment):
587 ## Private constructor.
588 def __init__(self, mesh, geom=0):
589 import Python1dPlugin
590 self.Create(mesh, geom, "Python_1D", "libPython1dEngine.so")
592 ## Define "PythonSplit1D" hypothesis based on the Erwan Adam patch, awaiting equivalent SALOME functionality
593 # @param n for the number of segments that cut an edge
594 # @param func for the python function that calculate the length of all segments
595 def PythonSplit1D(self, n, func):
596 hyp = self.Hypothesis("PythonSplit1D", [n], "libPython1dEngine.so")
597 hyp.SetNumberOfSegments(n)
598 hyp.SetPythonLog10RatioFunction(func)
601 # Public class: Mesh_Triangle
602 # ---------------------------
604 ## Class to define a triangle 2D algorithm
607 class Mesh_Triangle(Mesh_Algorithm):
612 ## Private constructor.
613 def __init__(self, mesh, algoType, geom=0):
614 if algoType == MEFISTO:
615 self.Create(mesh, geom, "MEFISTO_2D")
616 elif algoType == NETGEN:
618 print "Warning: NETGENPlugin module has not been imported."
619 self.Create(mesh, geom, "NETGEN_2D", "libNETGENEngine.so")
620 self.algoType = algoType
622 ## Define "MaxElementArea" hypothesis to give the maximun area of each triangles
623 # @param area for the maximum area of each triangles
624 def MaxElementArea(self, area):
625 if self.algoType == MEFISTO:
626 hyp = self.Hypothesis("MaxElementArea", [area])
627 hyp.SetMaxElementArea(area)
629 elif self.algoType == NETGEN:
630 print "Netgen 1D-2D algo doesn't support this hypothesis"
633 ## Define "LengthFromEdges" hypothesis to build triangles based on the length of the edges taken from the wire
634 def LengthFromEdges(self):
635 if self.algoType == MEFISTO:
636 hyp = self.Hypothesis("LengthFromEdges")
638 elif self.algoType == NETGEN:
639 print "Netgen 1D-2D algo doesn't support this hypothesis"
642 ## Define "Netgen 2D Parameters" hypothesis
643 def Parameters(self):
644 if self.algoType == NETGEN:
645 self.params = self.Hypothesis("NETGEN_Parameters_2D", [], "libNETGENEngine.so")
647 elif self.algoType == MEFISTO:
648 print "Mefisto algo doesn't support this hypothesis"
652 def SetMaxSize(self, theSize):
655 self.params.SetMaxSize(theSize)
657 ## Set SecondOrder flag
658 def SetSecondOrder(seld, theVal):
661 self.params.SetSecondOrder(theVal)
664 def SetOptimize(self, theVal):
667 self.params.SetOptimize(theVal)
670 # @param theFineness is:
671 # VeryCoarse, Coarse, Moderate, Fine, VeryFine or Custom
672 def SetFineness(self, theFineness):
675 self.params.SetFineness(theFineness)
678 def SetGrowthRate(self, theRate):
681 self.params.SetGrowthRate(theRate)
684 def SetNbSegPerEdge(self, theVal):
687 self.params.SetNbSegPerEdge(theVal)
689 ## Set NbSegPerRadius
690 def SetNbSegPerRadius(self, theVal):
693 self.params.SetNbSegPerRadius(theVal)
695 ## Set QuadAllowed flag
696 def SetQuadAllowed(self, toAllow):
699 self.params.SetQuadAllowed(toAllow)
702 # Public class: Mesh_Quadrangle
703 # -----------------------------
705 ## Class to define a quadrangle 2D algorithm
708 class Mesh_Quadrangle(Mesh_Algorithm):
710 ## Private constructor.
711 def __init__(self, mesh, geom=0):
712 self.Create(mesh, geom, "Quadrangle_2D")
714 ## Define "QuadranglePreference" hypothesis, forcing construction
715 # of quadrangles if the number of nodes on opposite edges is not the same
716 # in the case where the global number of nodes on edges is even
717 def QuadranglePreference(self):
718 hyp = self.Hypothesis("QuadranglePreference")
721 # Public class: Mesh_Tetrahedron
722 # ------------------------------
724 ## Class to define a tetrahedron 3D algorithm
727 class Mesh_Tetrahedron(Mesh_Algorithm):
732 ## Private constructor.
733 def __init__(self, mesh, algoType, geom=0):
734 if algoType == NETGEN:
735 self.Create(mesh, geom, "NETGEN_3D", "libNETGENEngine.so")
736 elif algoType == GHS3D:
738 self.Create(mesh, geom, "GHS3D_3D" , "libGHS3DEngine.so")
739 elif algoType == FULL_NETGEN:
741 print "Warning: NETGENPlugin module has not been imported."
742 self.Create(mesh, geom, "NETGEN_2D3D", "libNETGENEngine.so")
743 self.algoType = algoType
745 ## Define "MaxElementVolume" hypothesis to give the maximun volume of each tetrahedral
746 # @param vol for the maximum volume of each tetrahedral
747 def MaxElementVolume(self, vol):
748 hyp = self.Hypothesis("MaxElementVolume", [vol])
749 hyp.SetMaxElementVolume(vol)
752 ## Define "Netgen 3D Parameters" hypothesis
753 def Parameters(self):
754 if (self.algoType == FULL_NETGEN):
755 self.params = self.Hypothesis("NETGEN_Parameters", [], "libNETGENEngine.so")
758 print "Algo doesn't support this hypothesis"
762 def SetMaxSize(self, theSize):
765 self.params.SetMaxSize(theSize)
767 ## Set SecondOrder flag
768 def SetSecondOrder(self, theVal):
771 self.params.SetSecondOrder(theVal)
774 def SetOptimize(self, theVal):
777 self.params.SetOptimize(theVal)
780 # @param theFineness is:
781 # VeryCoarse, Coarse, Moderate, Fine, VeryFine or Custom
782 def SetFineness(self, theFineness):
785 self.params.SetFineness(theFineness)
788 def SetGrowthRate(self, theRate):
791 self.params.SetGrowthRate(theRate)
794 def SetNbSegPerEdge(self, theVal):
797 self.params.SetNbSegPerEdge(theVal)
799 ## Set NbSegPerRadius
800 def SetNbSegPerRadius(self, theVal):
803 self.params.SetNbSegPerRadius(theVal)
805 # Public class: Mesh_Hexahedron
806 # ------------------------------
808 ## Class to define a hexahedron 3D algorithm
811 class Mesh_Hexahedron(Mesh_Algorithm):
813 ## Private constructor.
814 def __init__(self, mesh, geom=0):
815 self.Create(mesh, geom, "Hexa_3D")
817 # Deprecated, only for compatibility!
818 # Public class: Mesh_Netgen
819 # ------------------------------
821 ## Class to define a NETGEN-based 2D or 3D algorithm
822 # that need no discrete boundary (i.e. independent)
824 # This class is deprecated, only for compatibility!
827 class Mesh_Netgen(Mesh_Algorithm):
831 ## Private constructor.
832 def __init__(self, mesh, is3D, geom=0):
834 print "Warning: NETGENPlugin module has not been imported."
838 self.Create(mesh, geom, "NETGEN_2D3D", "libNETGENEngine.so")
840 self.Create(mesh, geom, "NETGEN_2D", "libNETGENEngine.so")
842 ## Define hypothesis containing parameters of the algorithm
843 def Parameters(self):
845 hyp = self.Hypothesis("NETGEN_Parameters", [], "libNETGENEngine.so")
847 hyp = self.Hypothesis("NETGEN_Parameters_2D", [], "libNETGENEngine.so")
850 # Public class: Mesh_Projection1D
851 # ------------------------------
853 ## Class to define a projection 1D algorithm
856 class Mesh_Projection1D(Mesh_Algorithm):
858 ## Private constructor.
859 def __init__(self, mesh, geom=0):
860 self.Create(mesh, geom, "Projection_1D")
862 ## Define "Source Edge" hypothesis, specifying a meshed edge to
863 # take a mesh pattern from, and optionally association of vertices
864 # between the source edge and a target one (where a hipothesis is assigned to)
865 # @param edge to take nodes distribution from
866 # @param mesh to take nodes distribution from (optional)
867 # @param srcV is vertex of \a edge to associate with \a tgtV (optional)
868 # @param tgtV is vertex of \a the edge where the algorithm is assigned,
869 # to associate with \a srcV (optional)
870 def SourceEdge(self, edge, mesh=None, srcV=None, tgtV=None):
871 hyp = self.Hypothesis("ProjectionSource1D")
872 hyp.SetSourceEdge( edge )
873 if not mesh is None and isinstance(mesh, Mesh):
874 mesh = mesh.GetMesh()
875 hyp.SetSourceMesh( mesh )
876 hyp.SetVertexAssociation( srcV, tgtV )
880 # Public class: Mesh_Projection2D
881 # ------------------------------
883 ## Class to define a projection 2D algorithm
886 class Mesh_Projection2D(Mesh_Algorithm):
888 ## Private constructor.
889 def __init__(self, mesh, geom=0):
890 self.Create(mesh, geom, "Projection_2D")
892 ## Define "Source Face" hypothesis, specifying a meshed face to
893 # take a mesh pattern from, and optionally association of vertices
894 # between the source face and a target one (where a hipothesis is assigned to)
895 # @param face to take mesh pattern from
896 # @param mesh to take mesh pattern from (optional)
897 # @param srcV1 is vertex of \a face to associate with \a tgtV1 (optional)
898 # @param tgtV1 is vertex of \a the face where the algorithm is assigned,
899 # to associate with \a srcV1 (optional)
900 # @param srcV2 is vertex of \a face to associate with \a tgtV1 (optional)
901 # @param tgtV2 is vertex of \a the face where the algorithm is assigned,
902 # to associate with \a srcV2 (optional)
904 # Note: association vertices must belong to one edge of a face
905 def SourceFace(self, face, mesh=None, srcV1=None, tgtV1=None, srcV2=None, tgtV2=None):
906 hyp = self.Hypothesis("ProjectionSource2D")
907 hyp.SetSourceFace( face )
908 if not mesh is None and isinstance(mesh, Mesh):
909 mesh = mesh.GetMesh()
910 hyp.SetSourceMesh( mesh )
911 hyp.SetVertexAssociation( srcV1, srcV2, tgtV1, tgtV2 )
914 # Public class: Mesh_Projection3D
915 # ------------------------------
917 ## Class to define a projection 3D algorithm
920 class Mesh_Projection3D(Mesh_Algorithm):
922 ## Private constructor.
923 def __init__(self, mesh, geom=0):
924 self.Create(mesh, geom, "Projection_3D")
926 ## Define "Source Shape 3D" hypothesis, specifying a meshed solid to
927 # take a mesh pattern from, and optionally association of vertices
928 # between the source solid and a target one (where a hipothesis is assigned to)
929 # @param solid to take mesh pattern from
930 # @param mesh to take mesh pattern from (optional)
931 # @param srcV1 is vertex of \a solid to associate with \a tgtV1 (optional)
932 # @param tgtV1 is vertex of \a the solid where the algorithm is assigned,
933 # to associate with \a srcV1 (optional)
934 # @param srcV2 is vertex of \a solid to associate with \a tgtV1 (optional)
935 # @param tgtV2 is vertex of \a the solid where the algorithm is assigned,
936 # to associate with \a srcV2 (optional)
938 # Note: association vertices must belong to one edge of a solid
939 def SourceShape3D(self, solid, mesh=0, srcV1=0, tgtV1=0, srcV2=0, tgtV2=0):
940 hyp = self.Hypothesis("ProjectionSource3D")
941 hyp.SetSource3DShape( solid )
942 if not mesh is None and isinstance(mesh, Mesh):
943 mesh = mesh.GetMesh()
944 hyp.SetSourceMesh( mesh )
945 hyp.SetVertexAssociation( srcV1, srcV2, tgtV1, tgtV2 )
949 # Public class: Mesh_Prism
950 # ------------------------
952 ## Class to define a 3D extrusion algorithm
955 class Mesh_Prism3D(Mesh_Algorithm):
957 ## Private constructor.
958 def __init__(self, mesh, geom=0):
959 self.Create(mesh, geom, "Prism_3D")
961 # Public class: Mesh_RadialPrism
962 # -------------------------------
964 ## Class to define a Radial Prism 3D algorithm
967 class Mesh_RadialPrism3D(Mesh_Algorithm):
969 ## Private constructor.
970 def __init__(self, mesh, geom=0):
971 self.Create(mesh, geom, "RadialPrism_3D")
972 self.distribHyp = self.Hypothesis( "LayerDistribution" )
975 ## Return 3D hypothesis holding the 1D one
976 def Get3DHypothesis(self):
977 return self.distribHyp
979 ## Private method creating 1D hypothes and storing it in the LayerDistribution
980 # hypothes. Returns the created hypothes
981 def OwnHypothesis(self, hypType, args=[], so="libStdMeshersEngine.so"):
982 if not self.nbLayers is None:
983 self.mesh.GetMesh().RemoveHypothesis( self.geom, self.nbLayers )
984 self.mesh.GetMesh().AddHypothesis( self.geom, self.distribHyp )
985 study = GetCurrentStudy() # prevent publishing of own 1D hypothesis
986 hyp = smesh.CreateHypothesis(hypType, so)
987 SetCurrentStudy( study ) # anable publishing
988 self.distribHyp.SetLayerDistribution( hyp )
991 ## Define "NumberOfLayers" hypothesis, specifying a number of layers of
992 # prisms to build between the inner and outer shells
993 def NumberOfLayers(self, n ):
994 self.mesh.GetMesh().RemoveHypothesis( self.geom, self.distribHyp )
995 self.nbLayers = self.Hypothesis("NumberOfLayers")
996 self.nbLayers.SetNumberOfLayers( n )
999 ## Define "LocalLength" hypothesis, specifying segment length
1000 # to build between the inner and outer shells
1001 # @param l for the length of segments
1002 def LocalLength(self, l):
1003 hyp = self.OwnHypothesis("LocalLength", [l])
1007 ## Define "NumberOfSegments" hypothesis, specifying a number of layers of
1008 # prisms to build between the inner and outer shells
1009 # @param n for the number of segments
1010 # @param s for the scale factor (optional)
1011 def NumberOfSegments(self, n, s=[]):
1013 hyp = self.OwnHypothesis("NumberOfSegments", [n])
1015 hyp = self.OwnHypothesis("NumberOfSegments", [n,s])
1016 hyp.SetDistrType( 1 )
1017 hyp.SetScaleFactor(s)
1018 hyp.SetNumberOfSegments(n)
1021 ## Define "Arithmetic1D" hypothesis, specifying distribution of segments
1022 # to build between the inner and outer shells as arithmetic length increasing
1023 # @param start for the length of the first segment
1024 # @param end for the length of the last segment
1025 def Arithmetic1D(self, start, end):
1026 hyp = self.OwnHypothesis("Arithmetic1D", [start, end])
1027 hyp.SetLength(start, 1)
1028 hyp.SetLength(end , 0)
1031 ## Define "StartEndLength" hypothesis, specifying distribution of segments
1032 # to build between the inner and outer shells as geometric length increasing
1033 # @param start for the length of the first segment
1034 # @param end for the length of the last segment
1035 def StartEndLength(self, start, end):
1036 hyp = self.OwnHypothesis("StartEndLength", [start, end])
1037 hyp.SetLength(start, 1)
1038 hyp.SetLength(end , 0)
1041 ## Define "AutomaticLength" hypothesis, specifying number of segments
1042 # to build between the inner and outer shells
1043 # @param fineness for the fineness [0-1]
1044 def AutomaticLength(self, fineness=0):
1045 hyp = self.OwnHypothesis("AutomaticLength")
1046 hyp.SetFineness( fineness )
1050 # Public class: Mesh
1051 # ==================
1053 ## Class to define a mesh
1055 # The class contains mesh shape, SMESH_Mesh, SMESH_MeshEditor
1065 # Creates mesh on the shape \a geom(or the empty mesh if geom equal to 0),
1066 # sets GUI name of this mesh to \a name.
1067 # @param obj Shape to be meshed or SMESH_Mesh object
1068 # @param name Study name of the mesh
1069 def __init__(self, obj=0, name=0):
1073 if isinstance(obj, geompy.GEOM._objref_GEOM_Object):
1075 self.mesh = smesh.CreateMesh(self.geom)
1076 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1079 self.mesh = smesh.CreateEmptyMesh()
1081 SetName(self.mesh, name)
1083 SetName(self.mesh, GetName(obj))
1085 self.editor = self.mesh.GetMeshEditor()
1087 ## Method that inits the Mesh object from SMESH_Mesh interface
1088 # @param theMesh is SMESH_Mesh object
1089 def SetMesh(self, theMesh):
1091 self.geom = self.mesh.GetShapeToMesh()
1093 ## Method that returns the mesh
1094 # @return SMESH_Mesh object
1100 name = GetName(self.GetMesh())
1104 def SetName(self, name):
1105 SetName(self.GetMesh(), name)
1107 ## Get the subMesh object associated to a subShape. The subMesh object
1108 # gives access to nodes and elements IDs.
1109 # \n SubMesh will be used instead of SubShape in a next idl version to
1110 # adress a specific subMesh...
1111 def GetSubMesh(self, theSubObject, name):
1112 submesh = self.mesh.GetSubMesh(theSubObject, name)
1115 ## Method that returns the shape associated to the mesh
1116 # @return GEOM_Object
1120 ## Method that associates given shape to the mesh(entails the mesh recreation)
1121 # @param geom shape to be meshed(GEOM_Object)
1122 def SetShape(self, geom):
1123 self.mesh = smesh.CreateMesh(geom)
1125 ## Return true if hypotheses are defined well
1126 # @param theMesh is an instance of Mesh class
1127 # @param theSubObject subshape of a mesh shape
1128 def IsReadyToCompute(self, theSubObject):
1129 return smesh.IsReadyToCompute(self.mesh, theSubObject)
1131 ## Return errors of hypotheses definintion
1132 # error list is empty if everything is OK
1133 # @param theMesh is an instance of Mesh class
1134 # @param theSubObject subshape of a mesh shape
1135 # @return a list of errors
1136 def GetAlgoState(self, theSubObject):
1137 return smesh.GetAlgoState(self.mesh, theSubObject)
1139 ## Return geometrical object the given element is built on.
1140 # The returned geometrical object, if not nil, is either found in the
1141 # study or is published by this method with the given name
1142 # @param theMesh is an instance of Mesh class
1143 # @param theElementID an id of the mesh element
1144 # @param theGeomName user defined name of geometrical object
1145 # @return GEOM::GEOM_Object instance
1146 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1147 return smesh.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1149 ## Returns mesh dimension depending on shape one
1150 def MeshDimension(self):
1151 shells = geompy.SubShapeAllIDs( self.geom, geompy.ShapeType["SHELL"] )
1152 if len( shells ) > 0 :
1154 elif geompy.NumberOfFaces( self.geom ) > 0 :
1156 elif geompy.NumberOfEdges( self.geom ) > 0 :
1162 ## Creates a segment discretization 1D algorithm.
1163 # If the optional \a algo parameter is not sets, this algorithm is REGULAR.
1164 # If the optional \a geom parameter is not sets, this algorithm is global.
1165 # \n Otherwise, this algorithm define a submesh based on \a geom subshape.
1166 # @param algo values are smesh.REGULAR or smesh.PYTHON for discretization via python function
1167 # @param geom If defined, subshape to be meshed
1168 def Segment(self, algo=REGULAR, geom=0):
1169 ## if Segment(geom) is called by mistake
1170 if ( isinstance( algo, geompy.GEOM._objref_GEOM_Object)):
1171 algo, geom = geom, algo
1174 return Mesh_Segment(self, geom)
1175 elif algo == PYTHON:
1176 return Mesh_Segment_Python(self, geom)
1177 elif algo == COMPOSITE:
1178 return Mesh_CompositeSegment(self, geom)
1180 return Mesh_Segment(self, geom)
1182 ## Creates a triangle 2D algorithm for faces.
1183 # If the optional \a geom parameter is not sets, this algorithm is global.
1184 # \n Otherwise, this algorithm define a submesh based on \a geom subshape.
1185 # @param algo values are: smesh.MEFISTO or smesh.NETGEN
1186 # @param geom If defined, subshape to be meshed
1187 def Triangle(self, algo=MEFISTO, geom=0):
1188 ## if Triangle(geom) is called by mistake
1189 if ( isinstance( algo, geompy.GEOM._objref_GEOM_Object)):
1193 return Mesh_Triangle(self, algo, geom)
1195 ## Creates a quadrangle 2D algorithm for faces.
1196 # If the optional \a geom parameter is not sets, this algorithm is global.
1197 # \n Otherwise, this algorithm define a submesh based on \a geom subshape.
1198 # @param geom If defined, subshape to be meshed
1199 def Quadrangle(self, geom=0):
1200 return Mesh_Quadrangle(self, geom)
1202 ## Creates a tetrahedron 3D algorithm for solids.
1203 # The parameter \a algo permits to choice the algorithm: NETGEN or GHS3D
1204 # If the optional \a geom parameter is not sets, this algorithm is global.
1205 # \n Otherwise, this algorithm define a submesh based on \a geom subshape.
1206 # @param algo values are: smesh.NETGEN, smesh.GHS3D, smesh.FULL_NETGEN
1207 # @param geom If defined, subshape to be meshed
1208 def Tetrahedron(self, algo=NETGEN, geom=0):
1209 ## if Tetrahedron(geom) is called by mistake
1210 if ( isinstance( algo, geompy.GEOM._objref_GEOM_Object)):
1211 algo, geom = geom, algo
1213 return Mesh_Tetrahedron(self, algo, geom)
1215 ## Creates a hexahedron 3D algorithm for solids.
1216 # If the optional \a geom parameter is not sets, this algorithm is global.
1217 # \n Otherwise, this algorithm define a submesh based on \a geom subshape.
1218 # @param geom If defined, subshape to be meshed
1219 def Hexahedron(self, geom=0):
1220 return Mesh_Hexahedron(self, geom)
1222 ## Deprecated, only for compatibility!
1223 def Netgen(self, is3D, geom=0):
1224 return Mesh_Netgen(self, is3D, geom)
1226 ## Creates a projection 1D algorithm for edges.
1227 # If the optional \a geom parameter is not sets, this algorithm is global.
1228 # Otherwise, this algorithm define a submesh based on \a geom subshape.
1229 # @param geom If defined, subshape to be meshed
1230 def Projection1D(self, geom=0):
1231 return Mesh_Projection1D(self, geom)
1233 ## Creates a projection 2D algorithm for faces.
1234 # If the optional \a geom parameter is not sets, this algorithm is global.
1235 # Otherwise, this algorithm define a submesh based on \a geom subshape.
1236 # @param geom If defined, subshape to be meshed
1237 def Projection2D(self, geom=0):
1238 return Mesh_Projection2D(self, geom)
1240 ## Creates a projection 3D algorithm for solids.
1241 # If the optional \a geom parameter is not sets, this algorithm is global.
1242 # Otherwise, this algorithm define a submesh based on \a geom subshape.
1243 # @param geom If defined, subshape to be meshed
1244 def Projection3D(self, geom=0):
1245 return Mesh_Projection3D(self, geom)
1247 ## Creates a 3D extrusion (Prism 3D) or RadialPrism 3D algorithm for solids.
1248 # If the optional \a geom parameter is not sets, this algorithm is global.
1249 # Otherwise, this algorithm define a submesh based on \a geom subshape.
1250 # @param geom If defined, subshape to be meshed
1251 def Prism(self, geom=0):
1255 nbSolids = len( geompy.SubShapeAll( shape, geompy.ShapeType["SOLID"] ))
1256 nbShells = len( geompy.SubShapeAll( shape, geompy.ShapeType["SHELL"] ))
1257 if nbSolids == 0 or nbSolids == nbShells:
1258 return Mesh_Prism3D(self, geom)
1259 return Mesh_RadialPrism3D(self, geom)
1261 ## Compute the mesh and return the status of the computation
1262 def Compute(self, geom=0):
1263 if geom == 0 or not isinstance(geom, geompy.GEOM._objref_GEOM_Object):
1265 print "Compute impossible: mesh is not constructed on geom shape."
1269 ok = smesh.Compute(self.mesh, geom)
1271 errors = smesh.GetAlgoState( self.mesh, geom )
1274 if err.isGlobalAlgo:
1279 dim = str(err.algoDim)
1280 if err.name == MISSING_ALGO:
1281 reason = glob + dim + "D algorithm is missing"
1282 elif err.name == MISSING_HYPO:
1283 name = '"' + err.algoName + '"'
1284 reason = glob + dim + "D algorithm " + name + " misses " + dim + "D hypothesis"
1285 elif err.name == NOT_CONFORM_MESH:
1286 reason = "Global \"Not Conform mesh allowed\" hypothesis is missing"
1287 elif err.name == BAD_PARAM_VALUE:
1288 name = '"' + err.algoName + '"'
1289 reason = "Hypothesis of" + glob + dim + "D algorithm " + name +\
1290 " has a bad parameter value"
1292 reason = "For unknown reason."+\
1293 " Revise Mesh.Compute() implementation in smesh.py!"
1295 if allReasons != "":
1298 allReasons += reason
1300 if allReasons != "":
1301 print '"' + GetName(self.mesh) + '"',"not computed:"
1305 if salome.sg.hasDesktop():
1306 smeshgui = salome.ImportComponentGUI("SMESH")
1307 smeshgui.Init(salome.myStudyId)
1308 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok )
1309 salome.sg.updateObjBrowser(1)
1313 ## Compute tetrahedral mesh using AutomaticLength + MEFISTO + NETGEN
1314 # The parameter \a fineness [0,-1] defines mesh fineness
1315 def AutomaticTetrahedralization(self, fineness=0):
1316 dim = self.MeshDimension()
1318 self.RemoveGlobalHypotheses()
1319 self.Segment().AutomaticLength(fineness)
1321 self.Triangle().LengthFromEdges()
1324 self.Tetrahedron(NETGEN)
1326 return self.Compute()
1328 ## Compute hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1329 # The parameter \a fineness [0,-1] defines mesh fineness
1330 def AutomaticHexahedralization(self, fineness=0):
1331 dim = self.MeshDimension()
1333 self.RemoveGlobalHypotheses()
1334 self.Segment().AutomaticLength(fineness)
1341 return self.Compute()
1343 ## Get the list of hypothesis added on a geom
1344 # @param geom is subhape of mesh geometry
1345 def GetHypothesisList(self, geom):
1346 return self.mesh.GetHypothesisList( geom )
1348 ## Removes all global hypotheses
1349 def RemoveGlobalHypotheses(self):
1350 current_hyps = self.mesh.GetHypothesisList( self.geom )
1351 for hyp in current_hyps:
1352 self.mesh.RemoveHypothesis( self.geom, hyp )
1356 ## Create a mesh group based on geometric object \a grp
1357 # and give a \a name, \n if this parameter is not defined
1358 # the name is the same as the geometric group name \n
1359 # Note: Works like GroupOnGeom().
1360 # @param grp is a geometric group, a vertex, an edge, a face or a solid
1361 # @param name is the name of the mesh group
1362 # @return SMESH_GroupOnGeom
1363 def Group(self, grp, name=""):
1364 return self.GroupOnGeom(grp, name)
1366 ## Deprecated, only for compatibility! Please, use ExportMED() method instead.
1367 # Export the mesh in a file with the MED format and choice the \a version of MED format
1368 # @param f is the file name
1369 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1370 def ExportToMED(self, f, version, opt=0):
1371 self.mesh.ExportToMED(f, opt, version)
1373 ## Export the mesh in a file with the MED format
1374 # @param f is the file name
1375 # @param auto_groups boolean parameter for creating/not creating
1376 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1377 # the typical use is auto_groups=false.
1378 # @param version MED format version(MED_V2_1 or MED_V2_2)
1379 def ExportMED(self, f, auto_groups=0, version=MED_V2_2):
1380 self.mesh.ExportToMED(f, auto_groups, version)
1382 ## Export the mesh in a file with the DAT format
1383 # @param f is the file name
1384 def ExportDAT(self, f):
1385 self.mesh.ExportDAT(f)
1387 ## Export the mesh in a file with the UNV format
1388 # @param f is the file name
1389 def ExportUNV(self, f):
1390 self.mesh.ExportUNV(f)
1392 ## Export the mesh in a file with the STL format
1393 # @param f is the file name
1394 # @param ascii defined the kind of file contents
1395 def ExportSTL(self, f, ascii=1):
1396 self.mesh.ExportSTL(f, ascii)
1399 # Operations with groups:
1400 # ----------------------
1402 ## Creates an empty mesh group
1403 # @param elementType is the type of elements in the group
1404 # @param name is the name of the mesh group
1405 # @return SMESH_Group
1406 def CreateEmptyGroup(self, elementType, name):
1407 return self.mesh.CreateGroup(elementType, name)
1409 ## Creates a mesh group based on geometric object \a grp
1410 # and give a \a name, \n if this parameter is not defined
1411 # the name is the same as the geometric group name
1412 # @param grp is a geometric group, a vertex, an edge, a face or a solid
1413 # @param name is the name of the mesh group
1414 # @return SMESH_GroupOnGeom
1415 def GroupOnGeom(self, grp, name="", type=None):
1417 name = grp.GetName()
1420 tgeo = str(grp.GetShapeType())
1421 if tgeo == "VERTEX":
1423 elif tgeo == "EDGE":
1425 elif tgeo == "FACE":
1427 elif tgeo == "SOLID":
1429 elif tgeo == "SHELL":
1431 elif tgeo == "COMPOUND":
1432 if len( geompy.GetObjectIDs( grp )) == 0:
1433 print "Mesh.Group: empty geometric group", GetName( grp )
1435 tgeo = geompy.GetType(grp)
1436 if tgeo == geompy.ShapeType["VERTEX"]:
1438 elif tgeo == geompy.ShapeType["EDGE"]:
1440 elif tgeo == geompy.ShapeType["FACE"]:
1442 elif tgeo == geompy.ShapeType["SOLID"]:
1446 print "Mesh.Group: bad first argument: expected a group, a vertex, an edge, a face or a solid"
1449 return self.mesh.CreateGroupFromGEOM(type, name, grp)
1451 ## Create a mesh group by the given ids of elements
1452 # @param groupName is the name of the mesh group
1453 # @param elementType is the type of elements in the group
1454 # @param elemIDs is the list of ids
1455 # @return SMESH_Group
1456 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1457 group = self.mesh.CreateGroup(elementType, groupName)
1461 ## Create a mesh group by the given conditions
1462 # @param groupName is the name of the mesh group
1463 # @param elementType is the type of elements in the group
1464 # @param CritType is type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1465 # @param Compare belong to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1466 # @param Treshold is threshold value (range of id ids as string, shape, numeric)
1467 # @param UnaryOp is FT_LogicalNOT or FT_Undefined
1468 # @return SMESH_Group
1472 CritType=FT_Undefined,
1475 UnaryOp=FT_Undefined):
1476 aCriterion = GetCriterion(elementType, CritType, Compare, Treshold, UnaryOp, FT_Undefined)
1477 group = self.MakeGroupByCriterion(groupName, aCriterion)
1480 ## Create a mesh group by the given criterion
1481 # @param groupName is the name of the mesh group
1482 # @param Criterion is the instance of Criterion class
1483 # @return SMESH_Group
1484 def MakeGroupByCriterion(self, groupName, Criterion):
1485 aFilterMgr = smesh.CreateFilterManager()
1486 aFilter = aFilterMgr.CreateFilter()
1488 aCriteria.append(Criterion)
1489 aFilter.SetCriteria(aCriteria)
1490 group = self.MakeGroupByFilter(groupName, aFilter)
1493 ## Create a mesh group by the given criteria(list of criterions)
1494 # @param groupName is the name of the mesh group
1495 # @param Criteria is the list of criterions
1496 # @return SMESH_Group
1497 def MakeGroupByCriteria(self, groupName, theCriteria):
1498 aFilterMgr = smesh.CreateFilterManager()
1499 aFilter = aFilterMgr.CreateFilter()
1500 aFilter.SetCriteria(theCriteria)
1501 group = self.MakeGroupByFilter(groupName, aFilter)
1504 ## Create a mesh group by the given filter
1505 # @param groupName is the name of the mesh group
1506 # @param Criterion is the instance of Filter class
1507 # @return SMESH_Group
1508 def MakeGroupByFilter(self, groupName, theFilter):
1509 anIds = theFilter.GetElementsId(self.mesh)
1510 anElemType = theFilter.GetElementType()
1511 group = self.MakeGroupByIds(groupName, anElemType, anIds)
1514 ## Pass mesh elements through the given filter and return ids
1515 # @param theFilter is SMESH_Filter
1516 # @return list of ids
1517 def GetIdsFromFilter(self, theFilter):
1518 return theFilter.GetElementsId(self.mesh)
1520 ## Verify whether 2D mesh element has free edges(edges connected to one face only)\n
1521 # Returns list of special structures(borders).
1522 # @return list of SMESH.FreeEdges.Border structure: edge id and two its nodes ids.
1523 def GetFreeBorders(self):
1524 aFilterMgr = smesh.CreateFilterManager()
1525 aPredicate = aFilterMgr.CreateFreeEdges()
1526 aPredicate.SetMesh(self.mesh)
1527 aBorders = aPredicate.GetBorders()
1531 def RemoveGroup(self, group):
1532 self.mesh.RemoveGroup(group)
1534 ## Remove group with its contents
1535 def RemoveGroupWithContents(self, group):
1536 self.mesh.RemoveGroupWithContents(group)
1538 ## Get the list of groups existing in the mesh
1539 def GetGroups(self):
1540 return self.mesh.GetGroups()
1542 ## Get the list of names of groups existing in the mesh
1543 def GetGroupNames(self):
1544 groups = self.GetGroups()
1546 for group in groups:
1547 names.append(group.GetName())
1550 ## Union of two groups
1551 # New group is created. All mesh elements that are
1552 # present in initial groups are added to the new one
1553 def UnionGroups(self, group1, group2, name):
1554 return self.mesh.UnionGroups(group1, group2, name)
1556 ## Intersection of two groups
1557 # New group is created. All mesh elements that are
1558 # present in both initial groups are added to the new one.
1559 def IntersectGroups(self, group1, group2, name):
1560 return self.mesh.IntersectGroups(group1, group2, name)
1562 ## Cut of two groups
1563 # New group is created. All mesh elements that are present in
1564 # main group but do not present in tool group are added to the new one
1565 def CutGroups(self, mainGroup, toolGroup, name):
1566 return self.mesh.CutGroups(mainGroup, toolGroup, name)
1569 # Get some info about mesh:
1570 # ------------------------
1572 ## Get the log of nodes and elements added or removed since previous
1574 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
1575 # @return list of log_block structures:
1580 def GetLog(self, clearAfterGet):
1581 return self.mesh.GetLog(clearAfterGet)
1583 ## Clear the log of nodes and elements added or removed since previous
1584 # clear. Must be used immediately after GetLog if clearAfterGet is false.
1586 self.mesh.ClearLog()
1588 ## Get the internal Id
1590 return self.mesh.GetId()
1593 def GetStudyId(self):
1594 return self.mesh.GetStudyId()
1596 ## Check group names for duplications.
1597 # Consider maximum group name length stored in MED file.
1598 def HasDuplicatedGroupNamesMED(self):
1599 return self.mesh.GetStudyId()
1601 ## Obtain instance of SMESH_MeshEditor
1602 def GetMeshEditor(self):
1603 return self.mesh.GetMeshEditor()
1606 def GetMEDMesh(self):
1607 return self.mesh.GetMEDMesh()
1610 # Get informations about mesh contents:
1611 # ------------------------------------
1613 ## Returns number of nodes in mesh
1615 return self.mesh.NbNodes()
1617 ## Returns number of elements in mesh
1618 def NbElements(self):
1619 return self.mesh.NbElements()
1621 ## Returns number of edges in mesh
1623 return self.mesh.NbEdges()
1625 ## Returns number of edges with given order in mesh
1626 # @param elementOrder is order of elements:
1627 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1628 def NbEdgesOfOrder(self, elementOrder):
1629 return self.mesh.NbEdgesOfOrder(elementOrder)
1631 ## Returns number of faces in mesh
1633 return self.mesh.NbFaces()
1635 ## Returns number of faces with given order in mesh
1636 # @param elementOrder is order of elements:
1637 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1638 def NbFacesOfOrder(self, elementOrder):
1639 return self.mesh.NbFacesOfOrder(elementOrder)
1641 ## Returns number of triangles in mesh
1642 def NbTriangles(self):
1643 return self.mesh.NbTriangles()
1645 ## Returns number of triangles with given order in mesh
1646 # @param elementOrder is order of elements:
1647 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1648 def NbTrianglesOfOrder(self, elementOrder):
1649 return self.mesh.NbTrianglesOfOrder(elementOrder)
1651 ## Returns number of quadrangles in mesh
1652 def NbQuadrangles(self):
1653 return self.mesh.NbQuadrangles()
1655 ## Returns number of quadrangles with given order in mesh
1656 # @param elementOrder is order of elements:
1657 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1658 def NbQuadranglesOfOrder(self, elementOrder):
1659 return self.mesh.NbQuadranglesOfOrder(elementOrder)
1661 ## Returns number of polygons in mesh
1662 def NbPolygons(self):
1663 return self.mesh.NbPolygons()
1665 ## Returns number of volumes in mesh
1666 def NbVolumes(self):
1667 return self.mesh.NbVolumes()
1669 ## Returns number of volumes with given order in mesh
1670 # @param elementOrder is order of elements:
1671 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1672 def NbVolumesOfOrder(self, elementOrder):
1673 return self.mesh.NbVolumesOfOrder(elementOrder)
1675 ## Returns number of tetrahedrons in mesh
1677 return self.mesh.NbTetras()
1679 ## Returns number of tetrahedrons with given order in mesh
1680 # @param elementOrder is order of elements:
1681 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1682 def NbTetrasOfOrder(self, elementOrder):
1683 return self.mesh.NbTetrasOfOrder(elementOrder)
1685 ## Returns number of hexahedrons in mesh
1687 return self.mesh.NbHexas()
1689 ## Returns number of hexahedrons with given order in mesh
1690 # @param elementOrder is order of elements:
1691 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1692 def NbHexasOfOrder(self, elementOrder):
1693 return self.mesh.NbHexasOfOrder(elementOrder)
1695 ## Returns number of pyramids in mesh
1696 def NbPyramids(self):
1697 return self.mesh.NbPyramids()
1699 ## Returns number of pyramids with given order in mesh
1700 # @param elementOrder is order of elements:
1701 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1702 def NbPyramidsOfOrder(self, elementOrder):
1703 return self.mesh.NbPyramidsOfOrder(elementOrder)
1705 ## Returns number of prisms in mesh
1707 return self.mesh.NbPrisms()
1709 ## Returns number of prisms with given order in mesh
1710 # @param elementOrder is order of elements:
1711 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1712 def NbPrismsOfOrder(self, elementOrder):
1713 return self.mesh.NbPrismsOfOrder(elementOrder)
1715 ## Returns number of polyhedrons in mesh
1716 def NbPolyhedrons(self):
1717 return self.mesh.NbPolyhedrons()
1719 ## Returns number of submeshes in mesh
1720 def NbSubMesh(self):
1721 return self.mesh.NbSubMesh()
1723 ## Returns list of mesh elements ids
1724 def GetElementsId(self):
1725 return self.mesh.GetElementsId()
1727 ## Returns list of ids of mesh elements with given type
1728 # @param elementType is required type of elements
1729 def GetElementsByType(self, elementType):
1730 return self.mesh.GetElementsByType(elementType)
1732 ## Returns list of mesh nodes ids
1733 def GetNodesId(self):
1734 return self.mesh.GetNodesId()
1736 # Get informations about mesh elements:
1737 # ------------------------------------
1739 ## Returns type of mesh element
1740 def GetElementType(self, id, iselem):
1741 return self.mesh.GetElementType(id, iselem)
1743 ## Returns list of submesh elements ids
1744 # @param shapeID is geom object(subshape) IOR
1745 def GetSubMeshElementsId(self, shapeID):
1746 return self.mesh.GetSubMeshElementsId(shapeID)
1748 ## Returns list of submesh nodes ids
1749 # @param shapeID is geom object(subshape) IOR
1750 def GetSubMeshNodesId(self, shapeID, all):
1751 return self.mesh.GetSubMeshNodesId(shapeID, all)
1753 ## Returns list of ids of submesh elements with given type
1754 # @param shapeID is geom object(subshape) IOR
1755 def GetSubMeshElementType(self, shapeID):
1756 return self.mesh.GetSubMeshElementType(shapeID)
1758 ## Get mesh description
1760 return self.mesh.Dump()
1763 # Get information about nodes and elements of mesh by its ids:
1764 # -----------------------------------------------------------
1766 ## Get XYZ coordinates of node as list of double
1767 # \n If there is not node for given ID - returns empty list
1768 def GetNodeXYZ(self, id):
1769 return self.mesh.GetNodeXYZ(id)
1771 ## For given node returns list of IDs of inverse elements
1772 # \n If there is not node for given ID - returns empty list
1773 def GetNodeInverseElements(self, id):
1774 return self.mesh.GetNodeInverseElements(id)
1776 ## If given element is node returns IDs of shape from position
1777 # \n If there is not node for given ID - returns -1
1778 def GetShapeID(self, id):
1779 return self.mesh.GetShapeID(id)
1781 ## For given element returns ID of result shape after
1782 # FindShape() from SMESH_MeshEditor
1783 # \n If there is not element for given ID - returns -1
1784 def GetShapeIDForElem(id):
1785 return self.mesh.GetShapeIDForElem(id)
1787 ## Returns number of nodes for given element
1788 # \n If there is not element for given ID - returns -1
1789 def GetElemNbNodes(self, id):
1790 return self.mesh.GetElemNbNodes(id)
1792 ## Returns ID of node by given index for given element
1793 # \n If there is not element for given ID - returns -1
1794 # \n If there is not node for given index - returns -2
1795 def GetElemNode(self, id, index):
1796 return self.mesh.GetElemNode(id, index)
1798 ## Returns true if given node is medium node
1799 # in given quadratic element
1800 def IsMediumNode(self, elementID, nodeID):
1801 return self.mesh.IsMediumNode(elementID, nodeID)
1803 ## Returns true if given node is medium node
1804 # in one of quadratic elements
1805 def IsMediumNodeOfAnyElem(self, nodeID, elementType):
1806 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
1808 ## Returns number of edges for given element
1809 def ElemNbEdges(self, id):
1810 return self.mesh.ElemNbEdges(id)
1812 ## Returns number of faces for given element
1813 def ElemNbFaces(self, id):
1814 return self.mesh.ElemNbFaces(id)
1816 ## Returns true if given element is polygon
1817 def IsPoly(self, id):
1818 return self.mesh.IsPoly(id)
1820 ## Returns true if given element is quadratic
1821 def IsQuadratic(self, id):
1822 return self.mesh.IsQuadratic(id)
1824 ## Returns XYZ coordinates of bary center for given element
1826 # \n If there is not element for given ID - returns empty list
1827 def BaryCenter(self, id):
1828 return self.mesh.BaryCenter(id)
1831 # Mesh edition (SMESH_MeshEditor functionality):
1832 # ---------------------------------------------
1834 ## Removes elements from mesh by ids
1835 # @param IDsOfElements is list of ids of elements to remove
1836 def RemoveElements(self, IDsOfElements):
1837 return self.editor.RemoveElements(IDsOfElements)
1839 ## Removes nodes from mesh by ids
1840 # @param IDsOfNodes is list of ids of nodes to remove
1841 def RemoveNodes(self, IDsOfNodes):
1842 return self.editor.RemoveNodes(IDsOfNodes)
1844 ## Add node to mesh by coordinates
1845 def AddNode(self, x, y, z):
1846 return self.editor.AddNode( x, y, z)
1849 ## Create edge both similar and quadratic (this is determed
1850 # by number of given nodes).
1851 # @param IdsOfNodes List of node IDs for creation of element.
1852 # Needed order of nodes in this list corresponds to description
1853 # of MED. \n This description is located by the following link:
1854 # http://www.salome-platform.org/salome2/web_med_internet/logiciels/medV2.2.2_doc_html/html/modele_de_donnees.html#3.
1855 def AddEdge(self, IDsOfNodes):
1856 return self.editor.AddEdge(IDsOfNodes)
1858 ## Create face both similar and quadratic (this is determed
1859 # by number of given nodes).
1860 # @param IdsOfNodes List of node IDs for creation of element.
1861 # Needed order of nodes in this list corresponds to description
1862 # of MED. \n This description is located by the following link:
1863 # http://www.salome-platform.org/salome2/web_med_internet/logiciels/medV2.2.2_doc_html/html/modele_de_donnees.html#3.
1864 def AddFace(self, IDsOfNodes):
1865 return self.editor.AddFace(IDsOfNodes)
1867 ## Add polygonal face to mesh by list of nodes ids
1868 def AddPolygonalFace(self, IdsOfNodes):
1869 return self.editor.AddPolygonalFace(IdsOfNodes)
1871 ## Create volume both similar and quadratic (this is determed
1872 # by number of given nodes).
1873 # @param IdsOfNodes List of node IDs for creation of element.
1874 # Needed order of nodes in this list corresponds to description
1875 # of MED. \n This description is located by the following link:
1876 # http://www.salome-platform.org/salome2/web_med_internet/logiciels/medV2.2.2_doc_html/html/modele_de_donnees.html#3.
1877 def AddVolume(self, IDsOfNodes):
1878 return self.editor.AddVolume(IDsOfNodes)
1880 ## Create volume of many faces, giving nodes for each face.
1881 # @param IdsOfNodes List of node IDs for volume creation face by face.
1882 # @param Quantities List of integer values, Quantities[i]
1883 # gives quantity of nodes in face number i.
1884 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
1885 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
1887 ## Create volume of many faces, giving IDs of existing faces.
1888 # @param IdsOfFaces List of face IDs for volume creation.
1890 # Note: The created volume will refer only to nodes
1891 # of the given faces, not to the faces itself.
1892 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
1893 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
1895 ## Move node with given id
1896 # @param NodeID id of the node
1897 # @param x new X coordinate
1898 # @param y new Y coordinate
1899 # @param z new Z coordinate
1900 def MoveNode(self, NodeID, x, y, z):
1901 return self.editor.MoveNode(NodeID, x, y, z)
1903 ## Find a node closest to a point
1904 # @param x X coordinate of a point
1905 # @param y Y coordinate of a point
1906 # @param z Z coordinate of a point
1907 # @return id of a node
1908 def FindNodeClosestTo(self, x, y, z):
1909 preview = self.mesh.GetMeshEditPreviewer()
1910 return preview.MoveClosestNodeToPoint(x, y, z, -1)
1912 ## Find a node closest to a point and move it to a point location
1913 # @param x X coordinate of a point
1914 # @param y Y coordinate of a point
1915 # @param z Z coordinate of a point
1916 # @return id of a moved node
1917 def MeshToPassTroughAPoint(self, x, y, z):
1918 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
1920 ## Replace two neighbour triangles sharing Node1-Node2 link
1921 # with ones built on the same 4 nodes but having other common link.
1922 # @param NodeID1 first node id
1923 # @param NodeID2 second node id
1924 # @return false if proper faces not found
1925 def InverseDiag(self, NodeID1, NodeID2):
1926 return self.editor.InverseDiag(NodeID1, NodeID2)
1928 ## Replace two neighbour triangles sharing Node1-Node2 link
1929 # with a quadrangle built on the same 4 nodes.
1930 # @param NodeID1 first node id
1931 # @param NodeID2 second node id
1932 # @return false if proper faces not found
1933 def DeleteDiag(self, NodeID1, NodeID2):
1934 return self.editor.DeleteDiag(NodeID1, NodeID2)
1936 ## Reorient elements by ids
1937 # @param IDsOfElements if undefined reorient all mesh elements
1938 def Reorient(self, IDsOfElements=None):
1939 if IDsOfElements == None:
1940 IDsOfElements = self.GetElementsId()
1941 return self.editor.Reorient(IDsOfElements)
1943 ## Reorient all elements of the object
1944 # @param theObject is mesh, submesh or group
1945 def ReorientObject(self, theObject):
1946 return self.editor.ReorientObject(theObject)
1948 ## Fuse neighbour triangles into quadrangles.
1949 # @param IDsOfElements The triangles to be fused,
1950 # @param theCriterion is FT_...; used to choose a neighbour to fuse with.
1951 # @param MaxAngle is a max angle between element normals at which fusion
1952 # is still performed; theMaxAngle is mesured in radians.
1953 # @return TRUE in case of success, FALSE otherwise.
1954 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
1955 if IDsOfElements == []:
1956 IDsOfElements = self.GetElementsId()
1957 return self.editor.TriToQuad(IDsOfElements, GetFunctor(theCriterion), MaxAngle)
1959 ## Fuse neighbour triangles of the object into quadrangles
1960 # @param theObject is mesh, submesh or group
1961 # @param theCriterion is FT_...; used to choose a neighbour to fuse with.
1962 # @param MaxAngle is a max angle between element normals at which fusion
1963 # is still performed; theMaxAngle is mesured in radians.
1964 # @return TRUE in case of success, FALSE otherwise.
1965 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
1966 return self.editor.TriToQuadObject(theObject, GetFunctor(theCriterion), MaxAngle)
1968 ## Split quadrangles into triangles.
1969 # @param IDsOfElements the faces to be splitted.
1970 # @param theCriterion is FT_...; used to choose a diagonal for splitting.
1971 # @param @return TRUE in case of success, FALSE otherwise.
1972 def QuadToTri (self, IDsOfElements, theCriterion):
1973 if IDsOfElements == []:
1974 IDsOfElements = self.GetElementsId()
1975 return self.editor.QuadToTri(IDsOfElements, GetFunctor(theCriterion))
1977 ## Split quadrangles into triangles.
1978 # @param theObject object to taking list of elements from, is mesh, submesh or group
1979 # @param theCriterion is FT_...; used to choose a diagonal for splitting.
1980 def QuadToTriObject (self, theObject, theCriterion):
1981 return self.editor.QuadToTriObject(theObject, GetFunctor(theCriterion))
1983 ## Split quadrangles into triangles.
1984 # @param theElems The faces to be splitted
1985 # @param the13Diag is used to choose a diagonal for splitting.
1986 # @return TRUE in case of success, FALSE otherwise.
1987 def SplitQuad (self, IDsOfElements, Diag13):
1988 if IDsOfElements == []:
1989 IDsOfElements = self.GetElementsId()
1990 return self.editor.SplitQuad(IDsOfElements, Diag13)
1992 ## Split quadrangles into triangles.
1993 # @param theObject is object to taking list of elements from, is mesh, submesh or group
1994 def SplitQuadObject (self, theObject, Diag13):
1995 return self.editor.SplitQuadObject(theObject, Diag13)
1997 ## Find better splitting of the given quadrangle.
1998 # @param IDOfQuad ID of the quadrangle to be splitted.
1999 # @param theCriterion is FT_...; a criterion to choose a diagonal for splitting.
2000 # @return 1 if 1-3 diagonal is better, 2 if 2-4
2001 # diagonal is better, 0 if error occurs.
2002 def BestSplit (self, IDOfQuad, theCriterion):
2003 return self.editor.BestSplit(IDOfQuad, GetFunctor(theCriterion))
2005 ## Split quafrangle faces near triangular facets of volumes
2007 def SplitQuadsNearTriangularFacets(self):
2008 faces_array = self.GetElementsByType(SMESH.FACE)
2009 for face_id in faces_array:
2010 if self.GetElemNbNodes(face_id) == 4: # quadrangle
2011 quad_nodes = self.mesh.GetElemNodes(face_id)
2012 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
2013 isVolumeFound = False
2014 for node1_elem in node1_elems:
2015 if not isVolumeFound:
2016 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
2017 nb_nodes = self.GetElemNbNodes(node1_elem)
2018 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
2019 volume_elem = node1_elem
2020 volume_nodes = self.mesh.GetElemNodes(volume_elem)
2021 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
2022 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
2023 isVolumeFound = True
2024 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
2025 self.SplitQuad([face_id], False) # diagonal 2-4
2026 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
2027 isVolumeFound = True
2028 self.SplitQuad([face_id], True) # diagonal 1-3
2029 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
2030 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
2031 isVolumeFound = True
2032 self.SplitQuad([face_id], True) # diagonal 1-3
2034 ## @brief Split hexahedrons into tetrahedrons.
2036 # Use pattern mapping functionality for splitting.
2037 # @param theObject object to take list of hexahedrons from; is mesh, submesh or group.
2038 # @param theNode000,theNode001 is in range [0,7]; give an orientation of the
2039 # pattern relatively each hexahedron: the (0,0,0) key-point of pattern
2040 # will be mapped into <theNode000>-th node of each volume, the (0,0,1)
2041 # key-point will be mapped into <theNode001>-th node of each volume.
2042 # The (0,0,0) key-point of used pattern corresponds to not split corner.
2043 # @param @return TRUE in case of success, FALSE otherwise.
2044 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
2045 # Pattern: 5.---------.6
2050 # (0,0,1) 4.---------.7 * |
2057 # (0,0,0) 0.---------.3
2058 pattern_tetra = "!!! Nb of points: \n 8 \n\
2068 !!! Indices of points of 6 tetras: \n\
2076 pattern = GetPattern()
2077 isDone = pattern.LoadFromFile(pattern_tetra)
2079 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
2082 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
2083 isDone = pattern.MakeMesh(self.mesh, False, False)
2084 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
2086 # split quafrangle faces near triangular facets of volumes
2087 self.SplitQuadsNearTriangularFacets()
2091 ## @brief Split hexahedrons into prisms.
2093 # Use pattern mapping functionality for splitting.
2094 # @param theObject object to take list of hexahedrons from; is mesh, submesh or group.
2095 # @param theNode000,theNode001 is in range [0,7]; give an orientation of the
2096 # pattern relatively each hexahedron: the (0,0,0) key-point of pattern
2097 # will be mapped into <theNode000>-th node of each volume, the (0,0,1)
2098 # key-point will be mapped into <theNode001>-th node of each volume.
2099 # The edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
2100 # @param @return TRUE in case of success, FALSE otherwise.
2101 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
2102 # Pattern: 5.---------.6
2107 # (0,0,1) 4.---------.7 |
2114 # (0,0,0) 0.---------.3
2115 pattern_prism = "!!! Nb of points: \n 8 \n\
2125 !!! Indices of points of 2 prisms: \n\
2129 pattern = GetPattern()
2130 isDone = pattern.LoadFromFile(pattern_prism)
2132 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
2135 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
2136 isDone = pattern.MakeMesh(self.mesh, False, False)
2137 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
2139 # split quafrangle faces near triangular facets of volumes
2140 self.SplitQuadsNearTriangularFacets()
2145 # @param IDsOfElements list if ids of elements to smooth
2146 # @param IDsOfFixedNodes list of ids of fixed nodes.
2147 # Note that nodes built on edges and boundary nodes are always fixed.
2148 # @param MaxNbOfIterations maximum number of iterations
2149 # @param MaxAspectRatio varies in range [1.0, inf]
2150 # @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
2151 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
2152 MaxNbOfIterations, MaxAspectRatio, Method):
2153 if IDsOfElements == []:
2154 IDsOfElements = self.GetElementsId()
2155 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
2156 MaxNbOfIterations, MaxAspectRatio, Method)
2158 ## Smooth elements belong to given object
2159 # @param theObject object to smooth
2160 # @param IDsOfFixedNodes list of ids of fixed nodes.
2161 # Note that nodes built on edges and boundary nodes are always fixed.
2162 # @param MaxNbOfIterations maximum number of iterations
2163 # @param MaxAspectRatio varies in range [1.0, inf]
2164 # @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
2165 def SmoothObject(self, theObject, IDsOfFixedNodes,
2166 MaxNbOfIterations, MaxxAspectRatio, Method):
2167 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
2168 MaxNbOfIterations, MaxxAspectRatio, Method)
2170 ## Parametric smooth the given elements
2171 # @param IDsOfElements list if ids of elements to smooth
2172 # @param IDsOfFixedNodes list of ids of fixed nodes.
2173 # Note that nodes built on edges and boundary nodes are always fixed.
2174 # @param MaxNbOfIterations maximum number of iterations
2175 # @param MaxAspectRatio varies in range [1.0, inf]
2176 # @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
2177 def SmoothParametric(IDsOfElements, IDsOfFixedNodes,
2178 MaxNbOfIterations, MaxAspectRatio, Method):
2179 if IDsOfElements == []:
2180 IDsOfElements = self.GetElementsId()
2181 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
2182 MaxNbOfIterations, MaxAspectRatio, Method)
2184 ## Parametric smooth elements belong to given object
2185 # @param theObject object to smooth
2186 # @param IDsOfFixedNodes list of ids of fixed nodes.
2187 # Note that nodes built on edges and boundary nodes are always fixed.
2188 # @param MaxNbOfIterations maximum number of iterations
2189 # @param MaxAspectRatio varies in range [1.0, inf]
2190 # @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
2191 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
2192 MaxNbOfIterations, MaxAspectRatio, Method):
2193 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
2194 MaxNbOfIterations, MaxAspectRatio, Method)
2196 ## Converts all mesh to quadratic one, deletes old elements, replacing
2197 # them with quadratic ones with the same id.
2198 def ConvertToQuadratic(self, theForce3d):
2199 self.editor.ConvertToQuadratic(theForce3d)
2201 ## Converts all mesh from quadratic to ordinary ones,
2202 # deletes old quadratic elements, \n replacing
2203 # them with ordinary mesh elements with the same id.
2204 def ConvertFromQuadratic(self):
2205 return self.editor.ConvertFromQuadratic()
2207 ## Renumber mesh nodes
2208 def RenumberNodes(self):
2209 self.editor.RenumberNodes()
2211 ## Renumber mesh elements
2212 def RenumberElements(self):
2213 self.editor.RenumberElements()
2215 ## Generate new elements by rotation of the elements around the axis
2216 # @param IDsOfElements list of ids of elements to sweep
2217 # @param Axix axis of rotation, AxisStruct or line(geom object)
2218 # @param AngleInRadians angle of Rotation
2219 # @param NbOfSteps number of steps
2220 # @param Tolerance tolerance
2221 def RotationSweep(self, IDsOfElements, Axix, AngleInRadians, NbOfSteps, Tolerance):
2222 if IDsOfElements == []:
2223 IDsOfElements = self.GetElementsId()
2224 if ( isinstance( Axix, geompy.GEOM._objref_GEOM_Object)):
2225 Axix = GetAxisStruct(Axix)
2226 self.editor.RotationSweep(IDsOfElements, Axix, AngleInRadians, NbOfSteps, Tolerance)
2228 ## Generate new elements by rotation of the elements of object around the axis
2229 # @param theObject object wich elements should be sweeped
2230 # @param Axix axis of rotation, AxisStruct or line(geom object)
2231 # @param AngleInRadians angle of Rotation
2232 # @param NbOfSteps number of steps
2233 # @param Tolerance tolerance
2234 def RotationSweepObject(self, theObject, Axix, AngleInRadians, NbOfSteps, Tolerance):
2235 if ( isinstance( Axix, geompy.GEOM._objref_GEOM_Object)):
2236 Axix = GetAxisStruct(Axix)
2237 self.editor.RotationSweepObject(theObject, Axix, AngleInRadians, NbOfSteps, Tolerance)
2239 ## Generate new elements by extrusion of the elements with given ids
2240 # @param IDsOfElements list of elements ids for extrusion
2241 # @param StepVector vector, defining the direction and value of extrusion
2242 # @param NbOfSteps the number of steps
2243 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps):
2244 if IDsOfElements == []:
2245 IDsOfElements = self.GetElementsId()
2246 if ( isinstance( StepVector, geompy.GEOM._objref_GEOM_Object)):
2247 StepVector = GetDirStruct(StepVector)
2248 self.editor.ExtrusionSweep(IDsOfElements, StepVector, NbOfSteps)
2250 ## Generate new elements by extrusion of the elements with given ids
2251 # @param IDsOfElements is ids of elements
2252 # @param StepVector vector, defining the direction and value of extrusion
2253 # @param NbOfSteps the number of steps
2254 # @param ExtrFlags set flags for performing extrusion
2255 # @param SewTolerance uses for comparing locations of nodes if flag
2256 # EXTRUSION_FLAG_SEW is set
2257 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps, ExtrFlags, SewTolerance):
2258 if ( isinstance( StepVector, geompy.GEOM._objref_GEOM_Object)):
2259 StepVector = GetDirStruct(StepVector)
2260 self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps, ExtrFlags, SewTolerance)
2262 ## Generate new elements by extrusion of the elements belong to object
2263 # @param theObject object wich elements should be processed
2264 # @param StepVector vector, defining the direction and value of extrusion
2265 # @param NbOfSteps the number of steps
2266 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps):
2267 if ( isinstance( StepVector, geompy.GEOM._objref_GEOM_Object)):
2268 StepVector = GetDirStruct(StepVector)
2269 self.editor.ExtrusionSweepObject(theObject, StepVector, NbOfSteps)
2271 ## Generate new elements by extrusion of the elements belong to object
2272 # @param theObject object wich elements should be processed
2273 # @param StepVector vector, defining the direction and value of extrusion
2274 # @param NbOfSteps the number of steps
2275 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps):
2276 if ( isinstance( StepVector, geompy.GEOM._objref_GEOM_Object)):
2277 StepVector = GetDirStruct(StepVector)
2278 self.editor.ExtrusionSweepObject1D(theObject, StepVector, NbOfSteps)
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 ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps):
2285 if ( isinstance( StepVector, geompy.GEOM._objref_GEOM_Object)):
2286 StepVector = GetDirStruct(StepVector)
2287 self.editor.ExtrusionSweepObject2D(theObject, StepVector, NbOfSteps)
2289 ## Generate new elements by extrusion of the given elements
2290 # A path of extrusion must be a meshed edge.
2291 # @param IDsOfElements is ids of elements
2292 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
2293 # @param PathShape is shape(edge); as the mesh can be complex, the edge is used to define the sub-mesh for the path
2294 # @param NodeStart the first or the last node on the edge. It is used to define the direction of extrusion
2295 # @param HasAngles allows the shape to be rotated around the path to get the resulting mesh in a helical fashion
2296 # @param Angles list of angles
2297 # @param HasRefPoint allows to use base point
2298 # @param RefPoint point around which the shape is rotated(the mass center of the shape by default).
2299 # User can specify any point as the Base Point and the shape will be rotated with respect to this point.
2300 # @param LinearVariation makes compute rotation angles as linear variation of given Angles along path steps
2301 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
2302 HasAngles, Angles, HasRefPoint, RefPoint, LinearVariation=False):
2303 if IDsOfElements == []:
2304 IDsOfElements = self.GetElementsId()
2305 if ( isinstance( RefPoint, geompy.GEOM._objref_GEOM_Object)):
2306 RefPoint = GetPointStruct(RefPoint)
2308 return self.editor.ExtrusionAlongPath(IDsOfElements, PathMesh.GetMesh(), PathShape, NodeStart,
2309 HasAngles, Angles, HasRefPoint, RefPoint)
2311 ## Generate new elements by extrusion of the elements belong to object
2312 # A path of extrusion must be a meshed edge.
2313 # @param IDsOfElements is ids of elements
2314 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
2315 # @param PathShape is shape(edge); as the mesh can be complex, the edge is used to define the sub-mesh for the path
2316 # @param NodeStart the first or the last node on the edge. It is used to define the direction of extrusion
2317 # @param HasAngles allows the shape to be rotated around the path to get the resulting mesh in a helical fashion
2318 # @param Angles list of angles
2319 # @param HasRefPoint allows to use base point
2320 # @param RefPoint point around which the shape is rotated(the mass center of the shape by default).
2321 # User can specify any point as the Base Point and the shape will be rotated with respect to this point.
2322 # @param LinearVariation makes compute rotation angles as linear variation of given Angles along path steps
2323 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
2324 HasAngles, Angles, HasRefPoint, RefPoint, LinearVariation=False):
2325 if ( isinstance( RefPoint, geompy.GEOM._objref_GEOM_Object)):
2326 RefPoint = GetPointStruct(RefPoint)
2327 return self.editor.ExtrusionAlongPathObject(theObject, PathMesh.GetMesh(), PathShape, NodeStart,
2328 HasAngles, Angles, HasRefPoint, RefPoint, LinearVariation)
2330 ## Symmetrical copy of mesh elements
2331 # @param IDsOfElements list of elements ids
2332 # @param Mirror is AxisStruct or geom object(point, line, plane)
2333 # @param theMirrorType is POINT, AXIS or PLANE
2334 # If the Mirror is geom object this parameter is unnecessary
2335 # @param Copy allows to copy element(Copy is 1) or to replace with its mirroring(Copy is 0)
2336 def Mirror(self, IDsOfElements, Mirror, theMirrorType, Copy=0):
2337 if IDsOfElements == []:
2338 IDsOfElements = self.GetElementsId()
2339 if ( isinstance( Mirror, geompy.GEOM._objref_GEOM_Object)):
2340 Mirror = GetAxisStruct(Mirror)
2341 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
2343 ## Symmetrical copy of object
2344 # @param theObject mesh, submesh or group
2345 # @param Mirror is AxisStruct or geom object(point, line, plane)
2346 # @param theMirrorType is POINT, AXIS or PLANE
2347 # If the Mirror is geom object this parameter is unnecessary
2348 # @param Copy allows to copy element(Copy is 1) or to replace with its mirroring(Copy is 0)
2349 def MirrorObject (self, theObject, Mirror, theMirrorType, Copy=0):
2350 if ( isinstance( Mirror, geompy.GEOM._objref_GEOM_Object)):
2351 Mirror = GetAxisStruct(Mirror)
2352 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
2354 ## Translates the elements
2355 # @param IDsOfElements list of elements ids
2356 # @param Vector direction of translation(DirStruct or vector)
2357 # @param Copy allows to copy the translated elements
2358 def Translate(self, IDsOfElements, Vector, Copy):
2359 if IDsOfElements == []:
2360 IDsOfElements = self.GetElementsId()
2361 if ( isinstance( Vector, geompy.GEOM._objref_GEOM_Object)):
2362 Vector = GetDirStruct(Vector)
2363 self.editor.Translate(IDsOfElements, Vector, Copy)
2365 ## Translates the object
2366 # @param theObject object to translate(mesh, submesh, or group)
2367 # @param Vector direction of translation(DirStruct or geom vector)
2368 # @param Copy allows to copy the translated elements
2369 def TranslateObject(self, theObject, Vector, Copy):
2370 if ( isinstance( Vector, geompy.GEOM._objref_GEOM_Object)):
2371 Vector = GetDirStruct(Vector)
2372 self.editor.TranslateObject(theObject, Vector, Copy)
2374 ## Rotates the elements
2375 # @param IDsOfElements list of elements ids
2376 # @param Axis axis of rotation(AxisStruct or geom line)
2377 # @param AngleInRadians angle of rotation(in radians)
2378 # @param Copy allows to copy the rotated elements
2379 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy):
2380 if IDsOfElements == []:
2381 IDsOfElements = self.GetElementsId()
2382 if ( isinstance( Axis, geompy.GEOM._objref_GEOM_Object)):
2383 Axis = GetAxisStruct(Axis)
2384 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
2386 ## Rotates the object
2387 # @param theObject object to rotate(mesh, submesh, or group)
2388 # @param Axis axis of rotation(AxisStruct or geom line)
2389 # @param AngleInRadians angle of rotation(in radians)
2390 # @param Copy allows to copy the rotated elements
2391 def RotateObject (self, theObject, Axis, AngleInRadians, Copy):
2392 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
2394 ## Find group of nodes close to each other within Tolerance.
2395 # @param Tolerance tolerance value
2396 # @param list of group of nodes
2397 def FindCoincidentNodes (self, Tolerance):
2398 return self.editor.FindCoincidentNodes(Tolerance)
2401 # @param list of group of nodes
2402 def MergeNodes (self, GroupsOfNodes):
2403 self.editor.MergeNodes(GroupsOfNodes)
2405 ## Remove all but one of elements built on the same nodes.
2406 def MergeEqualElements(self):
2407 self.editor.MergeEqualElements()
2410 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
2411 FirstNodeID2, SecondNodeID2, LastNodeID2,
2412 CreatePolygons, CreatePolyedrs):
2413 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
2414 FirstNodeID2, SecondNodeID2, LastNodeID2,
2415 CreatePolygons, CreatePolyedrs)
2417 ## Sew conform free borders
2418 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
2419 FirstNodeID2, SecondNodeID2):
2420 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
2421 FirstNodeID2, SecondNodeID2)
2423 ## Sew border to side
2424 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
2425 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
2426 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
2427 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
2429 ## Sew two sides of a mesh. Nodes belonging to Side1 are
2430 # merged with nodes of elements of Side2.
2431 # Number of elements in theSide1 and in theSide2 must be
2432 # equal and they should have similar node connectivity.
2433 # The nodes to merge should belong to sides borders and
2434 # the first node should be linked to the second.
2435 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
2436 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
2437 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
2438 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
2439 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
2440 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
2442 ## Set new nodes for given element.
2443 # @param ide the element id
2444 # @param newIDs nodes ids
2445 # @return If number of nodes is not corresponded to type of element - returns false
2446 def ChangeElemNodes(self, ide, newIDs):
2447 return self.editor.ChangeElemNodes(ide, newIDs)
2449 ## If during last operation of MeshEditor some nodes were
2450 # created this method returns list of it's IDs, \n
2451 # if new nodes not created - returns empty list
2452 def GetLastCreatedNodes(self):
2453 return self.editor.GetLastCreatedNodes()
2455 ## If during last operation of MeshEditor some elements were
2456 # created this method returns list of it's IDs, \n
2457 # if new elements not creared - returns empty list
2458 def GetLastCreatedElems(self):
2459 return self.editor.GetLastCreatedElems()