1 # Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 # File : smeshBuilder.py
20 # Author : Francis KLOSS, OCC
24 from salome.geom import geomBuilder
26 import SMESH # This is necessary for back compatibility
28 from salome.smesh.smesh_algorithm import Mesh_Algorithm
35 """Private class used to workaround a problem that sometimes isinstance(m, Mesh) returns False
37 def __instancecheck__(cls, inst):
38 """Implement isinstance(inst, cls)."""
39 return any(cls.__subclasscheck__(c)
40 for c in {type(inst), inst.__class__})
42 def __subclasscheck__(cls, sub):
43 """Implement issubclass(sub, cls)."""
44 return type.__subclasscheck__(cls, sub) or (cls.__name__ == sub.__name__ and cls.__module__ == sub.__module__)
46 def DegreesToRadians(AngleInDegrees):
47 """Convert an angle from degrees to radians
50 return AngleInDegrees * pi / 180.0
52 import salome_notebook
53 notebook = salome_notebook.notebook
54 # Salome notebook variable separator
57 def ParseParameters(*args):
59 Return list of variable values from salome notebook.
60 The last argument, if is callable, is used to modify values got from notebook
66 if args and callable( args[-1] ):
67 args, varModifFun = args[:-1], args[-1]
68 for parameter in args:
70 Parameters += str(parameter) + var_separator
72 if isinstance(parameter,str):
73 # check if there is an inexistent variable name
74 if not notebook.isVariable(parameter):
75 raise ValueError, "Variable with name '" + parameter + "' doesn't exist!!!"
76 parameter = notebook.get(parameter)
79 parameter = varModifFun(parameter)
82 Result.append(parameter)
85 Parameters = Parameters[:-1]
86 Result.append( Parameters )
87 Result.append( hasVariables )
90 def ParseAngles(*args):
92 Parse parameters while converting variables to radians
94 return ParseParameters( *( args + (DegreesToRadians, )))
96 def __initPointStruct(point,*args):
98 Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
99 Parameters are stored in PointStruct.parameters attribute
101 point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
103 SMESH.PointStruct.__init__ = __initPointStruct
105 def __initAxisStruct(ax,*args):
107 Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
108 Parameters are stored in AxisStruct.parameters attribute
112 "Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args ))
113 ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
115 SMESH.AxisStruct.__init__ = __initAxisStruct
117 smeshPrecisionConfusion = 1.e-07
118 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
119 """Compare real values using smeshPrecisionConfusion as tolerance
121 if abs(val1 - val2) < tol:
134 if isinstance(obj, SALOMEDS._objref_SObject):
138 ior = salome.orb.object_to_string(obj)
143 studies = salome.myStudyManager.GetOpenStudies()
144 for sname in studies:
145 s = salome.myStudyManager.GetStudyByName(sname)
147 sobj = s.FindObjectIOR(ior)
148 if not sobj: continue
149 return sobj.GetName()
150 if hasattr(obj, "GetName"):
151 # unknown CORBA object, having GetName() method
154 # unknown CORBA object, no GetName() method
157 if hasattr(obj, "GetName"):
158 # unknown non-CORBA object, having GetName() method
161 raise RuntimeError, "Null or invalid object"
163 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
165 Print error message if a hypothesis was not assigned.
168 hypType = "algorithm"
170 hypType = "hypothesis"
173 if hasattr( status, "__getitem__" ):
174 status,reason = status[0],status[1]
175 if status == HYP_UNKNOWN_FATAL :
176 reason = "for unknown reason"
177 elif status == HYP_INCOMPATIBLE :
178 reason = "this hypothesis mismatches the algorithm"
179 elif status == HYP_NOTCONFORM :
180 reason = "a non-conform mesh would be built"
181 elif status == HYP_ALREADY_EXIST :
182 if isAlgo: return # it does not influence anything
183 reason = hypType + " of the same dimension is already assigned to this shape"
184 elif status == HYP_BAD_DIM :
185 reason = hypType + " mismatches the shape"
186 elif status == HYP_CONCURRENT :
187 reason = "there are concurrent hypotheses on sub-shapes"
188 elif status == HYP_BAD_SUBSHAPE :
189 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
190 elif status == HYP_BAD_GEOMETRY:
191 reason = "the algorithm is not applicable to this geometry"
192 elif status == HYP_HIDDEN_ALGO:
193 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
194 elif status == HYP_HIDING_ALGO:
195 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
196 elif status == HYP_NEED_SHAPE:
197 reason = "algorithm can't work without shape"
198 elif status == HYP_INCOMPAT_HYPS:
204 where = '"%s"' % geomName
206 meshName = GetName( mesh )
207 if meshName and meshName != NO_NAME:
208 where = '"%s" shape in "%s" mesh ' % ( geomName, meshName )
209 if status < HYP_UNKNOWN_FATAL and where:
210 print '"%s" was assigned to %s but %s' %( hypName, where, reason )
212 print '"%s" was not assigned to %s : %s' %( hypName, where, reason )
214 print '"%s" was not assigned : %s' %( hypName, reason )
217 def AssureGeomPublished(mesh, geom, name=''):
219 Private method. Add geom (sub-shape of the main shape) into the study if not yet there
221 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
223 if not geom.GetStudyEntry() and \
224 mesh.smeshpyD.GetCurrentStudy():
226 studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
227 if studyID != mesh.geompyD.myStudyId:
228 mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
230 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
231 # for all groups SubShapeName() return "Compound_-1"
232 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
234 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
236 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
239 def FirstVertexOnCurve(mesh, edge):
242 the first vertex of a geometrical edge by ignoring orientation
244 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
246 raise TypeError, "Given object has no vertices"
247 if len( vv ) == 1: return vv[0]
248 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
249 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
250 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
251 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
254 dist1 += abs( xyz[i] - xyz1[i] )
255 dist2 += abs( xyz[i] - xyz2[i] )
264 smeshInst is a singleton
270 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
272 This class allows to create, load or manipulate meshes.
273 It has a set of methods to create, load or copy meshes, to combine several meshes, etc.
274 It also has methods to get infos and measure meshes.
277 # MirrorType enumeration
278 POINT = SMESH_MeshEditor.POINT
279 AXIS = SMESH_MeshEditor.AXIS
280 PLANE = SMESH_MeshEditor.PLANE
282 # Smooth_Method enumeration
283 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
284 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
286 PrecisionConfusion = smeshPrecisionConfusion
288 # TopAbs_State enumeration
289 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
291 # Methods of splitting a hexahedron into tetrahedra
292 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
298 #print "==== __new__", engine, smeshInst, doLcc
300 if smeshInst is None:
301 # smesh engine is either retrieved from engine, or created
303 # Following test avoids a recursive loop
305 if smeshInst is not None:
306 # smesh engine not created: existing engine found
310 # FindOrLoadComponent called:
311 # 1. CORBA resolution of server
312 # 2. the __new__ method is called again
313 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
314 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
316 # FindOrLoadComponent not called
317 if smeshInst is None:
318 # smeshBuilder instance is created from lcc.FindOrLoadComponent
319 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
320 smeshInst = super(smeshBuilder,cls).__new__(cls)
322 # smesh engine not created: existing engine found
323 #print "==== existing ", engine, smeshInst, doLcc
325 #print "====1 ", smeshInst
328 #print "====2 ", smeshInst
333 #print "--------------- smeshbuilder __init__ ---", created
336 SMESH._objref_SMESH_Gen.__init__(self)
338 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
340 Dump component to the Python script
341 This method overrides IDL function to allow default values for the parameters.
344 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
346 def SetDumpPythonHistorical(self, isHistorical):
348 Set mode of DumpPython(), *historical* or *snapshot*.
349 In the *historical* mode, the Python Dump script includes all commands
350 performed by SMESH engine. In the *snapshot* mode, commands
351 relating to objects removed from the Study are excluded from the script
352 as well as commands not influencing the current state of meshes
355 if isHistorical: val = "true"
357 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
359 def init_smesh(self,theStudy,geompyD = None):
361 Set the current study and Geometry component
365 self.SetCurrentStudy(theStudy,geompyD)
368 notebook.myStudy = theStudy
370 def Mesh(self, obj=0, name=0):
372 Create a mesh. This can be either an empty mesh, possibly having an underlying geometry,
373 or a mesh wrapping a CORBA mesh given as a parameter.
376 obj: either (1) a CORBA mesh: (SMESH._objref_SMESH_Mesh) got e.g. by calling
377 salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
378 (2) a Geometrical object: for meshing or (3) none:.
379 name: the name for the new mesh.
382 an instance of Mesh class.
385 if isinstance(obj,str):
387 return Mesh(self,self.geompyD,obj,name)
389 def EnumToLong(self,theItem):
391 Return a long value from enumeration
396 def ColorToString(self,c):
399 a string representation of the color.
400 To be used with filters.
403 c: color value (SALOMEDS.Color)
407 if isinstance(c, SALOMEDS.Color):
408 val = "%s;%s;%s" % (c.R, c.G, c.B)
409 elif isinstance(c, str):
412 raise ValueError, "Color value should be of string or SALOMEDS.Color type"
415 def GetPointStruct(self,theVertex):
417 Get PointStruct from vertex
420 theVertex: a GEOM object(vertex)
426 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
427 return PointStruct(x,y,z)
429 def GetDirStruct(self,theVector):
431 Get DirStruct from vector
434 theVector: a GEOM object(vector)
440 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
441 if(len(vertices) != 2):
442 print "Error: vector object is incorrect."
444 p1 = self.geompyD.PointCoordinates(vertices[0])
445 p2 = self.geompyD.PointCoordinates(vertices[1])
446 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
447 dirst = DirStruct(pnt)
450 def MakeDirStruct(self,x,y,z):
452 Make DirStruct from a triplet
455 x,y,z: vector components
461 pnt = PointStruct(x,y,z)
462 return DirStruct(pnt)
464 def GetAxisStruct(self,theObj):
466 Get AxisStruct from object
469 theObj: a GEOM object (line or plane)
475 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
478 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
479 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
480 vertex1 = self.geompyD.PointCoordinates(vertex1)
481 vertex2 = self.geompyD.PointCoordinates(vertex2)
482 vertex3 = self.geompyD.PointCoordinates(vertex3)
483 vertex4 = self.geompyD.PointCoordinates(vertex4)
484 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
485 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
486 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] ]
487 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
488 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
489 elif len(edges) == 1:
490 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
491 p1 = self.geompyD.PointCoordinates( vertex1 )
492 p2 = self.geompyD.PointCoordinates( vertex2 )
493 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
494 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
495 elif theObj.GetShapeType() == GEOM.VERTEX:
496 x,y,z = self.geompyD.PointCoordinates( theObj )
497 axis = AxisStruct( x,y,z, 1,0,0,)
498 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
501 # From SMESH_Gen interface:
502 # ------------------------
504 def SetName(self, obj, name):
506 Set the given name to the object
509 obj: the object to rename
510 name: a new object name
513 if isinstance( obj, Mesh ):
515 elif isinstance( obj, Mesh_Algorithm ):
516 obj = obj.GetAlgorithm()
517 ior = salome.orb.object_to_string(obj)
518 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
520 def SetEmbeddedMode( self,theMode ):
525 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
527 def IsEmbeddedMode(self):
532 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
534 def SetCurrentStudy( self, theStudy, geompyD = None ):
536 Set the current study. Calling SetCurrentStudy( None ) allows to
537 switch OFF automatic pubilishing in the Study of mesh objects.
541 from salome.geom import geomBuilder
542 geompyD = geomBuilder.geom
545 self.SetGeomEngine(geompyD)
546 SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
549 notebook = salome_notebook.NoteBook( theStudy )
551 notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
553 sb = theStudy.NewBuilder()
554 sc = theStudy.FindComponent("SMESH")
555 if sc: sb.LoadWith(sc, self)
559 def GetCurrentStudy(self):
561 Get the current study
564 return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
566 def CreateMeshesFromUNV( self,theFileName ):
568 Create a Mesh object importing data from the given UNV file
571 an instance of Mesh class
574 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
575 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
578 def CreateMeshesFromMED( self,theFileName ):
580 Create a Mesh object(s) importing data from the given MED file
583 a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
586 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
587 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
588 return aMeshes, aStatus
590 def CreateMeshesFromSAUV( self,theFileName ):
592 Create a Mesh object(s) importing data from the given SAUV file
595 a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
598 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
599 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
600 return aMeshes, aStatus
602 def CreateMeshesFromSTL( self, theFileName ):
604 Create a Mesh object importing data from the given STL file
607 an instance of Mesh class
610 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
611 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
614 def CreateMeshesFromCGNS( self, theFileName ):
616 Create Mesh objects importing data from the given CGNS file
619 a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
622 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
623 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
624 return aMeshes, aStatus
626 def CreateMeshesFromGMF( self, theFileName ):
628 Create a Mesh object importing data from the given GMF file.
629 GMF files must have .mesh extension for the ASCII format and .meshb for
633 [ an instance of Mesh class, SMESH.ComputeError ]
636 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
639 if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
640 return Mesh(self, self.geompyD, aSmeshMesh), error
642 def Concatenate( self, meshes, uniteIdenticalGroups,
643 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
646 Concatenate the given meshes into one mesh. All groups of input meshes will be
647 present in the new mesh.
650 meshes: the meshes, sub-meshes and groups to combine into one mesh
651 uniteIdenticalGroups: if true, groups with same names are united, else they are renamed
652 mergeNodesAndElements: if true, equal nodes and elements are merged
653 mergeTolerance: tolerance for merging nodes
654 allGroups: forces creation of groups corresponding to every input mesh
655 name: name of a new mesh
658 an instance of Mesh class
661 if not meshes: return None
662 for i,m in enumerate(meshes):
663 if isinstance(m, Mesh):
664 meshes[i] = m.GetMesh()
665 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
666 meshes[0].SetParameters(Parameters)
668 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
669 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
671 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
672 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
673 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
676 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
678 Create a mesh by copying a part of another mesh.
681 meshPart: a part of mesh to copy, either a Mesh, a sub-mesh or a group;
682 to copy nodes or elements not contained in any mesh object,
683 pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
684 meshName: a name of the new mesh
685 toCopyGroups: to create in the new mesh groups the copied elements belongs to
686 toKeepIDs: to preserve order of the copied elements or not
689 an instance of Mesh class
692 if isinstance( meshPart, Mesh ):
693 meshPart = meshPart.GetMesh()
694 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
695 return Mesh(self, self.geompyD, mesh)
697 def CopyMeshWithGeom( self, sourceMesh, newGeom, meshName="", toCopyGroups=True,
698 toReuseHypotheses=True, toCopyElements=True):
700 Create a mesh by copying a mesh definition (hypotheses and groups) to a new geometry.
701 It is supposed that the new geometry is a modified geometry of *sourceMesh*.
702 To facilitate and speed up the operation, consider using
703 "Set presentation parameters and sub-shapes from arguments" option in
704 a dialog of geometrical operation used to create the new geometry.
707 sourceMesh: the mesh to copy definition of.
708 newGeom: the new geomtry.
709 meshName: an optional name of the new mesh. If omitted, the mesh name is kept.
710 toCopyGroups: to create groups in the new mesh.
711 toReuseHypotheses: to reuse hypotheses of the *sourceMesh*.
712 toCopyElements: to copy mesh elements present on non-modified sub-shapes of
715 tuple ( ok, newMesh, newGroups, newSubMeshes, newHypotheses, invalidEntries )
716 *invalidEntries* are study entries of objects whose
717 counterparts are not found in the *newGeom*, followed by entries
718 of mesh sub-objects that are invalid because they depend on a not found
721 if isinstance( sourceMesh, Mesh ):
722 sourceMesh = sourceMesh.GetMesh()
724 ok, newMesh, newGroups, newSubMeshes, newHypotheses, invalidEntries = \
725 SMESH._objref_SMESH_Gen.CopyMeshWithGeom( self, sourceMesh, newGeom, meshName,
729 return ( ok, Mesh(self, self.geompyD, newMesh),
730 newGroups, newSubMeshes, newHypotheses, invalidEntries )
732 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
734 Return IDs of sub-shapes
737 the list of integer values
740 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
742 def GetPattern(self):
744 Create a pattern mapper.
747 an instance of SMESH_Pattern
749 `Example of Patterns usage <../tui_modifying_meshes_page.html#tui_pattern_mapping>`_
752 return SMESH._objref_SMESH_Gen.GetPattern(self)
754 def SetBoundaryBoxSegmentation(self, nbSegments):
756 Set number of segments per diagonal of boundary box of geometry, by which
757 default segment length of appropriate 1D hypotheses is defined in GUI.
761 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
763 # Filtering. Auxiliary functions:
764 # ------------------------------
766 def GetEmptyCriterion(self):
768 Create an empty criterion
771 SMESH.Filter.Criterion
774 Type = self.EnumToLong(FT_Undefined)
775 Compare = self.EnumToLong(FT_Undefined)
779 UnaryOp = self.EnumToLong(FT_Undefined)
780 BinaryOp = self.EnumToLong(FT_Undefined)
783 Precision = -1 ##@1e-07
784 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
785 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
787 def GetCriterion(self,elementType,
789 Compare = FT_EqualTo,
791 UnaryOp=FT_Undefined,
792 BinaryOp=FT_Undefined,
795 Create a criterion by the given parameters
796 Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
799 elementType: the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
800 CritType: the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
801 Type SMESH.FunctorType._items in the Python Console to see all values.
802 Note that the items starting from FT_LessThan are not suitable for CritType.
803 Compare: belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
804 Threshold: the threshold value (range of ids as string, shape, numeric)
805 UnaryOp: SMESH.FT_LogicalNOT or SMESH.FT_Undefined
806 BinaryOp: a binary logical operation SMESH.FT_LogicalAND, SMESH.FT_LogicalOR or
808 Tolerance: the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
809 SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
812 SMESH.Filter.Criterion
814 href="../tui_filters_page.html#combining_filters"
817 if not CritType in SMESH.FunctorType._items:
818 raise TypeError, "CritType should be of SMESH.FunctorType"
819 aCriterion = self.GetEmptyCriterion()
820 aCriterion.TypeOfElement = elementType
821 aCriterion.Type = self.EnumToLong(CritType)
822 aCriterion.Tolerance = Tolerance
824 aThreshold = Threshold
826 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
827 aCriterion.Compare = self.EnumToLong(Compare)
828 elif Compare == "=" or Compare == "==":
829 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
831 aCriterion.Compare = self.EnumToLong(FT_LessThan)
833 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
834 elif Compare != FT_Undefined:
835 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
838 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
839 FT_BelongToCylinder, FT_LyingOnGeom]:
840 # Check that Threshold is GEOM object
841 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
842 aCriterion.ThresholdStr = GetName(aThreshold)
843 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
844 if not aCriterion.ThresholdID:
845 name = aCriterion.ThresholdStr
847 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
848 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
849 # or a name of GEOM object
850 elif isinstance( aThreshold, str ):
851 aCriterion.ThresholdStr = aThreshold
853 raise TypeError, "The Threshold should be a shape."
854 if isinstance(UnaryOp,float):
855 aCriterion.Tolerance = UnaryOp
856 UnaryOp = FT_Undefined
858 elif CritType == FT_BelongToMeshGroup:
859 # Check that Threshold is a group
860 if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
861 if aThreshold.GetType() != elementType:
862 raise ValueError, "Group type mismatches Element type"
863 aCriterion.ThresholdStr = aThreshold.GetName()
864 aCriterion.ThresholdID = salome.orb.object_to_string( aThreshold )
865 study = self.GetCurrentStudy()
867 so = study.FindObjectIOR( aCriterion.ThresholdID )
871 aCriterion.ThresholdID = entry
873 raise TypeError, "The Threshold should be a Mesh Group"
874 elif CritType == FT_RangeOfIds:
875 # Check that Threshold is string
876 if isinstance(aThreshold, str):
877 aCriterion.ThresholdStr = aThreshold
879 raise TypeError, "The Threshold should be a string."
880 elif CritType == FT_CoplanarFaces:
881 # Check the Threshold
882 if isinstance(aThreshold, int):
883 aCriterion.ThresholdID = str(aThreshold)
884 elif isinstance(aThreshold, str):
887 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
888 aCriterion.ThresholdID = aThreshold
891 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
892 elif CritType == FT_ConnectedElements:
893 # Check the Threshold
894 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
895 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
896 if not aCriterion.ThresholdID:
897 name = aThreshold.GetName()
899 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
900 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
901 elif isinstance(aThreshold, int): # node id
902 aCriterion.Threshold = aThreshold
903 elif isinstance(aThreshold, list): # 3 point coordinates
904 if len( aThreshold ) < 3:
905 raise ValueError, "too few point coordinates, must be 3"
906 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
907 elif isinstance(aThreshold, str):
908 if aThreshold.isdigit():
909 aCriterion.Threshold = aThreshold # node id
911 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
914 "The Threshold should either a VERTEX, or a node ID, "\
915 "or a list of point coordinates and not '%s'"%aThreshold
916 elif CritType == FT_ElemGeomType:
917 # Check the Threshold
919 aCriterion.Threshold = self.EnumToLong(aThreshold)
920 assert( aThreshold in SMESH.GeometryType._items )
922 if isinstance(aThreshold, int):
923 aCriterion.Threshold = aThreshold
925 raise TypeError, "The Threshold should be an integer or SMESH.GeometryType."
928 elif CritType == FT_EntityType:
929 # Check the Threshold
931 aCriterion.Threshold = self.EnumToLong(aThreshold)
932 assert( aThreshold in SMESH.EntityType._items )
934 if isinstance(aThreshold, int):
935 aCriterion.Threshold = aThreshold
937 raise TypeError, "The Threshold should be an integer or SMESH.EntityType."
941 elif CritType == FT_GroupColor:
942 # Check the Threshold
944 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
946 raise TypeError, "The threshold value should be of SALOMEDS.Color type"
948 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
949 FT_LinearOrQuadratic, FT_BadOrientedVolume,
950 FT_BareBorderFace, FT_BareBorderVolume,
951 FT_OverConstrainedFace, FT_OverConstrainedVolume,
952 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
953 # At this point the Threshold is unnecessary
954 if aThreshold == FT_LogicalNOT:
955 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
956 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
957 aCriterion.BinaryOp = aThreshold
961 aThreshold = float(aThreshold)
962 aCriterion.Threshold = aThreshold
964 raise TypeError, "The Threshold should be a number."
967 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
968 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
970 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
971 aCriterion.BinaryOp = self.EnumToLong(Threshold)
973 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
974 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
976 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
977 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
981 def GetFilter(self,elementType,
982 CritType=FT_Undefined,
985 UnaryOp=FT_Undefined,
989 Create a filter with the given parameters
992 elementType: the type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
993 CritType: the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
994 Type SMESH.FunctorType._items in the Python Console to see all values.
995 Note that the items starting from FT_LessThan are not suitable for CritType.
996 Compare: belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
997 Threshold: the threshold value (range of ids as string, shape, numeric)
998 UnaryOp: SMESH.FT_LogicalNOT or SMESH.FT_Undefined
999 Tolerance: the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
1000 SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces and SMESH.FT_EqualNodes criteria
1001 mesh: the mesh to initialize the filter with
1006 `Example of Filters usage <../tui_filters_page.html#tui_filters>`_
1009 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1010 aFilterMgr = self.CreateFilterManager()
1011 aFilter = aFilterMgr.CreateFilter()
1013 aCriteria.append(aCriterion)
1014 aFilter.SetCriteria(aCriteria)
1016 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
1017 else : aFilter.SetMesh( mesh )
1018 aFilterMgr.UnRegister()
1021 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
1023 Create a filter from criteria
1026 criteria: a list of criteria
1027 binOp: binary operator used when binary operator of criteria is undefined
1032 `Example of Filters usage <../tui_filters_page.html#tui_filters>`_
1035 for i in range( len( criteria ) - 1 ):
1036 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
1037 criteria[i].BinaryOp = self.EnumToLong( binOp )
1038 aFilterMgr = self.CreateFilterManager()
1039 aFilter = aFilterMgr.CreateFilter()
1040 aFilter.SetCriteria(criteria)
1041 aFilterMgr.UnRegister()
1044 def GetFunctor(self,theCriterion):
1046 Create a numerical functor by its type
1049 theCriterion: functor type - an item of SMESH.FunctorType enumeration.
1050 Type SMESH.FunctorType._items in the Python Console to see all items.
1051 Note that not all items correspond to numerical functors.
1054 SMESH_NumericalFunctor
1057 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
1059 aFilterMgr = self.CreateFilterManager()
1061 if theCriterion == FT_AspectRatio:
1062 functor = aFilterMgr.CreateAspectRatio()
1063 elif theCriterion == FT_AspectRatio3D:
1064 functor = aFilterMgr.CreateAspectRatio3D()
1065 elif theCriterion == FT_Warping:
1066 functor = aFilterMgr.CreateWarping()
1067 elif theCriterion == FT_MinimumAngle:
1068 functor = aFilterMgr.CreateMinimumAngle()
1069 elif theCriterion == FT_Taper:
1070 functor = aFilterMgr.CreateTaper()
1071 elif theCriterion == FT_Skew:
1072 functor = aFilterMgr.CreateSkew()
1073 elif theCriterion == FT_Area:
1074 functor = aFilterMgr.CreateArea()
1075 elif theCriterion == FT_Volume3D:
1076 functor = aFilterMgr.CreateVolume3D()
1077 elif theCriterion == FT_MaxElementLength2D:
1078 functor = aFilterMgr.CreateMaxElementLength2D()
1079 elif theCriterion == FT_MaxElementLength3D:
1080 functor = aFilterMgr.CreateMaxElementLength3D()
1081 elif theCriterion == FT_MultiConnection:
1082 functor = aFilterMgr.CreateMultiConnection()
1083 elif theCriterion == FT_MultiConnection2D:
1084 functor = aFilterMgr.CreateMultiConnection2D()
1085 elif theCriterion == FT_Length:
1086 functor = aFilterMgr.CreateLength()
1087 elif theCriterion == FT_Length2D:
1088 functor = aFilterMgr.CreateLength2D()
1089 elif theCriterion == FT_Deflection2D:
1090 functor = aFilterMgr.CreateDeflection2D()
1091 elif theCriterion == FT_NodeConnectivityNumber:
1092 functor = aFilterMgr.CreateNodeConnectivityNumber()
1093 elif theCriterion == FT_BallDiameter:
1094 functor = aFilterMgr.CreateBallDiameter()
1096 print "Error: given parameter is not numerical functor type."
1097 aFilterMgr.UnRegister()
1100 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
1105 theHType: mesh hypothesis type (string)
1106 theLibName: mesh plug-in library name
1109 created hypothesis instance
1111 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
1113 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
1116 # wrap hypothesis methods
1117 #print "HYPOTHESIS", theHType
1118 for meth_name in dir( hyp.__class__ ):
1119 if not meth_name.startswith("Get") and \
1120 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
1121 method = getattr ( hyp.__class__, meth_name )
1122 if callable(method):
1123 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
1127 def GetMeshInfo(self, obj):
1129 Get the mesh statistic
1132 dictionary "element type" - "count of elements"
1135 if isinstance( obj, Mesh ):
1138 if hasattr(obj, "GetMeshInfo"):
1139 values = obj.GetMeshInfo()
1140 for i in range(SMESH.Entity_Last._v):
1141 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1145 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1147 Get minimum distance between two objects
1149 If *src2* is None, and *id2* = 0, distance from *src1* / *id1* to the origin is computed.
1150 If *src2* None, and *id2* != 0, it is assumed that both *id1* and *id2* belong to *src1*.
1153 src1: first source object
1154 src2: second source object
1155 id1: node/element id from the first source
1156 id2: node/element id from the second (or first) source
1157 isElem1: *True* if *id1* is element id, *False* if it is node id
1158 isElem2: *True* if *id2* is element id, *False* if it is node id
1161 minimum distance value *GetMinDistance()*
1164 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1168 result = result.value
1171 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1173 Get measure structure specifying minimum distance data between two objects
1175 If *src2* is None, and *id2* = 0, distance from *src1* / *id1* to the origin is computed.
1176 If *src2* is None, and *id2* != 0, it is assumed that both *id1* and *id2* belong to *src1*.
1180 src1: first source object
1181 src2: second source object
1182 id1: node/element id from the first source
1183 id2: node/element id from the second (or first) source
1184 isElem1: *True* if **id1** is element id, *False* if it is node id
1185 isElem2: *True* if **id2** is element id, *False* if it is node id
1188 Measure structure or None if input data is invalid **MinDistance()**
1191 if isinstance(src1, Mesh): src1 = src1.mesh
1192 if isinstance(src2, Mesh): src2 = src2.mesh
1193 if src2 is None and id2 != 0: src2 = src1
1194 if not hasattr(src1, "_narrow"): return None
1195 src1 = src1._narrow(SMESH.SMESH_IDSource)
1196 if not src1: return None
1197 unRegister = genObjUnRegister()
1200 e = m.GetMeshEditor()
1202 src1 = e.MakeIDSource([id1], SMESH.FACE)
1204 src1 = e.MakeIDSource([id1], SMESH.NODE)
1205 unRegister.set( src1 )
1207 if hasattr(src2, "_narrow"):
1208 src2 = src2._narrow(SMESH.SMESH_IDSource)
1209 if src2 and id2 != 0:
1211 e = m.GetMeshEditor()
1213 src2 = e.MakeIDSource([id2], SMESH.FACE)
1215 src2 = e.MakeIDSource([id2], SMESH.NODE)
1216 unRegister.set( src2 )
1219 aMeasurements = self.CreateMeasurements()
1220 unRegister.set( aMeasurements )
1221 result = aMeasurements.MinDistance(src1, src2)
1224 def BoundingBox(self, objects):
1226 Get bounding box of the specified object(s)
1229 objects: single source object or list of source objects
1232 tuple of six values (minX, minY, minZ, maxX, maxY, maxZ) **GetBoundingBox()**
1235 result = self.GetBoundingBox(objects)
1239 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1242 def GetBoundingBox(self, objects):
1244 Get measure structure specifying bounding box data of the specified object(s)
1247 objects: single source object or list of source objects
1250 Measure structure **BoundingBox()**
1253 if isinstance(objects, tuple):
1254 objects = list(objects)
1255 if not isinstance(objects, list):
1259 if isinstance(o, Mesh):
1260 srclist.append(o.mesh)
1261 elif hasattr(o, "_narrow"):
1262 src = o._narrow(SMESH.SMESH_IDSource)
1263 if src: srclist.append(src)
1266 aMeasurements = self.CreateMeasurements()
1267 result = aMeasurements.BoundingBox(srclist)
1268 aMeasurements.UnRegister()
1271 def GetLength(self, obj):
1273 Get sum of lengths of all 1D elements in the mesh object.
1276 obj: mesh, submesh or group
1279 sum of lengths of all 1D elements
1282 if isinstance(obj, Mesh): obj = obj.mesh
1283 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1284 aMeasurements = self.CreateMeasurements()
1285 value = aMeasurements.Length(obj)
1286 aMeasurements.UnRegister()
1289 def GetArea(self, obj):
1291 Get sum of areas of all 2D elements in the mesh object.
1294 obj: mesh, submesh or group
1297 sum of areas of all 2D elements
1300 if isinstance(obj, Mesh): obj = obj.mesh
1301 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1302 aMeasurements = self.CreateMeasurements()
1303 value = aMeasurements.Area(obj)
1304 aMeasurements.UnRegister()
1307 def GetVolume(self, obj):
1309 Get sum of volumes of all 3D elements in the mesh object.
1312 obj: mesh, submesh or group
1315 sum of volumes of all 3D elements
1318 if isinstance(obj, Mesh): obj = obj.mesh
1319 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1320 aMeasurements = self.CreateMeasurements()
1321 value = aMeasurements.Volume(obj)
1322 aMeasurements.UnRegister()
1325 def GetGravityCenter(self, obj):
1327 Get gravity center of all nodes of the mesh object.
1330 obj: mesh, submesh or group
1333 Three components of the gravity center: x,y,z
1335 if isinstance(obj, Mesh): obj = obj.mesh
1336 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1337 aMeasurements = self.CreateMeasurements()
1338 pointStruct = aMeasurements.GravityCenter(obj)
1339 aMeasurements.UnRegister()
1340 return pointStruct.x, pointStruct.y, pointStruct.z
1342 pass # end of class smeshBuilder
1345 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1346 """Registering the new proxy for SMESH_Gen"""
1349 def New( study, instance=None, instanceGeom=None):
1351 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1352 interface to create or load meshes.
1356 salome.salome_init()
1357 from salome.smesh import smeshBuilder
1358 smesh = smeshBuilder.New(salome.myStudy)
1361 study: SALOME study, generally obtained by salome.myStudy.
1362 instance: CORBA proxy of SMESH Engine. If None, the default Engine is used.
1363 instanceGeom: CORBA proxy of GEOM Engine. If None, the default Engine is used.
1365 smeshBuilder instance
1373 smeshInst = smeshBuilder()
1374 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1375 smeshInst.init_smesh(study, instanceGeom)
1379 # Public class: Mesh
1380 # ==================
1384 This class allows defining and managing a mesh.
1385 It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1386 It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1387 new nodes and elements and by changing the existing entities), to get information
1388 about a mesh and to export a mesh in different formats.
1390 __metaclass__ = MeshMeta
1396 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1400 Create a mesh on the shape *obj* (or an empty mesh if *obj* is equal to 0) and
1401 sets the GUI name of this mesh to *name*.
1404 smeshpyD: an instance of smeshBuilder class
1405 geompyD: an instance of geomBuilder class
1406 obj: Shape to be meshed or SMESH_Mesh object
1407 name: Study name of the mesh
1410 self.smeshpyD=smeshpyD
1411 self.geompyD=geompyD
1416 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1419 # publish geom of mesh (issue 0021122)
1420 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1422 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1423 if studyID != geompyD.myStudyId:
1424 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1427 geo_name = name + " shape"
1429 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1430 geompyD.addToStudy( self.geom, geo_name )
1431 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1433 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1436 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1438 self.smeshpyD.SetName(self.mesh, name)
1440 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1443 self.geom = self.mesh.GetShapeToMesh()
1445 self.editor = self.mesh.GetMeshEditor()
1446 self.functors = [None] * SMESH.FT_Undefined._v
1448 # set self to algoCreator's
1449 for attrName in dir(self):
1450 attr = getattr( self, attrName )
1451 if isinstance( attr, algoCreator ):
1452 setattr( self, attrName, attr.copy( self ))
1459 Destructor. Clean-up resources
1462 #self.mesh.UnRegister()
1466 def SetMesh(self, theMesh):
1468 Initialize the Mesh object from an instance of SMESH_Mesh interface
1471 theMesh: a SMESH_Mesh object
1475 # do not call Register() as this prevents mesh servant deletion at closing study
1476 #if self.mesh: self.mesh.UnRegister()
1479 #self.mesh.Register()
1480 self.geom = self.mesh.GetShapeToMesh()
1485 Return the mesh, that is an instance of SMESH_Mesh interface
1495 Get the name of the mesh
1498 the name of the mesh as a string
1501 name = GetName(self.GetMesh())
1504 def SetName(self, name):
1506 Set a name to the mesh
1509 name: a new name of the mesh
1512 self.smeshpyD.SetName(self.GetMesh(), name)
1514 def GetSubMesh(self, geom, name):
1516 Get a sub-mesh object associated to a *geom* geometrical object.
1519 geom: a geometrical object (shape)
1520 name: a name for the sub-mesh in the Object Browser
1523 an object of type SMESH.SMESH_subMesh, representing a part of mesh,
1524 which lies on the given shape
1526 The sub-mesh object gives access to the IDs of nodes and elements.
1527 The sub-mesh object has the following methods:
1529 - SMESH.SMESH_subMesh.GetNumberOfElements()
1530 - SMESH.SMESH_subMesh.GetNumberOfNodes( all )
1531 - SMESH.SMESH_subMesh.GetElementsId()
1532 - SMESH.SMESH_subMesh.GetElementsByType( ElementType )
1533 - SMESH.SMESH_subMesh.GetNodesId()
1534 - SMESH.SMESH_subMesh.GetSubShape()
1535 - SMESH.SMESH_subMesh.GetFather()
1536 - SMESH.SMESH_subMesh.GetId()
1539 A sub-mesh is implicitly created when a sub-shape is specified at
1540 creating an algorithm, for example: algo1D = mesh.Segment(geom=Edge_1)
1541 creates a sub-mesh on *Edge_1* and assign Wire Discretization algorithm to it.
1542 The created sub-mesh can be retrieved from the algorithm:
1543 submesh = algo1D.GetSubMesh()
1546 AssureGeomPublished( self, geom, name )
1547 submesh = self.mesh.GetSubMesh( geom, name )
1552 Return the shape associated to the mesh
1560 def SetShape(self, geom):
1562 Associate the given shape to the mesh (entails the recreation of the mesh)
1565 geom: the shape to be meshed (GEOM_Object)
1568 self.mesh = self.smeshpyD.CreateMesh(geom)
1572 Load mesh from the study after opening the study
1576 def IsReadyToCompute(self, theSubObject):
1578 Return true if the hypotheses are defined well
1581 theSubObject: a sub-shape of a mesh shape
1587 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1589 def GetAlgoState(self, theSubObject):
1591 Return errors of hypotheses definition.
1592 The list of errors is empty if everything is OK.
1595 theSubObject: a sub-shape of a mesh shape
1601 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1603 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1605 Return a geometrical object on which the given element was built.
1606 The returned geometrical object, if not nil, is either found in the
1607 study or published by this method with the given name
1610 theElementID: the id of the mesh element
1611 theGeomName: the user-defined name of the geometrical object
1614 GEOM::GEOM_Object instance
1617 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1619 def MeshDimension(self):
1621 Return the mesh dimension depending on the dimension of the underlying shape
1622 or, if the mesh is not based on any shape, basing on deimension of elements
1625 mesh dimension as an integer value [0,3]
1628 if self.mesh.HasShapeToMesh():
1629 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1630 if len( shells ) > 0 :
1632 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1634 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1639 if self.NbVolumes() > 0: return 3
1640 if self.NbFaces() > 0: return 2
1641 if self.NbEdges() > 0: return 1
1644 def Evaluate(self, geom=0):
1646 Evaluate size of prospective mesh on a shape
1649 a list where i-th element is a number of elements of i-th SMESH.EntityType
1650 To know predicted number of e.g. edges, inquire it this way
1651 Evaluate()[ EnumToLong( Entity_Edge )]
1654 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1656 geom = self.mesh.GetShapeToMesh()
1659 return self.smeshpyD.Evaluate(self.mesh, geom)
1662 def Compute(self, geom=0, discardModifs=False, refresh=False):
1664 Compute the mesh and return the status of the computation
1667 geom: geomtrical shape on which mesh data should be computed
1668 discardModifs: if True and the mesh has been edited since
1669 a last total re-compute and that may prevent successful partial re-compute,
1670 then the mesh is cleaned before Compute()
1671 refresh: if *True*, Object browser is automatically updated (when running in GUI)
1677 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1679 geom = self.mesh.GetShapeToMesh()
1684 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1686 ok = self.smeshpyD.Compute(self.mesh, geom)
1687 except SALOME.SALOME_Exception, ex:
1688 print "Mesh computation failed, exception caught:"
1689 print " ", ex.details.text
1692 print "Mesh computation failed, exception caught:"
1693 traceback.print_exc()
1697 # Treat compute errors
1698 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1700 for err in computeErrors:
1701 if self.mesh.HasShapeToMesh():
1702 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1704 stdErrors = ["OK", #COMPERR_OK
1705 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1706 "std::exception", #COMPERR_STD_EXCEPTION
1707 "OCC exception", #COMPERR_OCC_EXCEPTION
1708 "..", #COMPERR_SLM_EXCEPTION
1709 "Unknown exception", #COMPERR_EXCEPTION
1710 "Memory allocation problem", #COMPERR_MEMORY_PB
1711 "Algorithm failed", #COMPERR_ALGO_FAILED
1712 "Unexpected geometry", #COMPERR_BAD_SHAPE
1713 "Warning", #COMPERR_WARNING
1714 "Computation cancelled",#COMPERR_CANCELED
1715 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1717 if err.code < len(stdErrors): errText = stdErrors[err.code]
1719 errText = "code %s" % -err.code
1720 if errText: errText += ". "
1721 errText += err.comment
1722 if allReasons: allReasons += "\n"
1724 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1726 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1730 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1732 if err.isGlobalAlgo:
1740 reason = '%s %sD algorithm is missing' % (glob, dim)
1741 elif err.state == HYP_MISSING:
1742 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1743 % (glob, dim, name, dim))
1744 elif err.state == HYP_NOTCONFORM:
1745 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1746 elif err.state == HYP_BAD_PARAMETER:
1747 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1748 % ( glob, dim, name ))
1749 elif err.state == HYP_BAD_GEOMETRY:
1750 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1751 'geometry' % ( glob, dim, name ))
1752 elif err.state == HYP_HIDDEN_ALGO:
1753 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1754 'algorithm of upper dimension generating %sD mesh'
1755 % ( glob, dim, name, glob, dim ))
1757 reason = ("For unknown reason. "
1758 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1760 if allReasons: allReasons += "\n"
1761 allReasons += "- " + reason
1763 if not ok or allReasons != "":
1764 msg = '"' + GetName(self.mesh) + '"'
1765 if ok: msg += " has been computed with warnings"
1766 else: msg += " has not been computed"
1767 if allReasons != "": msg += ":"
1772 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1773 if not isinstance( refresh, list): # not a call from subMesh.Compute()
1774 smeshgui = salome.ImportComponentGUI("SMESH")
1775 smeshgui.Init(self.mesh.GetStudyId())
1776 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1777 if refresh: salome.sg.updateObjBrowser(True)
1781 def GetComputeErrors(self, shape=0 ):
1783 Return a list of error messages (SMESH.ComputeError) of the last Compute()
1787 shape = self.mesh.GetShapeToMesh()
1788 return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1790 def GetSubShapeName(self, subShapeID ):
1792 Return a name of a sub-shape by its ID
1795 subShapeID: a unique ID of a sub-shape
1798 a string describing the sub-shape; possible variants:
1800 - "Face_12" (published sub-shape)
1801 - FACE #3 (not published sub-shape)
1802 - sub-shape #3 (invalid sub-shape ID)
1803 - #3 (error in this function)
1806 if not self.mesh.HasShapeToMesh():
1810 mainIOR = salome.orb.object_to_string( self.GetShape() )
1811 for sname in salome.myStudyManager.GetOpenStudies():
1812 s = salome.myStudyManager.GetStudyByName(sname)
1814 mainSO = s.FindObjectIOR(mainIOR)
1815 if not mainSO: continue
1817 shapeText = '"%s"' % mainSO.GetName()
1818 subIt = s.NewChildIterator(mainSO)
1820 subSO = subIt.Value()
1822 obj = subSO.GetObject()
1823 if not obj: continue
1824 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1827 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1830 if ids == subShapeID:
1831 shapeText = '"%s"' % subSO.GetName()
1834 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1836 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1838 shapeText = 'sub-shape #%s' % (subShapeID)
1840 shapeText = "#%s" % (subShapeID)
1843 def GetFailedShapes(self, publish=False):
1845 Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1846 error of an algorithm
1849 publish: if *True*, the returned groups will be published in the study
1852 a list of GEOM groups each named after a failed algorithm
1857 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1858 for err in computeErrors:
1859 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1860 if not shape: continue
1861 if err.algoName in algo2shapes:
1862 algo2shapes[ err.algoName ].append( shape )
1864 algo2shapes[ err.algoName ] = [ shape ]
1868 for algoName, shapes in algo2shapes.items():
1870 groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
1871 otherTypeShapes = []
1873 group = self.geompyD.CreateGroup( self.geom, groupType )
1874 for shape in shapes:
1875 if shape.GetShapeType() == shapes[0].GetShapeType():
1876 sameTypeShapes.append( shape )
1878 otherTypeShapes.append( shape )
1879 self.geompyD.UnionList( group, sameTypeShapes )
1881 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1883 group.SetName( algoName )
1884 groups.append( group )
1885 shapes = otherTypeShapes
1888 for group in groups:
1889 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1892 def GetMeshOrder(self):
1894 Return sub-mesh objects list in meshing order
1897 list of lists of sub-meshes
1900 return self.mesh.GetMeshOrder()
1902 def SetMeshOrder(self, submeshes):
1904 Set order in which concurrent sub-meshes should be meshed
1907 submeshes list of lists of sub-meshes
1910 return self.mesh.SetMeshOrder(submeshes)
1912 def Clear(self, refresh=False):
1914 Remove all nodes and elements generated on geometry. Imported elements remain.
1917 refresh if *True*, Object browser is automatically updated (when running in GUI)
1921 if ( salome.sg.hasDesktop() and
1922 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1923 smeshgui = salome.ImportComponentGUI("SMESH")
1924 smeshgui.Init(self.mesh.GetStudyId())
1925 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1926 if refresh: salome.sg.updateObjBrowser(True)
1928 def ClearSubMesh(self, geomId, refresh=False):
1930 Remove all nodes and elements of indicated shape
1933 refresh: if *True*, Object browser is automatically updated (when running in GUI)
1934 geomId: the ID of a sub-shape to remove elements on
1937 self.mesh.ClearSubMesh(geomId)
1938 if salome.sg.hasDesktop():
1939 smeshgui = salome.ImportComponentGUI("SMESH")
1940 smeshgui.Init(self.mesh.GetStudyId())
1941 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1942 if refresh: salome.sg.updateObjBrowser(True)
1944 def AutomaticTetrahedralization(self, fineness=0):
1946 Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1949 fineness: [0.0,1.0] defines mesh fineness
1955 dim = self.MeshDimension()
1957 self.RemoveGlobalHypotheses()
1958 self.Segment().AutomaticLength(fineness)
1960 self.Triangle().LengthFromEdges()
1965 return self.Compute()
1967 def AutomaticHexahedralization(self, fineness=0):
1969 Compute an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1972 fineness [0.0, 1.0] defines mesh fineness
1978 dim = self.MeshDimension()
1979 # assign the hypotheses
1980 self.RemoveGlobalHypotheses()
1981 self.Segment().AutomaticLength(fineness)
1988 return self.Compute()
1990 def AddHypothesis(self, hyp, geom=0):
1995 hyp: a hypothesis to assign
1996 geom: a subhape of mesh geometry
1999 SMESH.Hypothesis_Status
2002 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
2003 hyp, geom = geom, hyp
2004 if isinstance( hyp, Mesh_Algorithm ):
2005 hyp = hyp.GetAlgorithm()
2010 geom = self.mesh.GetShapeToMesh()
2013 if self.mesh.HasShapeToMesh():
2014 hyp_type = hyp.GetName()
2015 lib_name = hyp.GetLibName()
2016 # checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
2017 # if checkAll and geom:
2018 # checkAll = geom.GetType() == 37
2020 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
2022 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
2023 status = self.mesh.AddHypothesis(geom, hyp)
2025 status = HYP_BAD_GEOMETRY,""
2026 hyp_name = GetName( hyp )
2029 geom_name = geom.GetName()
2030 isAlgo = hyp._narrow( SMESH_Algo )
2031 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
2034 def IsUsedHypothesis(self, hyp, geom):
2036 Return True if an algorithm of hypothesis is assigned to a given shape
2039 hyp: a hypothesis to check
2040 geom: a subhape of mesh geometry
2046 if not hyp: # or not geom
2048 if isinstance( hyp, Mesh_Algorithm ):
2049 hyp = hyp.GetAlgorithm()
2051 hyps = self.GetHypothesisList(geom)
2053 if h.GetId() == hyp.GetId():
2057 def RemoveHypothesis(self, hyp, geom=0):
2059 Unassign a hypothesis
2062 hyp: a hypothesis to unassign
2063 geom: a sub-shape of mesh geometry
2066 SMESH.Hypothesis_Status
2071 if isinstance( hyp, Mesh_Algorithm ):
2072 hyp = hyp.GetAlgorithm()
2078 if self.IsUsedHypothesis( hyp, shape ):
2079 return self.mesh.RemoveHypothesis( shape, hyp )
2080 hypName = GetName( hyp )
2081 geoName = GetName( shape )
2082 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
2085 def GetHypothesisList(self, geom):
2087 Get the list of hypotheses added on a geometry
2090 geom: a sub-shape of mesh geometry
2093 the sequence of SMESH_Hypothesis
2096 return self.mesh.GetHypothesisList( geom )
2098 def RemoveGlobalHypotheses(self):
2100 Remove all global hypotheses
2103 current_hyps = self.mesh.GetHypothesisList( self.geom )
2104 for hyp in current_hyps:
2105 self.mesh.RemoveHypothesis( self.geom, hyp )
2109 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
2110 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
2112 Export the mesh in a file in MED format
2113 allowing to overwrite the file if it exists or add the exported data to its contents
2117 auto_groups: boolean parameter for creating/not creating
2118 the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
2119 the typical use is auto_groups=False.
2120 version: MED format version (MED_V2_1 or MED_V2_2,
2121 the latter meaning any current version). The parameter is
2122 obsolete since MED_V2_1 is no longer supported.
2123 overwrite: boolean parameter for overwriting/not overwriting the file
2124 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2125 autoDimension: if *True* (default), a space dimension of a MED mesh can be either
2127 - 1D if all mesh nodes lie on OX coordinate axis, or
2128 - 2D if all mesh nodes lie on XOY coordinate plane, or
2129 - 3D in the rest cases.
2131 If *autoDimension* is *False*, the space dimension is always 3.
2132 fields: list of GEOM fields defined on the shape to mesh.
2133 geomAssocFields: each character of this string means a need to export a
2134 corresponding field; correspondence between fields and characters is following:
2136 - 'v' stands for "_vertices _" field;
2137 - 'e' stands for "_edges _" field;
2138 - 'f' stands for "_faces _" field;
2139 - 's' stands for "_solids _" field.
2142 if meshPart or fields or geomAssocFields:
2143 unRegister = genObjUnRegister()
2144 if isinstance( meshPart, list ):
2145 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2146 unRegister.set( meshPart )
2147 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
2148 fields, geomAssocFields)
2150 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
2152 def ExportSAUV(self, f, auto_groups=0):
2154 Export the mesh in a file in SAUV format
2159 auto_groups: boolean parameter for creating/not creating
2160 the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
2161 the typical use is auto_groups=false.
2164 self.mesh.ExportSAUV(f, auto_groups)
2166 def ExportDAT(self, f, meshPart=None):
2168 Export the mesh in a file in DAT format
2172 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2176 unRegister = genObjUnRegister()
2177 if isinstance( meshPart, list ):
2178 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2179 unRegister.set( meshPart )
2180 self.mesh.ExportPartToDAT( meshPart, f )
2182 self.mesh.ExportDAT(f)
2184 def ExportUNV(self, f, meshPart=None):
2186 Export the mesh in a file in UNV format
2190 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2194 unRegister = genObjUnRegister()
2195 if isinstance( meshPart, list ):
2196 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2197 unRegister.set( meshPart )
2198 self.mesh.ExportPartToUNV( meshPart, f )
2200 self.mesh.ExportUNV(f)
2202 def ExportSTL(self, f, ascii=1, meshPart=None):
2204 Export the mesh in a file in STL format
2208 ascii: defines the file encoding
2209 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2213 unRegister = genObjUnRegister()
2214 if isinstance( meshPart, list ):
2215 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2216 unRegister.set( meshPart )
2217 self.mesh.ExportPartToSTL( meshPart, f, ascii )
2219 self.mesh.ExportSTL(f, ascii)
2221 def ExportCGNS(self, f, overwrite=1, meshPart=None, groupElemsByType=False):
2223 Export the mesh in a file in CGNS format
2227 overwrite: boolean parameter for overwriting/not overwriting the file
2228 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2229 groupElemsByType: if true all elements of same entity type are exported at ones,
2230 else elements are exported in order of their IDs which can cause creation
2231 of multiple cgns sections
2234 unRegister = genObjUnRegister()
2235 if isinstance( meshPart, list ):
2236 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2237 unRegister.set( meshPart )
2238 if isinstance( meshPart, Mesh ):
2239 meshPart = meshPart.mesh
2241 meshPart = self.mesh
2242 self.mesh.ExportCGNS(meshPart, f, overwrite, groupElemsByType)
2244 def ExportGMF(self, f, meshPart=None):
2246 Export the mesh in a file in GMF format.
2247 GMF files must have .mesh extension for the ASCII format and .meshb for
2248 the bynary format. Other extensions are not allowed.
2252 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2255 unRegister = genObjUnRegister()
2256 if isinstance( meshPart, list ):
2257 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2258 unRegister.set( meshPart )
2259 if isinstance( meshPart, Mesh ):
2260 meshPart = meshPart.mesh
2262 meshPart = self.mesh
2263 self.mesh.ExportGMF(meshPart, f, True)
2265 def ExportToMED(self, f, version=MED_V2_2, opt=0, overwrite=1, autoDimension=True):
2267 Deprecated, used only for compatibility! Please, use ExportMED() method instead.
2268 Export the mesh in a file in MED format
2269 allowing to overwrite the file if it exists or add the exported data to its contents
2273 version: MED format version (MED_V2_1 or MED_V2_2,
2274 the latter meaning any current version). The parameter is
2275 obsolete since MED_V2_1 is no longer supported.
2276 opt: boolean parameter for creating/not creating
2277 the groups Group_On_All_Nodes, Group_On_All_Faces, ...
2278 overwrite: boolean parameter for overwriting/not overwriting the file
2279 autoDimension: if *True* (default), a space dimension of a MED mesh can be either
2281 - 1D if all mesh nodes lie on OX coordinate axis, or
2282 - 2D if all mesh nodes lie on XOY coordinate plane, or
2283 - 3D in the rest cases.
2285 If **autoDimension** isc **False**, the space dimension is always 3.
2288 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
2290 # Operations with groups:
2291 # ----------------------
2293 def CreateEmptyGroup(self, elementType, name):
2295 Create an empty mesh group
2298 elementType: the type of elements in the group; either of
2299 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2300 name: the name of the mesh group
2306 return self.mesh.CreateGroup(elementType, name)
2308 def Group(self, grp, name=""):
2310 Create a mesh group based on the geometric object *grp*
2312 if this parameter is not defined
2313 the name is the same as the geometric group name
2316 Works like GroupOnGeom().
2319 grp: a geometric group, a vertex, an edge, a face or a solid
2320 name: the name of the mesh group
2326 return self.GroupOnGeom(grp, name)
2328 def GroupOnGeom(self, grp, name="", typ=None):
2330 Create a mesh group based on the geometrical object *grp*
2332 if this parameter is not defined the name is the same as the geometrical group name
2335 grp: a geometrical group, a vertex, an edge, a face or a solid
2336 name: the name of the mesh group
2337 typ: the type of elements in the group; either of
2338 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
2339 automatically detected by the type of the geometry
2345 AssureGeomPublished( self, grp, name )
2347 name = grp.GetName()
2349 typ = self._groupTypeFromShape( grp )
2350 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
2352 def _groupTypeFromShape( self, shape ):
2354 Pivate method to get a type of group on geometry
2356 tgeo = str(shape.GetShapeType())
2357 if tgeo == "VERTEX":
2359 elif tgeo == "EDGE":
2361 elif tgeo == "FACE" or tgeo == "SHELL":
2363 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
2365 elif tgeo == "COMPOUND":
2366 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
2368 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
2369 return self._groupTypeFromShape( sub[0] )
2372 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
2375 def GroupOnFilter(self, typ, name, filter):
2377 Create a mesh group with given *name* based on the *filter* which
2378 is a special type of group dynamically updating it's contents during
2382 typ: the type of elements in the group; either of
2383 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2384 name: the name of the mesh group
2385 filter: the filter defining group contents
2391 return self.mesh.CreateGroupFromFilter(typ, name, filter)
2393 def MakeGroupByIds(self, groupName, elementType, elemIDs):
2395 Create a mesh group by the given ids of elements
2398 groupName: the name of the mesh group
2399 elementType: the type of elements in the group; either of
2400 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2401 elemIDs: either the list of ids, group, sub-mesh, or filter
2407 group = self.mesh.CreateGroup(elementType, groupName)
2408 if isinstance( elemIDs, Mesh ):
2409 elemIDs = elemIDs.GetMesh()
2410 if hasattr( elemIDs, "GetIDs" ):
2411 if hasattr( elemIDs, "SetMesh" ):
2412 elemIDs.SetMesh( self.GetMesh() )
2413 group.AddFrom( elemIDs )
2421 CritType=FT_Undefined,
2424 UnaryOp=FT_Undefined,
2427 Create a mesh group by the given conditions
2430 groupName: the name of the mesh group
2431 elementType: the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2432 CritType: the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
2433 Type SMESH.FunctorType._items in the Python Console to see all values.
2434 Note that the items starting from FT_LessThan are not suitable for CritType.
2435 Compare: belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
2436 Threshold: the threshold value (range of ids as string, shape, numeric)
2437 UnaryOp: SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2438 Tolerance: the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2439 SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2445 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2446 group = self.MakeGroupByCriterion(groupName, aCriterion)
2449 def MakeGroupByCriterion(self, groupName, Criterion):
2451 Create a mesh group by the given criterion
2454 groupName: the name of the mesh group
2455 Criterion: the instance of Criterion class
2461 return self.MakeGroupByCriteria( groupName, [Criterion] )
2463 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2465 Create a mesh group by the given criteria (list of criteria)
2468 groupName: the name of the mesh group
2469 theCriteria: the list of criteria
2470 binOp: binary operator used when binary operator of criteria is undefined
2476 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2477 group = self.MakeGroupByFilter(groupName, aFilter)
2480 def MakeGroupByFilter(self, groupName, theFilter):
2482 Create a mesh group by the given filter
2485 groupName: the name of the mesh group
2486 theFilter: the instance of Filter class
2492 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2493 #theFilter.SetMesh( self.mesh )
2494 #group.AddFrom( theFilter )
2495 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2498 def RemoveGroup(self, group):
2503 self.mesh.RemoveGroup(group)
2505 def RemoveGroupWithContents(self, group):
2507 Remove a group with its contents
2510 self.mesh.RemoveGroupWithContents(group)
2512 def GetGroups(self, elemType = SMESH.ALL):
2514 Get the list of groups existing in the mesh in the order
2515 of creation (starting from the oldest one)
2518 elemType: type of elements the groups contain; either of
2519 (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2520 by default groups of elements of all types are returned
2523 a sequence of SMESH_GroupBase
2526 groups = self.mesh.GetGroups()
2527 if elemType == SMESH.ALL:
2531 if g.GetType() == elemType:
2532 typedGroups.append( g )
2539 Get the number of groups existing in the mesh
2542 the quantity of groups as an integer value
2545 return self.mesh.NbGroups()
2547 def GetGroupNames(self):
2549 Get the list of names of groups existing in the mesh
2555 groups = self.GetGroups()
2557 for group in groups:
2558 names.append(group.GetName())
2561 def GetGroupByName(self, name, elemType = None):
2563 Find groups by name and type
2566 name: name of the group of interest
2567 elemType: type of elements the groups contain; either of
2568 (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2569 by default one group of any type of elements is returned
2570 if elemType == SMESH.ALL then all groups of any type are returned
2573 a list of SMESH_GroupBase's
2577 for group in self.GetGroups():
2578 if group.GetName() == name:
2579 if elemType is None:
2581 if ( elemType == SMESH.ALL or
2582 group.GetType() == elemType ):
2583 groups.append( group )
2586 def UnionGroups(self, group1, group2, name):
2588 Produce a union of two groups.
2589 A new group is created. All mesh elements that are
2590 present in the initial groups are added to the new one
2593 an instance of SMESH_Group
2596 return self.mesh.UnionGroups(group1, group2, name)
2598 def UnionListOfGroups(self, groups, name):
2600 Produce a union list of groups.
2601 New group is created. All mesh elements that are present in
2602 initial groups are added to the new one
2606 an instance of SMESH_Group
2609 return self.mesh.UnionListOfGroups(groups, name)
2611 def IntersectGroups(self, group1, group2, name):
2613 Prodice an intersection of two groups.
2614 A new group is created. All mesh elements that are common
2615 for the two initial groups are added to the new one.
2618 an instance of SMESH_Group
2621 return self.mesh.IntersectGroups(group1, group2, name)
2623 def IntersectListOfGroups(self, groups, name):
2625 Produce an intersection of groups.
2626 New group is created. All mesh elements that are present in all
2627 initial groups simultaneously are added to the new one
2630 an instance of SMESH_Group
2633 return self.mesh.IntersectListOfGroups(groups, name)
2635 def CutGroups(self, main_group, tool_group, name):
2637 Produce a cut of two groups.
2638 A new group is created. All mesh elements that are present in
2639 the main group but are not present in the tool group are added to the new one
2642 an instance of SMESH_Group
2645 return self.mesh.CutGroups(main_group, tool_group, name)
2647 def CutListOfGroups(self, main_groups, tool_groups, name):
2649 Produce a cut of groups.
2650 A new group is created. All mesh elements that are present in main groups
2651 but do not present in tool groups are added to the new one
2654 an instance of SMESH_Group
2657 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2659 def CreateDimGroup(self, groups, elemType, name,
2660 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2662 Create a standalone group of entities basing on nodes of other groups.
2665 groups: list of reference groups, sub-meshes or filters, of any type.
2666 elemType: a type of elements to include to the new group; either of
2667 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2668 name: a name of the new group.
2669 nbCommonNodes: a criterion of inclusion of an element to the new group
2670 basing on number of element nodes common with reference *groups*.
2671 Meaning of possible values are:
2673 - SMESH.ALL_NODES - include if all nodes are common,
2674 - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2675 - SMESH.AT_LEAST_ONE - include if one or more node is common,
2676 - SMEHS.MAJORITY - include if half of nodes or more are common.
2677 underlyingOnly: if *True* (default), an element is included to the
2678 new group provided that it is based on nodes of an element of *groups*;
2679 in this case the reference *groups* are supposed to be of higher dimension
2680 than *elemType*, which can be useful for example to get all faces lying on
2681 volumes of the reference *groups*.
2684 an instance of SMESH_Group
2687 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2689 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2692 def ConvertToStandalone(self, group):
2694 Convert group on geom into standalone group
2697 return self.mesh.ConvertToStandalone(group)
2699 # Get some info about mesh:
2700 # ------------------------
2702 def GetLog(self, clearAfterGet):
2704 Return the log of nodes and elements added or removed
2705 since the previous clear of the log.
2708 clearAfterGet: log is emptied after Get (safe if concurrents access)
2711 list of log_block structures:
2718 return self.mesh.GetLog(clearAfterGet)
2722 Clear the log of nodes and elements added or removed since the previous
2723 clear. Must be used immediately after GetLog if clearAfterGet is false.
2726 self.mesh.ClearLog()
2728 def SetAutoColor(self, theAutoColor):
2730 Toggle auto color mode on the object.
2733 theAutoColor: the flag which toggles auto color mode.
2734 If switched on, a default color of a new group in Create Group dialog is chosen randomly.
2737 self.mesh.SetAutoColor(theAutoColor)
2739 def GetAutoColor(self):
2741 Get flag of object auto color mode.
2747 return self.mesh.GetAutoColor()
2754 integer value, which is the internal Id of the mesh
2757 return self.mesh.GetId()
2759 def GetStudyId(self):
2764 integer value, which is the study Id of the mesh
2767 return self.mesh.GetStudyId()
2769 def HasDuplicatedGroupNamesMED(self):
2771 Check the group names for duplications.
2772 Consider the maximum group name length stored in MED file.
2778 return self.mesh.HasDuplicatedGroupNamesMED()
2780 def GetMeshEditor(self):
2782 Obtain the mesh editor tool
2785 an instance of SMESH_MeshEditor
2790 def GetIDSource(self, ids, elemType = SMESH.ALL):
2792 Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2793 can be passed as argument to a method accepting mesh, group or sub-mesh
2797 lemType: type of elements; this parameter is used to distinguish
2798 IDs of nodes from IDs of elements; by default ids are treated as
2799 IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2802 an instance of SMESH_IDSource
2805 call UnRegister() for the returned object as soon as it is no more useful:
2806 idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2807 mesh.DoSomething( idSrc )
2811 if isinstance( ids, int ):
2813 return self.editor.MakeIDSource(ids, elemType)
2816 # Get information about mesh contents:
2817 # ------------------------------------
2819 def GetMeshInfo(self, obj = None):
2821 Get the mesh statistic
2824 dictionary type element - count of elements
2827 if not obj: obj = self.mesh
2828 return self.smeshpyD.GetMeshInfo(obj)
2832 Return the number of nodes in the mesh
2838 return self.mesh.NbNodes()
2840 def NbElements(self):
2842 Return the number of elements in the mesh
2848 return self.mesh.NbElements()
2850 def Nb0DElements(self):
2852 Return the number of 0d elements in the mesh
2858 return self.mesh.Nb0DElements()
2862 Return the number of ball discrete elements in the mesh
2868 return self.mesh.NbBalls()
2872 Return the number of edges in the mesh
2878 return self.mesh.NbEdges()
2880 def NbEdgesOfOrder(self, elementOrder):
2882 Return the number of edges with the given order in the mesh
2885 elementOrder: the order of elements:
2886 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2892 return self.mesh.NbEdgesOfOrder(elementOrder)
2896 Return the number of faces in the mesh
2902 return self.mesh.NbFaces()
2904 def NbFacesOfOrder(self, elementOrder):
2906 Return the number of faces with the given order in the mesh
2909 elementOrder: the order of elements:
2910 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2916 return self.mesh.NbFacesOfOrder(elementOrder)
2918 def NbTriangles(self):
2920 Return the number of triangles in the mesh
2926 return self.mesh.NbTriangles()
2928 def NbTrianglesOfOrder(self, elementOrder):
2930 Return the number of triangles with the given order in the mesh
2933 elementOrder: is the order of elements:
2934 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2940 return self.mesh.NbTrianglesOfOrder(elementOrder)
2942 def NbBiQuadTriangles(self):
2944 Return the number of biquadratic triangles in the mesh
2950 return self.mesh.NbBiQuadTriangles()
2952 def NbQuadrangles(self):
2954 Return the number of quadrangles in the mesh
2960 return self.mesh.NbQuadrangles()
2962 def NbQuadranglesOfOrder(self, elementOrder):
2964 Return the number of quadrangles with the given order in the mesh
2967 elementOrder the order of elements:
2968 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2974 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2976 def NbBiQuadQuadrangles(self):
2978 Return the number of biquadratic quadrangles in the mesh
2984 return self.mesh.NbBiQuadQuadrangles()
2986 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2988 Return the number of polygons of given order in the mesh
2991 elementOrder: the order of elements:
2992 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2998 return self.mesh.NbPolygonsOfOrder(elementOrder)
3000 def NbVolumes(self):
3002 Return the number of volumes in the mesh
3008 return self.mesh.NbVolumes()
3011 def NbVolumesOfOrder(self, elementOrder):
3013 Return the number of volumes with the given order in the mesh
3016 elementOrder: the order of elements:
3017 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
3023 return self.mesh.NbVolumesOfOrder(elementOrder)
3027 Return the number of tetrahedrons in the mesh
3033 return self.mesh.NbTetras()
3035 def NbTetrasOfOrder(self, elementOrder):
3037 Return the number of tetrahedrons with the given order in the mesh
3040 elementOrder: the order of elements:
3041 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
3047 return self.mesh.NbTetrasOfOrder(elementOrder)
3051 Return the number of hexahedrons in the mesh
3057 return self.mesh.NbHexas()
3059 def NbHexasOfOrder(self, elementOrder):
3061 Return the number of hexahedrons with the given order in the mesh
3064 elementOrder: the order of elements:
3065 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
3071 return self.mesh.NbHexasOfOrder(elementOrder)
3073 def NbTriQuadraticHexas(self):
3075 Return the number of triquadratic hexahedrons in the mesh
3081 return self.mesh.NbTriQuadraticHexas()
3083 def NbPyramids(self):
3085 Return the number of pyramids in the mesh
3091 return self.mesh.NbPyramids()
3093 def NbPyramidsOfOrder(self, elementOrder):
3095 Return the number of pyramids with the given order in the mesh
3098 elementOrder: the order of elements:
3099 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
3105 return self.mesh.NbPyramidsOfOrder(elementOrder)
3109 Return the number of prisms in the mesh
3115 return self.mesh.NbPrisms()
3117 def NbPrismsOfOrder(self, elementOrder):
3119 Return the number of prisms with the given order in the mesh
3122 elementOrder: the order of elements:
3123 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
3129 return self.mesh.NbPrismsOfOrder(elementOrder)
3131 def NbHexagonalPrisms(self):
3133 Return the number of hexagonal prisms in the mesh
3139 return self.mesh.NbHexagonalPrisms()
3141 def NbPolyhedrons(self):
3143 Return the number of polyhedrons in the mesh
3149 return self.mesh.NbPolyhedrons()
3151 def NbSubMesh(self):
3153 Return the number of submeshes in the mesh
3159 return self.mesh.NbSubMesh()
3161 def GetElementsId(self):
3163 Return the list of mesh elements IDs
3166 the list of integer values
3169 return self.mesh.GetElementsId()
3171 def GetElementsByType(self, elementType):
3173 Return the list of IDs of mesh elements with the given type
3176 elementType: the required type of elements, either of
3177 (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
3180 list of integer values
3183 return self.mesh.GetElementsByType(elementType)
3185 def GetNodesId(self):
3187 Return the list of mesh nodes IDs
3190 the list of integer values
3193 return self.mesh.GetNodesId()
3195 # Get the information about mesh elements:
3196 # ------------------------------------
3198 def GetElementType(self, id, iselem=True):
3200 Return the type of mesh element
3203 the value from SMESH::ElementType enumeration
3204 Type SMESH.ElementType._items in the Python Console to see all possible values.
3207 return self.mesh.GetElementType(id, iselem)
3209 def GetElementGeomType(self, id):
3211 Return the geometric type of mesh element
3214 the value from SMESH::EntityType enumeration
3215 Type SMESH.EntityType._items in the Python Console to see all possible values.
3218 return self.mesh.GetElementGeomType(id)
3220 def GetElementShape(self, id):
3222 Return the shape type of mesh element
3225 the value from SMESH::GeometryType enumeration.
3226 Type SMESH.GeometryType._items in the Python Console to see all possible values.
3229 return self.mesh.GetElementShape(id)
3231 def GetSubMeshElementsId(self, Shape):
3233 Return the list of submesh elements IDs
3236 Shape: a geom object(sub-shape)
3237 Shape must be the sub-shape of a ShapeToMesh()
3240 the list of integer values
3243 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
3244 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3247 return self.mesh.GetSubMeshElementsId(ShapeID)
3249 def GetSubMeshNodesId(self, Shape, all):
3251 Return the list of submesh nodes IDs
3254 Shape: a geom object(sub-shape)
3255 Shape must be the sub-shape of a ShapeToMesh()
3256 all: If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
3259 the list of integer values
3262 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
3263 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3266 return self.mesh.GetSubMeshNodesId(ShapeID, all)
3268 def GetSubMeshElementType(self, Shape):
3270 Return type of elements on given shape
3273 Shape: a geom object(sub-shape)
3274 Shape must be a sub-shape of a ShapeToMesh()
3280 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
3281 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3284 return self.mesh.GetSubMeshElementType(ShapeID)
3288 Get the mesh description
3294 return self.mesh.Dump()
3297 # Get the information about nodes and elements of a mesh by its IDs:
3298 # -----------------------------------------------------------
3300 def GetNodeXYZ(self, id):
3302 Get XYZ coordinates of a node
3303 If there is no nodes for the given ID - return an empty list
3306 a list of double precision values
3309 return self.mesh.GetNodeXYZ(id)
3311 def GetNodeInverseElements(self, id):
3313 Return list of IDs of inverse elements for the given node
3314 If there is no node for the given ID - return an empty list
3317 a list of integer values
3320 return self.mesh.GetNodeInverseElements(id)
3322 def GetNodePosition(self,NodeID):
3324 Return the position of a node on the shape
3330 return self.mesh.GetNodePosition(NodeID)
3332 def GetElementPosition(self,ElemID):
3334 Return the position of an element on the shape
3337 SMESH::ElementPosition
3340 return self.mesh.GetElementPosition(ElemID)
3342 def GetShapeID(self, id):
3344 Return the ID of the shape, on which the given node was generated.
3347 an integer value > 0 or -1 if there is no node for the given
3348 ID or the node is not assigned to any geometry
3351 return self.mesh.GetShapeID(id)
3353 def GetShapeIDForElem(self,id):
3355 Return the ID of the shape, on which the given element was generated.
3358 an integer value > 0 or -1 if there is no element for the given
3359 ID or the element is not assigned to any geometry
3362 return self.mesh.GetShapeIDForElem(id)
3364 def GetElemNbNodes(self, id):
3366 Return the number of nodes of the given element
3369 an integer value > 0 or -1 if there is no element for the given ID
3372 return self.mesh.GetElemNbNodes(id)
3374 def GetElemNode(self, id, index):
3376 Return the node ID the given (zero based) index for the given element
3377 If there is no element for the given ID - return -1
3378 If there is no node for the given index - return -2
3384 return self.mesh.GetElemNode(id, index)
3386 def GetElemNodes(self, id):
3388 Return the IDs of nodes of the given element
3391 a list of integer values
3394 return self.mesh.GetElemNodes(id)
3396 def IsMediumNode(self, elementID, nodeID):
3398 Return true if the given node is the medium node in the given quadratic element
3401 return self.mesh.IsMediumNode(elementID, nodeID)
3403 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
3405 Return true if the given node is the medium node in one of quadratic elements
3408 nodeID: ID of the node
3409 elementType: the type of elements to check a state of the node, either of
3410 (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
3413 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
3415 def ElemNbEdges(self, id):
3417 Return the number of edges for the given element
3420 return self.mesh.ElemNbEdges(id)
3422 def ElemNbFaces(self, id):
3424 Return the number of faces for the given element
3427 return self.mesh.ElemNbFaces(id)
3429 def GetElemFaceNodes(self,elemId, faceIndex):
3431 Return nodes of given face (counted from zero) for given volumic element.
3434 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
3436 def GetFaceNormal(self, faceId, normalized=False):
3438 Return three components of normal of given mesh face
3439 (or an empty array in KO case)
3442 return self.mesh.GetFaceNormal(faceId,normalized)
3444 def FindElementByNodes(self, nodes):
3446 Return an element based on all given nodes.
3449 return self.mesh.FindElementByNodes(nodes)
3451 def GetElementsByNodes(self, nodes, elemType=SMESH.ALL):
3453 Return elements including all given nodes.
3456 return self.mesh.GetElementsByNodes( nodes, elemType )
3458 def IsPoly(self, id):
3460 Return true if the given element is a polygon
3463 return self.mesh.IsPoly(id)
3465 def IsQuadratic(self, id):
3467 Return true if the given element is quadratic
3470 return self.mesh.IsQuadratic(id)
3472 def GetBallDiameter(self, id):
3474 Return diameter of a ball discrete element or zero in case of an invalid *id*
3477 return self.mesh.GetBallDiameter(id)
3479 def BaryCenter(self, id):
3481 Return XYZ coordinates of the barycenter of the given element
3482 If there is no element for the given ID - return an empty list
3485 a list of three double values
3488 return self.mesh.BaryCenter(id)
3490 def GetIdsFromFilter(self, theFilter):
3492 Pass mesh elements through the given filter and return IDs of fitting elements
3495 theFilter: SMESH_Filter
3501 theFilter.SetMesh( self.mesh )
3502 return theFilter.GetIDs()
3504 # Get mesh measurements information:
3505 # ------------------------------------
3507 def GetFreeBorders(self):
3509 Verify whether a 2D mesh element has free edges (edges connected to one face only)\n
3510 Return a list of special structures (borders).
3513 a list of SMESH.FreeEdges. Border structure:: edge id and ids of two its nodes.
3516 aFilterMgr = self.smeshpyD.CreateFilterManager()
3517 aPredicate = aFilterMgr.CreateFreeEdges()
3518 aPredicate.SetMesh(self.mesh)
3519 aBorders = aPredicate.GetBorders()
3520 aFilterMgr.UnRegister()
3523 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
3525 Get minimum distance between two nodes, elements or distance to the origin
3528 id1: first node/element id
3529 id2: second node/element id (if 0, distance from *id1* to the origin is computed)
3530 isElem1: *True* if *id1* is element id, *False* if it is node id
3531 isElem2: *True* if *id2* is element id, *False* if it is node id
3534 minimum distance value **GetMinDistance()**
3537 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
3538 return aMeasure.value
3540 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
3542 Get measure structure specifying minimum distance data between two objects
3545 id1: first node/element id
3546 id2: second node/element id (if 0, distance from *id1* to the origin is computed)
3547 isElem1: *True* if *id1* is element id, *False* if it is node id
3548 isElem2: *True* if *id2* is element id, *False* if it is node id
3551 Measure structure **MinDistance()**
3555 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
3557 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
3560 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
3562 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
3567 aMeasurements = self.smeshpyD.CreateMeasurements()
3568 aMeasure = aMeasurements.MinDistance(id1, id2)
3569 genObjUnRegister([aMeasurements,id1, id2])
3572 def BoundingBox(self, objects=None, isElem=False):
3574 Get bounding box of the specified object(s)
3577 objects: single source object or list of source objects or list of nodes/elements IDs
3578 isElem: if *objects* is a list of IDs, *True* value in this parameters specifies that *objects* are elements,
3579 *False* specifies that *objects* are nodes
3582 tuple of six values (minX, minY, minZ, maxX, maxY, maxZ) **GetBoundingBox()**
3585 result = self.GetBoundingBox(objects, isElem)
3589 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
3592 def GetBoundingBox(self, IDs=None, isElem=False):
3594 Get measure structure specifying bounding box data of the specified object(s)
3597 IDs: single source object or list of source objects or list of nodes/elements IDs
3598 isElem: if *IDs* is a list of IDs, *True* value in this parameters specifies that *objects* are elements,
3599 *False* specifies that *objects* are nodes
3602 Measure structure **BoundingBox()**
3607 elif isinstance(IDs, tuple):
3609 if not isinstance(IDs, list):
3611 if len(IDs) > 0 and isinstance(IDs[0], int):
3614 unRegister = genObjUnRegister()
3616 if isinstance(o, Mesh):
3617 srclist.append(o.mesh)
3618 elif hasattr(o, "_narrow"):
3619 src = o._narrow(SMESH.SMESH_IDSource)
3620 if src: srclist.append(src)
3622 elif isinstance(o, list):
3624 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
3626 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
3627 unRegister.set( srclist[-1] )
3630 aMeasurements = self.smeshpyD.CreateMeasurements()
3631 unRegister.set( aMeasurements )
3632 aMeasure = aMeasurements.BoundingBox(srclist)
3635 # Mesh edition (SMESH_MeshEditor functionality):
3636 # ---------------------------------------------
3638 def RemoveElements(self, IDsOfElements):
3640 Remove the elements from the mesh by ids
3643 IDsOfElements: is a list of ids of elements to remove
3649 return self.editor.RemoveElements(IDsOfElements)
3651 def RemoveNodes(self, IDsOfNodes):
3653 Remove nodes from mesh by ids
3656 IDsOfNodes: is a list of ids of nodes to remove
3662 return self.editor.RemoveNodes(IDsOfNodes)
3664 def RemoveOrphanNodes(self):
3666 Remove all orphan (free) nodes from mesh
3669 number of the removed nodes
3672 return self.editor.RemoveOrphanNodes()
3674 def AddNode(self, x, y, z):
3676 Add a node to the mesh by coordinates
3682 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3683 if hasVars: self.mesh.SetParameters(Parameters)
3684 return self.editor.AddNode( x, y, z)
3686 def Add0DElement( self, IDOfNode, DuplicateElements=True ):
3688 Create a 0D element on a node with given number.
3691 IDOfNode: the ID of node for creation of the element.
3692 DuplicateElements: to add one more 0D element to a node or not
3695 the Id of the new 0D element
3698 return self.editor.Add0DElement( IDOfNode, DuplicateElements )
3700 def Add0DElementsToAllNodes(self, theObject, theGroupName="", DuplicateElements=False):
3702 Create 0D elements on all nodes of the given elements except those
3703 nodes on which a 0D element already exists.
3706 theObject: an object on whose nodes 0D elements will be created.
3707 It can be mesh, sub-mesh, group, list of element IDs or a holder
3708 of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
3709 theGroupName: optional name of a group to add 0D elements created
3710 and/or found on nodes of *theObject*.
3711 DuplicateElements: to add one more 0D element to a node or not
3714 an object (a new group or a temporary SMESH_IDSource) holding
3715 IDs of new and/or found 0D elements. IDs of 0D elements
3716 can be retrieved from the returned object by calling GetIDs()
3719 unRegister = genObjUnRegister()
3720 if isinstance( theObject, Mesh ):
3721 theObject = theObject.GetMesh()
3722 elif isinstance( theObject, list ):
3723 theObject = self.GetIDSource( theObject, SMESH.ALL )
3724 unRegister.set( theObject )
3725 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName, DuplicateElements )
3727 def AddBall(self, IDOfNode, diameter):
3729 Create a ball element on a node with given ID.
3732 IDOfNode: the ID of node for creation of the element.
3733 diameter: the bal diameter.
3736 the Id of the new ball element
3739 return self.editor.AddBall( IDOfNode, diameter )
3741 def AddEdge(self, IDsOfNodes):
3743 Create a linear or quadratic edge (this is determined
3744 by the number of given nodes).
3747 IDsOfNodes: the list of node IDs for creation of the element.
3748 The order of nodes in this list should correspond to the description
3750 This description is located by the following link:
3751 http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3754 the Id of the new edge
3757 return self.editor.AddEdge(IDsOfNodes)
3759 def AddFace(self, IDsOfNodes):
3761 Create a linear or quadratic face (this is determined
3762 by the number of given nodes).
3765 IDsOfNodes: the list of node IDs for creation of the element.
3766 The order of nodes in this list should correspond to the description
3768 This description is located by the following link:
3769 http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3772 the Id of the new face
3775 return self.editor.AddFace(IDsOfNodes)
3777 def AddPolygonalFace(self, IdsOfNodes):
3779 Add a polygonal face to the mesh by the list of node IDs
3782 IdsOfNodes: the list of node IDs for creation of the element.
3785 the Id of the new face
3788 return self.editor.AddPolygonalFace(IdsOfNodes)
3790 def AddQuadPolygonalFace(self, IdsOfNodes):
3792 Add a quadratic polygonal face to the mesh by the list of node IDs
3795 IdsOfNodes: the list of node IDs for creation of the element;
3796 corner nodes follow first.
3799 the Id of the new face
3802 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
3804 def AddVolume(self, IDsOfNodes):
3806 Create both simple and quadratic volume (this is determined
3807 by the number of given nodes).
3810 IDsOfNodes: the list of node IDs for creation of the element.
3811 The order of nodes in this list should correspond to the description
3813 This description is located by the following link:
3814 http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3817 the Id of the new volumic element
3820 return self.editor.AddVolume(IDsOfNodes)
3822 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
3824 Create a volume of many faces, giving nodes for each face.
3827 IdsOfNodes: the list of node IDs for volume creation face by face.
3828 Quantities: the list of integer values, Quantities[i]
3829 gives the quantity of nodes in face number i.
3832 the Id of the new volumic element
3835 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
3837 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
3839 Create a volume of many faces, giving the IDs of the existing faces.
3842 IdsOfFaces: the list of face IDs for volume creation.
3845 The created volume will refer only to the nodes
3846 of the given faces, not to the faces themselves.
3849 the Id of the new volumic element
3852 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
3855 def SetNodeOnVertex(self, NodeID, Vertex):
3857 **Binds** a node to a vertex
3861 Vertex: a vertex or vertex ID
3864 True if succeed else raises an exception
3867 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
3868 VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
3872 self.editor.SetNodeOnVertex(NodeID, VertexID)
3873 except SALOME.SALOME_Exception, inst:
3874 raise ValueError, inst.details.text
3878 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
3880 **Stores** the node position on an edge
3884 Edge: an edge or edge ID
3885 paramOnEdge: a parameter on the edge where the node is located
3888 True if succeed else raises an exception
3891 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
3892 EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
3896 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
3897 except SALOME.SALOME_Exception, inst:
3898 raise ValueError, inst.details.text
3901 def SetNodeOnFace(self, NodeID, Face, u, v):
3903 **Stores** node position on a face
3907 Face: a face or face ID
3908 u: U parameter on the face where the node is located
3909 v: V parameter on the face where the node is located
3912 True if succeed else raises an exception
3915 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
3916 FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
3920 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
3921 except SALOME.SALOME_Exception, inst:
3922 raise ValueError, inst.details.text
3925 def SetNodeInVolume(self, NodeID, Solid):
3927 **Binds** a node to a solid
3931 Solid: a solid or solid ID
3934 True if succeed else raises an exception
3937 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
3938 SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
3942 self.editor.SetNodeInVolume(NodeID, SolidID)
3943 except SALOME.SALOME_Exception, inst:
3944 raise ValueError, inst.details.text
3947 def SetMeshElementOnShape(self, ElementID, Shape):
3949 **Bind** an element to a shape
3952 ElementID: an element ID
3953 Shape: a shape or shape ID
3956 True if succeed else raises an exception
3959 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
3960 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3964 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
3965 except SALOME.SALOME_Exception, inst:
3966 raise ValueError, inst.details.text
3970 def MoveNode(self, NodeID, x, y, z):
3972 Move the node with the given id
3975 NodeID: the id of the node
3976 x: a new X coordinate
3977 y: a new Y coordinate
3978 z: a new Z coordinate
3981 True if succeed else False
3984 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3985 if hasVars: self.mesh.SetParameters(Parameters)
3986 return self.editor.MoveNode(NodeID, x, y, z)
3988 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3990 Find the node closest to a point and moves it to a point location
3993 x: the X coordinate of a point
3994 y: the Y coordinate of a point
3995 z: the Z coordinate of a point
3996 NodeID: if specified (>0), the node with this ID is moved,
3997 otherwise, the node closest to point (*x*, *y*, *z*) is moved
4003 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
4004 if hasVars: self.mesh.SetParameters(Parameters)
4005 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
4007 def FindNodeClosestTo(self, x, y, z):
4009 Find the node closest to a point
4012 x: the X coordinate of a point
4013 y: the Y coordinate of a point
4014 z: the Z coordinate of a point
4020 #preview = self.mesh.GetMeshEditPreviewer()
4021 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
4022 return self.editor.FindNodeClosestTo(x, y, z)
4024 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
4026 Find the elements where a point lays IN or ON
4029 x: the X coordinate of a point
4030 y: the Y coordinate of a point
4031 z: the Z coordinate of a point
4032 elementType: type of elements to find; either of
4033 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
4034 means elements of any type excluding nodes, discrete and 0D elements.
4035 meshPart: a part of mesh (group, sub-mesh) to search within
4038 list of IDs of found elements
4042 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
4044 return self.editor.FindElementsByPoint(x, y, z, elementType)
4046 def GetPointState(self, x, y, z):
4048 Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
4049 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
4050 UNKNOWN state means that either mesh is wrong or the analysis fails.
4053 return self.editor.GetPointState(x, y, z)
4055 def IsManifold(self):
4057 Check if a 2D mesh is manifold
4060 return self.editor.IsManifold()
4062 def IsCoherentOrientation2D(self):
4064 Check if orientation of 2D elements is coherent
4067 return self.editor.IsCoherentOrientation2D()
4069 def MeshToPassThroughAPoint(self, x, y, z):
4071 Find the node closest to a point and moves it to a point location
4074 x: the X coordinate of a point
4075 y: the Y coordinate of a point
4076 z: the Z coordinate of a point
4079 the ID of a moved node
4082 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
4084 def InverseDiag(self, NodeID1, NodeID2):
4086 Replace two neighbour triangles sharing Node1-Node2 link
4087 with the triangles built on the same 4 nodes but having other common link.
4090 NodeID1: the ID of the first node
4091 NodeID2: the ID of the second node
4094 false if proper faces were not found
4096 return self.editor.InverseDiag(NodeID1, NodeID2)
4098 def DeleteDiag(self, NodeID1, NodeID2):
4100 Replace two neighbour triangles sharing Node1-Node2 link
4101 with a quadrangle built on the same 4 nodes.
4104 NodeID1: the ID of the first node
4105 NodeID2: the ID of the second node
4108 false if proper faces were not found
4111 return self.editor.DeleteDiag(NodeID1, NodeID2)
4113 def Reorient(self, IDsOfElements=None):
4115 Reorient elements by ids
4118 IDsOfElements: if undefined reorients all mesh elements
4121 True if succeed else False
4124 if IDsOfElements == None:
4125 IDsOfElements = self.GetElementsId()
4126 return self.editor.Reorient(IDsOfElements)
4128 def ReorientObject(self, theObject):
4130 Reorient all elements of the object
4133 theObject: mesh, submesh or group
4136 True if succeed else False
4139 if ( isinstance( theObject, Mesh )):
4140 theObject = theObject.GetMesh()
4141 return self.editor.ReorientObject(theObject)
4143 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
4145 Reorient faces contained in *the2DObject*.
4148 the2DObject: is a mesh, sub-mesh, group or list of IDs of 2D elements
4149 theDirection: is a desired direction of normal of *theFace*.
4150 It can be either a GEOM vector or a list of coordinates [x,y,z].
4151 theFaceOrPoint: defines a face of *the2DObject* whose normal will be
4152 compared with theDirection. It can be either ID of face or a point
4153 by which the face will be found. The point can be given as either
4154 a GEOM vertex or a list of point coordinates.
4157 number of reoriented faces
4160 unRegister = genObjUnRegister()
4162 if isinstance( the2DObject, Mesh ):
4163 the2DObject = the2DObject.GetMesh()
4164 if isinstance( the2DObject, list ):
4165 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
4166 unRegister.set( the2DObject )
4167 # check theDirection
4168 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
4169 theDirection = self.smeshpyD.GetDirStruct( theDirection )
4170 if isinstance( theDirection, list ):
4171 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
4172 # prepare theFace and thePoint
4173 theFace = theFaceOrPoint
4174 thePoint = PointStruct(0,0,0)
4175 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
4176 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
4178 if isinstance( theFaceOrPoint, list ):
4179 thePoint = PointStruct( *theFaceOrPoint )
4181 if isinstance( theFaceOrPoint, PointStruct ):
4182 thePoint = theFaceOrPoint
4184 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
4186 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
4188 Reorient faces according to adjacent volumes.
4191 the2DObject: is a mesh, sub-mesh, group or list of
4192 either IDs of faces or face groups.
4193 the3DObject: is a mesh, sub-mesh, group or list of IDs of volumes.
4194 theOutsideNormal: to orient faces to have their normals
4195 pointing either *outside* or *inside* the adjacent volumes.
4198 number of reoriented faces.
4201 unRegister = genObjUnRegister()
4203 if not isinstance( the2DObject, list ):
4204 the2DObject = [ the2DObject ]
4205 elif the2DObject and isinstance( the2DObject[0], int ):
4206 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
4207 unRegister.set( the2DObject )
4208 the2DObject = [ the2DObject ]
4209 for i,obj2D in enumerate( the2DObject ):
4210 if isinstance( obj2D, Mesh ):
4211 the2DObject[i] = obj2D.GetMesh()
4212 if isinstance( obj2D, list ):
4213 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
4214 unRegister.set( the2DObject[i] )
4216 if isinstance( the3DObject, Mesh ):
4217 the3DObject = the3DObject.GetMesh()
4218 if isinstance( the3DObject, list ):
4219 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
4220 unRegister.set( the3DObject )
4221 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
4223 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
4225 Fuse the neighbouring triangles into quadrangles.
4228 IDsOfElements: The triangles to be fused.
4229 theCriterion: a numerical functor, in terms of enum SMESH.FunctorType, used to
4230 applied to possible quadrangles to choose a neighbour to fuse with.
4231 Type SMESH.FunctorType._items in the Python Console to see all items.
4232 Note that not all items correspond to numerical functors.
4233 MaxAngle: is the maximum angle between element normals at which the fusion
4234 is still performed; theMaxAngle is measured in radians.
4235 Also it could be a name of variable which defines angle in degrees.
4238 TRUE in case of success, FALSE otherwise.
4241 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
4242 self.mesh.SetParameters(Parameters)
4243 if not IDsOfElements:
4244 IDsOfElements = self.GetElementsId()
4245 Functor = self.smeshpyD.GetFunctor(theCriterion)
4246 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
4248 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
4250 Fuse the neighbouring triangles of the object into quadrangles
4253 theObject: is mesh, submesh or group
4254 theCriterion: is a numerical functor, in terms of enum SMESH.FunctorType,
4255 applied to possible quadrangles to choose a neighbour to fuse with.
4256 Type SMESH.FunctorType._items in the Python Console to see all items.
4257 Note that not all items correspond to numerical functors.
4258 MaxAngle: a max angle between element normals at which the fusion
4259 is still performed; theMaxAngle is measured in radians.
4262 TRUE in case of success, FALSE otherwise.
4265 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
4266 self.mesh.SetParameters(Parameters)
4267 if isinstance( theObject, Mesh ):
4268 theObject = theObject.GetMesh()
4269 Functor = self.smeshpyD.GetFunctor(theCriterion)
4270 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
4272 def QuadToTri (self, IDsOfElements, theCriterion = None):
4274 Split quadrangles into triangles.
4277 IDsOfElements: the faces to be splitted.
4278 theCriterion: is a numerical functor, in terms of enum SMESH.FunctorType, used to
4279 choose a diagonal for splitting. If *theCriterion* is None, which is a default
4280 value, then quadrangles will be split by the smallest diagonal.
4281 Type SMESH.FunctorType._items in the Python Console to see all items.
4282 Note that not all items correspond to numerical functors.
4285 TRUE in case of success, FALSE otherwise.
4287 if IDsOfElements == []:
4288 IDsOfElements = self.GetElementsId()
4289 if theCriterion is None:
4290 theCriterion = FT_MaxElementLength2D
4291 Functor = self.smeshpyD.GetFunctor(theCriterion)
4292 return self.editor.QuadToTri(IDsOfElements, Functor)
4294 def QuadToTriObject (self, theObject, theCriterion = None):
4296 Split quadrangles into triangles.
4299 theObject: the object from which the list of elements is taken,
4300 this is mesh, submesh or group
4301 theCriterion: is a numerical functor, in terms of enum SMESH.FunctorType, used to
4302 choose a diagonal for splitting. If *theCriterion* is None, which is a default
4303 value, then quadrangles will be split by the smallest diagonal.
4304 Type SMESH.FunctorType._items in the Python Console to see all items.
4305 Note that not all items correspond to numerical functors.
4308 TRUE in case of success, FALSE otherwise.
4310 if ( isinstance( theObject, Mesh )):
4311 theObject = theObject.GetMesh()
4312 if theCriterion is None:
4313 theCriterion = FT_MaxElementLength2D
4314 Functor = self.smeshpyD.GetFunctor(theCriterion)
4315 return self.editor.QuadToTriObject(theObject, Functor)
4317 def QuadTo4Tri (self, theElements=[]):
4319 Split each of given quadrangles into 4 triangles. A node is added at the center of
4323 theElements: the faces to be splitted. This can be either mesh, sub-mesh,
4324 group or a list of face IDs. By default all quadrangles are split
4326 unRegister = genObjUnRegister()
4327 if isinstance( theElements, Mesh ):
4328 theElements = theElements.mesh
4329 elif not theElements:
4330 theElements = self.mesh
4331 elif isinstance( theElements, list ):
4332 theElements = self.GetIDSource( theElements, SMESH.FACE )
4333 unRegister.set( theElements )
4334 return self.editor.QuadTo4Tri( theElements )
4336 def SplitQuad (self, IDsOfElements, Diag13):
4338 Split quadrangles into triangles.
4341 IDsOfElements: the faces to be splitted
4342 Diag13: is used to choose a diagonal for splitting.
4345 TRUE in case of success, FALSE otherwise.
4347 if IDsOfElements == []:
4348 IDsOfElements = self.GetElementsId()
4349 return self.editor.SplitQuad(IDsOfElements, Diag13)
4351 def SplitQuadObject (self, theObject, Diag13):
4353 Split quadrangles into triangles.
4356 theObject: the object from which the list of elements is taken,
4357 this is mesh, submesh or group
4358 Diag13: is used to choose a diagonal for splitting.
4361 TRUE in case of success, FALSE otherwise.
4363 if ( isinstance( theObject, Mesh )):
4364 theObject = theObject.GetMesh()
4365 return self.editor.SplitQuadObject(theObject, Diag13)
4367 def BestSplit (self, IDOfQuad, theCriterion):
4369 Find a better splitting of the given quadrangle.
4372 IDOfQuad: the ID of the quadrangle to be splitted.
4373 theCriterion: is a numerical functor, in terms of enum SMESH.FunctorType, used to
4374 choose a diagonal for splitting.
4375 Type SMESH.FunctorType._items in the Python Console to see all items.
4376 Note that not all items correspond to numerical functors.
4379 1 if 1-3 diagonal is better, 2 if 2-4
4380 diagonal is better, 0 if error occurs.
4382 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
4384 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
4386 Split volumic elements into tetrahedrons
4389 elems: either a list of elements or a mesh or a group or a submesh or a filter
4390 method: flags passing splitting method:
4391 smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
4392 smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
4394 unRegister = genObjUnRegister()
4395 if isinstance( elems, Mesh ):
4396 elems = elems.GetMesh()
4397 if ( isinstance( elems, list )):
4398 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
4399 unRegister.set( elems )
4400 self.editor.SplitVolumesIntoTetra(elems, method)
4403 def SplitBiQuadraticIntoLinear(self, elems=None):
4405 Split bi-quadratic elements into linear ones without creation of additional nodes:
4407 - bi-quadratic triangle will be split into 3 linear quadrangles;
4408 - bi-quadratic quadrangle will be split into 4 linear quadrangles;
4409 - tri-quadratic hexahedron will be split into 8 linear hexahedra.
4411 Quadratic elements of lower dimension adjacent to the split bi-quadratic element
4412 will be split in order to keep the mesh conformal.
4415 elems: elements to split\: sub-meshes, groups, filters or element IDs;
4416 if None (default), all bi-quadratic elements will be split
4418 unRegister = genObjUnRegister()
4419 if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
4420 elems = self.editor.MakeIDSource(elems, SMESH.ALL)
4421 unRegister.set( elems )
4423 elems = [ self.GetMesh() ]
4424 if isinstance( elems, Mesh ):
4425 elems = [ elems.GetMesh() ]
4426 if not isinstance( elems, list ):
4428 self.editor.SplitBiQuadraticIntoLinear( elems )
4430 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
4431 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
4433 Split hexahedra into prisms
4436 elems: either a list of elements or a mesh or a group or a submesh or a filter
4437 startHexPoint: a point used to find a hexahedron for which *facetNormal*
4438 gives a normal vector defining facets to split into triangles.
4439 **startHexPoint** can be either a triple of coordinates or a vertex.
4440 facetNormal: a normal to a facet to split into triangles of a
4441 hexahedron found by *startHexPoint*.
4442 **facetNormal** can be either a triple of coordinates or an edge.
4443 method: flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
4444 smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
4445 allDomains: if :code:`False`, only hexahedra adjacent to one closest
4446 to **startHexPoint** are split, else **startHexPoint**
4447 is used to find the facet to split in all domains present in *elems*.
4450 unRegister = genObjUnRegister()
4451 if isinstance( elems, Mesh ):
4452 elems = elems.GetMesh()
4453 if ( isinstance( elems, list )):
4454 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
4455 unRegister.set( elems )
4458 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
4459 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
4460 elif isinstance( startHexPoint, list ):
4461 startHexPoint = SMESH.PointStruct( startHexPoint[0],
4464 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
4465 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
4466 elif isinstance( facetNormal, list ):
4467 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
4470 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
4472 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
4474 def SplitQuadsNearTriangularFacets(self):
4476 Split quadrangle faces near triangular facets of volumes
4478 faces_array = self.GetElementsByType(SMESH.FACE)
4479 for face_id in faces_array:
4480 if self.GetElemNbNodes(face_id) == 4: # quadrangle
4481 quad_nodes = self.mesh.GetElemNodes(face_id)
4482 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
4483 isVolumeFound = False
4484 for node1_elem in node1_elems:
4485 if not isVolumeFound:
4486 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
4487 nb_nodes = self.GetElemNbNodes(node1_elem)
4488 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
4489 volume_elem = node1_elem
4490 volume_nodes = self.mesh.GetElemNodes(volume_elem)
4491 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
4492 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
4493 isVolumeFound = True
4494 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
4495 self.SplitQuad([face_id], False) # diagonal 2-4
4496 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
4497 isVolumeFound = True
4498 self.SplitQuad([face_id], True) # diagonal 1-3
4499 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
4500 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
4501 isVolumeFound = True
4502 self.SplitQuad([face_id], True) # diagonal 1-3
4504 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
4506 **Splits** hexahedrons into tetrahedrons.
4508 This operation uses pattern mapping functionality for splitting.
4511 theObject: the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
4512 theNode000,theNode001: within the range [0,7]; gives the orientation of the
4513 pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
4514 will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
4515 key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
4516 The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
4519 TRUE in case of success, FALSE otherwise.
4527 # (0,0,1) 4.---------.7 * |
4534 # (0,0,0) 0.---------.3
4535 pattern_tetra = "!!! Nb of points: \n 8 \n\
4545 !!! Indices of points of 6 tetras: \n\
4553 pattern = self.smeshpyD.GetPattern()
4554 isDone = pattern.LoadFromFile(pattern_tetra)
4556 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
4559 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
4560 isDone = pattern.MakeMesh(self.mesh, False, False)
4561 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
4563 # split quafrangle faces near triangular facets of volumes
4564 self.SplitQuadsNearTriangularFacets()
4568 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
4570 **Split** hexahedrons into prisms.
4572 Uses the pattern mapping functionality for splitting.
4575 theObject: the object (mesh, submesh or group) from where the list of hexahedrons is taken;
4576 theNode000,theNode001: (within the range [0,7]) gives the orientation of the
4577 pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
4578 will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
4579 will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
4580 Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
4583 TRUE in case of success, FALSE otherwise.
4585 # Pattern: 5.---------.6
4590 # (0,0,1) 4.---------.7 |
4597 # (0,0,0) 0.---------.3
4598 pattern_prism = "!!! Nb of points: \n 8 \n\
4608 !!! Indices of points of 2 prisms: \n\
4612 pattern = self.smeshpyD.GetPattern()
4613 isDone = pattern.LoadFromFile(pattern_prism)
4615 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
4618 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
4619 isDone = pattern.MakeMesh(self.mesh, False, False)
4620 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
4622 # Split quafrangle faces near triangular facets of volumes
4623 self.SplitQuadsNearTriangularFacets()
4627 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
4628 MaxNbOfIterations, MaxAspectRatio, Method):
4633 IDsOfElements: the list if ids of elements to smooth
4634 IDsOfFixedNodes: the list of ids of fixed nodes.
4635 Note that nodes built on edges and boundary nodes are always fixed.
4636 MaxNbOfIterations: the maximum number of iterations
4637 MaxAspectRatio: varies in range [1.0, inf]
4638 Method: is either Laplacian (smesh.LAPLACIAN_SMOOTH)
4639 or Centroidal (smesh.CENTROIDAL_SMOOTH)
4642 TRUE in case of success, FALSE otherwise.
4645 if IDsOfElements == []:
4646 IDsOfElements = self.GetElementsId()
4647 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
4648 self.mesh.SetParameters(Parameters)
4649 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
4650 MaxNbOfIterations, MaxAspectRatio, Method)
4652 def SmoothObject(self, theObject, IDsOfFixedNodes,
4653 MaxNbOfIterations, MaxAspectRatio, Method):
4655 Smooth elements which belong to the given object
4658 theObject: the object to smooth
4659 IDsOfFixedNodes: the list of ids of fixed nodes.
4660 Note that nodes built on edges and boundary nodes are always fixed.
4661 MaxNbOfIterations: the maximum number of iterations
4662 MaxAspectRatio: varies in range [1.0, inf]
4663 Method: is either Laplacian (smesh.LAPLACIAN_SMOOTH)
4664 or Centroidal (smesh.CENTROIDAL_SMOOTH)
4667 TRUE in case of success, FALSE otherwise.
4670 if ( isinstance( theObject, Mesh )):
4671 theObject = theObject.GetMesh()
4672 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
4673 MaxNbOfIterations, MaxAspectRatio, Method)
4675 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
4676 MaxNbOfIterations, MaxAspectRatio, Method):
4678 Parametrically smooth the given elements
4681 IDsOfElements: the list if ids of elements to smooth
4682 IDsOfFixedNodes: the list of ids of fixed nodes.
4683 Note that nodes built on edges and boundary nodes are always fixed.
4684 MaxNbOfIterations: the maximum number of iterations
4685 MaxAspectRatio: varies in range [1.0, inf]
4686 Method: is either Laplacian (smesh.LAPLACIAN_SMOOTH)
4687 or Centroidal (smesh.CENTROIDAL_SMOOTH)
4690 TRUE in case of success, FALSE otherwise.
4693 if IDsOfElements == []:
4694 IDsOfElements = self.GetElementsId()
4695 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
4696 self.mesh.SetParameters(Parameters)
4697 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
4698 MaxNbOfIterations, MaxAspectRatio, Method)
4700 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
4701 MaxNbOfIterations, MaxAspectRatio, Method):
4703 Parametrically smooth the elements which belong to the given object
4706 theObject: the object to smooth
4707 IDsOfFixedNodes: the list of ids of fixed nodes.
4708 Note that nodes built on edges and boundary nodes are always fixed.
4709 MaxNbOfIterations: the maximum number of iterations
4710 MaxAspectRatio: varies in range [1.0, inf]
4711 Method: is either Laplacian (smesh.LAPLACIAN_SMOOTH)
4712 or Centroidal (smesh.CENTROIDAL_SMOOTH)
4715 TRUE in case of success, FALSE otherwise.
4718 if ( isinstance( theObject, Mesh )):
4719 theObject = theObject.GetMesh()
4720 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
4721 MaxNbOfIterations, MaxAspectRatio, Method)
4723 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
4725 Convert the mesh to quadratic or bi-quadratic, deletes old elements, replacing
4726 them with quadratic with the same id.
4729 theForce3d: new node creation method:
4730 0 - the medium node lies at the geometrical entity from which the mesh element is built
4731 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
4732 theSubMesh: a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
4733 theToBiQuad: If True, converts the mesh to bi-quadratic
4736 SMESH.ComputeError which can hold a warning
4739 if isinstance( theSubMesh, Mesh ):
4740 theSubMesh = theSubMesh.mesh
4742 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
4745 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
4747 self.editor.ConvertToQuadratic(theForce3d)
4748 error = self.editor.GetLastError()
4749 if error and error.comment:
4753 def ConvertFromQuadratic(self, theSubMesh=None):
4755 Convert the mesh from quadratic to ordinary,
4756 deletes old quadratic elements,
4757 replacing them with ordinary mesh elements with the same id.
4760 theSubMesh: a group or a sub-mesh to convert;
4763 in this case the mesh can become not conformal
4767 self.editor.ConvertFromQuadraticObject(theSubMesh)
4769 return self.editor.ConvertFromQuadratic()
4771 def Make2DMeshFrom3D(self):
4773 Create 2D mesh as skin on boundary faces of a 3D mesh
4776 TRUE if operation has been completed successfully, FALSE otherwise
4779 return self.editor.Make2DMeshFrom3D()
4781 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
4782 toCopyElements=False, toCopyExistingBondary=False):
4784 Create missing boundary elements
4787 elements: elements whose boundary is to be checked:
4788 mesh, group, sub-mesh or list of elements
4789 if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
4790 dimension: defines type of boundary elements to create, either of
4791 { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
4792 SMESH.BND_1DFROM3D create mesh edges on all borders of free facets of 3D cells
4793 groupName: a name of group to store created boundary elements in,
4794 "" means not to create the group
4795 meshName: a name of new mesh to store created boundary elements in,
4796 "" means not to create the new mesh
4797 toCopyElements: if true, the checked elements will be copied into
4798 the new mesh else only boundary elements will be copied into the new mesh
4799 toCopyExistingBondary: if true, not only new but also pre-existing
4800 boundary elements will be copied into the new mesh
4803 tuple (mesh, group) where boundary elements were added to
4806 unRegister = genObjUnRegister()
4807 if isinstance( elements, Mesh ):
4808 elements = elements.GetMesh()
4809 if ( isinstance( elements, list )):
4810 elemType = SMESH.ALL
4811 if elements: elemType = self.GetElementType( elements[0], iselem=True)
4812 elements = self.editor.MakeIDSource(elements, elemType)
4813 unRegister.set( elements )
4814 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
4815 toCopyElements,toCopyExistingBondary)
4816 if mesh: mesh = self.smeshpyD.Mesh(mesh)
4819 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
4820 toCopyAll=False, groups=[]):
4822 **Create** missing boundary elements around either the whole mesh or
4826 dimension: defines type of boundary elements to create, either of
4827 { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
4828 groupName: a name of group to store all boundary elements in,
4829 "" means not to create the group
4830 meshName: a name of a new mesh, which is a copy of the initial
4831 mesh + created boundary elements; "" means not to create the new mesh
4832 toCopyAll: if true, the whole initial mesh will be copied into
4833 the new mesh else only boundary elements will be copied into the new mesh
4834 groups: groups of elements to make boundary around
4837 tuple( long, mesh, groups )
4838 long - number of added boundary elements
4839 mesh - the mesh where elements were added to
4840 group - the group of boundary elements or None
4843 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
4845 if mesh: mesh = self.smeshpyD.Mesh(mesh)
4846 return nb, mesh, group
4848 def RenumberNodes(self):
4850 Renumber mesh nodes (Obsolete, does nothing)
4852 self.editor.RenumberNodes()
4854 def RenumberElements(self):
4856 Renumber mesh elements (Obsole, does nothing)
4858 self.editor.RenumberElements()
4860 def _getIdSourceList(self, arg, idType, unRegister):
4862 Private method converting *arg* into a list of SMESH_IdSource's
4864 if arg and isinstance( arg, list ):
4865 if isinstance( arg[0], int ):
4866 arg = self.GetIDSource( arg, idType )
4867 unRegister.set( arg )
4868 elif isinstance( arg[0], Mesh ):
4869 arg[0] = arg[0].GetMesh()
4870 elif isinstance( arg, Mesh ):
4872 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
4876 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
4877 MakeGroups=False, TotalAngle=False):
4879 Generate new elements by rotation of the given elements and nodes around the axis
4882 nodes: nodes to revolve: a list including ids, groups, sub-meshes or a mesh
4883 edges: edges to revolve: a list including ids, groups, sub-meshes or a mesh
4884 faces: faces to revolve: a list including ids, groups, sub-meshes or a mesh
4885 Axis: the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
4886 AngleInRadians: the angle of Rotation (in radians) or a name of variable
4887 which defines angle in degrees
4888 NbOfSteps: the number of steps
4889 Tolerance: tolerance
4890 MakeGroups: forces the generation of new groups from existing ones
4891 TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
4892 of all steps, else - size of each step
4895 the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4898 unRegister = genObjUnRegister()
4899 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
4900 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
4901 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
4903 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
4904 Axis = self.smeshpyD.GetAxisStruct( Axis )
4905 if isinstance( Axis, list ):
4906 Axis = SMESH.AxisStruct( *Axis )
4908 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
4909 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
4910 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
4911 self.mesh.SetParameters(Parameters)
4912 if TotalAngle and NbOfSteps:
4913 AngleInRadians /= NbOfSteps
4914 return self.editor.RotationSweepObjects( nodes, edges, faces,
4915 Axis, AngleInRadians,
4916 NbOfSteps, Tolerance, MakeGroups)
4918 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
4919 MakeGroups=False, TotalAngle=False):
4921 Generate new elements by rotation of the elements around the axis
4924 IDsOfElements: the list of ids of elements to sweep
4925 Axis: the axis of rotation, AxisStruct or line(geom object)
4926 AngleInRadians: the angle of Rotation (in radians) or a name of variable which defines angle in degrees
4927 NbOfSteps: the number of steps
4928 Tolerance: tolerance
4929 MakeGroups: forces the generation of new groups from existing ones
4930 TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
4931 of all steps, else - size of each step
4934 the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4937 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
4938 AngleInRadians, NbOfSteps, Tolerance,
4939 MakeGroups, TotalAngle)
4941 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
4942 MakeGroups=False, TotalAngle=False):
4944 Generate new elements by rotation of the elements of object around the axis
4945 theObject object which elements should be sweeped.
4946 It can be a mesh, a sub mesh or a group.
4949 Axis: the axis of rotation, AxisStruct or line(geom object)
4950 AngleInRadians: the angle of Rotation
4951 NbOfSteps: number of steps
4952 Tolerance: tolerance
4953 MakeGroups: forces the generation of new groups from existing ones
4954 TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
4955 of all steps, else - size of each step
4958 the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4961 return self.RotationSweepObjects( [], theObject, theObject, Axis,
4962 AngleInRadians, NbOfSteps, Tolerance,
4963 MakeGroups, TotalAngle )
4965 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
4966 MakeGroups=False, TotalAngle=False):
4968 Generate new elements by rotation of the elements of object around the axis
4969 theObject object which elements should be sweeped.
4970 It can be a mesh, a sub mesh or a group.
4973 Axis: the axis of rotation, AxisStruct or line(geom object)
4974 AngleInRadians: the angle of Rotation
4975 NbOfSteps: number of steps
4976 Tolerance: tolerance
4977 MakeGroups: forces the generation of new groups from existing ones
4978 TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
4979 of all steps, else - size of each step
4982 the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4985 return self.RotationSweepObjects([],theObject,[], Axis,
4986 AngleInRadians, NbOfSteps, Tolerance,
4987 MakeGroups, TotalAngle)
4989 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
4990 MakeGroups=False, TotalAngle=False):
4992 Generate new elements by rotation of the elements of object around the axis
4993 theObject object which elements should be sweeped.
4994 It can be a mesh, a sub mesh or a group.
4997 Axis: the axis of rotation, AxisStruct or line(geom object)
4998 AngleInRadians: the angle of Rotation
4999 NbOfSteps: number of steps
5000 Tolerance: tolerance
5001 MakeGroups: forces the generation of new groups from existing ones
5002 TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
5003 of all steps, else - size of each step
5006 the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5009 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
5010 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
5012 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False,
5013 scaleFactors=[], linearVariation=False, basePoint=[] ):
5015 Generate new elements by extrusion of the given elements and nodes
5018 nodes: nodes to extrude: a list including ids, groups, sub-meshes or a mesh
5019 edges: edges to extrude: a list including ids, groups, sub-meshes or a mesh
5020 faces: faces to extrude: a list including ids, groups, sub-meshes or a mesh
5021 StepVector: vector or DirStruct or 3 vector components, defining
5022 the direction and value of extrusion for one step (the total extrusion
5023 length will be NbOfSteps * ||StepVector||)
5024 NbOfSteps: the number of steps
5025 MakeGroups: forces the generation of new groups from existing ones
5026 scaleFactors: optional scale factors to apply during extrusion
5027 linearVariation: if *True*, scaleFactors are spread over all *scaleFactors*,
5028 else scaleFactors[i] is applied to nodes at the i-th extrusion step
5029 basePoint: optional scaling center; if not provided, a gravity center of
5030 nodes and elements being extruded is used as the scaling center.
5033 - a list of tree components of the point or
5038 the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5040 :ref:`tui_extrusion` example
5042 unRegister = genObjUnRegister()
5043 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
5044 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
5045 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
5047 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
5048 StepVector = self.smeshpyD.GetDirStruct(StepVector)
5049 if isinstance( StepVector, list ):
5050 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
5052 if isinstance( basePoint, int):
5053 xyz = self.GetNodeXYZ( basePoint )
5055 raise RuntimeError, "Invalid node ID: %s" % basePoint
5057 if isinstance( basePoint, geomBuilder.GEOM._objref_GEOM_Object ):
5058 basePoint = self.geompyD.PointCoordinates( basePoint )
5060 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
5061 Parameters = StepVector.PS.parameters + var_separator + Parameters
5062 self.mesh.SetParameters(Parameters)
5064 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
5065 StepVector, NbOfSteps,
5066 scaleFactors, linearVariation, basePoint,
5070 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
5072 Generate new elements by extrusion of the elements with given ids
5075 IDsOfElements: the list of ids of elements or nodes for extrusion
5076 StepVector: vector or DirStruct or 3 vector components, defining
5077 the direction and value of extrusion for one step (the total extrusion
5078 length will be NbOfSteps * ||StepVector||)
5079 NbOfSteps: the number of steps
5080 MakeGroups: forces the generation of new groups from existing ones
5081 IsNodes: is True if elements with given ids are nodes
5084 the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5086 :ref:`tui_extrusion` example
5089 if IsNodes: n = IDsOfElements
5090 else : e,f, = IDsOfElements,IDsOfElements
5091 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
5093 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
5094 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
5096 Generate new elements by extrusion along the normal to a discretized surface or wire
5099 Elements: elements to extrude - a list including ids, groups, sub-meshes or a mesh.
5100 Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
5101 StepSize: length of one extrusion step (the total extrusion
5102 length will be *NbOfSteps* *StepSize*).
5103 NbOfSteps: number of extrusion steps.
5104 ByAverageNormal: if True each node is translated by *StepSize*
5105 along the average of the normal vectors to the faces sharing the node;
5106 else each node is translated along the same average normal till
5107 intersection with the plane got by translation of the face sharing
5108 the node along its own normal by *StepSize*.
5109 UseInputElemsOnly: to use only *Elements* when computing extrusion direction
5110 for every node of *Elements*.
5111 MakeGroups: forces generation of new groups from existing ones.
5112 Dim: dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
5113 is not yet implemented. This parameter is used if *Elements* contains
5114 both faces and edges, i.e. *Elements* is a Mesh.
5117 the list of created groups (SMESH_GroupBase) if *MakeGroups=True*,
5118 empty list otherwise.
5119 :ref:`tui_extrusion` example
5122 unRegister = genObjUnRegister()
5123 if isinstance( Elements, Mesh ):
5124 Elements = [ Elements.GetMesh() ]
5125 if isinstance( Elements, list ):
5127 raise RuntimeError, "Elements empty!"
5128 if isinstance( Elements[0], int ):
5129 Elements = self.GetIDSource( Elements, SMESH.ALL )
5130 unRegister.set( Elements )
5131 if not isinstance( Elements, list ):
5132 Elements = [ Elements ]
5133 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
5134 self.mesh.SetParameters(Parameters)
5135 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
5136 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
5138 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
5140 Generate new elements by extrusion of the elements or nodes which belong to the object
5143 theObject: the object whose elements or nodes should be processed.
5144 It can be a mesh, a sub-mesh or a group.
5145 StepVector: vector or DirStruct or 3 vector components, defining
5146 the direction and value of extrusion for one step (the total extrusion
5147 length will be NbOfSteps * ||StepVector||)
5148 NbOfSteps: the number of steps
5149 MakeGroups: forces the generation of new groups from existing ones
5150 IsNodes: is True if elements to extrude are nodes
5153 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5154 :ref:`tui_extrusion` example
5158 if IsNodes: n = theObject
5159 else : e,f, = theObject,theObject
5160 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
5162 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
5164 Generate new elements by extrusion of edges which belong to the object
5167 theObject: object whose 1D elements should be processed.
5168 It can be a mesh, a sub-mesh or a group.
5169 StepVector: vector or DirStruct or 3 vector components, defining
5170 the direction and value of extrusion for one step (the total extrusion
5171 length will be NbOfSteps * ||StepVector||)
5172 NbOfSteps: the number of steps
5173 MakeGroups: to generate new groups from existing ones
5176 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5177 :ref:`tui_extrusion` example
5180 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
5182 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
5184 Generate new elements by extrusion of faces which belong to the object
5187 theObject: object whose 2D elements should be processed.
5188 It can be a mesh, a sub-mesh or a group.
5189 StepVector: vector or DirStruct or 3 vector components, defining
5190 the direction and value of extrusion for one step (the total extrusion
5191 length will be NbOfSteps * ||StepVector||)
5192 NbOfSteps: the number of steps
5193 MakeGroups: forces the generation of new groups from existing ones
5196 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5197 :ref:`tui_extrusion` example
5200 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
5202 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
5203 ExtrFlags, SewTolerance, MakeGroups=False):
5205 Generate new elements by extrusion of the elements with given ids
5208 IDsOfElements: is ids of elements
5209 StepVector: vector or DirStruct or 3 vector components, defining
5210 the direction and value of extrusion for one step (the total extrusion
5211 length will be NbOfSteps * ||StepVector||)
5212 NbOfSteps: the number of steps
5213 ExtrFlags: sets flags for extrusion
5214 SewTolerance: uses for comparing locations of nodes if flag
5215 EXTRUSION_FLAG_SEW is set
5216 MakeGroups: forces the generation of new groups from existing ones
5219 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5222 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
5223 StepVector = self.smeshpyD.GetDirStruct(StepVector)
5224 if isinstance( StepVector, list ):
5225 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
5226 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
5227 ExtrFlags, SewTolerance, MakeGroups)
5229 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
5230 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
5231 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
5233 Generate new elements by extrusion of the given elements and nodes along the path.
5234 The path of extrusion must be a meshed edge.
5237 Nodes: nodes to extrude: a list including ids, groups, sub-meshes or a mesh
5238 Edges: edges to extrude: a list including ids, groups, sub-meshes or a mesh
5239 Faces: faces to extrude: a list including ids, groups, sub-meshes or a mesh
5240 PathMesh: 1D mesh or 1D sub-mesh, along which proceeds the extrusion
5241 PathShape: shape (edge) defines the sub-mesh of PathMesh if PathMesh
5242 contains not only path segments, else it can be None
5243 NodeStart: the first or the last node on the path. Defines the direction of extrusion
5244 HasAngles: allows the shape to be rotated around the path
5245 to get the resulting mesh in a helical fashion
5246 Angles: list of angles
5247 LinearVariation: forces the computation of rotation angles as linear
5248 variation of the given Angles along path steps
5249 HasRefPoint: allows using the reference point
5250 RefPoint: the point around which the shape is rotated (the mass center of the
5251 shape by default). The User can specify any point as the Reference Point.
5252 MakeGroups: forces the generation of new groups from existing ones
5255 list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
5256 :ref:`tui_extrusion_along_path` example
5259 unRegister = genObjUnRegister()
5260 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
5261 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
5262 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
5264 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
5265 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
5266 if isinstance( RefPoint, list ):
5267 if not RefPoint: RefPoint = [0,0,0]
5268 RefPoint = SMESH.PointStruct( *RefPoint )
5269 if isinstance( PathMesh, Mesh ):
5270 PathMesh = PathMesh.GetMesh()
5271 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
5272 Parameters = AnglesParameters + var_separator + RefPoint.parameters
5273 self.mesh.SetParameters(Parameters)
5274 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
5275 PathMesh, PathShape, NodeStart,
5276 HasAngles, Angles, LinearVariation,
5277 HasRefPoint, RefPoint, MakeGroups)
5279 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
5280 HasAngles=False, Angles=[], LinearVariation=False,
5281 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
5282 ElemType=SMESH.FACE):
5284 Generate new elements by extrusion of the given elements
5285 The path of extrusion must be a meshed edge.
5288 Base: mesh or group, or sub-mesh, or list of ids of elements for extrusion
5289 Path: 1D mesh or 1D sub-mesh, along which proceeds the extrusion
5290 NodeStart: the start node from Path. Defines the direction of extrusion
5291 HasAngles: allows the shape to be rotated around the path
5292 to get the resulting mesh in a helical fashion
5293 Angles: list of angles in radians
5294 LinearVariation: forces the computation of rotation angles as linear
5295 variation of the given Angles along path steps
5296 HasRefPoint: allows using the reference point
5297 RefPoint: the point around which the elements are rotated (the mass
5298 center of the elements by default).
5299 The User can specify any point as the Reference Point.
5300 RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
5301 MakeGroups: forces the generation of new groups from existing ones
5302 ElemType: type of elements for extrusion (if param Base is a mesh)
5305 list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
5306 only SMESH::Extrusion_Error otherwise
5307 :ref:`tui_extrusion_along_path` example
5311 if ElemType == SMESH.NODE: n = Base
5312 if ElemType == SMESH.EDGE: e = Base
5313 if ElemType == SMESH.FACE: f = Base
5314 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
5315 HasAngles, Angles, LinearVariation,
5316 HasRefPoint, RefPoint, MakeGroups)
5317 if MakeGroups: return gr,er
5320 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
5321 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
5322 MakeGroups=False, LinearVariation=False):
5324 Generate new elements by extrusion of the given elements
5325 The path of extrusion must be a meshed edge.
5328 IDsOfElements: ids of elements
5329 PathMesh: mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
5330 PathShape: shape(edge) defines the sub-mesh for the path
5331 NodeStart: the first or the last node on the edge. Defines the direction of extrusion
5332 HasAngles: allows the shape to be rotated around the path
5333 to get the resulting mesh in a helical fashion
5334 Angles: list of angles in radians
5335 HasRefPoint: allows using the reference point
5336 RefPoint: the point around which the shape is rotated (the mass center of the shape by default).
5337 The User can specify any point as the Reference Point.
5338 MakeGroups: forces the generation of new groups from existing ones
5339 LinearVariation: forces the computation of rotation angles as linear
5340 variation of the given Angles along path steps
5343 list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
5344 only SMESH::Extrusion_Error otherwise
5345 :ref:`tui_extrusion_along_path` example
5348 n,e,f = [],IDsOfElements,IDsOfElements
5349 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
5350 NodeStart, HasAngles, Angles,
5352 HasRefPoint, RefPoint, MakeGroups)
5353 if MakeGroups: return gr,er
5356 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
5357 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
5358 MakeGroups=False, LinearVariation=False):
5360 Generate new elements by extrusion of the elements which belong to the object
5361 The path of extrusion must be a meshed edge.
5364 theObject: the object whose elements should be processed.
5365 It can be a mesh, a sub-mesh or a group.
5366 PathMesh: mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
5367 PathShape: shape(edge) defines the sub-mesh for the path
5368 NodeStart: the first or the last node on the edge. Defines the direction of extrusion
5369 HasAngles: allows the shape to be rotated around the path
5370 to get the resulting mesh in a helical fashion
5371 Angles: list of angles
5372 HasRefPoint: allows using the reference point
5373 RefPoint: the point around which the shape is rotated (the mass center of the shape by default).
5374 The User can specify any point as the Reference Point.
5375 MakeGroups: forces the generation of new groups from existing ones
5376 LinearVariation: forces the computation of rotation angles as linear
5377 variation of the given Angles along path steps
5380 list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
5381 only SMESH::Extrusion_Error otherwise
5382 :ref:`tui_extrusion_along_path` example
5385 n,e,f = [],theObject,theObject
5386 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
5387 HasAngles, Angles, LinearVariation,
5388 HasRefPoint, RefPoint, MakeGroups)
5389 if MakeGroups: return gr,er
5392 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
5393 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
5394 MakeGroups=False, LinearVariation=False):
5396 Generate new elements by extrusion of mesh segments which belong to the object
5397 The path of extrusion must be a meshed edge.
5400 theObject: the object whose 1D elements should be processed.
5401 It can be a mesh, a sub-mesh or a group.
5402 PathMesh: mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
5403 PathShape: shape(edge) defines the sub-mesh for the path
5404 NodeStart: the first or the last node on the edge. Defines the direction of extrusion
5405 HasAngles: allows the shape to be rotated around the path
5406 to get the resulting mesh in a helical fashion
5407 Angles: list of angles
5408 HasRefPoint: allows using the reference point
5409 RefPoint the point: around which the shape is rotated (the mass center of the shape by default).
5410 The User can specify any point as the Reference Point.
5411 MakeGroups: forces the generation of new groups from existing ones
5412 LinearVariation: forces the computation of rotation angles as linear
5413 variation of the given Angles along path steps
5416 list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
5417 only SMESH::Extrusion_Error otherwise
5418 :ref:`tui_extrusion_along_path` example
5421 n,e,f = [],theObject,[]
5422 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
5423 HasAngles, Angles, LinearVariation,
5424 HasRefPoint, RefPoint, MakeGroups)
5425 if MakeGroups: return gr,er
5428 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
5429 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
5430 MakeGroups=False, LinearVariation=False):
5432 Generate new elements by extrusion of faces which belong to the object
5433 The path of extrusion must be a meshed edge.
5436 theObject: the object whose 2D elements should be processed.
5437 It can be a mesh, a sub-mesh or a group.
5438 PathMesh: mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
5439 PathShape: shape(edge) defines the sub-mesh for the path
5440 NodeStart: the first or the last node on the edge. Defines the direction of extrusion
5441 HasAngles: allows the shape to be rotated around the path
5442 to get the resulting mesh in a helical fashion
5443 Angles: list of angles
5444 HasRefPoint: allows using the reference point
5445 RefPoint: the point around which the shape is rotated (the mass center of the shape by default).
5446 The User can specify any point as the Reference Point.
5447 MakeGroups: forces the generation of new groups from existing ones
5448 LinearVariation: forces the computation of rotation angles as linear
5449 variation of the given Angles along path steps
5452 list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
5453 only SMESH::Extrusion_Error otherwise
5454 :ref:`tui_extrusion_along_path` example
5457 n,e,f = [],[],theObject
5458 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
5459 HasAngles, Angles, LinearVariation,
5460 HasRefPoint, RefPoint, MakeGroups)
5461 if MakeGroups: return gr,er
5464 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
5466 Create a symmetrical copy of mesh elements
5469 IDsOfElements: list of elements ids
5470 Mirror: is AxisStruct or geom object(point, line, plane)
5471 theMirrorType: smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
5472 If the Mirror is a geom object this parameter is unnecessary
5473 Copy: allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
5474 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5477 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5480 if IDsOfElements == []:
5481 IDsOfElements = self.GetElementsId()
5482 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
5483 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
5484 theMirrorType = Mirror._mirrorType
5486 self.mesh.SetParameters(Mirror.parameters)
5487 if Copy and MakeGroups:
5488 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
5489 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
5492 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
5494 Create a new mesh by a symmetrical copy of mesh elements
5497 IDsOfElements: the list of elements ids
5498 Mirror: is AxisStruct or geom object (point, line, plane)
5499 theMirrorType: smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
5500 If the Mirror is a geom object this parameter is unnecessary
5501 MakeGroups: to generate new groups from existing ones
5502 NewMeshName: a name of the new mesh to create
5505 instance of Mesh class
5508 if IDsOfElements == []:
5509 IDsOfElements = self.GetElementsId()
5510 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
5511 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
5512 theMirrorType = Mirror._mirrorType
5514 self.mesh.SetParameters(Mirror.parameters)
5515 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
5516 MakeGroups, NewMeshName)
5517 return Mesh(self.smeshpyD,self.geompyD,mesh)
5519 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
5521 Create a symmetrical copy of the object
5524 theObject: mesh, submesh or group
5525 Mirror: AxisStruct or geom object (point, line, plane)
5526 theMirrorType: smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
5527 If the Mirror is a geom object this parameter is unnecessary
5528 Copy: allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
5529 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5532 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5535 if ( isinstance( theObject, Mesh )):
5536 theObject = theObject.GetMesh()
5537 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
5538 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
5539 theMirrorType = Mirror._mirrorType
5541 self.mesh.SetParameters(Mirror.parameters)
5542 if Copy and MakeGroups:
5543 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
5544 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
5547 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
5549 Create a new mesh by a symmetrical copy of the object
5552 theObject: mesh, submesh or group
5553 Mirror: AxisStruct or geom object (point, line, plane)
5554 theMirrorType: smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
5555 If the Mirror is a geom object this parameter is unnecessary
5556 MakeGroups: forces the generation of new groups from existing ones
5557 NewMeshName: the name of the new mesh to create
5560 instance of Mesh class
5563 if ( isinstance( theObject, Mesh )):
5564 theObject = theObject.GetMesh()
5565 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
5566 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
5567 theMirrorType = Mirror._mirrorType
5569 self.mesh.SetParameters(Mirror.parameters)
5570 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
5571 MakeGroups, NewMeshName)
5572 return Mesh( self.smeshpyD,self.geompyD,mesh )
5574 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
5576 Translate the elements
5579 IDsOfElements: list of elements ids
5580 Vector: the direction of translation (DirStruct or vector or 3 vector components)
5581 Copy: allows copying the translated elements
5582 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5585 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5588 if IDsOfElements == []:
5589 IDsOfElements = self.GetElementsId()
5590 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
5591 Vector = self.smeshpyD.GetDirStruct(Vector)
5592 if isinstance( Vector, list ):
5593 Vector = self.smeshpyD.MakeDirStruct(*Vector)
5594 self.mesh.SetParameters(Vector.PS.parameters)
5595 if Copy and MakeGroups:
5596 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
5597 self.editor.Translate(IDsOfElements, Vector, Copy)
5600 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
5602 Create a new mesh of translated elements
5605 IDsOfElements: list of elements ids
5606 Vector: the direction of translation (DirStruct or vector or 3 vector components)
5607 MakeGroups: forces the generation of new groups from existing ones
5608 NewMeshName: the name of the newly created mesh
5611 instance of Mesh class
5614 if IDsOfElements == []:
5615 IDsOfElements = self.GetElementsId()
5616 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
5617 Vector = self.smeshpyD.GetDirStruct(Vector)
5618 if isinstance( Vector, list ):
5619 Vector = self.smeshpyD.MakeDirStruct(*Vector)
5620 self.mesh.SetParameters(Vector.PS.parameters)
5621 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
5622 return Mesh ( self.smeshpyD, self.geompyD, mesh )
5624 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
5626 Translate the object
5629 theObject: the object to translate (mesh, submesh, or group)
5630 Vector: direction of translation (DirStruct or geom vector or 3 vector components)
5631 Copy: allows copying the translated elements
5632 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5635 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5638 if ( isinstance( theObject, Mesh )):
5639 theObject = theObject.GetMesh()
5640 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
5641 Vector = self.smeshpyD.GetDirStruct(Vector)
5642 if isinstance( Vector, list ):
5643 Vector = self.smeshpyD.MakeDirStruct(*Vector)
5644 self.mesh.SetParameters(Vector.PS.parameters)
5645 if Copy and MakeGroups:
5646 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
5647 self.editor.TranslateObject(theObject, Vector, Copy)
5650 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
5652 Create a new mesh from the translated object
5655 theObject: the object to translate (mesh, submesh, or group)
5656 Vector: the direction of translation (DirStruct or geom vector or 3 vector components)
5657 MakeGroups: forces the generation of new groups from existing ones
5658 NewMeshName: the name of the newly created mesh
5661 instance of Mesh class
5664 if isinstance( theObject, Mesh ):
5665 theObject = theObject.GetMesh()
5666 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
5667 Vector = self.smeshpyD.GetDirStruct(Vector)
5668 if isinstance( Vector, list ):
5669 Vector = self.smeshpyD.MakeDirStruct(*Vector)
5670 self.mesh.SetParameters(Vector.PS.parameters)
5671 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
5672 return Mesh( self.smeshpyD, self.geompyD, mesh )
5676 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
5681 theObject: the object to translate (mesh, submesh, or group)
5682 thePoint: base point for scale (SMESH.PointStruct or list of 3 coordinates)
5683 theScaleFact: list of 1-3 scale factors for axises
5684 Copy: allows copying the translated elements
5685 MakeGroups: forces the generation of new groups from existing
5689 list of created groups (SMESH_GroupBase) if MakeGroups=True,
5690 empty list otherwise
5692 unRegister = genObjUnRegister()
5693 if ( isinstance( theObject, Mesh )):
5694 theObject = theObject.GetMesh()
5695 if ( isinstance( theObject, list )):
5696 theObject = self.GetIDSource(theObject, SMESH.ALL)
5697 unRegister.set( theObject )
5698 if ( isinstance( thePoint, list )):
5699 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
5700 if ( isinstance( theScaleFact, float )):
5701 theScaleFact = [theScaleFact]
5702 if ( isinstance( theScaleFact, int )):
5703 theScaleFact = [ float(theScaleFact)]
5705 self.mesh.SetParameters(thePoint.parameters)
5707 if Copy and MakeGroups:
5708 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
5709 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
5712 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
5714 Create a new mesh from the translated object
5717 theObject: the object to translate (mesh, submesh, or group)
5718 thePoint: base point for scale (SMESH.PointStruct or list of 3 coordinates)
5719 theScaleFact: list of 1-3 scale factors for axises
5720 MakeGroups: forces the generation of new groups from existing ones
5721 NewMeshName: the name of the newly created mesh
5724 instance of Mesh class
5726 unRegister = genObjUnRegister()
5727 if (isinstance(theObject, Mesh)):
5728 theObject = theObject.GetMesh()
5729 if ( isinstance( theObject, list )):
5730 theObject = self.GetIDSource(theObject,SMESH.ALL)
5731 unRegister.set( theObject )
5732 if ( isinstance( thePoint, list )):
5733 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
5734 if ( isinstance( theScaleFact, float )):
5735 theScaleFact = [theScaleFact]
5736 if ( isinstance( theScaleFact, int )):
5737 theScaleFact = [ float(theScaleFact)]
5739 self.mesh.SetParameters(thePoint.parameters)
5740 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
5741 MakeGroups, NewMeshName)
5742 return Mesh( self.smeshpyD, self.geompyD, mesh )
5746 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
5751 IDsOfElements: list of elements ids
5752 Axis: the axis of rotation (AxisStruct or geom line)
5753 AngleInRadians: the angle of rotation (in radians) or a name of variable which defines angle in degrees
5754 Copy: allows copying the rotated elements
5755 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5758 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5762 if IDsOfElements == []:
5763 IDsOfElements = self.GetElementsId()
5764 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
5765 Axis = self.smeshpyD.GetAxisStruct(Axis)
5766 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
5767 Parameters = Axis.parameters + var_separator + Parameters
5768 self.mesh.SetParameters(Parameters)
5769 if Copy and MakeGroups:
5770 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
5771 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
5774 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
5776 Create a new mesh of rotated elements
5779 IDsOfElements: list of element ids
5780 Axis: the axis of rotation (AxisStruct or geom line)
5781 AngleInRadians: the angle of rotation (in radians) or a name of variable which defines angle in degrees
5782 MakeGroups: forces the generation of new groups from existing ones
5783 NewMeshName: the name of the newly created mesh
5786 instance of Mesh class
5789 if IDsOfElements == []:
5790 IDsOfElements = self.GetElementsId()
5791 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
5792 Axis = self.smeshpyD.GetAxisStruct(Axis)
5793 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
5794 Parameters = Axis.parameters + var_separator + Parameters
5795 self.mesh.SetParameters(Parameters)
5796 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
5797 MakeGroups, NewMeshName)
5798 return Mesh( self.smeshpyD, self.geompyD, mesh )
5800 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
5805 theObject: the object to rotate( mesh, submesh, or group)
5806 Axis: the axis of rotation (AxisStruct or geom line)
5807 AngleInRadians: the angle of rotation (in radians) or a name of variable which defines angle in degrees
5808 Copy: allows copying the rotated elements
5809 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5812 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5815 if (isinstance(theObject, Mesh)):
5816 theObject = theObject.GetMesh()
5817 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
5818 Axis = self.smeshpyD.GetAxisStruct(Axis)
5819 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
5820 Parameters = Axis.parameters + ":" + Parameters
5821 self.mesh.SetParameters(Parameters)
5822 if Copy and MakeGroups:
5823 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
5824 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
5827 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
5829 Create a new mesh from the rotated object
5832 theObject: the object to rotate (mesh, submesh, or group)
5833 Axis: the axis of rotation (AxisStruct or geom line)
5834 AngleInRadians: the angle of rotation (in radians) or a name of variable which defines angle in degrees
5835 MakeGroups: forces the generation of new groups from existing ones
5836 NewMeshName: the name of the newly created mesh
5839 instance of Mesh class
5842 if (isinstance( theObject, Mesh )):
5843 theObject = theObject.GetMesh()
5844 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
5845 Axis = self.smeshpyD.GetAxisStruct(Axis)
5846 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
5847 Parameters = Axis.parameters + ":" + Parameters
5848 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
5849 MakeGroups, NewMeshName)
5850 self.mesh.SetParameters(Parameters)
5851 return Mesh( self.smeshpyD, self.geompyD, mesh )
5853 def Offset(self, theObject, theValue, MakeGroups=False, NewMeshName=''):
5855 Create an offset mesh from the given 2D object
5858 theObject: the source object (mesh, submesh, group or filter)
5859 theValue: signed offset size
5860 MakeGroups: forces the generation of new groups from existing ones
5861 NewMeshName: the name of a mesh to create. If empty, offset elements are added to this mesh
5864 A tuple (mesh, list_of_groups)
5867 if isinstance( theObject, Mesh ):
5868 theObject = theObject.GetMesh()
5869 theValue,Parameters,hasVars = ParseParameters(theValue)
5870 mesh_groups = self.editor.Offset(theObject, theValue, MakeGroups, NewMeshName )
5871 self.mesh.SetParameters(Parameters)
5872 # if mesh_groups[0]:
5873 # return Mesh( self.smeshpyD, self.geompyD, mesh_groups[0] ), mesh_groups[1]
5876 def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
5878 Find groups of adjacent nodes within Tolerance.
5881 Tolerance: the value of tolerance
5882 SeparateCornerAndMediumNodes: if *True*, in quadratic mesh puts
5883 corner and medium nodes in separate groups thus preventing
5884 their further merge.
5887 the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
5890 return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
5892 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
5893 exceptNodes=[], SeparateCornerAndMediumNodes=False):
5895 Find groups of ajacent nodes within Tolerance.
5898 Tolerance: the value of tolerance
5899 SubMeshOrGroup: SubMesh, Group or Filter
5900 exceptNodes: list of either SubMeshes, Groups or node IDs to exclude from search
5901 SeparateCornerAndMediumNodes: if *True*, in quadratic mesh puts
5902 corner and medium nodes in separate groups thus preventing
5903 their further merge.
5906 the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
5909 unRegister = genObjUnRegister()
5910 if (isinstance( SubMeshOrGroup, Mesh )):
5911 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
5912 if not isinstance( exceptNodes, list ):
5913 exceptNodes = [ exceptNodes ]
5914 if exceptNodes and isinstance( exceptNodes[0], int ):
5915 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
5916 unRegister.set( exceptNodes )
5917 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
5918 exceptNodes, SeparateCornerAndMediumNodes)
5920 def MergeNodes (self, GroupsOfNodes, NodesToKeep=[], AvoidMakingHoles=False):
5925 GroupsOfNodes: a list of groups of nodes IDs for merging
5926 (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
5927 by nodes 1 and 25 correspondingly in all elements and groups
5928 NodesToKeep: nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
5929 If *NodesToKeep* does not include a node to keep for some group to merge,
5930 then the first node in the group is kept.
5931 AvoidMakingHoles: prevent merging nodes which cause removal of elements becoming
5936 # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
5937 self.editor.MergeNodes( GroupsOfNodes, NodesToKeep, AvoidMakingHoles )
5939 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
5941 Find the elements built on the same nodes.
5944 MeshOrSubMeshOrGroup: Mesh or SubMesh, or Group of elements for searching
5947 the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
5950 if not MeshOrSubMeshOrGroup:
5951 MeshOrSubMeshOrGroup=self.mesh
5952 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
5953 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
5954 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
5956 def MergeElements(self, GroupsOfElementsID):
5958 Merge elements in each given group.
5961 GroupsOfElementsID: a list of groups of elements IDs for merging
5962 (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
5963 replaced by elements 1 and 25 in all groups)
5966 self.editor.MergeElements(GroupsOfElementsID)
5968 def MergeEqualElements(self):
5970 Leave one element and remove all other elements built on the same nodes.
5973 self.editor.MergeEqualElements()
5975 def FindFreeBorders(self, ClosedOnly=True):
5977 Returns all or only closed free borders
5980 list of SMESH.FreeBorder's
5983 return self.editor.FindFreeBorders( ClosedOnly )
5985 def FillHole(self, holeNodes):
5987 Fill with 2D elements a hole defined by a SMESH.FreeBorder.
5990 FreeBorder: either a SMESH.FreeBorder or a list on node IDs. These nodes
5991 must describe all sequential nodes of the hole border. The first and the last
5992 nodes must be the same. Use FindFreeBorders() to get nodes of holes.
5996 if holeNodes and isinstance( holeNodes, list ) and isinstance( holeNodes[0], int ):
5997 holeNodes = SMESH.FreeBorder(nodeIDs=holeNodes)
5998 if not isinstance( holeNodes, SMESH.FreeBorder ):
5999 raise TypeError, "holeNodes must be either SMESH.FreeBorder or list of integer and not %s" % holeNodes
6000 self.editor.FillHole( holeNodes )
6002 def FindCoincidentFreeBorders (self, tolerance=0.):
6004 Return groups of FreeBorder's coincident within the given tolerance.
6007 tolerance: the tolerance. If the tolerance <= 0.0 then one tenth of an average
6008 size of elements adjacent to free borders being compared is used.
6011 SMESH.CoincidentFreeBorders structure
6014 return self.editor.FindCoincidentFreeBorders( tolerance )
6016 def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
6018 Sew FreeBorder's of each group
6021 freeBorders: either a SMESH.CoincidentFreeBorders structure or a list of lists
6022 where each enclosed list contains node IDs of a group of coincident free
6023 borders such that each consequent triple of IDs within a group describes
6024 a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
6025 last node of a border.
6026 For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
6027 groups of coincident free borders, each group including two borders.
6028 createPolygons: if :code:`True` faces adjacent to free borders are converted to
6029 polygons if a node of opposite border falls on a face edge, else such
6030 faces are split into several ones.
6031 createPolyhedra: if :code:`True` volumes adjacent to free borders are converted to
6032 polyhedra if a node of opposite border falls on a volume edge, else such
6033 volumes, if any, remain intact and the mesh becomes non-conformal.
6036 a number of successfully sewed groups
6039 if freeBorders and isinstance( freeBorders, list ):
6040 # construct SMESH.CoincidentFreeBorders
6041 if isinstance( freeBorders[0], int ):
6042 freeBorders = [freeBorders]
6044 coincidentGroups = []
6045 for nodeList in freeBorders:
6046 if not nodeList or len( nodeList ) % 3:
6047 raise ValueError, "Wrong number of nodes in this group: %s" % nodeList
6050 group.append ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
6051 borders.append( SMESH.FreeBorder( nodeList[:3] ))
6052 nodeList = nodeList[3:]
6054 coincidentGroups.append( group )
6056 freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
6058 return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
6060 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
6061 FirstNodeID2, SecondNodeID2, LastNodeID2,
6062 CreatePolygons, CreatePolyedrs):
6070 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
6071 FirstNodeID2, SecondNodeID2, LastNodeID2,
6072 CreatePolygons, CreatePolyedrs)
6074 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
6075 FirstNodeID2, SecondNodeID2):
6077 Sew conform free borders
6083 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
6084 FirstNodeID2, SecondNodeID2)
6086 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
6087 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
6095 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
6096 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
6098 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
6099 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
6100 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
6102 Sew two sides of a mesh. The nodes belonging to Side1 are
6103 merged with the nodes of elements of Side2.
6104 The number of elements in theSide1 and in theSide2 must be
6105 equal and they should have similar nodal connectivity.
6106 The nodes to merge should belong to side borders and
6107 the first node should be linked to the second.
6113 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
6114 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
6115 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
6117 def ChangeElemNodes(self, ide, newIDs):
6119 Set new nodes for the given element.
6126 If the number of nodes does not correspond to the type of element - return false
6129 return self.editor.ChangeElemNodes(ide, newIDs)
6131 def GetLastCreatedNodes(self):
6133 If during the last operation of MeshEditor some nodes were
6134 created, this method return the list of their IDs, \n
6135 if new nodes were not created - return empty list
6138 the list of integer values (can be empty)
6141 return self.editor.GetLastCreatedNodes()
6143 def GetLastCreatedElems(self):
6145 If during the last operation of MeshEditor some elements were
6146 created this method return the list of their IDs, \n
6147 if new elements were not created - return empty list
6150 the list of integer values (can be empty)
6153 return self.editor.GetLastCreatedElems()
6155 def ClearLastCreated(self):
6157 Forget what nodes and elements were created by the last mesh edition operation
6160 self.editor.ClearLastCreated()
6162 def DoubleElements(self, theElements, theGroupName=""):
6164 Create duplicates of given elements, i.e. create new elements based on the
6165 same nodes as the given ones.
6168 theElements: container of elements to duplicate. It can be a Mesh,
6169 sub-mesh, group, filter or a list of element IDs. If *theElements* is
6170 a Mesh, elements of highest dimension are duplicated
6171 theGroupName: a name of group to contain the generated elements.
6172 If a group with such a name already exists, the new elements
6173 are added to the existng group, else a new group is created.
6174 If *theGroupName* is empty, new elements are not added
6178 a group where the new elements are added. None if theGroupName == "".
6181 unRegister = genObjUnRegister()
6182 if isinstance( theElements, Mesh ):
6183 theElements = theElements.mesh
6184 elif isinstance( theElements, list ):
6185 theElements = self.GetIDSource( theElements, SMESH.ALL )
6186 unRegister.set( theElements )
6187 return self.editor.DoubleElements(theElements, theGroupName)
6189 def DoubleNodes(self, theNodes, theModifiedElems):
6191 Create a hole in a mesh by doubling the nodes of some particular elements
6194 theNodes: identifiers of nodes to be doubled
6195 theModifiedElems: identifiers of elements to be updated by the new (doubled)
6196 nodes. If list of element identifiers is empty then nodes are doubled but
6197 they not assigned to elements
6200 TRUE if operation has been completed successfully, FALSE otherwise
6203 return self.editor.DoubleNodes(theNodes, theModifiedElems)
6205 def DoubleNode(self, theNodeId, theModifiedElems):
6207 Create a hole in a mesh by doubling the nodes of some particular elements
6208 This method provided for convenience works as DoubleNodes() described above.
6211 theNodeId: identifiers of node to be doubled
6212 theModifiedElems: identifiers of elements to be updated
6215 TRUE if operation has been completed successfully, FALSE otherwise
6218 return self.editor.DoubleNode(theNodeId, theModifiedElems)
6220 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
6222 Create a hole in a mesh by doubling the nodes of some particular elements
6223 This method provided for convenience works as DoubleNodes() described above.
6226 theNodes: group of nodes to be doubled
6227 theModifiedElems: group of elements to be updated.
6228 theMakeGroup: forces the generation of a group containing new nodes.
6231 TRUE or a created group if operation has been completed successfully,
6232 FALSE or None otherwise
6236 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
6237 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
6239 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
6241 Create a hole in a mesh by doubling the nodes of some particular elements
6242 This method provided for convenience works as DoubleNodes() described above.
6245 theNodes: list of groups of nodes to be doubled
6246 theModifiedElems: list of groups of elements to be updated.
6247 theMakeGroup: forces the generation of a group containing new nodes.
6250 TRUE if operation has been completed successfully, FALSE otherwise
6254 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
6255 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
6257 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
6259 Create a hole in a mesh by doubling the nodes of some particular elements
6262 theElems: the list of elements (edges or faces) to be replicated
6263 The nodes for duplication could be found from these elements
6264 theNodesNot: list of nodes to NOT replicate
6265 theAffectedElems: the list of elements (cells and edges) to which the
6266 replicated nodes should be associated to.
6269 TRUE if operation has been completed successfully, FALSE otherwise
6272 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
6274 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
6276 Create a hole in a mesh by doubling the nodes of some particular elements
6279 theElems: the list of elements (edges or faces) to be replicated
6280 The nodes for duplication could be found from these elements
6281 theNodesNot: list of nodes to NOT replicate
6282 theShape: shape to detect affected elements (element which geometric center
6283 located on or inside shape).
6284 The replicated nodes should be associated to affected elements.
6287 TRUE if operation has been completed successfully, FALSE otherwise
6290 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
6292 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
6293 theMakeGroup=False, theMakeNodeGroup=False):
6295 Create a hole in a mesh by doubling the nodes of some particular elements
6296 This method provided for convenience works as DoubleNodes() described above.
6299 theElems: group of of elements (edges or faces) to be replicated
6300 theNodesNot: group of nodes not to replicated
6301 theAffectedElems: group of elements to which the replicated nodes
6302 should be associated to.
6303 theMakeGroup: forces the generation of a group containing new elements.
6304 theMakeNodeGroup: forces the generation of a group containing new nodes.
6307 TRUE or created groups (one or two) if operation has been completed successfully,
6308 FALSE or None otherwise
6311 if theMakeGroup or theMakeNodeGroup:
6312 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
6314 theMakeGroup, theMakeNodeGroup)
6315 if theMakeGroup and theMakeNodeGroup:
6318 return twoGroups[ int(theMakeNodeGroup) ]
6319 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
6321 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
6323 Create a hole in a mesh by doubling the nodes of some particular elements
6324 This method provided for convenience works as DoubleNodes() described above.
6327 theElems: group of of elements (edges or faces) to be replicated
6328 theNodesNot: group of nodes not to replicated
6329 theShape: shape to detect affected elements (element which geometric center
6330 located on or inside shape).
6331 The replicated nodes should be associated to affected elements.
6334 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
6336 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
6337 theMakeGroup=False, theMakeNodeGroup=False):
6339 Create a hole in a mesh by doubling the nodes of some particular elements
6340 This method provided for convenience works as DoubleNodes() described above.
6343 theElems: list of groups of elements (edges or faces) to be replicated
6344 theNodesNot: list of groups of nodes not to replicated
6345 theAffectedElems: group of elements to which the replicated nodes
6346 should be associated to.
6347 theMakeGroup: forces the generation of a group containing new elements.
6348 theMakeNodeGroup: forces the generation of a group containing new nodes.
6351 TRUE or created groups (one or two) if operation has been completed successfully,
6352 FALSE or None otherwise
6355 if theMakeGroup or theMakeNodeGroup:
6356 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
6358 theMakeGroup, theMakeNodeGroup)
6359 if theMakeGroup and theMakeNodeGroup:
6362 return twoGroups[ int(theMakeNodeGroup) ]
6363 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
6365 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
6367 Create a hole in a mesh by doubling the nodes of some particular elements
6368 This method provided for convenience works as DoubleNodes() described above.
6371 theElems: list of groups of elements (edges or faces) to be replicated
6372 theNodesNot: list of groups of nodes not to replicated
6373 theShape: shape to detect affected elements (element which geometric center
6374 located on or inside shape).
6375 The replicated nodes should be associated to affected elements.
6378 TRUE if operation has been completed successfully, FALSE otherwise
6381 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
6383 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
6385 Identify the elements that will be affected by node duplication (actual duplication is not performed.
6386 This method is the first step of DoubleNodeElemGroupsInRegion.
6389 theElems: list of groups of nodes or elements (edges or faces) to be replicated
6390 theNodesNot: list of groups of nodes not to replicated
6391 theShape: shape to detect affected elements (element which geometric center
6392 located on or inside shape).
6393 The replicated nodes should be associated to affected elements.
6396 groups of affected elements in order:: volumes, faces, edges
6399 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
6401 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
6403 Double nodes on shared faces between groups of volumes and create flat elements on demand.
6404 The list of groups must describe a partition of the mesh volumes.
6405 The nodes of the internal faces at the boundaries of the groups are doubled.
6406 In option, the internal faces are replaced by flat elements.
6407 Triangles are transformed in prisms, and quadrangles in hexahedrons.
6410 theDomains: list of groups of volumes
6411 createJointElems: if TRUE, create the elements
6412 onAllBoundaries: if TRUE, the nodes and elements are also created on
6413 the boundary between *theDomains* and the rest mesh
6416 TRUE if operation has been completed successfully, FALSE otherwise
6419 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
6421 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
6423 Double nodes on some external faces and create flat elements.
6424 Flat elements are mainly used by some types of mechanic calculations.
6426 Each group of the list must be constituted of faces.
6427 Triangles are transformed in prisms, and quadrangles in hexahedrons.
6430 theGroupsOfFaces: list of groups of faces
6433 TRUE if operation has been completed successfully, FALSE otherwise
6436 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
6438 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
6440 identify all the elements around a geom shape, get the faces delimiting the hole
6442 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
6444 def MakePolyLine(self, segments, groupName='', isPreview=False ):
6446 Create a polyline consisting of 1D mesh elements each lying on a 2D element of
6447 the initial mesh. Positions of new nodes are found by cutting the mesh by the
6448 plane passing through pairs of points specified by each PolySegment structure.
6449 If there are several paths connecting a pair of points, the shortest path is
6450 selected by the module. Position of the cutting plane is defined by the two
6451 points and an optional vector lying on the plane specified by a PolySegment.
6452 By default the vector is defined by Mesh module as following. A middle point
6453 of the two given points is computed. The middle point is projected to the mesh.
6454 The vector goes from the middle point to the projection point. In case of planar
6455 mesh, the vector is normal to the mesh.
6458 segments - PolySegment's defining positions of cutting planes.
6459 groupName - optional name of a group where created mesh segments will
6463 The used vector which goes from the middle point to its projection.
6465 editor = self.editor
6467 editor = self.mesh.GetMeshEditPreviewer()
6468 segmentsRes = editor.MakePolyLine( segments, groupName )
6469 for i, seg in enumerate( segmentsRes ):
6470 segments[i].vector = seg.vector
6472 return editor.GetPreviewData()
6475 def GetFunctor(self, funcType ):
6477 Return a cached numerical functor by its type.
6480 theCriterion functor type: an item of SMESH.FunctorType enumeration.
6481 Type SMESH.FunctorType._items in the Python Console to see all items.
6482 Note that not all items correspond to numerical functors.
6485 SMESH_NumericalFunctor. The functor is already initialized
6489 fn = self.functors[ funcType._v ]
6491 fn = self.smeshpyD.GetFunctor(funcType)
6492 fn.SetMesh(self.mesh)
6493 self.functors[ funcType._v ] = fn
6496 def FunctorValue(self, funcType, elemId, isElem=True):
6498 Return value of a functor for a given element
6501 funcType: an item of SMESH.FunctorType enum
6502 Type "SMESH.FunctorType._items" in the Python Console to see all items.
6503 elemId: element or node ID
6504 isElem: *elemId* is ID of element or node
6507 the functor value or zero in case of invalid arguments
6510 fn = self.GetFunctor( funcType )
6511 if fn.GetElementType() == self.GetElementType(elemId, isElem):
6512 val = fn.GetValue(elemId)
6517 def GetLength(self, elemId=None):
6519 Get length of 1D element or sum of lengths of all 1D mesh elements
6522 elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
6525 element's length value if *elemId* is specified or sum of all 1D mesh elements' lengths otherwise
6530 length = self.smeshpyD.GetLength(self)
6532 length = self.FunctorValue(SMESH.FT_Length, elemId)
6535 def GetArea(self, elemId=None):
6537 Get area of 2D element or sum of areas of all 2D mesh elements
6538 elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
6541 element's area value if *elemId* is specified or sum of all 2D mesh elements' areas otherwise
6546 area = self.smeshpyD.GetArea(self)
6548 area = self.FunctorValue(SMESH.FT_Area, elemId)
6551 def GetVolume(self, elemId=None):
6553 Get volume of 3D element or sum of volumes of all 3D mesh elements
6554 elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
6557 element's volume value if *elemId* is specified or sum of all 3D mesh elements' volumes otherwise
6562 volume = self.smeshpyD.GetVolume(self)
6564 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
6567 def GetMaxElementLength(self, elemId):
6569 Get maximum element length.
6572 elemId mesh element ID
6575 element's maximum length value
6578 if self.GetElementType(elemId, True) == SMESH.VOLUME:
6579 ftype = SMESH.FT_MaxElementLength3D
6581 ftype = SMESH.FT_MaxElementLength2D
6582 return self.FunctorValue(ftype, elemId)
6584 def GetAspectRatio(self, elemId):
6586 Get aspect ratio of 2D or 3D element.
6589 elemId mesh element ID
6592 element's aspect ratio value
6595 if self.GetElementType(elemId, True) == SMESH.VOLUME:
6596 ftype = SMESH.FT_AspectRatio3D
6598 ftype = SMESH.FT_AspectRatio
6599 return self.FunctorValue(ftype, elemId)
6601 def GetWarping(self, elemId):
6603 Get warping angle of 2D element.
6606 elemId mesh element ID
6609 element's warping angle value
6612 return self.FunctorValue(SMESH.FT_Warping, elemId)
6614 def GetMinimumAngle(self, elemId):
6616 Get minimum angle of 2D element.
6619 elemId mesh element ID
6622 element's minimum angle value
6625 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
6627 def GetTaper(self, elemId):
6629 Get taper of 2D element.
6632 elemId mesh element ID
6635 element's taper value
6638 return self.FunctorValue(SMESH.FT_Taper, elemId)
6640 def GetSkew(self, elemId):
6642 Get skew of 2D element.
6645 elemId mesh element ID
6648 element's skew value
6651 return self.FunctorValue(SMESH.FT_Skew, elemId)
6653 def GetMinMax(self, funType, meshPart=None):
6655 Return minimal and maximal value of a given functor.
6658 funType a functor type, an item of SMESH.FunctorType enum
6659 (one of SMESH.FunctorType._items)
6660 meshPart a part of mesh (group, sub-mesh) to treat
6666 unRegister = genObjUnRegister()
6667 if isinstance( meshPart, list ):
6668 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
6669 unRegister.set( meshPart )
6670 if isinstance( meshPart, Mesh ):
6671 meshPart = meshPart.mesh
6672 fun = self.GetFunctor( funType )
6675 if hasattr( meshPart, "SetMesh" ):
6676 meshPart.SetMesh( self.mesh ) # set mesh to filter
6677 hist = fun.GetLocalHistogram( 1, False, meshPart )
6679 hist = fun.GetHistogram( 1, False )
6681 return hist[0].min, hist[0].max
6684 pass # end of Mesh class
6687 class meshProxy(SMESH._objref_SMESH_Mesh):
6689 Private class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
6690 with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
6693 SMESH._objref_SMESH_Mesh.__init__(self)
6694 def __deepcopy__(self, memo=None):
6695 new = self.__class__()
6697 def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
6698 if len( args ) == 3:
6699 args += SMESH.ALL_NODES, True
6700 return SMESH._objref_SMESH_Mesh.CreateDimGroup( self, *args )
6702 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
6705 class submeshProxy(SMESH._objref_SMESH_subMesh):
6707 Private class wrapping SMESH.SMESH_SubMesh in order to add Compute()
6710 SMESH._objref_SMESH_subMesh.__init__(self)
6712 def __deepcopy__(self, memo=None):
6713 new = self.__class__()
6716 def Compute(self,refresh=False):
6718 Compute the sub-mesh and return the status of the computation
6719 refresh if *True*, Object browser is automatically updated (when running in GUI)
6723 This is a method of SMESH.SMESH_submesh that can be obtained via Mesh.GetSubMesh() or
6724 :meth:`smeshBuilder.Mesh.GetSubMesh`.
6728 self.mesh = Mesh( smeshBuilder(), None, self.GetMesh())
6730 ok = self.mesh.Compute( self.GetSubShape(),refresh=[] )
6732 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
6733 smeshgui = salome.ImportComponentGUI("SMESH")
6734 smeshgui.Init(self.mesh.GetStudyId())
6735 smeshgui.SetMeshIcon( salome.ObjectToID( self ), ok, (self.GetNumberOfElements()==0) )
6736 if refresh: salome.sg.updateObjBrowser(True)
6741 omniORB.registerObjref(SMESH._objref_SMESH_subMesh._NP_RepositoryId, submeshProxy)
6744 class meshEditor(SMESH._objref_SMESH_MeshEditor):
6746 Private class used to compensate change of CORBA API of SMESH_MeshEditor for backward
6747 compatibility with old dump scripts which call SMESH_MeshEditor directly and not via
6751 SMESH._objref_SMESH_MeshEditor.__init__(self)
6753 def __getattr__(self, name ): # method called if an attribute not found
6754 if not self.mesh: # look for name() method in Mesh class
6755 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
6756 if hasattr( self.mesh, name ):
6757 return getattr( self.mesh, name )
6758 if name == "ExtrusionAlongPathObjX":
6759 return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
6760 print "meshEditor: attribute '%s' NOT FOUND" % name
6762 def __deepcopy__(self, memo=None):
6763 new = self.__class__()
6765 def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
6766 if len( args ) == 1: args += False,
6767 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
6768 def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
6769 if len( args ) == 2: args += False,
6770 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
6771 def MergeNodes(self,*args): # 2 args added (NodesToKeep,AvoidMakingHoles)
6772 if len( args ) == 1:
6773 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [], False )
6774 NodesToKeep = args[1]
6775 AvoidMakingHoles = args[2] if len( args ) == 3 else False
6776 unRegister = genObjUnRegister()
6778 if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
6779 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
6780 if not isinstance( NodesToKeep, list ):
6781 NodesToKeep = [ NodesToKeep ]
6782 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep, AvoidMakingHoles )
6784 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
6786 class Pattern(SMESH._objref_SMESH_Pattern):
6788 Private class wrapping SMESH.SMESH_Pattern CORBA class in order to treat Notebook
6789 variables in some methods
6792 def LoadFromFile(self, patternTextOrFile ):
6793 text = patternTextOrFile
6794 if os.path.exists( text ):
6795 text = open( patternTextOrFile ).read()
6797 return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
6799 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
6800 decrFun = lambda i: i-1
6801 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
6802 theMesh.SetParameters(Parameters)
6803 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
6805 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
6806 decrFun = lambda i: i-1
6807 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
6808 theMesh.SetParameters(Parameters)
6809 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
6811 def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
6812 if isinstance( mesh, Mesh ):
6813 mesh = mesh.GetMesh()
6814 return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
6816 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
6818 Registering the new proxy for Pattern
6823 Private class used to bind methods creating algorithms to the class Mesh
6826 def __init__(self, method):
6828 self.defaultAlgoType = ""
6829 self.algoTypeToClass = {}
6830 self.method = method
6832 def add(self, algoClass):
6834 Store a python class of algorithm
6836 if type( algoClass ).__name__ == 'classobj' and \
6837 hasattr( algoClass, "algoType"):
6838 self.algoTypeToClass[ algoClass.algoType ] = algoClass
6839 if not self.defaultAlgoType and \
6840 hasattr( algoClass, "isDefault") and algoClass.isDefault:
6841 self.defaultAlgoType = algoClass.algoType
6842 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
6844 def copy(self, mesh):
6846 Create a copy of self and assign mesh to the copy
6849 other = algoCreator( self.method )
6850 other.defaultAlgoType = self.defaultAlgoType
6851 other.algoTypeToClass = self.algoTypeToClass
6855 def __call__(self,algo="",geom=0,*args):
6857 Create an instance of algorithm
6861 if isinstance( algo, str ):
6863 elif ( isinstance( algo, geomBuilder.GEOM._objref_GEOM_Object ) and \
6864 not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object )):
6869 if isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
6871 elif not algoType and isinstance( geom, str ):
6876 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ) and not shape:
6878 elif isinstance( arg, str ) and not algoType:
6881 import traceback, sys
6882 msg = "Warning. Unexpected argument in mesh.%s() ---> %s" % ( self.method, arg )
6883 sys.stderr.write( msg + '\n' )
6884 tb = traceback.extract_stack(None,2)
6885 traceback.print_list( [tb[0]] )
6887 algoType = self.defaultAlgoType
6888 if not algoType and self.algoTypeToClass:
6889 algoType = sorted( self.algoTypeToClass.keys() )[0]
6890 if self.algoTypeToClass.has_key( algoType ):
6891 #print "Create algo",algoType
6892 return self.algoTypeToClass[ algoType ]( self.mesh, shape )
6893 raise RuntimeError, "No class found for algo type %s" % algoType
6896 class hypMethodWrapper:
6898 Private class used to substitute and store variable parameters of hypotheses.
6901 def __init__(self, hyp, method):
6903 self.method = method
6904 #print "REBIND:", method.__name__
6907 def __call__(self,*args):
6909 call a method of hypothesis with calling SetVarParameter() before
6913 return self.method( self.hyp, *args ) # hypothesis method with no args
6915 #print "MethWrapper.__call__",self.method.__name__, args
6917 parsed = ParseParameters(*args) # replace variables with their values
6918 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
6919 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
6920 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
6921 # maybe there is a replaced string arg which is not variable
6922 result = self.method( self.hyp, *args )
6923 except ValueError, detail: # raised by ParseParameters()
6925 result = self.method( self.hyp, *args )
6926 except omniORB.CORBA.BAD_PARAM:
6927 raise ValueError, detail # wrong variable name
6932 class genObjUnRegister:
6934 A helper class that calls UnRegister() of SALOME.GenericObj'es stored in it
6937 def __init__(self, genObj=None):
6938 self.genObjList = []
6942 def set(self, genObj):
6943 "Store one or a list of of SALOME.GenericObj'es"
6944 if isinstance( genObj, list ):
6945 self.genObjList.extend( genObj )
6947 self.genObjList.append( genObj )
6951 for genObj in self.genObjList:
6952 if genObj and hasattr( genObj, "UnRegister" ):
6955 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
6957 Bind methods creating mesher plug-ins to the Mesh class
6960 # print "pluginName: ", pluginName
6961 pluginBuilderName = pluginName + "Builder"
6963 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
6964 except Exception, e:
6965 from salome_utils import verbose
6966 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
6968 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
6969 plugin = eval( pluginBuilderName )
6970 # print " plugin:" , str(plugin)
6972 # add methods creating algorithms to Mesh
6973 for k in dir( plugin ):
6974 if k[0] == '_': continue
6975 algo = getattr( plugin, k )
6976 # print " algo:", str(algo)
6977 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
6978 # print " meshMethod:" , str(algo.meshMethod)
6979 if not hasattr( Mesh, algo.meshMethod ):
6980 setattr( Mesh, algo.meshMethod, algoCreator( algo.meshMethod ))
6982 _mmethod = getattr( Mesh, algo.meshMethod )
6983 if hasattr( _mmethod, "add" ):