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 GetSubShapesId( self, theMainObject, theListOfSubObjects ):
699 Return IDs of sub-shapes
702 the list of integer values
705 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
707 def GetPattern(self):
709 Create a pattern mapper.
712 an instance of SMESH_Pattern
714 `Example of Patterns usage <../tui_modifying_meshes_page.html#tui_pattern_mapping>`_
717 return SMESH._objref_SMESH_Gen.GetPattern(self)
719 def SetBoundaryBoxSegmentation(self, nbSegments):
721 Set number of segments per diagonal of boundary box of geometry, by which
722 default segment length of appropriate 1D hypotheses is defined in GUI.
726 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
728 # Filtering. Auxiliary functions:
729 # ------------------------------
731 def GetEmptyCriterion(self):
733 Create an empty criterion
736 SMESH.Filter.Criterion
739 Type = self.EnumToLong(FT_Undefined)
740 Compare = self.EnumToLong(FT_Undefined)
744 UnaryOp = self.EnumToLong(FT_Undefined)
745 BinaryOp = self.EnumToLong(FT_Undefined)
748 Precision = -1 ##@1e-07
749 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
750 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
752 def GetCriterion(self,elementType,
754 Compare = FT_EqualTo,
756 UnaryOp=FT_Undefined,
757 BinaryOp=FT_Undefined,
760 Create a criterion by the given parameters
761 Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
764 elementType: the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
765 CritType: the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
766 Type SMESH.FunctorType._items in the Python Console to see all values.
767 Note that the items starting from FT_LessThan are not suitable for CritType.
768 Compare: belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
769 Threshold: the threshold value (range of ids as string, shape, numeric)
770 UnaryOp: SMESH.FT_LogicalNOT or SMESH.FT_Undefined
771 BinaryOp: a binary logical operation SMESH.FT_LogicalAND, SMESH.FT_LogicalOR or
773 Tolerance: the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
774 SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
777 SMESH.Filter.Criterion
779 href="../tui_filters_page.html#combining_filters"
782 if not CritType in SMESH.FunctorType._items:
783 raise TypeError, "CritType should be of SMESH.FunctorType"
784 aCriterion = self.GetEmptyCriterion()
785 aCriterion.TypeOfElement = elementType
786 aCriterion.Type = self.EnumToLong(CritType)
787 aCriterion.Tolerance = Tolerance
789 aThreshold = Threshold
791 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
792 aCriterion.Compare = self.EnumToLong(Compare)
793 elif Compare == "=" or Compare == "==":
794 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
796 aCriterion.Compare = self.EnumToLong(FT_LessThan)
798 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
799 elif Compare != FT_Undefined:
800 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
803 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
804 FT_BelongToCylinder, FT_LyingOnGeom]:
805 # Check that Threshold is GEOM object
806 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
807 aCriterion.ThresholdStr = GetName(aThreshold)
808 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
809 if not aCriterion.ThresholdID:
810 name = aCriterion.ThresholdStr
812 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
813 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
814 # or a name of GEOM object
815 elif isinstance( aThreshold, str ):
816 aCriterion.ThresholdStr = aThreshold
818 raise TypeError, "The Threshold should be a shape."
819 if isinstance(UnaryOp,float):
820 aCriterion.Tolerance = UnaryOp
821 UnaryOp = FT_Undefined
823 elif CritType == FT_BelongToMeshGroup:
824 # Check that Threshold is a group
825 if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
826 if aThreshold.GetType() != elementType:
827 raise ValueError, "Group type mismatches Element type"
828 aCriterion.ThresholdStr = aThreshold.GetName()
829 aCriterion.ThresholdID = salome.orb.object_to_string( aThreshold )
830 study = self.GetCurrentStudy()
832 so = study.FindObjectIOR( aCriterion.ThresholdID )
836 aCriterion.ThresholdID = entry
838 raise TypeError, "The Threshold should be a Mesh Group"
839 elif CritType == FT_RangeOfIds:
840 # Check that Threshold is string
841 if isinstance(aThreshold, str):
842 aCriterion.ThresholdStr = aThreshold
844 raise TypeError, "The Threshold should be a string."
845 elif CritType == FT_CoplanarFaces:
846 # Check the Threshold
847 if isinstance(aThreshold, int):
848 aCriterion.ThresholdID = str(aThreshold)
849 elif isinstance(aThreshold, str):
852 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
853 aCriterion.ThresholdID = aThreshold
856 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
857 elif CritType == FT_ConnectedElements:
858 # Check the Threshold
859 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
860 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
861 if not aCriterion.ThresholdID:
862 name = aThreshold.GetName()
864 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
865 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
866 elif isinstance(aThreshold, int): # node id
867 aCriterion.Threshold = aThreshold
868 elif isinstance(aThreshold, list): # 3 point coordinates
869 if len( aThreshold ) < 3:
870 raise ValueError, "too few point coordinates, must be 3"
871 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
872 elif isinstance(aThreshold, str):
873 if aThreshold.isdigit():
874 aCriterion.Threshold = aThreshold # node id
876 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
879 "The Threshold should either a VERTEX, or a node ID, "\
880 "or a list of point coordinates and not '%s'"%aThreshold
881 elif CritType == FT_ElemGeomType:
882 # Check the Threshold
884 aCriterion.Threshold = self.EnumToLong(aThreshold)
885 assert( aThreshold in SMESH.GeometryType._items )
887 if isinstance(aThreshold, int):
888 aCriterion.Threshold = aThreshold
890 raise TypeError, "The Threshold should be an integer or SMESH.GeometryType."
893 elif CritType == FT_EntityType:
894 # Check the Threshold
896 aCriterion.Threshold = self.EnumToLong(aThreshold)
897 assert( aThreshold in SMESH.EntityType._items )
899 if isinstance(aThreshold, int):
900 aCriterion.Threshold = aThreshold
902 raise TypeError, "The Threshold should be an integer or SMESH.EntityType."
906 elif CritType == FT_GroupColor:
907 # Check the Threshold
909 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
911 raise TypeError, "The threshold value should be of SALOMEDS.Color type"
913 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
914 FT_LinearOrQuadratic, FT_BadOrientedVolume,
915 FT_BareBorderFace, FT_BareBorderVolume,
916 FT_OverConstrainedFace, FT_OverConstrainedVolume,
917 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
918 # At this point the Threshold is unnecessary
919 if aThreshold == FT_LogicalNOT:
920 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
921 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
922 aCriterion.BinaryOp = aThreshold
926 aThreshold = float(aThreshold)
927 aCriterion.Threshold = aThreshold
929 raise TypeError, "The Threshold should be a number."
932 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
933 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
935 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
936 aCriterion.BinaryOp = self.EnumToLong(Threshold)
938 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
939 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
941 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
942 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
946 def GetFilter(self,elementType,
947 CritType=FT_Undefined,
950 UnaryOp=FT_Undefined,
954 Create a filter with the given parameters
957 elementType: the type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
958 CritType: the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
959 Type SMESH.FunctorType._items in the Python Console to see all values.
960 Note that the items starting from FT_LessThan are not suitable for CritType.
961 Compare: belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
962 Threshold: the threshold value (range of ids as string, shape, numeric)
963 UnaryOp: SMESH.FT_LogicalNOT or SMESH.FT_Undefined
964 Tolerance: the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
965 SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces and SMESH.FT_EqualNodes criteria
966 mesh: the mesh to initialize the filter with
971 `Example of Filters usage <../tui_filters_page.html#tui_filters>`_
974 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
975 aFilterMgr = self.CreateFilterManager()
976 aFilter = aFilterMgr.CreateFilter()
978 aCriteria.append(aCriterion)
979 aFilter.SetCriteria(aCriteria)
981 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
982 else : aFilter.SetMesh( mesh )
983 aFilterMgr.UnRegister()
986 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
988 Create a filter from criteria
991 criteria: a list of criteria
992 binOp: binary operator used when binary operator of criteria is undefined
997 `Example of Filters usage <../tui_filters_page.html#tui_filters>`_
1000 for i in range( len( criteria ) - 1 ):
1001 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
1002 criteria[i].BinaryOp = self.EnumToLong( binOp )
1003 aFilterMgr = self.CreateFilterManager()
1004 aFilter = aFilterMgr.CreateFilter()
1005 aFilter.SetCriteria(criteria)
1006 aFilterMgr.UnRegister()
1009 def GetFunctor(self,theCriterion):
1011 Create a numerical functor by its type
1014 theCriterion: functor type - an item of SMESH.FunctorType enumeration.
1015 Type SMESH.FunctorType._items in the Python Console to see all items.
1016 Note that not all items correspond to numerical functors.
1019 SMESH_NumericalFunctor
1022 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
1024 aFilterMgr = self.CreateFilterManager()
1026 if theCriterion == FT_AspectRatio:
1027 functor = aFilterMgr.CreateAspectRatio()
1028 elif theCriterion == FT_AspectRatio3D:
1029 functor = aFilterMgr.CreateAspectRatio3D()
1030 elif theCriterion == FT_Warping:
1031 functor = aFilterMgr.CreateWarping()
1032 elif theCriterion == FT_MinimumAngle:
1033 functor = aFilterMgr.CreateMinimumAngle()
1034 elif theCriterion == FT_Taper:
1035 functor = aFilterMgr.CreateTaper()
1036 elif theCriterion == FT_Skew:
1037 functor = aFilterMgr.CreateSkew()
1038 elif theCriterion == FT_Area:
1039 functor = aFilterMgr.CreateArea()
1040 elif theCriterion == FT_Volume3D:
1041 functor = aFilterMgr.CreateVolume3D()
1042 elif theCriterion == FT_MaxElementLength2D:
1043 functor = aFilterMgr.CreateMaxElementLength2D()
1044 elif theCriterion == FT_MaxElementLength3D:
1045 functor = aFilterMgr.CreateMaxElementLength3D()
1046 elif theCriterion == FT_MultiConnection:
1047 functor = aFilterMgr.CreateMultiConnection()
1048 elif theCriterion == FT_MultiConnection2D:
1049 functor = aFilterMgr.CreateMultiConnection2D()
1050 elif theCriterion == FT_Length:
1051 functor = aFilterMgr.CreateLength()
1052 elif theCriterion == FT_Length2D:
1053 functor = aFilterMgr.CreateLength2D()
1054 elif theCriterion == FT_Deflection2D:
1055 functor = aFilterMgr.CreateDeflection2D()
1056 elif theCriterion == FT_NodeConnectivityNumber:
1057 functor = aFilterMgr.CreateNodeConnectivityNumber()
1058 elif theCriterion == FT_BallDiameter:
1059 functor = aFilterMgr.CreateBallDiameter()
1061 print "Error: given parameter is not numerical functor type."
1062 aFilterMgr.UnRegister()
1065 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
1070 theHType: mesh hypothesis type (string)
1071 theLibName: mesh plug-in library name
1074 created hypothesis instance
1076 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
1078 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
1081 # wrap hypothesis methods
1082 #print "HYPOTHESIS", theHType
1083 for meth_name in dir( hyp.__class__ ):
1084 if not meth_name.startswith("Get") and \
1085 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
1086 method = getattr ( hyp.__class__, meth_name )
1087 if callable(method):
1088 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
1092 def GetMeshInfo(self, obj):
1094 Get the mesh statistic
1097 dictionary "element type" - "count of elements"
1100 if isinstance( obj, Mesh ):
1103 if hasattr(obj, "GetMeshInfo"):
1104 values = obj.GetMeshInfo()
1105 for i in range(SMESH.Entity_Last._v):
1106 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1110 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1112 Get minimum distance between two objects
1114 If *src2* is None, and *id2* = 0, distance from *src1* / *id1* to the origin is computed.
1115 If *src2* None, and *id2* != 0, it is assumed that both *id1* and *id2* belong to *src1*.
1118 src1: first source object
1119 src2: second source object
1120 id1: node/element id from the first source
1121 id2: node/element id from the second (or first) source
1122 isElem1: *True* if *id1* is element id, *False* if it is node id
1123 isElem2: *True* if *id2* is element id, *False* if it is node id
1126 minimum distance value *GetMinDistance()*
1129 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1133 result = result.value
1136 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1138 Get measure structure specifying minimum distance data between two objects
1140 If *src2* is None, and *id2* = 0, distance from *src1* / *id1* to the origin is computed.
1141 If *src2* is None, and *id2* != 0, it is assumed that both *id1* and *id2* belong to *src1*.
1145 src1: first source object
1146 src2: second source object
1147 id1: node/element id from the first source
1148 id2: node/element id from the second (or first) source
1149 isElem1: *True* if **id1** is element id, *False* if it is node id
1150 isElem2: *True* if **id2** is element id, *False* if it is node id
1153 Measure structure or None if input data is invalid **MinDistance()**
1156 if isinstance(src1, Mesh): src1 = src1.mesh
1157 if isinstance(src2, Mesh): src2 = src2.mesh
1158 if src2 is None and id2 != 0: src2 = src1
1159 if not hasattr(src1, "_narrow"): return None
1160 src1 = src1._narrow(SMESH.SMESH_IDSource)
1161 if not src1: return None
1162 unRegister = genObjUnRegister()
1165 e = m.GetMeshEditor()
1167 src1 = e.MakeIDSource([id1], SMESH.FACE)
1169 src1 = e.MakeIDSource([id1], SMESH.NODE)
1170 unRegister.set( src1 )
1172 if hasattr(src2, "_narrow"):
1173 src2 = src2._narrow(SMESH.SMESH_IDSource)
1174 if src2 and id2 != 0:
1176 e = m.GetMeshEditor()
1178 src2 = e.MakeIDSource([id2], SMESH.FACE)
1180 src2 = e.MakeIDSource([id2], SMESH.NODE)
1181 unRegister.set( src2 )
1184 aMeasurements = self.CreateMeasurements()
1185 unRegister.set( aMeasurements )
1186 result = aMeasurements.MinDistance(src1, src2)
1189 def BoundingBox(self, objects):
1191 Get bounding box of the specified object(s)
1194 objects: single source object or list of source objects
1197 tuple of six values (minX, minY, minZ, maxX, maxY, maxZ) **GetBoundingBox()**
1200 result = self.GetBoundingBox(objects)
1204 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1207 def GetBoundingBox(self, objects):
1209 Get measure structure specifying bounding box data of the specified object(s)
1212 objects: single source object or list of source objects
1215 Measure structure **BoundingBox()**
1218 if isinstance(objects, tuple):
1219 objects = list(objects)
1220 if not isinstance(objects, list):
1224 if isinstance(o, Mesh):
1225 srclist.append(o.mesh)
1226 elif hasattr(o, "_narrow"):
1227 src = o._narrow(SMESH.SMESH_IDSource)
1228 if src: srclist.append(src)
1231 aMeasurements = self.CreateMeasurements()
1232 result = aMeasurements.BoundingBox(srclist)
1233 aMeasurements.UnRegister()
1236 def GetLength(self, obj):
1238 Get sum of lengths of all 1D elements in the mesh object.
1241 obj: mesh, submesh or group
1244 sum of lengths of all 1D elements
1247 if isinstance(obj, Mesh): obj = obj.mesh
1248 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1249 aMeasurements = self.CreateMeasurements()
1250 value = aMeasurements.Length(obj)
1251 aMeasurements.UnRegister()
1254 def GetArea(self, obj):
1256 Get sum of areas of all 2D elements in the mesh object.
1259 obj: mesh, submesh or group
1262 sum of areas of all 2D elements
1265 if isinstance(obj, Mesh): obj = obj.mesh
1266 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1267 aMeasurements = self.CreateMeasurements()
1268 value = aMeasurements.Area(obj)
1269 aMeasurements.UnRegister()
1272 def GetVolume(self, obj):
1274 Get sum of volumes of all 3D elements in the mesh object.
1277 obj: mesh, submesh or group
1280 sum of volumes of all 3D elements
1283 if isinstance(obj, Mesh): obj = obj.mesh
1284 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1285 aMeasurements = self.CreateMeasurements()
1286 value = aMeasurements.Volume(obj)
1287 aMeasurements.UnRegister()
1290 def GetGravityCenter(self, obj):
1292 Get gravity center of all nodes of the mesh object.
1295 obj: mesh, submesh or group
1298 Three components of the gravity center: x,y,z
1300 if isinstance(obj, Mesh): obj = obj.mesh
1301 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1302 aMeasurements = self.CreateMeasurements()
1303 pointStruct = aMeasurements.GravityCenter(obj)
1304 aMeasurements.UnRegister()
1305 return pointStruct.x, pointStruct.y, pointStruct.z
1307 pass # end of class smeshBuilder
1310 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1311 """Registering the new proxy for SMESH_Gen"""
1314 def New( study, instance=None, instanceGeom=None):
1316 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1317 interface to create or load meshes.
1321 salome.salome_init()
1322 from salome.smesh import smeshBuilder
1323 smesh = smeshBuilder.New(salome.myStudy)
1326 study: SALOME study, generally obtained by salome.myStudy.
1327 instance: CORBA proxy of SMESH Engine. If None, the default Engine is used.
1328 instanceGeom: CORBA proxy of GEOM Engine. If None, the default Engine is used.
1330 smeshBuilder instance
1338 smeshInst = smeshBuilder()
1339 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1340 smeshInst.init_smesh(study, instanceGeom)
1344 # Public class: Mesh
1345 # ==================
1349 This class allows defining and managing a mesh.
1350 It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1351 It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1352 new nodes and elements and by changing the existing entities), to get information
1353 about a mesh and to export a mesh in different formats.
1355 __metaclass__ = MeshMeta
1361 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1365 Create a mesh on the shape *obj* (or an empty mesh if *obj* is equal to 0) and
1366 sets the GUI name of this mesh to *name*.
1369 smeshpyD: an instance of smeshBuilder class
1370 geompyD: an instance of geomBuilder class
1371 obj: Shape to be meshed or SMESH_Mesh object
1372 name: Study name of the mesh
1375 self.smeshpyD=smeshpyD
1376 self.geompyD=geompyD
1381 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1384 # publish geom of mesh (issue 0021122)
1385 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1387 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1388 if studyID != geompyD.myStudyId:
1389 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1392 geo_name = name + " shape"
1394 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1395 geompyD.addToStudy( self.geom, geo_name )
1396 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1398 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1401 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1403 self.smeshpyD.SetName(self.mesh, name)
1405 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1408 self.geom = self.mesh.GetShapeToMesh()
1410 self.editor = self.mesh.GetMeshEditor()
1411 self.functors = [None] * SMESH.FT_Undefined._v
1413 # set self to algoCreator's
1414 for attrName in dir(self):
1415 attr = getattr( self, attrName )
1416 if isinstance( attr, algoCreator ):
1417 setattr( self, attrName, attr.copy( self ))
1424 Destructor. Clean-up resources
1427 #self.mesh.UnRegister()
1431 def SetMesh(self, theMesh):
1433 Initialize the Mesh object from an instance of SMESH_Mesh interface
1436 theMesh: a SMESH_Mesh object
1440 # do not call Register() as this prevents mesh servant deletion at closing study
1441 #if self.mesh: self.mesh.UnRegister()
1444 #self.mesh.Register()
1445 self.geom = self.mesh.GetShapeToMesh()
1450 Return the mesh, that is an instance of SMESH_Mesh interface
1460 Get the name of the mesh
1463 the name of the mesh as a string
1466 name = GetName(self.GetMesh())
1469 def SetName(self, name):
1471 Set a name to the mesh
1474 name: a new name of the mesh
1477 self.smeshpyD.SetName(self.GetMesh(), name)
1479 def GetSubMesh(self, geom, name):
1481 Get a sub-mesh object associated to a *geom* geometrical object.
1484 geom: a geometrical object (shape)
1485 name: a name for the sub-mesh in the Object Browser
1488 an object of type SMESH.SMESH_subMesh, representing a part of mesh,
1489 which lies on the given shape
1491 The sub-mesh object gives access to the IDs of nodes and elements.
1492 The sub-mesh object has the following methods:
1494 - SMESH.SMESH_subMesh.GetNumberOfElements()
1495 - SMESH.SMESH_subMesh.GetNumberOfNodes( all )
1496 - SMESH.SMESH_subMesh.GetElementsId()
1497 - SMESH.SMESH_subMesh.GetElementsByType( ElementType )
1498 - SMESH.SMESH_subMesh.GetNodesId()
1499 - SMESH.SMESH_subMesh.GetSubShape()
1500 - SMESH.SMESH_subMesh.GetFather()
1501 - SMESH.SMESH_subMesh.GetId()
1504 A sub-mesh is implicitly created when a sub-shape is specified at
1505 creating an algorithm, for example: algo1D = mesh.Segment(geom=Edge_1)
1506 creates a sub-mesh on *Edge_1* and assign Wire Discretization algorithm to it.
1507 The created sub-mesh can be retrieved from the algorithm:
1508 submesh = algo1D.GetSubMesh()
1511 AssureGeomPublished( self, geom, name )
1512 submesh = self.mesh.GetSubMesh( geom, name )
1517 Return the shape associated to the mesh
1525 def SetShape(self, geom):
1527 Associate the given shape to the mesh (entails the recreation of the mesh)
1530 geom: the shape to be meshed (GEOM_Object)
1533 self.mesh = self.smeshpyD.CreateMesh(geom)
1537 Load mesh from the study after opening the study
1541 def IsReadyToCompute(self, theSubObject):
1543 Return true if the hypotheses are defined well
1546 theSubObject: a sub-shape of a mesh shape
1552 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1554 def GetAlgoState(self, theSubObject):
1556 Return errors of hypotheses definition.
1557 The list of errors is empty if everything is OK.
1560 theSubObject: a sub-shape of a mesh shape
1566 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1568 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1570 Return a geometrical object on which the given element was built.
1571 The returned geometrical object, if not nil, is either found in the
1572 study or published by this method with the given name
1575 theElementID: the id of the mesh element
1576 theGeomName: the user-defined name of the geometrical object
1579 GEOM::GEOM_Object instance
1582 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1584 def MeshDimension(self):
1586 Return the mesh dimension depending on the dimension of the underlying shape
1587 or, if the mesh is not based on any shape, basing on deimension of elements
1590 mesh dimension as an integer value [0,3]
1593 if self.mesh.HasShapeToMesh():
1594 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1595 if len( shells ) > 0 :
1597 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1599 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1604 if self.NbVolumes() > 0: return 3
1605 if self.NbFaces() > 0: return 2
1606 if self.NbEdges() > 0: return 1
1609 def Evaluate(self, geom=0):
1611 Evaluate size of prospective mesh on a shape
1614 a list where i-th element is a number of elements of i-th SMESH.EntityType
1615 To know predicted number of e.g. edges, inquire it this way
1616 Evaluate()[ EnumToLong( Entity_Edge )]
1619 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1621 geom = self.mesh.GetShapeToMesh()
1624 return self.smeshpyD.Evaluate(self.mesh, geom)
1627 def Compute(self, geom=0, discardModifs=False, refresh=False):
1629 Compute the mesh and return the status of the computation
1632 geom: geomtrical shape on which mesh data should be computed
1633 discardModifs: if True and the mesh has been edited since
1634 a last total re-compute and that may prevent successful partial re-compute,
1635 then the mesh is cleaned before Compute()
1636 refresh: if *True*, Object browser is automatically updated (when running in GUI)
1642 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1644 geom = self.mesh.GetShapeToMesh()
1649 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1651 ok = self.smeshpyD.Compute(self.mesh, geom)
1652 except SALOME.SALOME_Exception, ex:
1653 print "Mesh computation failed, exception caught:"
1654 print " ", ex.details.text
1657 print "Mesh computation failed, exception caught:"
1658 traceback.print_exc()
1662 # Treat compute errors
1663 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1665 for err in computeErrors:
1666 if self.mesh.HasShapeToMesh():
1667 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1669 stdErrors = ["OK", #COMPERR_OK
1670 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1671 "std::exception", #COMPERR_STD_EXCEPTION
1672 "OCC exception", #COMPERR_OCC_EXCEPTION
1673 "..", #COMPERR_SLM_EXCEPTION
1674 "Unknown exception", #COMPERR_EXCEPTION
1675 "Memory allocation problem", #COMPERR_MEMORY_PB
1676 "Algorithm failed", #COMPERR_ALGO_FAILED
1677 "Unexpected geometry", #COMPERR_BAD_SHAPE
1678 "Warning", #COMPERR_WARNING
1679 "Computation cancelled",#COMPERR_CANCELED
1680 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1682 if err.code < len(stdErrors): errText = stdErrors[err.code]
1684 errText = "code %s" % -err.code
1685 if errText: errText += ". "
1686 errText += err.comment
1687 if allReasons: allReasons += "\n"
1689 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1691 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1695 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1697 if err.isGlobalAlgo:
1705 reason = '%s %sD algorithm is missing' % (glob, dim)
1706 elif err.state == HYP_MISSING:
1707 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1708 % (glob, dim, name, dim))
1709 elif err.state == HYP_NOTCONFORM:
1710 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1711 elif err.state == HYP_BAD_PARAMETER:
1712 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1713 % ( glob, dim, name ))
1714 elif err.state == HYP_BAD_GEOMETRY:
1715 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1716 'geometry' % ( glob, dim, name ))
1717 elif err.state == HYP_HIDDEN_ALGO:
1718 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1719 'algorithm of upper dimension generating %sD mesh'
1720 % ( glob, dim, name, glob, dim ))
1722 reason = ("For unknown reason. "
1723 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1725 if allReasons: allReasons += "\n"
1726 allReasons += "- " + reason
1728 if not ok or allReasons != "":
1729 msg = '"' + GetName(self.mesh) + '"'
1730 if ok: msg += " has been computed with warnings"
1731 else: msg += " has not been computed"
1732 if allReasons != "": msg += ":"
1737 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1738 if not isinstance( refresh, list): # not a call from subMesh.Compute()
1739 smeshgui = salome.ImportComponentGUI("SMESH")
1740 smeshgui.Init(self.mesh.GetStudyId())
1741 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1742 if refresh: salome.sg.updateObjBrowser(True)
1746 def GetComputeErrors(self, shape=0 ):
1748 Return a list of error messages (SMESH.ComputeError) of the last Compute()
1752 shape = self.mesh.GetShapeToMesh()
1753 return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1755 def GetSubShapeName(self, subShapeID ):
1757 Return a name of a sub-shape by its ID
1760 subShapeID: a unique ID of a sub-shape
1763 a string describing the sub-shape; possible variants:
1765 - "Face_12" (published sub-shape)
1766 - FACE #3 (not published sub-shape)
1767 - sub-shape #3 (invalid sub-shape ID)
1768 - #3 (error in this function)
1771 if not self.mesh.HasShapeToMesh():
1775 mainIOR = salome.orb.object_to_string( self.GetShape() )
1776 for sname in salome.myStudyManager.GetOpenStudies():
1777 s = salome.myStudyManager.GetStudyByName(sname)
1779 mainSO = s.FindObjectIOR(mainIOR)
1780 if not mainSO: continue
1782 shapeText = '"%s"' % mainSO.GetName()
1783 subIt = s.NewChildIterator(mainSO)
1785 subSO = subIt.Value()
1787 obj = subSO.GetObject()
1788 if not obj: continue
1789 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1792 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1795 if ids == subShapeID:
1796 shapeText = '"%s"' % subSO.GetName()
1799 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1801 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1803 shapeText = 'sub-shape #%s' % (subShapeID)
1805 shapeText = "#%s" % (subShapeID)
1808 def GetFailedShapes(self, publish=False):
1810 Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1811 error of an algorithm
1814 publish: if *True*, the returned groups will be published in the study
1817 a list of GEOM groups each named after a failed algorithm
1822 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1823 for err in computeErrors:
1824 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1825 if not shape: continue
1826 if err.algoName in algo2shapes:
1827 algo2shapes[ err.algoName ].append( shape )
1829 algo2shapes[ err.algoName ] = [ shape ]
1833 for algoName, shapes in algo2shapes.items():
1835 groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
1836 otherTypeShapes = []
1838 group = self.geompyD.CreateGroup( self.geom, groupType )
1839 for shape in shapes:
1840 if shape.GetShapeType() == shapes[0].GetShapeType():
1841 sameTypeShapes.append( shape )
1843 otherTypeShapes.append( shape )
1844 self.geompyD.UnionList( group, sameTypeShapes )
1846 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1848 group.SetName( algoName )
1849 groups.append( group )
1850 shapes = otherTypeShapes
1853 for group in groups:
1854 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1857 def GetMeshOrder(self):
1859 Return sub-mesh objects list in meshing order
1862 list of lists of sub-meshes
1865 return self.mesh.GetMeshOrder()
1867 def SetMeshOrder(self, submeshes):
1869 Set order in which concurrent sub-meshes should be meshed
1872 submeshes list of lists of sub-meshes
1875 return self.mesh.SetMeshOrder(submeshes)
1877 def Clear(self, refresh=False):
1879 Remove all nodes and elements generated on geometry. Imported elements remain.
1882 refresh if *True*, Object browser is automatically updated (when running in GUI)
1886 if ( salome.sg.hasDesktop() and
1887 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1888 smeshgui = salome.ImportComponentGUI("SMESH")
1889 smeshgui.Init(self.mesh.GetStudyId())
1890 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1891 if refresh: salome.sg.updateObjBrowser(True)
1893 def ClearSubMesh(self, geomId, refresh=False):
1895 Remove all nodes and elements of indicated shape
1898 refresh: if *True*, Object browser is automatically updated (when running in GUI)
1899 geomId: the ID of a sub-shape to remove elements on
1902 self.mesh.ClearSubMesh(geomId)
1903 if salome.sg.hasDesktop():
1904 smeshgui = salome.ImportComponentGUI("SMESH")
1905 smeshgui.Init(self.mesh.GetStudyId())
1906 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1907 if refresh: salome.sg.updateObjBrowser(True)
1909 def AutomaticTetrahedralization(self, fineness=0):
1911 Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1914 fineness: [0.0,1.0] defines mesh fineness
1920 dim = self.MeshDimension()
1922 self.RemoveGlobalHypotheses()
1923 self.Segment().AutomaticLength(fineness)
1925 self.Triangle().LengthFromEdges()
1930 return self.Compute()
1932 def AutomaticHexahedralization(self, fineness=0):
1934 Compute an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1937 fineness [0.0, 1.0] defines mesh fineness
1943 dim = self.MeshDimension()
1944 # assign the hypotheses
1945 self.RemoveGlobalHypotheses()
1946 self.Segment().AutomaticLength(fineness)
1953 return self.Compute()
1955 def AddHypothesis(self, hyp, geom=0):
1960 hyp: a hypothesis to assign
1961 geom: a subhape of mesh geometry
1964 SMESH.Hypothesis_Status
1967 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1968 hyp, geom = geom, hyp
1969 if isinstance( hyp, Mesh_Algorithm ):
1970 hyp = hyp.GetAlgorithm()
1975 geom = self.mesh.GetShapeToMesh()
1978 if self.mesh.HasShapeToMesh():
1979 hyp_type = hyp.GetName()
1980 lib_name = hyp.GetLibName()
1981 # checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1982 # if checkAll and geom:
1983 # checkAll = geom.GetType() == 37
1985 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1987 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1988 status = self.mesh.AddHypothesis(geom, hyp)
1990 status = HYP_BAD_GEOMETRY,""
1991 hyp_name = GetName( hyp )
1994 geom_name = geom.GetName()
1995 isAlgo = hyp._narrow( SMESH_Algo )
1996 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1999 def IsUsedHypothesis(self, hyp, geom):
2001 Return True if an algorithm of hypothesis is assigned to a given shape
2004 hyp: a hypothesis to check
2005 geom: a subhape of mesh geometry
2011 if not hyp: # or not geom
2013 if isinstance( hyp, Mesh_Algorithm ):
2014 hyp = hyp.GetAlgorithm()
2016 hyps = self.GetHypothesisList(geom)
2018 if h.GetId() == hyp.GetId():
2022 def RemoveHypothesis(self, hyp, geom=0):
2024 Unassign a hypothesis
2027 hyp: a hypothesis to unassign
2028 geom: a sub-shape of mesh geometry
2031 SMESH.Hypothesis_Status
2036 if isinstance( hyp, Mesh_Algorithm ):
2037 hyp = hyp.GetAlgorithm()
2043 if self.IsUsedHypothesis( hyp, shape ):
2044 return self.mesh.RemoveHypothesis( shape, hyp )
2045 hypName = GetName( hyp )
2046 geoName = GetName( shape )
2047 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
2050 def GetHypothesisList(self, geom):
2052 Get the list of hypotheses added on a geometry
2055 geom: a sub-shape of mesh geometry
2058 the sequence of SMESH_Hypothesis
2061 return self.mesh.GetHypothesisList( geom )
2063 def RemoveGlobalHypotheses(self):
2065 Remove all global hypotheses
2068 current_hyps = self.mesh.GetHypothesisList( self.geom )
2069 for hyp in current_hyps:
2070 self.mesh.RemoveHypothesis( self.geom, hyp )
2074 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
2075 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
2077 Export the mesh in a file in MED format
2078 allowing to overwrite the file if it exists or add the exported data to its contents
2082 auto_groups: boolean parameter for creating/not creating
2083 the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
2084 the typical use is auto_groups=False.
2085 version: MED format version (MED_V2_1 or MED_V2_2,
2086 the latter meaning any current version). The parameter is
2087 obsolete since MED_V2_1 is no longer supported.
2088 overwrite: boolean parameter for overwriting/not overwriting the file
2089 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2090 autoDimension: if *True* (default), a space dimension of a MED mesh can be either
2092 - 1D if all mesh nodes lie on OX coordinate axis, or
2093 - 2D if all mesh nodes lie on XOY coordinate plane, or
2094 - 3D in the rest cases.
2096 If *autoDimension* is *False*, the space dimension is always 3.
2097 fields: list of GEOM fields defined on the shape to mesh.
2098 geomAssocFields: each character of this string means a need to export a
2099 corresponding field; correspondence between fields and characters is following:
2101 - 'v' stands for "_vertices _" field;
2102 - 'e' stands for "_edges _" field;
2103 - 'f' stands for "_faces _" field;
2104 - 's' stands for "_solids _" field.
2107 if meshPart or fields or geomAssocFields:
2108 unRegister = genObjUnRegister()
2109 if isinstance( meshPart, list ):
2110 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2111 unRegister.set( meshPart )
2112 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
2113 fields, geomAssocFields)
2115 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
2117 def ExportSAUV(self, f, auto_groups=0):
2119 Export the mesh in a file in SAUV format
2124 auto_groups: boolean parameter for creating/not creating
2125 the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
2126 the typical use is auto_groups=false.
2129 self.mesh.ExportSAUV(f, auto_groups)
2131 def ExportDAT(self, f, meshPart=None):
2133 Export the mesh in a file in DAT format
2137 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2141 unRegister = genObjUnRegister()
2142 if isinstance( meshPart, list ):
2143 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2144 unRegister.set( meshPart )
2145 self.mesh.ExportPartToDAT( meshPart, f )
2147 self.mesh.ExportDAT(f)
2149 def ExportUNV(self, f, meshPart=None):
2151 Export the mesh in a file in UNV format
2155 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2159 unRegister = genObjUnRegister()
2160 if isinstance( meshPart, list ):
2161 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2162 unRegister.set( meshPart )
2163 self.mesh.ExportPartToUNV( meshPart, f )
2165 self.mesh.ExportUNV(f)
2167 def ExportSTL(self, f, ascii=1, meshPart=None):
2169 Export the mesh in a file in STL format
2173 ascii: defines the file encoding
2174 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2178 unRegister = genObjUnRegister()
2179 if isinstance( meshPart, list ):
2180 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2181 unRegister.set( meshPart )
2182 self.mesh.ExportPartToSTL( meshPart, f, ascii )
2184 self.mesh.ExportSTL(f, ascii)
2186 def ExportCGNS(self, f, overwrite=1, meshPart=None, groupElemsByType=False):
2188 Export the mesh in a file in CGNS format
2192 overwrite: boolean parameter for overwriting/not overwriting the file
2193 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2194 groupElemsByType: if true all elements of same entity type are exported at ones,
2195 else elements are exported in order of their IDs which can cause creation
2196 of multiple cgns sections
2199 unRegister = genObjUnRegister()
2200 if isinstance( meshPart, list ):
2201 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2202 unRegister.set( meshPart )
2203 if isinstance( meshPart, Mesh ):
2204 meshPart = meshPart.mesh
2206 meshPart = self.mesh
2207 self.mesh.ExportCGNS(meshPart, f, overwrite, groupElemsByType)
2209 def ExportGMF(self, f, meshPart=None):
2211 Export the mesh in a file in GMF format.
2212 GMF files must have .mesh extension for the ASCII format and .meshb for
2213 the bynary format. Other extensions are not allowed.
2217 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2220 unRegister = genObjUnRegister()
2221 if isinstance( meshPart, list ):
2222 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2223 unRegister.set( meshPart )
2224 if isinstance( meshPart, Mesh ):
2225 meshPart = meshPart.mesh
2227 meshPart = self.mesh
2228 self.mesh.ExportGMF(meshPart, f, True)
2230 def ExportToMED(self, f, version=MED_V2_2, opt=0, overwrite=1, autoDimension=True):
2232 Deprecated, used only for compatibility! Please, use ExportMED() method instead.
2233 Export the mesh in a file in MED format
2234 allowing to overwrite the file if it exists or add the exported data to its contents
2238 version: MED format version (MED_V2_1 or MED_V2_2,
2239 the latter meaning any current version). The parameter is
2240 obsolete since MED_V2_1 is no longer supported.
2241 opt: boolean parameter for creating/not creating
2242 the groups Group_On_All_Nodes, Group_On_All_Faces, ...
2243 overwrite: boolean parameter for overwriting/not overwriting the file
2244 autoDimension: if *True* (default), a space dimension of a MED mesh can be either
2246 - 1D if all mesh nodes lie on OX coordinate axis, or
2247 - 2D if all mesh nodes lie on XOY coordinate plane, or
2248 - 3D in the rest cases.
2250 If **autoDimension** isc **False**, the space dimension is always 3.
2253 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
2255 # Operations with groups:
2256 # ----------------------
2258 def CreateEmptyGroup(self, elementType, name):
2260 Create an empty mesh group
2263 elementType: the type of elements in the group; either of
2264 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2265 name: the name of the mesh group
2271 return self.mesh.CreateGroup(elementType, name)
2273 def Group(self, grp, name=""):
2275 Create a mesh group based on the geometric object *grp*
2277 if this parameter is not defined
2278 the name is the same as the geometric group name
2281 Works like GroupOnGeom().
2284 grp: a geometric group, a vertex, an edge, a face or a solid
2285 name: the name of the mesh group
2291 return self.GroupOnGeom(grp, name)
2293 def GroupOnGeom(self, grp, name="", typ=None):
2295 Create a mesh group based on the geometrical object *grp*
2297 if this parameter is not defined the name is the same as the geometrical group name
2300 grp: a geometrical group, a vertex, an edge, a face or a solid
2301 name: the name of the mesh group
2302 typ: the type of elements in the group; either of
2303 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
2304 automatically detected by the type of the geometry
2310 AssureGeomPublished( self, grp, name )
2312 name = grp.GetName()
2314 typ = self._groupTypeFromShape( grp )
2315 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
2317 def _groupTypeFromShape( self, shape ):
2319 Pivate method to get a type of group on geometry
2321 tgeo = str(shape.GetShapeType())
2322 if tgeo == "VERTEX":
2324 elif tgeo == "EDGE":
2326 elif tgeo == "FACE" or tgeo == "SHELL":
2328 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
2330 elif tgeo == "COMPOUND":
2331 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
2333 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
2334 return self._groupTypeFromShape( sub[0] )
2337 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
2340 def GroupOnFilter(self, typ, name, filter):
2342 Create a mesh group with given *name* based on the *filter* which
2343 is a special type of group dynamically updating it's contents during
2347 typ: the type of elements in the group; either of
2348 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2349 name: the name of the mesh group
2350 filter: the filter defining group contents
2356 return self.mesh.CreateGroupFromFilter(typ, name, filter)
2358 def MakeGroupByIds(self, groupName, elementType, elemIDs):
2360 Create a mesh group by the given ids of elements
2363 groupName: the name of the mesh group
2364 elementType: the type of elements in the group; either of
2365 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2366 elemIDs: either the list of ids, group, sub-mesh, or filter
2372 group = self.mesh.CreateGroup(elementType, groupName)
2373 if isinstance( elemIDs, Mesh ):
2374 elemIDs = elemIDs.GetMesh()
2375 if hasattr( elemIDs, "GetIDs" ):
2376 if hasattr( elemIDs, "SetMesh" ):
2377 elemIDs.SetMesh( self.GetMesh() )
2378 group.AddFrom( elemIDs )
2386 CritType=FT_Undefined,
2389 UnaryOp=FT_Undefined,
2392 Create a mesh group by the given conditions
2395 groupName: the name of the mesh group
2396 elementType: the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2397 CritType: the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
2398 Type SMESH.FunctorType._items in the Python Console to see all values.
2399 Note that the items starting from FT_LessThan are not suitable for CritType.
2400 Compare: belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
2401 Threshold: the threshold value (range of ids as string, shape, numeric)
2402 UnaryOp: SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2403 Tolerance: the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2404 SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2410 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2411 group = self.MakeGroupByCriterion(groupName, aCriterion)
2414 def MakeGroupByCriterion(self, groupName, Criterion):
2416 Create a mesh group by the given criterion
2419 groupName: the name of the mesh group
2420 Criterion: the instance of Criterion class
2426 return self.MakeGroupByCriteria( groupName, [Criterion] )
2428 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2430 Create a mesh group by the given criteria (list of criteria)
2433 groupName: the name of the mesh group
2434 theCriteria: the list of criteria
2435 binOp: binary operator used when binary operator of criteria is undefined
2441 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2442 group = self.MakeGroupByFilter(groupName, aFilter)
2445 def MakeGroupByFilter(self, groupName, theFilter):
2447 Create a mesh group by the given filter
2450 groupName: the name of the mesh group
2451 theFilter: the instance of Filter class
2457 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2458 #theFilter.SetMesh( self.mesh )
2459 #group.AddFrom( theFilter )
2460 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2463 def RemoveGroup(self, group):
2468 self.mesh.RemoveGroup(group)
2470 def RemoveGroupWithContents(self, group):
2472 Remove a group with its contents
2475 self.mesh.RemoveGroupWithContents(group)
2477 def GetGroups(self, elemType = SMESH.ALL):
2479 Get the list of groups existing in the mesh in the order
2480 of creation (starting from the oldest one)
2483 elemType: type of elements the groups contain; either of
2484 (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2485 by default groups of elements of all types are returned
2488 a sequence of SMESH_GroupBase
2491 groups = self.mesh.GetGroups()
2492 if elemType == SMESH.ALL:
2496 if g.GetType() == elemType:
2497 typedGroups.append( g )
2504 Get the number of groups existing in the mesh
2507 the quantity of groups as an integer value
2510 return self.mesh.NbGroups()
2512 def GetGroupNames(self):
2514 Get the list of names of groups existing in the mesh
2520 groups = self.GetGroups()
2522 for group in groups:
2523 names.append(group.GetName())
2526 def GetGroupByName(self, name, elemType = None):
2528 Find groups by name and type
2531 name: name of the group of interest
2532 elemType: type of elements the groups contain; either of
2533 (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2534 by default one group of any type of elements is returned
2535 if elemType == SMESH.ALL then all groups of any type are returned
2538 a list of SMESH_GroupBase's
2542 for group in self.GetGroups():
2543 if group.GetName() == name:
2544 if elemType is None:
2546 if ( elemType == SMESH.ALL or
2547 group.GetType() == elemType ):
2548 groups.append( group )
2551 def UnionGroups(self, group1, group2, name):
2553 Produce a union of two groups.
2554 A new group is created. All mesh elements that are
2555 present in the initial groups are added to the new one
2558 an instance of SMESH_Group
2561 return self.mesh.UnionGroups(group1, group2, name)
2563 def UnionListOfGroups(self, groups, name):
2565 Produce a union list of groups.
2566 New group is created. All mesh elements that are present in
2567 initial groups are added to the new one
2571 an instance of SMESH_Group
2574 return self.mesh.UnionListOfGroups(groups, name)
2576 def IntersectGroups(self, group1, group2, name):
2578 Prodice an intersection of two groups.
2579 A new group is created. All mesh elements that are common
2580 for the two initial groups are added to the new one.
2583 an instance of SMESH_Group
2586 return self.mesh.IntersectGroups(group1, group2, name)
2588 def IntersectListOfGroups(self, groups, name):
2590 Produce an intersection of groups.
2591 New group is created. All mesh elements that are present in all
2592 initial groups simultaneously are added to the new one
2595 an instance of SMESH_Group
2598 return self.mesh.IntersectListOfGroups(groups, name)
2600 def CutGroups(self, main_group, tool_group, name):
2602 Produce a cut of two groups.
2603 A new group is created. All mesh elements that are present in
2604 the main group but are not present in the tool group are added to the new one
2607 an instance of SMESH_Group
2610 return self.mesh.CutGroups(main_group, tool_group, name)
2612 def CutListOfGroups(self, main_groups, tool_groups, name):
2614 Produce a cut of groups.
2615 A new group is created. All mesh elements that are present in main groups
2616 but do not present in tool groups are added to the new one
2619 an instance of SMESH_Group
2622 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2624 def CreateDimGroup(self, groups, elemType, name,
2625 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2627 Create a standalone group of entities basing on nodes of other groups.
2630 groups: list of reference groups, sub-meshes or filters, of any type.
2631 elemType: a type of elements to include to the new group; either of
2632 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2633 name: a name of the new group.
2634 nbCommonNodes: a criterion of inclusion of an element to the new group
2635 basing on number of element nodes common with reference *groups*.
2636 Meaning of possible values are:
2638 - SMESH.ALL_NODES - include if all nodes are common,
2639 - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2640 - SMESH.AT_LEAST_ONE - include if one or more node is common,
2641 - SMEHS.MAJORITY - include if half of nodes or more are common.
2642 underlyingOnly: if *True* (default), an element is included to the
2643 new group provided that it is based on nodes of an element of *groups*;
2644 in this case the reference *groups* are supposed to be of higher dimension
2645 than *elemType*, which can be useful for example to get all faces lying on
2646 volumes of the reference *groups*.
2649 an instance of SMESH_Group
2652 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2654 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2657 def ConvertToStandalone(self, group):
2659 Convert group on geom into standalone group
2662 return self.mesh.ConvertToStandalone(group)
2664 # Get some info about mesh:
2665 # ------------------------
2667 def GetLog(self, clearAfterGet):
2669 Return the log of nodes and elements added or removed
2670 since the previous clear of the log.
2673 clearAfterGet: log is emptied after Get (safe if concurrents access)
2676 list of log_block structures:
2683 return self.mesh.GetLog(clearAfterGet)
2687 Clear the log of nodes and elements added or removed since the previous
2688 clear. Must be used immediately after GetLog if clearAfterGet is false.
2691 self.mesh.ClearLog()
2693 def SetAutoColor(self, theAutoColor):
2695 Toggle auto color mode on the object.
2698 theAutoColor: the flag which toggles auto color mode.
2699 If switched on, a default color of a new group in Create Group dialog is chosen randomly.
2702 self.mesh.SetAutoColor(theAutoColor)
2704 def GetAutoColor(self):
2706 Get flag of object auto color mode.
2712 return self.mesh.GetAutoColor()
2719 integer value, which is the internal Id of the mesh
2722 return self.mesh.GetId()
2724 def GetStudyId(self):
2729 integer value, which is the study Id of the mesh
2732 return self.mesh.GetStudyId()
2734 def HasDuplicatedGroupNamesMED(self):
2736 Check the group names for duplications.
2737 Consider the maximum group name length stored in MED file.
2743 return self.mesh.HasDuplicatedGroupNamesMED()
2745 def GetMeshEditor(self):
2747 Obtain the mesh editor tool
2750 an instance of SMESH_MeshEditor
2755 def GetIDSource(self, ids, elemType = SMESH.ALL):
2757 Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2758 can be passed as argument to a method accepting mesh, group or sub-mesh
2762 lemType: type of elements; this parameter is used to distinguish
2763 IDs of nodes from IDs of elements; by default ids are treated as
2764 IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2767 an instance of SMESH_IDSource
2770 call UnRegister() for the returned object as soon as it is no more useful:
2771 idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2772 mesh.DoSomething( idSrc )
2776 if isinstance( ids, int ):
2778 return self.editor.MakeIDSource(ids, elemType)
2781 # Get information about mesh contents:
2782 # ------------------------------------
2784 def GetMeshInfo(self, obj = None):
2786 Get the mesh statistic
2789 dictionary type element - count of elements
2792 if not obj: obj = self.mesh
2793 return self.smeshpyD.GetMeshInfo(obj)
2797 Return the number of nodes in the mesh
2803 return self.mesh.NbNodes()
2805 def NbElements(self):
2807 Return the number of elements in the mesh
2813 return self.mesh.NbElements()
2815 def Nb0DElements(self):
2817 Return the number of 0d elements in the mesh
2823 return self.mesh.Nb0DElements()
2827 Return the number of ball discrete elements in the mesh
2833 return self.mesh.NbBalls()
2837 Return the number of edges in the mesh
2843 return self.mesh.NbEdges()
2845 def NbEdgesOfOrder(self, elementOrder):
2847 Return the number of edges with the given order in the mesh
2850 elementOrder: the order of elements:
2851 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2857 return self.mesh.NbEdgesOfOrder(elementOrder)
2861 Return the number of faces in the mesh
2867 return self.mesh.NbFaces()
2869 def NbFacesOfOrder(self, elementOrder):
2871 Return the number of faces with the given order in the mesh
2874 elementOrder: the order of elements:
2875 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2881 return self.mesh.NbFacesOfOrder(elementOrder)
2883 def NbTriangles(self):
2885 Return the number of triangles in the mesh
2891 return self.mesh.NbTriangles()
2893 def NbTrianglesOfOrder(self, elementOrder):
2895 Return the number of triangles with the given order in the mesh
2898 elementOrder: is the order of elements:
2899 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2905 return self.mesh.NbTrianglesOfOrder(elementOrder)
2907 def NbBiQuadTriangles(self):
2909 Return the number of biquadratic triangles in the mesh
2915 return self.mesh.NbBiQuadTriangles()
2917 def NbQuadrangles(self):
2919 Return the number of quadrangles in the mesh
2925 return self.mesh.NbQuadrangles()
2927 def NbQuadranglesOfOrder(self, elementOrder):
2929 Return the number of quadrangles with the given order in the mesh
2932 elementOrder the order of elements:
2933 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2939 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2941 def NbBiQuadQuadrangles(self):
2943 Return the number of biquadratic quadrangles in the mesh
2949 return self.mesh.NbBiQuadQuadrangles()
2951 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2953 Return the number of polygons of given order in the mesh
2956 elementOrder: the order of elements:
2957 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2963 return self.mesh.NbPolygonsOfOrder(elementOrder)
2965 def NbVolumes(self):
2967 Return the number of volumes in the mesh
2973 return self.mesh.NbVolumes()
2976 def NbVolumesOfOrder(self, elementOrder):
2978 Return the number of volumes with the given order in the mesh
2981 elementOrder: the order of elements:
2982 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2988 return self.mesh.NbVolumesOfOrder(elementOrder)
2992 Return the number of tetrahedrons in the mesh
2998 return self.mesh.NbTetras()
3000 def NbTetrasOfOrder(self, elementOrder):
3002 Return the number of tetrahedrons with the given order in the mesh
3005 elementOrder: the order of elements:
3006 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
3012 return self.mesh.NbTetrasOfOrder(elementOrder)
3016 Return the number of hexahedrons in the mesh
3022 return self.mesh.NbHexas()
3024 def NbHexasOfOrder(self, elementOrder):
3026 Return the number of hexahedrons with the given order in the mesh
3029 elementOrder: the order of elements:
3030 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
3036 return self.mesh.NbHexasOfOrder(elementOrder)
3038 def NbTriQuadraticHexas(self):
3040 Return the number of triquadratic hexahedrons in the mesh
3046 return self.mesh.NbTriQuadraticHexas()
3048 def NbPyramids(self):
3050 Return the number of pyramids in the mesh
3056 return self.mesh.NbPyramids()
3058 def NbPyramidsOfOrder(self, elementOrder):
3060 Return the number of pyramids with the given order in the mesh
3063 elementOrder: the order of elements:
3064 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
3070 return self.mesh.NbPyramidsOfOrder(elementOrder)
3074 Return the number of prisms in the mesh
3080 return self.mesh.NbPrisms()
3082 def NbPrismsOfOrder(self, elementOrder):
3084 Return the number of prisms with the given order in the mesh
3087 elementOrder: the order of elements:
3088 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
3094 return self.mesh.NbPrismsOfOrder(elementOrder)
3096 def NbHexagonalPrisms(self):
3098 Return the number of hexagonal prisms in the mesh
3104 return self.mesh.NbHexagonalPrisms()
3106 def NbPolyhedrons(self):
3108 Return the number of polyhedrons in the mesh
3114 return self.mesh.NbPolyhedrons()
3116 def NbSubMesh(self):
3118 Return the number of submeshes in the mesh
3124 return self.mesh.NbSubMesh()
3126 def GetElementsId(self):
3128 Return the list of mesh elements IDs
3131 the list of integer values
3134 return self.mesh.GetElementsId()
3136 def GetElementsByType(self, elementType):
3138 Return the list of IDs of mesh elements with the given type
3141 elementType: the required type of elements, either of
3142 (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
3145 list of integer values
3148 return self.mesh.GetElementsByType(elementType)
3150 def GetNodesId(self):
3152 Return the list of mesh nodes IDs
3155 the list of integer values
3158 return self.mesh.GetNodesId()
3160 # Get the information about mesh elements:
3161 # ------------------------------------
3163 def GetElementType(self, id, iselem=True):
3165 Return the type of mesh element
3168 the value from SMESH::ElementType enumeration
3169 Type SMESH.ElementType._items in the Python Console to see all possible values.
3172 return self.mesh.GetElementType(id, iselem)
3174 def GetElementGeomType(self, id):
3176 Return the geometric type of mesh element
3179 the value from SMESH::EntityType enumeration
3180 Type SMESH.EntityType._items in the Python Console to see all possible values.
3183 return self.mesh.GetElementGeomType(id)
3185 def GetElementShape(self, id):
3187 Return the shape type of mesh element
3190 the value from SMESH::GeometryType enumeration.
3191 Type SMESH.GeometryType._items in the Python Console to see all possible values.
3194 return self.mesh.GetElementShape(id)
3196 def GetSubMeshElementsId(self, Shape):
3198 Return the list of submesh elements IDs
3201 Shape: a geom object(sub-shape)
3202 Shape must be the sub-shape of a ShapeToMesh()
3205 the list of integer values
3208 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
3209 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3212 return self.mesh.GetSubMeshElementsId(ShapeID)
3214 def GetSubMeshNodesId(self, Shape, all):
3216 Return the list of submesh nodes IDs
3219 Shape: a geom object(sub-shape)
3220 Shape must be the sub-shape of a ShapeToMesh()
3221 all: If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
3224 the list of integer values
3227 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
3228 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3231 return self.mesh.GetSubMeshNodesId(ShapeID, all)
3233 def GetSubMeshElementType(self, Shape):
3235 Return type of elements on given shape
3238 Shape: a geom object(sub-shape)
3239 Shape must be a sub-shape of a ShapeToMesh()
3245 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
3246 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3249 return self.mesh.GetSubMeshElementType(ShapeID)
3253 Get the mesh description
3259 return self.mesh.Dump()
3262 # Get the information about nodes and elements of a mesh by its IDs:
3263 # -----------------------------------------------------------
3265 def GetNodeXYZ(self, id):
3267 Get XYZ coordinates of a node
3268 If there is no nodes for the given ID - return an empty list
3271 a list of double precision values
3274 return self.mesh.GetNodeXYZ(id)
3276 def GetNodeInverseElements(self, id):
3278 Return list of IDs of inverse elements for the given node
3279 If there is no node for the given ID - return an empty list
3282 a list of integer values
3285 return self.mesh.GetNodeInverseElements(id)
3287 def GetNodePosition(self,NodeID):
3289 Return the position of a node on the shape
3295 return self.mesh.GetNodePosition(NodeID)
3297 def GetElementPosition(self,ElemID):
3299 Return the position of an element on the shape
3302 SMESH::ElementPosition
3305 return self.mesh.GetElementPosition(ElemID)
3307 def GetShapeID(self, id):
3309 Return the ID of the shape, on which the given node was generated.
3312 an integer value > 0 or -1 if there is no node for the given
3313 ID or the node is not assigned to any geometry
3316 return self.mesh.GetShapeID(id)
3318 def GetShapeIDForElem(self,id):
3320 Return the ID of the shape, on which the given element was generated.
3323 an integer value > 0 or -1 if there is no element for the given
3324 ID or the element is not assigned to any geometry
3327 return self.mesh.GetShapeIDForElem(id)
3329 def GetElemNbNodes(self, id):
3331 Return the number of nodes of the given element
3334 an integer value > 0 or -1 if there is no element for the given ID
3337 return self.mesh.GetElemNbNodes(id)
3339 def GetElemNode(self, id, index):
3341 Return the node ID the given (zero based) index for the given element
3342 If there is no element for the given ID - return -1
3343 If there is no node for the given index - return -2
3349 return self.mesh.GetElemNode(id, index)
3351 def GetElemNodes(self, id):
3353 Return the IDs of nodes of the given element
3356 a list of integer values
3359 return self.mesh.GetElemNodes(id)
3361 def IsMediumNode(self, elementID, nodeID):
3363 Return true if the given node is the medium node in the given quadratic element
3366 return self.mesh.IsMediumNode(elementID, nodeID)
3368 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
3370 Return true if the given node is the medium node in one of quadratic elements
3373 nodeID: ID of the node
3374 elementType: the type of elements to check a state of the node, either of
3375 (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
3378 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
3380 def ElemNbEdges(self, id):
3382 Return the number of edges for the given element
3385 return self.mesh.ElemNbEdges(id)
3387 def ElemNbFaces(self, id):
3389 Return the number of faces for the given element
3392 return self.mesh.ElemNbFaces(id)
3394 def GetElemFaceNodes(self,elemId, faceIndex):
3396 Return nodes of given face (counted from zero) for given volumic element.
3399 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
3401 def GetFaceNormal(self, faceId, normalized=False):
3403 Return three components of normal of given mesh face
3404 (or an empty array in KO case)
3407 return self.mesh.GetFaceNormal(faceId,normalized)
3409 def FindElementByNodes(self, nodes):
3411 Return an element based on all given nodes.
3414 return self.mesh.FindElementByNodes(nodes)
3416 def GetElementsByNodes(self, nodes, elemType=SMESH.ALL):
3418 Return elements including all given nodes.
3421 return self.mesh.GetElementsByNodes( nodes, elemType )
3423 def IsPoly(self, id):
3425 Return true if the given element is a polygon
3428 return self.mesh.IsPoly(id)
3430 def IsQuadratic(self, id):
3432 Return true if the given element is quadratic
3435 return self.mesh.IsQuadratic(id)
3437 def GetBallDiameter(self, id):
3439 Return diameter of a ball discrete element or zero in case of an invalid *id*
3442 return self.mesh.GetBallDiameter(id)
3444 def BaryCenter(self, id):
3446 Return XYZ coordinates of the barycenter of the given element
3447 If there is no element for the given ID - return an empty list
3450 a list of three double values
3453 return self.mesh.BaryCenter(id)
3455 def GetIdsFromFilter(self, theFilter):
3457 Pass mesh elements through the given filter and return IDs of fitting elements
3460 theFilter: SMESH_Filter
3466 theFilter.SetMesh( self.mesh )
3467 return theFilter.GetIDs()
3469 # Get mesh measurements information:
3470 # ------------------------------------
3472 def GetFreeBorders(self):
3474 Verify whether a 2D mesh element has free edges (edges connected to one face only)\n
3475 Return a list of special structures (borders).
3478 a list of SMESH.FreeEdges. Border structure:: edge id and ids of two its nodes.
3481 aFilterMgr = self.smeshpyD.CreateFilterManager()
3482 aPredicate = aFilterMgr.CreateFreeEdges()
3483 aPredicate.SetMesh(self.mesh)
3484 aBorders = aPredicate.GetBorders()
3485 aFilterMgr.UnRegister()
3488 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
3490 Get minimum distance between two nodes, elements or distance to the origin
3493 id1: first node/element id
3494 id2: second node/element id (if 0, distance from *id1* to the origin is computed)
3495 isElem1: *True* if *id1* is element id, *False* if it is node id
3496 isElem2: *True* if *id2* is element id, *False* if it is node id
3499 minimum distance value **GetMinDistance()**
3502 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
3503 return aMeasure.value
3505 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
3507 Get measure structure specifying minimum distance data between two objects
3510 id1: first node/element id
3511 id2: second node/element id (if 0, distance from *id1* to the origin is computed)
3512 isElem1: *True* if *id1* is element id, *False* if it is node id
3513 isElem2: *True* if *id2* is element id, *False* if it is node id
3516 Measure structure **MinDistance()**
3520 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
3522 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
3525 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
3527 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
3532 aMeasurements = self.smeshpyD.CreateMeasurements()
3533 aMeasure = aMeasurements.MinDistance(id1, id2)
3534 genObjUnRegister([aMeasurements,id1, id2])
3537 def BoundingBox(self, objects=None, isElem=False):
3539 Get bounding box of the specified object(s)
3542 objects: single source object or list of source objects or list of nodes/elements IDs
3543 isElem: if *objects* is a list of IDs, *True* value in this parameters specifies that *objects* are elements,
3544 *False* specifies that *objects* are nodes
3547 tuple of six values (minX, minY, minZ, maxX, maxY, maxZ) **GetBoundingBox()**
3550 result = self.GetBoundingBox(objects, isElem)
3554 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
3557 def GetBoundingBox(self, IDs=None, isElem=False):
3559 Get measure structure specifying bounding box data of the specified object(s)
3562 IDs: single source object or list of source objects or list of nodes/elements IDs
3563 isElem: if *IDs* is a list of IDs, *True* value in this parameters specifies that *objects* are elements,
3564 *False* specifies that *objects* are nodes
3567 Measure structure **BoundingBox()**
3572 elif isinstance(IDs, tuple):
3574 if not isinstance(IDs, list):
3576 if len(IDs) > 0 and isinstance(IDs[0], int):
3579 unRegister = genObjUnRegister()
3581 if isinstance(o, Mesh):
3582 srclist.append(o.mesh)
3583 elif hasattr(o, "_narrow"):
3584 src = o._narrow(SMESH.SMESH_IDSource)
3585 if src: srclist.append(src)
3587 elif isinstance(o, list):
3589 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
3591 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
3592 unRegister.set( srclist[-1] )
3595 aMeasurements = self.smeshpyD.CreateMeasurements()
3596 unRegister.set( aMeasurements )
3597 aMeasure = aMeasurements.BoundingBox(srclist)
3600 # Mesh edition (SMESH_MeshEditor functionality):
3601 # ---------------------------------------------
3603 def RemoveElements(self, IDsOfElements):
3605 Remove the elements from the mesh by ids
3608 IDsOfElements: is a list of ids of elements to remove
3614 return self.editor.RemoveElements(IDsOfElements)
3616 def RemoveNodes(self, IDsOfNodes):
3618 Remove nodes from mesh by ids
3621 IDsOfNodes: is a list of ids of nodes to remove
3627 return self.editor.RemoveNodes(IDsOfNodes)
3629 def RemoveOrphanNodes(self):
3631 Remove all orphan (free) nodes from mesh
3634 number of the removed nodes
3637 return self.editor.RemoveOrphanNodes()
3639 def AddNode(self, x, y, z):
3641 Add a node to the mesh by coordinates
3647 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3648 if hasVars: self.mesh.SetParameters(Parameters)
3649 return self.editor.AddNode( x, y, z)
3651 def Add0DElement( self, IDOfNode, DuplicateElements=True ):
3653 Create a 0D element on a node with given number.
3656 IDOfNode: the ID of node for creation of the element.
3657 DuplicateElements: to add one more 0D element to a node or not
3660 the Id of the new 0D element
3663 return self.editor.Add0DElement( IDOfNode, DuplicateElements )
3665 def Add0DElementsToAllNodes(self, theObject, theGroupName="", DuplicateElements=False):
3667 Create 0D elements on all nodes of the given elements except those
3668 nodes on which a 0D element already exists.
3671 theObject: an object on whose nodes 0D elements will be created.
3672 It can be mesh, sub-mesh, group, list of element IDs or a holder
3673 of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
3674 theGroupName: optional name of a group to add 0D elements created
3675 and/or found on nodes of *theObject*.
3676 DuplicateElements: to add one more 0D element to a node or not
3679 an object (a new group or a temporary SMESH_IDSource) holding
3680 IDs of new and/or found 0D elements. IDs of 0D elements
3681 can be retrieved from the returned object by calling GetIDs()
3684 unRegister = genObjUnRegister()
3685 if isinstance( theObject, Mesh ):
3686 theObject = theObject.GetMesh()
3687 elif isinstance( theObject, list ):
3688 theObject = self.GetIDSource( theObject, SMESH.ALL )
3689 unRegister.set( theObject )
3690 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName, DuplicateElements )
3692 def AddBall(self, IDOfNode, diameter):
3694 Create a ball element on a node with given ID.
3697 IDOfNode: the ID of node for creation of the element.
3698 diameter: the bal diameter.
3701 the Id of the new ball element
3704 return self.editor.AddBall( IDOfNode, diameter )
3706 def AddEdge(self, IDsOfNodes):
3708 Create a linear or quadratic edge (this is determined
3709 by the number of given nodes).
3712 IDsOfNodes: the list of node IDs for creation of the element.
3713 The order of nodes in this list should correspond to the description
3715 This description is located by the following link:
3716 http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3719 the Id of the new edge
3722 return self.editor.AddEdge(IDsOfNodes)
3724 def AddFace(self, IDsOfNodes):
3726 Create a linear or quadratic face (this is determined
3727 by the number of given nodes).
3730 IDsOfNodes: the list of node IDs for creation of the element.
3731 The order of nodes in this list should correspond to the description
3733 This description is located by the following link:
3734 http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3737 the Id of the new face
3740 return self.editor.AddFace(IDsOfNodes)
3742 def AddPolygonalFace(self, IdsOfNodes):
3744 Add a polygonal face to the mesh by the list of node IDs
3747 IdsOfNodes: the list of node IDs for creation of the element.
3750 the Id of the new face
3753 return self.editor.AddPolygonalFace(IdsOfNodes)
3755 def AddQuadPolygonalFace(self, IdsOfNodes):
3757 Add a quadratic polygonal face to the mesh by the list of node IDs
3760 IdsOfNodes: the list of node IDs for creation of the element;
3761 corner nodes follow first.
3764 the Id of the new face
3767 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
3769 def AddVolume(self, IDsOfNodes):
3771 Create both simple and quadratic volume (this is determined
3772 by the number of given nodes).
3775 IDsOfNodes: the list of node IDs for creation of the element.
3776 The order of nodes in this list should correspond to the description
3778 This description is located by the following link:
3779 http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3782 the Id of the new volumic element
3785 return self.editor.AddVolume(IDsOfNodes)
3787 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
3789 Create a volume of many faces, giving nodes for each face.
3792 IdsOfNodes: the list of node IDs for volume creation face by face.
3793 Quantities: the list of integer values, Quantities[i]
3794 gives the quantity of nodes in face number i.
3797 the Id of the new volumic element
3800 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
3802 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
3804 Create a volume of many faces, giving the IDs of the existing faces.
3807 IdsOfFaces: the list of face IDs for volume creation.
3810 The created volume will refer only to the nodes
3811 of the given faces, not to the faces themselves.
3814 the Id of the new volumic element
3817 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
3820 def SetNodeOnVertex(self, NodeID, Vertex):
3822 **Binds** a node to a vertex
3826 Vertex: a vertex or vertex ID
3829 True if succeed else raises an exception
3832 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
3833 VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
3837 self.editor.SetNodeOnVertex(NodeID, VertexID)
3838 except SALOME.SALOME_Exception, inst:
3839 raise ValueError, inst.details.text
3843 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
3845 **Stores** the node position on an edge
3849 Edge: an edge or edge ID
3850 paramOnEdge: a parameter on the edge where the node is located
3853 True if succeed else raises an exception
3856 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
3857 EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
3861 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
3862 except SALOME.SALOME_Exception, inst:
3863 raise ValueError, inst.details.text
3866 def SetNodeOnFace(self, NodeID, Face, u, v):
3868 **Stores** node position on a face
3872 Face: a face or face ID
3873 u: U parameter on the face where the node is located
3874 v: V parameter on the face where the node is located
3877 True if succeed else raises an exception
3880 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
3881 FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
3885 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
3886 except SALOME.SALOME_Exception, inst:
3887 raise ValueError, inst.details.text
3890 def SetNodeInVolume(self, NodeID, Solid):
3892 **Binds** a node to a solid
3896 Solid: a solid or solid ID
3899 True if succeed else raises an exception
3902 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
3903 SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
3907 self.editor.SetNodeInVolume(NodeID, SolidID)
3908 except SALOME.SALOME_Exception, inst:
3909 raise ValueError, inst.details.text
3912 def SetMeshElementOnShape(self, ElementID, Shape):
3914 **Bind** an element to a shape
3917 ElementID: an element ID
3918 Shape: a shape or shape ID
3921 True if succeed else raises an exception
3924 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
3925 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3929 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
3930 except SALOME.SALOME_Exception, inst:
3931 raise ValueError, inst.details.text
3935 def MoveNode(self, NodeID, x, y, z):
3937 Move the node with the given id
3940 NodeID: the id of the node
3941 x: a new X coordinate
3942 y: a new Y coordinate
3943 z: a new Z coordinate
3946 True if succeed else False
3949 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3950 if hasVars: self.mesh.SetParameters(Parameters)
3951 return self.editor.MoveNode(NodeID, x, y, z)
3953 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3955 Find the node closest to a point and moves it to a point location
3958 x: the X coordinate of a point
3959 y: the Y coordinate of a point
3960 z: the Z coordinate of a point
3961 NodeID: if specified (>0), the node with this ID is moved,
3962 otherwise, the node closest to point (*x*, *y*, *z*) is moved
3968 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3969 if hasVars: self.mesh.SetParameters(Parameters)
3970 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3972 def FindNodeClosestTo(self, x, y, z):
3974 Find the node closest to a point
3977 x: the X coordinate of a point
3978 y: the Y coordinate of a point
3979 z: the Z coordinate of a point
3985 #preview = self.mesh.GetMeshEditPreviewer()
3986 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3987 return self.editor.FindNodeClosestTo(x, y, z)
3989 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3991 Find the elements where a point lays IN or ON
3994 x: the X coordinate of a point
3995 y: the Y coordinate of a point
3996 z: the Z coordinate of a point
3997 elementType: type of elements to find; either of
3998 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3999 means elements of any type excluding nodes, discrete and 0D elements.
4000 meshPart: a part of mesh (group, sub-mesh) to search within
4003 list of IDs of found elements
4007 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
4009 return self.editor.FindElementsByPoint(x, y, z, elementType)
4011 def GetPointState(self, x, y, z):
4013 Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
4014 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
4015 UNKNOWN state means that either mesh is wrong or the analysis fails.
4018 return self.editor.GetPointState(x, y, z)
4020 def IsManifold(self):
4022 Check if a 2D mesh is manifold
4025 return self.editor.IsManifold()
4027 def IsCoherentOrientation2D(self):
4029 Check if orientation of 2D elements is coherent
4032 return self.editor.IsCoherentOrientation2D()
4034 def MeshToPassThroughAPoint(self, x, y, z):
4036 Find the node closest to a point and moves it to a point location
4039 x: the X coordinate of a point
4040 y: the Y coordinate of a point
4041 z: the Z coordinate of a point
4044 the ID of a moved node
4047 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
4049 def InverseDiag(self, NodeID1, NodeID2):
4051 Replace two neighbour triangles sharing Node1-Node2 link
4052 with the triangles built on the same 4 nodes but having other common link.
4055 NodeID1: the ID of the first node
4056 NodeID2: the ID of the second node
4059 false if proper faces were not found
4061 return self.editor.InverseDiag(NodeID1, NodeID2)
4063 def DeleteDiag(self, NodeID1, NodeID2):
4065 Replace two neighbour triangles sharing Node1-Node2 link
4066 with a quadrangle built on the same 4 nodes.
4069 NodeID1: the ID of the first node
4070 NodeID2: the ID of the second node
4073 false if proper faces were not found
4076 return self.editor.DeleteDiag(NodeID1, NodeID2)
4078 def Reorient(self, IDsOfElements=None):
4080 Reorient elements by ids
4083 IDsOfElements: if undefined reorients all mesh elements
4086 True if succeed else False
4089 if IDsOfElements == None:
4090 IDsOfElements = self.GetElementsId()
4091 return self.editor.Reorient(IDsOfElements)
4093 def ReorientObject(self, theObject):
4095 Reorient all elements of the object
4098 theObject: mesh, submesh or group
4101 True if succeed else False
4104 if ( isinstance( theObject, Mesh )):
4105 theObject = theObject.GetMesh()
4106 return self.editor.ReorientObject(theObject)
4108 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
4110 Reorient faces contained in *the2DObject*.
4113 the2DObject: is a mesh, sub-mesh, group or list of IDs of 2D elements
4114 theDirection: is a desired direction of normal of *theFace*.
4115 It can be either a GEOM vector or a list of coordinates [x,y,z].
4116 theFaceOrPoint: defines a face of *the2DObject* whose normal will be
4117 compared with theDirection. It can be either ID of face or a point
4118 by which the face will be found. The point can be given as either
4119 a GEOM vertex or a list of point coordinates.
4122 number of reoriented faces
4125 unRegister = genObjUnRegister()
4127 if isinstance( the2DObject, Mesh ):
4128 the2DObject = the2DObject.GetMesh()
4129 if isinstance( the2DObject, list ):
4130 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
4131 unRegister.set( the2DObject )
4132 # check theDirection
4133 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
4134 theDirection = self.smeshpyD.GetDirStruct( theDirection )
4135 if isinstance( theDirection, list ):
4136 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
4137 # prepare theFace and thePoint
4138 theFace = theFaceOrPoint
4139 thePoint = PointStruct(0,0,0)
4140 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
4141 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
4143 if isinstance( theFaceOrPoint, list ):
4144 thePoint = PointStruct( *theFaceOrPoint )
4146 if isinstance( theFaceOrPoint, PointStruct ):
4147 thePoint = theFaceOrPoint
4149 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
4151 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
4153 Reorient faces according to adjacent volumes.
4156 the2DObject: is a mesh, sub-mesh, group or list of
4157 either IDs of faces or face groups.
4158 the3DObject: is a mesh, sub-mesh, group or list of IDs of volumes.
4159 theOutsideNormal: to orient faces to have their normals
4160 pointing either *outside* or *inside* the adjacent volumes.
4163 number of reoriented faces.
4166 unRegister = genObjUnRegister()
4168 if not isinstance( the2DObject, list ):
4169 the2DObject = [ the2DObject ]
4170 elif the2DObject and isinstance( the2DObject[0], int ):
4171 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
4172 unRegister.set( the2DObject )
4173 the2DObject = [ the2DObject ]
4174 for i,obj2D in enumerate( the2DObject ):
4175 if isinstance( obj2D, Mesh ):
4176 the2DObject[i] = obj2D.GetMesh()
4177 if isinstance( obj2D, list ):
4178 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
4179 unRegister.set( the2DObject[i] )
4181 if isinstance( the3DObject, Mesh ):
4182 the3DObject = the3DObject.GetMesh()
4183 if isinstance( the3DObject, list ):
4184 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
4185 unRegister.set( the3DObject )
4186 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
4188 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
4190 Fuse the neighbouring triangles into quadrangles.
4193 IDsOfElements: The triangles to be fused.
4194 theCriterion: a numerical functor, in terms of enum SMESH.FunctorType, used to
4195 applied to possible quadrangles to choose a neighbour to fuse with.
4196 Type SMESH.FunctorType._items in the Python Console to see all items.
4197 Note that not all items correspond to numerical functors.
4198 MaxAngle: is the maximum angle between element normals at which the fusion
4199 is still performed; theMaxAngle is measured in radians.
4200 Also it could be a name of variable which defines angle in degrees.
4203 TRUE in case of success, FALSE otherwise.
4206 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
4207 self.mesh.SetParameters(Parameters)
4208 if not IDsOfElements:
4209 IDsOfElements = self.GetElementsId()
4210 Functor = self.smeshpyD.GetFunctor(theCriterion)
4211 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
4213 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
4215 Fuse the neighbouring triangles of the object into quadrangles
4218 theObject: is mesh, submesh or group
4219 theCriterion: is a numerical functor, in terms of enum SMESH.FunctorType,
4220 applied to possible quadrangles to choose a neighbour to fuse with.
4221 Type SMESH.FunctorType._items in the Python Console to see all items.
4222 Note that not all items correspond to numerical functors.
4223 MaxAngle: a max angle between element normals at which the fusion
4224 is still performed; theMaxAngle is measured in radians.
4227 TRUE in case of success, FALSE otherwise.
4230 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
4231 self.mesh.SetParameters(Parameters)
4232 if isinstance( theObject, Mesh ):
4233 theObject = theObject.GetMesh()
4234 Functor = self.smeshpyD.GetFunctor(theCriterion)
4235 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
4237 def QuadToTri (self, IDsOfElements, theCriterion = None):
4239 Split quadrangles into triangles.
4242 IDsOfElements: the faces to be splitted.
4243 theCriterion: is a numerical functor, in terms of enum SMESH.FunctorType, used to
4244 choose a diagonal for splitting. If *theCriterion* is None, which is a default
4245 value, then quadrangles will be split by the smallest diagonal.
4246 Type SMESH.FunctorType._items in the Python Console to see all items.
4247 Note that not all items correspond to numerical functors.
4250 TRUE in case of success, FALSE otherwise.
4252 if IDsOfElements == []:
4253 IDsOfElements = self.GetElementsId()
4254 if theCriterion is None:
4255 theCriterion = FT_MaxElementLength2D
4256 Functor = self.smeshpyD.GetFunctor(theCriterion)
4257 return self.editor.QuadToTri(IDsOfElements, Functor)
4259 def QuadToTriObject (self, theObject, theCriterion = None):
4261 Split quadrangles into triangles.
4264 theObject: the object from which the list of elements is taken,
4265 this is mesh, submesh or group
4266 theCriterion: is a numerical functor, in terms of enum SMESH.FunctorType, used to
4267 choose a diagonal for splitting. If *theCriterion* is None, which is a default
4268 value, then quadrangles will be split by the smallest diagonal.
4269 Type SMESH.FunctorType._items in the Python Console to see all items.
4270 Note that not all items correspond to numerical functors.
4273 TRUE in case of success, FALSE otherwise.
4275 if ( isinstance( theObject, Mesh )):
4276 theObject = theObject.GetMesh()
4277 if theCriterion is None:
4278 theCriterion = FT_MaxElementLength2D
4279 Functor = self.smeshpyD.GetFunctor(theCriterion)
4280 return self.editor.QuadToTriObject(theObject, Functor)
4282 def QuadTo4Tri (self, theElements=[]):
4284 Split each of given quadrangles into 4 triangles. A node is added at the center of
4288 theElements: the faces to be splitted. This can be either mesh, sub-mesh,
4289 group or a list of face IDs. By default all quadrangles are split
4291 unRegister = genObjUnRegister()
4292 if isinstance( theElements, Mesh ):
4293 theElements = theElements.mesh
4294 elif not theElements:
4295 theElements = self.mesh
4296 elif isinstance( theElements, list ):
4297 theElements = self.GetIDSource( theElements, SMESH.FACE )
4298 unRegister.set( theElements )
4299 return self.editor.QuadTo4Tri( theElements )
4301 def SplitQuad (self, IDsOfElements, Diag13):
4303 Split quadrangles into triangles.
4306 IDsOfElements: the faces to be splitted
4307 Diag13: is used to choose a diagonal for splitting.
4310 TRUE in case of success, FALSE otherwise.
4312 if IDsOfElements == []:
4313 IDsOfElements = self.GetElementsId()
4314 return self.editor.SplitQuad(IDsOfElements, Diag13)
4316 def SplitQuadObject (self, theObject, Diag13):
4318 Split quadrangles into triangles.
4321 theObject: the object from which the list of elements is taken,
4322 this is mesh, submesh or group
4323 Diag13: is used to choose a diagonal for splitting.
4326 TRUE in case of success, FALSE otherwise.
4328 if ( isinstance( theObject, Mesh )):
4329 theObject = theObject.GetMesh()
4330 return self.editor.SplitQuadObject(theObject, Diag13)
4332 def BestSplit (self, IDOfQuad, theCriterion):
4334 Find a better splitting of the given quadrangle.
4337 IDOfQuad: the ID of the quadrangle to be splitted.
4338 theCriterion: is a numerical functor, in terms of enum SMESH.FunctorType, used to
4339 choose a diagonal for splitting.
4340 Type SMESH.FunctorType._items in the Python Console to see all items.
4341 Note that not all items correspond to numerical functors.
4344 1 if 1-3 diagonal is better, 2 if 2-4
4345 diagonal is better, 0 if error occurs.
4347 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
4349 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
4351 Split volumic elements into tetrahedrons
4354 elems: either a list of elements or a mesh or a group or a submesh or a filter
4355 method: flags passing splitting method:
4356 smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
4357 smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
4359 unRegister = genObjUnRegister()
4360 if isinstance( elems, Mesh ):
4361 elems = elems.GetMesh()
4362 if ( isinstance( elems, list )):
4363 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
4364 unRegister.set( elems )
4365 self.editor.SplitVolumesIntoTetra(elems, method)
4368 def SplitBiQuadraticIntoLinear(self, elems=None):
4370 Split bi-quadratic elements into linear ones without creation of additional nodes:
4372 - bi-quadratic triangle will be split into 3 linear quadrangles;
4373 - bi-quadratic quadrangle will be split into 4 linear quadrangles;
4374 - tri-quadratic hexahedron will be split into 8 linear hexahedra.
4376 Quadratic elements of lower dimension adjacent to the split bi-quadratic element
4377 will be split in order to keep the mesh conformal.
4380 elems: elements to split\: sub-meshes, groups, filters or element IDs;
4381 if None (default), all bi-quadratic elements will be split
4383 unRegister = genObjUnRegister()
4384 if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
4385 elems = self.editor.MakeIDSource(elems, SMESH.ALL)
4386 unRegister.set( elems )
4388 elems = [ self.GetMesh() ]
4389 if isinstance( elems, Mesh ):
4390 elems = [ elems.GetMesh() ]
4391 if not isinstance( elems, list ):
4393 self.editor.SplitBiQuadraticIntoLinear( elems )
4395 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
4396 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
4398 Split hexahedra into prisms
4401 elems: either a list of elements or a mesh or a group or a submesh or a filter
4402 startHexPoint: a point used to find a hexahedron for which *facetNormal*
4403 gives a normal vector defining facets to split into triangles.
4404 **startHexPoint** can be either a triple of coordinates or a vertex.
4405 facetNormal: a normal to a facet to split into triangles of a
4406 hexahedron found by *startHexPoint*.
4407 **facetNormal** can be either a triple of coordinates or an edge.
4408 method: flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
4409 smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
4410 allDomains: if :code:`False`, only hexahedra adjacent to one closest
4411 to **startHexPoint** are split, else **startHexPoint**
4412 is used to find the facet to split in all domains present in *elems*.
4415 unRegister = genObjUnRegister()
4416 if isinstance( elems, Mesh ):
4417 elems = elems.GetMesh()
4418 if ( isinstance( elems, list )):
4419 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
4420 unRegister.set( elems )
4423 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
4424 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
4425 elif isinstance( startHexPoint, list ):
4426 startHexPoint = SMESH.PointStruct( startHexPoint[0],
4429 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
4430 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
4431 elif isinstance( facetNormal, list ):
4432 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
4435 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
4437 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
4439 def SplitQuadsNearTriangularFacets(self):
4441 Split quadrangle faces near triangular facets of volumes
4443 faces_array = self.GetElementsByType(SMESH.FACE)
4444 for face_id in faces_array:
4445 if self.GetElemNbNodes(face_id) == 4: # quadrangle
4446 quad_nodes = self.mesh.GetElemNodes(face_id)
4447 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
4448 isVolumeFound = False
4449 for node1_elem in node1_elems:
4450 if not isVolumeFound:
4451 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
4452 nb_nodes = self.GetElemNbNodes(node1_elem)
4453 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
4454 volume_elem = node1_elem
4455 volume_nodes = self.mesh.GetElemNodes(volume_elem)
4456 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
4457 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
4458 isVolumeFound = True
4459 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
4460 self.SplitQuad([face_id], False) # diagonal 2-4
4461 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
4462 isVolumeFound = True
4463 self.SplitQuad([face_id], True) # diagonal 1-3
4464 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
4465 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
4466 isVolumeFound = True
4467 self.SplitQuad([face_id], True) # diagonal 1-3
4469 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
4471 **Splits** hexahedrons into tetrahedrons.
4473 This operation uses pattern mapping functionality for splitting.
4476 theObject: the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
4477 theNode000,theNode001: within the range [0,7]; gives the orientation of the
4478 pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
4479 will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
4480 key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
4481 The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
4484 TRUE in case of success, FALSE otherwise.
4492 # (0,0,1) 4.---------.7 * |
4499 # (0,0,0) 0.---------.3
4500 pattern_tetra = "!!! Nb of points: \n 8 \n\
4510 !!! Indices of points of 6 tetras: \n\
4518 pattern = self.smeshpyD.GetPattern()
4519 isDone = pattern.LoadFromFile(pattern_tetra)
4521 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
4524 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
4525 isDone = pattern.MakeMesh(self.mesh, False, False)
4526 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
4528 # split quafrangle faces near triangular facets of volumes
4529 self.SplitQuadsNearTriangularFacets()
4533 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
4535 **Split** hexahedrons into prisms.
4537 Uses the pattern mapping functionality for splitting.
4540 theObject: the object (mesh, submesh or group) from where the list of hexahedrons is taken;
4541 theNode000,theNode001: (within the range [0,7]) gives the orientation of the
4542 pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
4543 will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
4544 will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
4545 Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
4548 TRUE in case of success, FALSE otherwise.
4550 # Pattern: 5.---------.6
4555 # (0,0,1) 4.---------.7 |
4562 # (0,0,0) 0.---------.3
4563 pattern_prism = "!!! Nb of points: \n 8 \n\
4573 !!! Indices of points of 2 prisms: \n\
4577 pattern = self.smeshpyD.GetPattern()
4578 isDone = pattern.LoadFromFile(pattern_prism)
4580 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
4583 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
4584 isDone = pattern.MakeMesh(self.mesh, False, False)
4585 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
4587 # Split quafrangle faces near triangular facets of volumes
4588 self.SplitQuadsNearTriangularFacets()
4592 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
4593 MaxNbOfIterations, MaxAspectRatio, Method):
4598 IDsOfElements: the list if ids of elements to smooth
4599 IDsOfFixedNodes: the list of ids of fixed nodes.
4600 Note that nodes built on edges and boundary nodes are always fixed.
4601 MaxNbOfIterations: the maximum number of iterations
4602 MaxAspectRatio: varies in range [1.0, inf]
4603 Method: is either Laplacian (smesh.LAPLACIAN_SMOOTH)
4604 or Centroidal (smesh.CENTROIDAL_SMOOTH)
4607 TRUE in case of success, FALSE otherwise.
4610 if IDsOfElements == []:
4611 IDsOfElements = self.GetElementsId()
4612 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
4613 self.mesh.SetParameters(Parameters)
4614 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
4615 MaxNbOfIterations, MaxAspectRatio, Method)
4617 def SmoothObject(self, theObject, IDsOfFixedNodes,
4618 MaxNbOfIterations, MaxAspectRatio, Method):
4620 Smooth elements which belong to the given object
4623 theObject: the object to smooth
4624 IDsOfFixedNodes: the list of ids of fixed nodes.
4625 Note that nodes built on edges and boundary nodes are always fixed.
4626 MaxNbOfIterations: the maximum number of iterations
4627 MaxAspectRatio: varies in range [1.0, inf]
4628 Method: is either Laplacian (smesh.LAPLACIAN_SMOOTH)
4629 or Centroidal (smesh.CENTROIDAL_SMOOTH)
4632 TRUE in case of success, FALSE otherwise.
4635 if ( isinstance( theObject, Mesh )):
4636 theObject = theObject.GetMesh()
4637 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
4638 MaxNbOfIterations, MaxAspectRatio, Method)
4640 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
4641 MaxNbOfIterations, MaxAspectRatio, Method):
4643 Parametrically smooth the given elements
4646 IDsOfElements: the list if ids of elements to smooth
4647 IDsOfFixedNodes: the list of ids of fixed nodes.
4648 Note that nodes built on edges and boundary nodes are always fixed.
4649 MaxNbOfIterations: the maximum number of iterations
4650 MaxAspectRatio: varies in range [1.0, inf]
4651 Method: is either Laplacian (smesh.LAPLACIAN_SMOOTH)
4652 or Centroidal (smesh.CENTROIDAL_SMOOTH)
4655 TRUE in case of success, FALSE otherwise.
4658 if IDsOfElements == []:
4659 IDsOfElements = self.GetElementsId()
4660 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
4661 self.mesh.SetParameters(Parameters)
4662 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
4663 MaxNbOfIterations, MaxAspectRatio, Method)
4665 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
4666 MaxNbOfIterations, MaxAspectRatio, Method):
4668 Parametrically smooth the elements which belong to the given object
4671 theObject: the object to smooth
4672 IDsOfFixedNodes: the list of ids of fixed nodes.
4673 Note that nodes built on edges and boundary nodes are always fixed.
4674 MaxNbOfIterations: the maximum number of iterations
4675 MaxAspectRatio: varies in range [1.0, inf]
4676 Method: is either Laplacian (smesh.LAPLACIAN_SMOOTH)
4677 or Centroidal (smesh.CENTROIDAL_SMOOTH)
4680 TRUE in case of success, FALSE otherwise.
4683 if ( isinstance( theObject, Mesh )):
4684 theObject = theObject.GetMesh()
4685 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
4686 MaxNbOfIterations, MaxAspectRatio, Method)
4688 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
4690 Convert the mesh to quadratic or bi-quadratic, deletes old elements, replacing
4691 them with quadratic with the same id.
4694 theForce3d: new node creation method:
4695 0 - the medium node lies at the geometrical entity from which the mesh element is built
4696 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
4697 theSubMesh: a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
4698 theToBiQuad: If True, converts the mesh to bi-quadratic
4701 SMESH.ComputeError which can hold a warning
4704 if isinstance( theSubMesh, Mesh ):
4705 theSubMesh = theSubMesh.mesh
4707 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
4710 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
4712 self.editor.ConvertToQuadratic(theForce3d)
4713 error = self.editor.GetLastError()
4714 if error and error.comment:
4718 def ConvertFromQuadratic(self, theSubMesh=None):
4720 Convert the mesh from quadratic to ordinary,
4721 deletes old quadratic elements,
4722 replacing them with ordinary mesh elements with the same id.
4725 theSubMesh: a group or a sub-mesh to convert;
4728 in this case the mesh can become not conformal
4732 self.editor.ConvertFromQuadraticObject(theSubMesh)
4734 return self.editor.ConvertFromQuadratic()
4736 def Make2DMeshFrom3D(self):
4738 Create 2D mesh as skin on boundary faces of a 3D mesh
4741 TRUE if operation has been completed successfully, FALSE otherwise
4744 return self.editor.Make2DMeshFrom3D()
4746 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
4747 toCopyElements=False, toCopyExistingBondary=False):
4749 Create missing boundary elements
4752 elements: elements whose boundary is to be checked:
4753 mesh, group, sub-mesh or list of elements
4754 if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
4755 dimension: defines type of boundary elements to create, either of
4756 { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
4757 SMESH.BND_1DFROM3D create mesh edges on all borders of free facets of 3D cells
4758 groupName: a name of group to store created boundary elements in,
4759 "" means not to create the group
4760 meshName: a name of new mesh to store created boundary elements in,
4761 "" means not to create the new mesh
4762 toCopyElements: if true, the checked elements will be copied into
4763 the new mesh else only boundary elements will be copied into the new mesh
4764 toCopyExistingBondary: if true, not only new but also pre-existing
4765 boundary elements will be copied into the new mesh
4768 tuple (mesh, group) where boundary elements were added to
4771 unRegister = genObjUnRegister()
4772 if isinstance( elements, Mesh ):
4773 elements = elements.GetMesh()
4774 if ( isinstance( elements, list )):
4775 elemType = SMESH.ALL
4776 if elements: elemType = self.GetElementType( elements[0], iselem=True)
4777 elements = self.editor.MakeIDSource(elements, elemType)
4778 unRegister.set( elements )
4779 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
4780 toCopyElements,toCopyExistingBondary)
4781 if mesh: mesh = self.smeshpyD.Mesh(mesh)
4784 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
4785 toCopyAll=False, groups=[]):
4787 **Create** missing boundary elements around either the whole mesh or
4791 dimension: defines type of boundary elements to create, either of
4792 { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
4793 groupName: a name of group to store all boundary elements in,
4794 "" means not to create the group
4795 meshName: a name of a new mesh, which is a copy of the initial
4796 mesh + created boundary elements; "" means not to create the new mesh
4797 toCopyAll: if true, the whole initial mesh will be copied into
4798 the new mesh else only boundary elements will be copied into the new mesh
4799 groups: groups of elements to make boundary around
4802 tuple( long, mesh, groups )
4803 long - number of added boundary elements
4804 mesh - the mesh where elements were added to
4805 group - the group of boundary elements or None
4808 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
4810 if mesh: mesh = self.smeshpyD.Mesh(mesh)
4811 return nb, mesh, group
4813 def RenumberNodes(self):
4815 Renumber mesh nodes (Obsolete, does nothing)
4817 self.editor.RenumberNodes()
4819 def RenumberElements(self):
4821 Renumber mesh elements (Obsole, does nothing)
4823 self.editor.RenumberElements()
4825 def _getIdSourceList(self, arg, idType, unRegister):
4827 Private method converting *arg* into a list of SMESH_IdSource's
4829 if arg and isinstance( arg, list ):
4830 if isinstance( arg[0], int ):
4831 arg = self.GetIDSource( arg, idType )
4832 unRegister.set( arg )
4833 elif isinstance( arg[0], Mesh ):
4834 arg[0] = arg[0].GetMesh()
4835 elif isinstance( arg, Mesh ):
4837 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
4841 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
4842 MakeGroups=False, TotalAngle=False):
4844 Generate new elements by rotation of the given elements and nodes around the axis
4847 nodes: nodes to revolve: a list including ids, groups, sub-meshes or a mesh
4848 edges: edges to revolve: a list including ids, groups, sub-meshes or a mesh
4849 faces: faces to revolve: a list including ids, groups, sub-meshes or a mesh
4850 Axis: the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
4851 AngleInRadians: the angle of Rotation (in radians) or a name of variable
4852 which defines angle in degrees
4853 NbOfSteps: the number of steps
4854 Tolerance: tolerance
4855 MakeGroups: forces the generation of new groups from existing ones
4856 TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
4857 of all steps, else - size of each step
4860 the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4863 unRegister = genObjUnRegister()
4864 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
4865 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
4866 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
4868 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
4869 Axis = self.smeshpyD.GetAxisStruct( Axis )
4870 if isinstance( Axis, list ):
4871 Axis = SMESH.AxisStruct( *Axis )
4873 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
4874 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
4875 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
4876 self.mesh.SetParameters(Parameters)
4877 if TotalAngle and NbOfSteps:
4878 AngleInRadians /= NbOfSteps
4879 return self.editor.RotationSweepObjects( nodes, edges, faces,
4880 Axis, AngleInRadians,
4881 NbOfSteps, Tolerance, MakeGroups)
4883 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
4884 MakeGroups=False, TotalAngle=False):
4886 Generate new elements by rotation of the elements around the axis
4889 IDsOfElements: the list of ids of elements to sweep
4890 Axis: the axis of rotation, AxisStruct or line(geom object)
4891 AngleInRadians: the angle of Rotation (in radians) or a name of variable which defines angle in degrees
4892 NbOfSteps: the number of steps
4893 Tolerance: tolerance
4894 MakeGroups: forces the generation of new groups from existing ones
4895 TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
4896 of all steps, else - size of each step
4899 the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4902 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
4903 AngleInRadians, NbOfSteps, Tolerance,
4904 MakeGroups, TotalAngle)
4906 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
4907 MakeGroups=False, TotalAngle=False):
4909 Generate new elements by rotation of the elements of object around the axis
4910 theObject object which elements should be sweeped.
4911 It can be a mesh, a sub mesh or a group.
4914 Axis: the axis of rotation, AxisStruct or line(geom object)
4915 AngleInRadians: the angle of Rotation
4916 NbOfSteps: number of steps
4917 Tolerance: tolerance
4918 MakeGroups: forces the generation of new groups from existing ones
4919 TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
4920 of all steps, else - size of each step
4923 the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4926 return self.RotationSweepObjects( [], theObject, theObject, Axis,
4927 AngleInRadians, NbOfSteps, Tolerance,
4928 MakeGroups, TotalAngle )
4930 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
4931 MakeGroups=False, TotalAngle=False):
4933 Generate new elements by rotation of the elements of object around the axis
4934 theObject object which elements should be sweeped.
4935 It can be a mesh, a sub mesh or a group.
4938 Axis: the axis of rotation, AxisStruct or line(geom object)
4939 AngleInRadians: the angle of Rotation
4940 NbOfSteps: number of steps
4941 Tolerance: tolerance
4942 MakeGroups: forces the generation of new groups from existing ones
4943 TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
4944 of all steps, else - size of each step
4947 the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4950 return self.RotationSweepObjects([],theObject,[], Axis,
4951 AngleInRadians, NbOfSteps, Tolerance,
4952 MakeGroups, TotalAngle)
4954 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
4955 MakeGroups=False, TotalAngle=False):
4957 Generate new elements by rotation of the elements of object around the axis
4958 theObject object which elements should be sweeped.
4959 It can be a mesh, a sub mesh or a group.
4962 Axis: the axis of rotation, AxisStruct or line(geom object)
4963 AngleInRadians: the angle of Rotation
4964 NbOfSteps: number of steps
4965 Tolerance: tolerance
4966 MakeGroups: forces the generation of new groups from existing ones
4967 TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
4968 of all steps, else - size of each step
4971 the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4974 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
4975 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
4977 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False,
4978 scaleFactors=[], linearVariation=False, basePoint=[] ):
4980 Generate new elements by extrusion of the given elements and nodes
4983 nodes: nodes to extrude: a list including ids, groups, sub-meshes or a mesh
4984 edges: edges to extrude: a list including ids, groups, sub-meshes or a mesh
4985 faces: faces to extrude: a list including ids, groups, sub-meshes or a mesh
4986 StepVector: vector or DirStruct or 3 vector components, defining
4987 the direction and value of extrusion for one step (the total extrusion
4988 length will be NbOfSteps * ||StepVector||)
4989 NbOfSteps: the number of steps
4990 MakeGroups: forces the generation of new groups from existing ones
4991 scaleFactors: optional scale factors to apply during extrusion
4992 linearVariation: if *True*, scaleFactors are spread over all *scaleFactors*,
4993 else scaleFactors[i] is applied to nodes at the i-th extrusion step
4994 basePoint: optional scaling center; if not provided, a gravity center of
4995 nodes and elements being extruded is used as the scaling center.
4998 - a list of tree components of the point or
5003 the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5005 :ref:`tui_extrusion` example
5007 unRegister = genObjUnRegister()
5008 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
5009 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
5010 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
5012 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
5013 StepVector = self.smeshpyD.GetDirStruct(StepVector)
5014 if isinstance( StepVector, list ):
5015 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
5017 if isinstance( basePoint, int):
5018 xyz = self.GetNodeXYZ( basePoint )
5020 raise RuntimeError, "Invalid node ID: %s" % basePoint
5022 if isinstance( basePoint, geomBuilder.GEOM._objref_GEOM_Object ):
5023 basePoint = self.geompyD.PointCoordinates( basePoint )
5025 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
5026 Parameters = StepVector.PS.parameters + var_separator + Parameters
5027 self.mesh.SetParameters(Parameters)
5029 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
5030 StepVector, NbOfSteps,
5031 scaleFactors, linearVariation, basePoint,
5035 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
5037 Generate new elements by extrusion of the elements with given ids
5040 IDsOfElements: the list of ids of elements or nodes for extrusion
5041 StepVector: vector or DirStruct or 3 vector components, defining
5042 the direction and value of extrusion for one step (the total extrusion
5043 length will be NbOfSteps * ||StepVector||)
5044 NbOfSteps: the number of steps
5045 MakeGroups: forces the generation of new groups from existing ones
5046 IsNodes: is True if elements with given ids are nodes
5049 the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5051 :ref:`tui_extrusion` example
5054 if IsNodes: n = IDsOfElements
5055 else : e,f, = IDsOfElements,IDsOfElements
5056 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
5058 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
5059 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
5061 Generate new elements by extrusion along the normal to a discretized surface or wire
5064 Elements: elements to extrude - a list including ids, groups, sub-meshes or a mesh.
5065 Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
5066 StepSize: length of one extrusion step (the total extrusion
5067 length will be *NbOfSteps* *StepSize*).
5068 NbOfSteps: number of extrusion steps.
5069 ByAverageNormal: if True each node is translated by *StepSize*
5070 along the average of the normal vectors to the faces sharing the node;
5071 else each node is translated along the same average normal till
5072 intersection with the plane got by translation of the face sharing
5073 the node along its own normal by *StepSize*.
5074 UseInputElemsOnly: to use only *Elements* when computing extrusion direction
5075 for every node of *Elements*.
5076 MakeGroups: forces generation of new groups from existing ones.
5077 Dim: dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
5078 is not yet implemented. This parameter is used if *Elements* contains
5079 both faces and edges, i.e. *Elements* is a Mesh.
5082 the list of created groups (SMESH_GroupBase) if *MakeGroups=True*,
5083 empty list otherwise.
5084 :ref:`tui_extrusion` example
5087 unRegister = genObjUnRegister()
5088 if isinstance( Elements, Mesh ):
5089 Elements = [ Elements.GetMesh() ]
5090 if isinstance( Elements, list ):
5092 raise RuntimeError, "Elements empty!"
5093 if isinstance( Elements[0], int ):
5094 Elements = self.GetIDSource( Elements, SMESH.ALL )
5095 unRegister.set( Elements )
5096 if not isinstance( Elements, list ):
5097 Elements = [ Elements ]
5098 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
5099 self.mesh.SetParameters(Parameters)
5100 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
5101 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
5103 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
5105 Generate new elements by extrusion of the elements or nodes which belong to the object
5108 theObject: the object whose elements or nodes should be processed.
5109 It can be a mesh, a sub-mesh or a group.
5110 StepVector: vector or DirStruct or 3 vector components, defining
5111 the direction and value of extrusion for one step (the total extrusion
5112 length will be NbOfSteps * ||StepVector||)
5113 NbOfSteps: the number of steps
5114 MakeGroups: forces the generation of new groups from existing ones
5115 IsNodes: is True if elements to extrude are nodes
5118 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5119 :ref:`tui_extrusion` example
5123 if IsNodes: n = theObject
5124 else : e,f, = theObject,theObject
5125 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
5127 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
5129 Generate new elements by extrusion of edges which belong to the object
5132 theObject: object whose 1D elements should be processed.
5133 It can be a mesh, a sub-mesh or a group.
5134 StepVector: vector or DirStruct or 3 vector components, defining
5135 the direction and value of extrusion for one step (the total extrusion
5136 length will be NbOfSteps * ||StepVector||)
5137 NbOfSteps: the number of steps
5138 MakeGroups: to generate new groups from existing ones
5141 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5142 :ref:`tui_extrusion` example
5145 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
5147 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
5149 Generate new elements by extrusion of faces which belong to the object
5152 theObject: object whose 2D elements should be processed.
5153 It can be a mesh, a sub-mesh or a group.
5154 StepVector: vector or DirStruct or 3 vector components, defining
5155 the direction and value of extrusion for one step (the total extrusion
5156 length will be NbOfSteps * ||StepVector||)
5157 NbOfSteps: the number of steps
5158 MakeGroups: forces the generation of new groups from existing ones
5161 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5162 :ref:`tui_extrusion` example
5165 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
5167 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
5168 ExtrFlags, SewTolerance, MakeGroups=False):
5170 Generate new elements by extrusion of the elements with given ids
5173 IDsOfElements: is ids of elements
5174 StepVector: vector or DirStruct or 3 vector components, defining
5175 the direction and value of extrusion for one step (the total extrusion
5176 length will be NbOfSteps * ||StepVector||)
5177 NbOfSteps: the number of steps
5178 ExtrFlags: sets flags for extrusion
5179 SewTolerance: uses for comparing locations of nodes if flag
5180 EXTRUSION_FLAG_SEW is set
5181 MakeGroups: forces the generation of new groups from existing ones
5184 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5187 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
5188 StepVector = self.smeshpyD.GetDirStruct(StepVector)
5189 if isinstance( StepVector, list ):
5190 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
5191 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
5192 ExtrFlags, SewTolerance, MakeGroups)
5194 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
5195 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
5196 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
5198 Generate new elements by extrusion of the given elements and nodes along the path.
5199 The path of extrusion must be a meshed edge.
5202 Nodes: nodes to extrude: a list including ids, groups, sub-meshes or a mesh
5203 Edges: edges to extrude: a list including ids, groups, sub-meshes or a mesh
5204 Faces: faces to extrude: a list including ids, groups, sub-meshes or a mesh
5205 PathMesh: 1D mesh or 1D sub-mesh, along which proceeds the extrusion
5206 PathShape: shape (edge) defines the sub-mesh of PathMesh if PathMesh
5207 contains not only path segments, else it can be None
5208 NodeStart: the first or the last node on the path. Defines the direction of extrusion
5209 HasAngles: allows the shape to be rotated around the path
5210 to get the resulting mesh in a helical fashion
5211 Angles: list of angles
5212 LinearVariation: forces the computation of rotation angles as linear
5213 variation of the given Angles along path steps
5214 HasRefPoint: allows using the reference point
5215 RefPoint: the point around which the shape is rotated (the mass center of the
5216 shape by default). The User can specify any point as the Reference Point.
5217 MakeGroups: forces the generation of new groups from existing ones
5220 list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
5221 :ref:`tui_extrusion_along_path` example
5224 unRegister = genObjUnRegister()
5225 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
5226 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
5227 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
5229 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
5230 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
5231 if isinstance( RefPoint, list ):
5232 if not RefPoint: RefPoint = [0,0,0]
5233 RefPoint = SMESH.PointStruct( *RefPoint )
5234 if isinstance( PathMesh, Mesh ):
5235 PathMesh = PathMesh.GetMesh()
5236 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
5237 Parameters = AnglesParameters + var_separator + RefPoint.parameters
5238 self.mesh.SetParameters(Parameters)
5239 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
5240 PathMesh, PathShape, NodeStart,
5241 HasAngles, Angles, LinearVariation,
5242 HasRefPoint, RefPoint, MakeGroups)
5244 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
5245 HasAngles=False, Angles=[], LinearVariation=False,
5246 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
5247 ElemType=SMESH.FACE):
5249 Generate new elements by extrusion of the given elements
5250 The path of extrusion must be a meshed edge.
5253 Base: mesh or group, or sub-mesh, or list of ids of elements for extrusion
5254 Path: 1D mesh or 1D sub-mesh, along which proceeds the extrusion
5255 NodeStart: the start node from Path. Defines the direction of extrusion
5256 HasAngles: allows the shape to be rotated around the path
5257 to get the resulting mesh in a helical fashion
5258 Angles: list of angles in radians
5259 LinearVariation: forces the computation of rotation angles as linear
5260 variation of the given Angles along path steps
5261 HasRefPoint: allows using the reference point
5262 RefPoint: the point around which the elements are rotated (the mass
5263 center of the elements by default).
5264 The User can specify any point as the Reference Point.
5265 RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
5266 MakeGroups: forces the generation of new groups from existing ones
5267 ElemType: type of elements for extrusion (if param Base is a mesh)
5270 list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
5271 only SMESH::Extrusion_Error otherwise
5272 :ref:`tui_extrusion_along_path` example
5276 if ElemType == SMESH.NODE: n = Base
5277 if ElemType == SMESH.EDGE: e = Base
5278 if ElemType == SMESH.FACE: f = Base
5279 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
5280 HasAngles, Angles, LinearVariation,
5281 HasRefPoint, RefPoint, MakeGroups)
5282 if MakeGroups: return gr,er
5285 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
5286 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
5287 MakeGroups=False, LinearVariation=False):
5289 Generate new elements by extrusion of the given elements
5290 The path of extrusion must be a meshed edge.
5293 IDsOfElements: ids of elements
5294 PathMesh: mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
5295 PathShape: shape(edge) defines the sub-mesh for the path
5296 NodeStart: the first or the last node on the edge. Defines the direction of extrusion
5297 HasAngles: allows the shape to be rotated around the path
5298 to get the resulting mesh in a helical fashion
5299 Angles: list of angles in radians
5300 HasRefPoint: allows using the reference point
5301 RefPoint: the point around which the shape is rotated (the mass center of the shape by default).
5302 The User can specify any point as the Reference Point.
5303 MakeGroups: forces the generation of new groups from existing ones
5304 LinearVariation: forces the computation of rotation angles as linear
5305 variation of the given Angles along path steps
5308 list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
5309 only SMESH::Extrusion_Error otherwise
5310 :ref:`tui_extrusion_along_path` example
5313 n,e,f = [],IDsOfElements,IDsOfElements
5314 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
5315 NodeStart, HasAngles, Angles,
5317 HasRefPoint, RefPoint, MakeGroups)
5318 if MakeGroups: return gr,er
5321 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
5322 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
5323 MakeGroups=False, LinearVariation=False):
5325 Generate new elements by extrusion of the elements which belong to the object
5326 The path of extrusion must be a meshed edge.
5329 theObject: the object whose elements should be processed.
5330 It can be a mesh, a sub-mesh or a group.
5331 PathMesh: mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
5332 PathShape: shape(edge) defines the sub-mesh for the path
5333 NodeStart: the first or the last node on the edge. Defines the direction of extrusion
5334 HasAngles: allows the shape to be rotated around the path
5335 to get the resulting mesh in a helical fashion
5336 Angles: list of angles
5337 HasRefPoint: allows using the reference point
5338 RefPoint: the point around which the shape is rotated (the mass center of the shape by default).
5339 The User can specify any point as the Reference Point.
5340 MakeGroups: forces the generation of new groups from existing ones
5341 LinearVariation: forces the computation of rotation angles as linear
5342 variation of the given Angles along path steps
5345 list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
5346 only SMESH::Extrusion_Error otherwise
5347 :ref:`tui_extrusion_along_path` example
5350 n,e,f = [],theObject,theObject
5351 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
5352 HasAngles, Angles, LinearVariation,
5353 HasRefPoint, RefPoint, MakeGroups)
5354 if MakeGroups: return gr,er
5357 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
5358 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
5359 MakeGroups=False, LinearVariation=False):
5361 Generate new elements by extrusion of mesh segments which belong to the object
5362 The path of extrusion must be a meshed edge.
5365 theObject: the object whose 1D elements should be processed.
5366 It can be a mesh, a sub-mesh or a group.
5367 PathMesh: mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
5368 PathShape: shape(edge) defines the sub-mesh for the path
5369 NodeStart: the first or the last node on the edge. Defines the direction of extrusion
5370 HasAngles: allows the shape to be rotated around the path
5371 to get the resulting mesh in a helical fashion
5372 Angles: list of angles
5373 HasRefPoint: allows using the reference point
5374 RefPoint the point: around which the shape is rotated (the mass center of the shape by default).
5375 The User can specify any point as the Reference Point.
5376 MakeGroups: forces the generation of new groups from existing ones
5377 LinearVariation: forces the computation of rotation angles as linear
5378 variation of the given Angles along path steps
5381 list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
5382 only SMESH::Extrusion_Error otherwise
5383 :ref:`tui_extrusion_along_path` example
5386 n,e,f = [],theObject,[]
5387 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
5388 HasAngles, Angles, LinearVariation,
5389 HasRefPoint, RefPoint, MakeGroups)
5390 if MakeGroups: return gr,er
5393 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
5394 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
5395 MakeGroups=False, LinearVariation=False):
5397 Generate new elements by extrusion of faces which belong to the object
5398 The path of extrusion must be a meshed edge.
5401 theObject: the object whose 2D elements should be processed.
5402 It can be a mesh, a sub-mesh or a group.
5403 PathMesh: mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
5404 PathShape: shape(edge) defines the sub-mesh for the path
5405 NodeStart: the first or the last node on the edge. Defines the direction of extrusion
5406 HasAngles: allows the shape to be rotated around the path
5407 to get the resulting mesh in a helical fashion
5408 Angles: list of angles
5409 HasRefPoint: allows using the reference point
5410 RefPoint: the point around which the shape is rotated (the mass center of the shape by default).
5411 The User can specify any point as the Reference Point.
5412 MakeGroups: forces the generation of new groups from existing ones
5413 LinearVariation: forces the computation of rotation angles as linear
5414 variation of the given Angles along path steps
5417 list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
5418 only SMESH::Extrusion_Error otherwise
5419 :ref:`tui_extrusion_along_path` example
5422 n,e,f = [],[],theObject
5423 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
5424 HasAngles, Angles, LinearVariation,
5425 HasRefPoint, RefPoint, MakeGroups)
5426 if MakeGroups: return gr,er
5429 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
5431 Create a symmetrical copy of mesh elements
5434 IDsOfElements: list of elements ids
5435 Mirror: is AxisStruct or geom object(point, line, plane)
5436 theMirrorType: smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
5437 If the Mirror is a geom object this parameter is unnecessary
5438 Copy: allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
5439 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5442 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5445 if IDsOfElements == []:
5446 IDsOfElements = self.GetElementsId()
5447 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
5448 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
5449 theMirrorType = Mirror._mirrorType
5451 self.mesh.SetParameters(Mirror.parameters)
5452 if Copy and MakeGroups:
5453 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
5454 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
5457 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
5459 Create a new mesh by a symmetrical copy of mesh elements
5462 IDsOfElements: the list of elements ids
5463 Mirror: is AxisStruct or geom object (point, line, plane)
5464 theMirrorType: smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
5465 If the Mirror is a geom object this parameter is unnecessary
5466 MakeGroups: to generate new groups from existing ones
5467 NewMeshName: a name of the new mesh to create
5470 instance of Mesh class
5473 if IDsOfElements == []:
5474 IDsOfElements = self.GetElementsId()
5475 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
5476 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
5477 theMirrorType = Mirror._mirrorType
5479 self.mesh.SetParameters(Mirror.parameters)
5480 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
5481 MakeGroups, NewMeshName)
5482 return Mesh(self.smeshpyD,self.geompyD,mesh)
5484 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
5486 Create a symmetrical copy of the object
5489 theObject: mesh, submesh or group
5490 Mirror: AxisStruct or geom object (point, line, plane)
5491 theMirrorType: smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
5492 If the Mirror is a geom object this parameter is unnecessary
5493 Copy: allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
5494 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5497 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5500 if ( isinstance( theObject, Mesh )):
5501 theObject = theObject.GetMesh()
5502 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
5503 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
5504 theMirrorType = Mirror._mirrorType
5506 self.mesh.SetParameters(Mirror.parameters)
5507 if Copy and MakeGroups:
5508 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
5509 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
5512 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
5514 Create a new mesh by a symmetrical copy of the object
5517 theObject: mesh, submesh or group
5518 Mirror: AxisStruct or geom object (point, line, plane)
5519 theMirrorType: smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
5520 If the Mirror is a geom object this parameter is unnecessary
5521 MakeGroups: forces the generation of new groups from existing ones
5522 NewMeshName: the name of the new mesh to create
5525 instance of Mesh class
5528 if ( isinstance( theObject, Mesh )):
5529 theObject = theObject.GetMesh()
5530 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
5531 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
5532 theMirrorType = Mirror._mirrorType
5534 self.mesh.SetParameters(Mirror.parameters)
5535 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
5536 MakeGroups, NewMeshName)
5537 return Mesh( self.smeshpyD,self.geompyD,mesh )
5539 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
5541 Translate the elements
5544 IDsOfElements: list of elements ids
5545 Vector: the direction of translation (DirStruct or vector or 3 vector components)
5546 Copy: allows copying the translated elements
5547 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5550 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5553 if IDsOfElements == []:
5554 IDsOfElements = self.GetElementsId()
5555 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
5556 Vector = self.smeshpyD.GetDirStruct(Vector)
5557 if isinstance( Vector, list ):
5558 Vector = self.smeshpyD.MakeDirStruct(*Vector)
5559 self.mesh.SetParameters(Vector.PS.parameters)
5560 if Copy and MakeGroups:
5561 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
5562 self.editor.Translate(IDsOfElements, Vector, Copy)
5565 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
5567 Create a new mesh of translated elements
5570 IDsOfElements: list of elements ids
5571 Vector: the direction of translation (DirStruct or vector or 3 vector components)
5572 MakeGroups: forces the generation of new groups from existing ones
5573 NewMeshName: the name of the newly created mesh
5576 instance of Mesh class
5579 if IDsOfElements == []:
5580 IDsOfElements = self.GetElementsId()
5581 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
5582 Vector = self.smeshpyD.GetDirStruct(Vector)
5583 if isinstance( Vector, list ):
5584 Vector = self.smeshpyD.MakeDirStruct(*Vector)
5585 self.mesh.SetParameters(Vector.PS.parameters)
5586 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
5587 return Mesh ( self.smeshpyD, self.geompyD, mesh )
5589 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
5591 Translate the object
5594 theObject: the object to translate (mesh, submesh, or group)
5595 Vector: direction of translation (DirStruct or geom vector or 3 vector components)
5596 Copy: allows copying the translated elements
5597 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5600 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5603 if ( isinstance( theObject, Mesh )):
5604 theObject = theObject.GetMesh()
5605 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
5606 Vector = self.smeshpyD.GetDirStruct(Vector)
5607 if isinstance( Vector, list ):
5608 Vector = self.smeshpyD.MakeDirStruct(*Vector)
5609 self.mesh.SetParameters(Vector.PS.parameters)
5610 if Copy and MakeGroups:
5611 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
5612 self.editor.TranslateObject(theObject, Vector, Copy)
5615 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
5617 Create a new mesh from the translated object
5620 theObject: the object to translate (mesh, submesh, or group)
5621 Vector: the direction of translation (DirStruct or geom vector or 3 vector components)
5622 MakeGroups: forces the generation of new groups from existing ones
5623 NewMeshName: the name of the newly created mesh
5626 instance of Mesh class
5629 if isinstance( theObject, Mesh ):
5630 theObject = theObject.GetMesh()
5631 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
5632 Vector = self.smeshpyD.GetDirStruct(Vector)
5633 if isinstance( Vector, list ):
5634 Vector = self.smeshpyD.MakeDirStruct(*Vector)
5635 self.mesh.SetParameters(Vector.PS.parameters)
5636 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
5637 return Mesh( self.smeshpyD, self.geompyD, mesh )
5641 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
5646 theObject: the object to translate (mesh, submesh, or group)
5647 thePoint: base point for scale (SMESH.PointStruct or list of 3 coordinates)
5648 theScaleFact: list of 1-3 scale factors for axises
5649 Copy: allows copying the translated elements
5650 MakeGroups: forces the generation of new groups from existing
5654 list of created groups (SMESH_GroupBase) if MakeGroups=True,
5655 empty list otherwise
5657 unRegister = genObjUnRegister()
5658 if ( isinstance( theObject, Mesh )):
5659 theObject = theObject.GetMesh()
5660 if ( isinstance( theObject, list )):
5661 theObject = self.GetIDSource(theObject, SMESH.ALL)
5662 unRegister.set( theObject )
5663 if ( isinstance( thePoint, list )):
5664 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
5665 if ( isinstance( theScaleFact, float )):
5666 theScaleFact = [theScaleFact]
5667 if ( isinstance( theScaleFact, int )):
5668 theScaleFact = [ float(theScaleFact)]
5670 self.mesh.SetParameters(thePoint.parameters)
5672 if Copy and MakeGroups:
5673 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
5674 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
5677 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
5679 Create a new mesh from the translated object
5682 theObject: the object to translate (mesh, submesh, or group)
5683 thePoint: base point for scale (SMESH.PointStruct or list of 3 coordinates)
5684 theScaleFact: list of 1-3 scale factors for axises
5685 MakeGroups: forces the generation of new groups from existing ones
5686 NewMeshName: the name of the newly created mesh
5689 instance of Mesh class
5691 unRegister = genObjUnRegister()
5692 if (isinstance(theObject, Mesh)):
5693 theObject = theObject.GetMesh()
5694 if ( isinstance( theObject, list )):
5695 theObject = self.GetIDSource(theObject,SMESH.ALL)
5696 unRegister.set( theObject )
5697 if ( isinstance( thePoint, list )):
5698 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
5699 if ( isinstance( theScaleFact, float )):
5700 theScaleFact = [theScaleFact]
5701 if ( isinstance( theScaleFact, int )):
5702 theScaleFact = [ float(theScaleFact)]
5704 self.mesh.SetParameters(thePoint.parameters)
5705 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
5706 MakeGroups, NewMeshName)
5707 return Mesh( self.smeshpyD, self.geompyD, mesh )
5711 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
5716 IDsOfElements: list of elements ids
5717 Axis: the axis of rotation (AxisStruct or geom line)
5718 AngleInRadians: the angle of rotation (in radians) or a name of variable which defines angle in degrees
5719 Copy: allows copying the rotated elements
5720 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5723 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5727 if IDsOfElements == []:
5728 IDsOfElements = self.GetElementsId()
5729 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
5730 Axis = self.smeshpyD.GetAxisStruct(Axis)
5731 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
5732 Parameters = Axis.parameters + var_separator + Parameters
5733 self.mesh.SetParameters(Parameters)
5734 if Copy and MakeGroups:
5735 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
5736 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
5739 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
5741 Create a new mesh of rotated elements
5744 IDsOfElements: list of element ids
5745 Axis: the axis of rotation (AxisStruct or geom line)
5746 AngleInRadians: the angle of rotation (in radians) or a name of variable which defines angle in degrees
5747 MakeGroups: forces the generation of new groups from existing ones
5748 NewMeshName: the name of the newly created mesh
5751 instance of Mesh class
5754 if IDsOfElements == []:
5755 IDsOfElements = self.GetElementsId()
5756 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
5757 Axis = self.smeshpyD.GetAxisStruct(Axis)
5758 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
5759 Parameters = Axis.parameters + var_separator + Parameters
5760 self.mesh.SetParameters(Parameters)
5761 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
5762 MakeGroups, NewMeshName)
5763 return Mesh( self.smeshpyD, self.geompyD, mesh )
5765 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
5770 theObject: the object to rotate( mesh, submesh, or group)
5771 Axis: the axis of rotation (AxisStruct or geom line)
5772 AngleInRadians: the angle of rotation (in radians) or a name of variable which defines angle in degrees
5773 Copy: allows copying the rotated elements
5774 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5777 list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5780 if (isinstance(theObject, Mesh)):
5781 theObject = theObject.GetMesh()
5782 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
5783 Axis = self.smeshpyD.GetAxisStruct(Axis)
5784 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
5785 Parameters = Axis.parameters + ":" + Parameters
5786 self.mesh.SetParameters(Parameters)
5787 if Copy and MakeGroups:
5788 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
5789 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
5792 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
5794 Create a new mesh from the rotated object
5797 theObject: the object to rotate (mesh, submesh, or group)
5798 Axis: the axis of rotation (AxisStruct or geom line)
5799 AngleInRadians: the angle of rotation (in radians) or a name of variable which defines angle in degrees
5800 MakeGroups: forces the generation of new groups from existing ones
5801 NewMeshName: the name of the newly created mesh
5804 instance of Mesh class
5807 if (isinstance( theObject, Mesh )):
5808 theObject = theObject.GetMesh()
5809 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
5810 Axis = self.smeshpyD.GetAxisStruct(Axis)
5811 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
5812 Parameters = Axis.parameters + ":" + Parameters
5813 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
5814 MakeGroups, NewMeshName)
5815 self.mesh.SetParameters(Parameters)
5816 return Mesh( self.smeshpyD, self.geompyD, mesh )
5818 def Offset(self, theObject, theValue, MakeGroups=False, NewMeshName=''):
5820 Create an offset mesh from the given 2D object
5823 theObject: the source object (mesh, submesh, group or filter)
5824 theValue: signed offset size
5825 MakeGroups: forces the generation of new groups from existing ones
5826 NewMeshName: the name of a mesh to create. If empty, offset elements are added to this mesh
5829 A tuple (mesh, list_of_groups)
5832 if isinstance( theObject, Mesh ):
5833 theObject = theObject.GetMesh()
5834 theValue,Parameters,hasVars = ParseParameters(theValue)
5835 mesh_groups = self.editor.Offset(theObject, theValue, MakeGroups, NewMeshName )
5836 self.mesh.SetParameters(Parameters)
5837 # if mesh_groups[0]:
5838 # return Mesh( self.smeshpyD, self.geompyD, mesh_groups[0] ), mesh_groups[1]
5841 def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
5843 Find groups of adjacent nodes within Tolerance.
5846 Tolerance: the value of tolerance
5847 SeparateCornerAndMediumNodes: if *True*, in quadratic mesh puts
5848 corner and medium nodes in separate groups thus preventing
5849 their further merge.
5852 the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
5855 return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
5857 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
5858 exceptNodes=[], SeparateCornerAndMediumNodes=False):
5860 Find groups of ajacent nodes within Tolerance.
5863 Tolerance: the value of tolerance
5864 SubMeshOrGroup: SubMesh, Group or Filter
5865 exceptNodes: list of either SubMeshes, Groups or node IDs to exclude from search
5866 SeparateCornerAndMediumNodes: if *True*, in quadratic mesh puts
5867 corner and medium nodes in separate groups thus preventing
5868 their further merge.
5871 the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
5874 unRegister = genObjUnRegister()
5875 if (isinstance( SubMeshOrGroup, Mesh )):
5876 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
5877 if not isinstance( exceptNodes, list ):
5878 exceptNodes = [ exceptNodes ]
5879 if exceptNodes and isinstance( exceptNodes[0], int ):
5880 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
5881 unRegister.set( exceptNodes )
5882 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
5883 exceptNodes, SeparateCornerAndMediumNodes)
5885 def MergeNodes (self, GroupsOfNodes, NodesToKeep=[], AvoidMakingHoles=False):
5890 GroupsOfNodes: a list of groups of nodes IDs for merging
5891 (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
5892 by nodes 1 and 25 correspondingly in all elements and groups
5893 NodesToKeep: nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
5894 If *NodesToKeep* does not include a node to keep for some group to merge,
5895 then the first node in the group is kept.
5896 AvoidMakingHoles: prevent merging nodes which cause removal of elements becoming
5901 # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
5902 self.editor.MergeNodes( GroupsOfNodes, NodesToKeep, AvoidMakingHoles )
5904 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
5906 Find the elements built on the same nodes.
5909 MeshOrSubMeshOrGroup: Mesh or SubMesh, or Group of elements for searching
5912 the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
5915 if not MeshOrSubMeshOrGroup:
5916 MeshOrSubMeshOrGroup=self.mesh
5917 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
5918 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
5919 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
5921 def MergeElements(self, GroupsOfElementsID):
5923 Merge elements in each given group.
5926 GroupsOfElementsID: a list of groups of elements IDs for merging
5927 (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
5928 replaced by elements 1 and 25 in all groups)
5931 self.editor.MergeElements(GroupsOfElementsID)
5933 def MergeEqualElements(self):
5935 Leave one element and remove all other elements built on the same nodes.
5938 self.editor.MergeEqualElements()
5940 def FindFreeBorders(self, ClosedOnly=True):
5942 Returns all or only closed free borders
5945 list of SMESH.FreeBorder's
5948 return self.editor.FindFreeBorders( ClosedOnly )
5950 def FillHole(self, holeNodes):
5952 Fill with 2D elements a hole defined by a SMESH.FreeBorder.
5955 FreeBorder: either a SMESH.FreeBorder or a list on node IDs. These nodes
5956 must describe all sequential nodes of the hole border. The first and the last
5957 nodes must be the same. Use FindFreeBorders() to get nodes of holes.
5961 if holeNodes and isinstance( holeNodes, list ) and isinstance( holeNodes[0], int ):
5962 holeNodes = SMESH.FreeBorder(nodeIDs=holeNodes)
5963 if not isinstance( holeNodes, SMESH.FreeBorder ):
5964 raise TypeError, "holeNodes must be either SMESH.FreeBorder or list of integer and not %s" % holeNodes
5965 self.editor.FillHole( holeNodes )
5967 def FindCoincidentFreeBorders (self, tolerance=0.):
5969 Return groups of FreeBorder's coincident within the given tolerance.
5972 tolerance: the tolerance. If the tolerance <= 0.0 then one tenth of an average
5973 size of elements adjacent to free borders being compared is used.
5976 SMESH.CoincidentFreeBorders structure
5979 return self.editor.FindCoincidentFreeBorders( tolerance )
5981 def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
5983 Sew FreeBorder's of each group
5986 freeBorders: either a SMESH.CoincidentFreeBorders structure or a list of lists
5987 where each enclosed list contains node IDs of a group of coincident free
5988 borders such that each consequent triple of IDs within a group describes
5989 a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
5990 last node of a border.
5991 For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
5992 groups of coincident free borders, each group including two borders.
5993 createPolygons: if :code:`True` faces adjacent to free borders are converted to
5994 polygons if a node of opposite border falls on a face edge, else such
5995 faces are split into several ones.
5996 createPolyhedra: if :code:`True` volumes adjacent to free borders are converted to
5997 polyhedra if a node of opposite border falls on a volume edge, else such
5998 volumes, if any, remain intact and the mesh becomes non-conformal.
6001 a number of successfully sewed groups
6004 if freeBorders and isinstance( freeBorders, list ):
6005 # construct SMESH.CoincidentFreeBorders
6006 if isinstance( freeBorders[0], int ):
6007 freeBorders = [freeBorders]
6009 coincidentGroups = []
6010 for nodeList in freeBorders:
6011 if not nodeList or len( nodeList ) % 3:
6012 raise ValueError, "Wrong number of nodes in this group: %s" % nodeList
6015 group.append ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
6016 borders.append( SMESH.FreeBorder( nodeList[:3] ))
6017 nodeList = nodeList[3:]
6019 coincidentGroups.append( group )
6021 freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
6023 return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
6025 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
6026 FirstNodeID2, SecondNodeID2, LastNodeID2,
6027 CreatePolygons, CreatePolyedrs):
6035 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
6036 FirstNodeID2, SecondNodeID2, LastNodeID2,
6037 CreatePolygons, CreatePolyedrs)
6039 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
6040 FirstNodeID2, SecondNodeID2):
6042 Sew conform free borders
6048 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
6049 FirstNodeID2, SecondNodeID2)
6051 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
6052 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
6060 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
6061 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
6063 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
6064 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
6065 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
6067 Sew two sides of a mesh. The nodes belonging to Side1 are
6068 merged with the nodes of elements of Side2.
6069 The number of elements in theSide1 and in theSide2 must be
6070 equal and they should have similar nodal connectivity.
6071 The nodes to merge should belong to side borders and
6072 the first node should be linked to the second.
6078 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
6079 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
6080 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
6082 def ChangeElemNodes(self, ide, newIDs):
6084 Set new nodes for the given element.
6091 If the number of nodes does not correspond to the type of element - return false
6094 return self.editor.ChangeElemNodes(ide, newIDs)
6096 def GetLastCreatedNodes(self):
6098 If during the last operation of MeshEditor some nodes were
6099 created, this method return the list of their IDs, \n
6100 if new nodes were not created - return empty list
6103 the list of integer values (can be empty)
6106 return self.editor.GetLastCreatedNodes()
6108 def GetLastCreatedElems(self):
6110 If during the last operation of MeshEditor some elements were
6111 created this method return the list of their IDs, \n
6112 if new elements were not created - return empty list
6115 the list of integer values (can be empty)
6118 return self.editor.GetLastCreatedElems()
6120 def ClearLastCreated(self):
6122 Forget what nodes and elements were created by the last mesh edition operation
6125 self.editor.ClearLastCreated()
6127 def DoubleElements(self, theElements, theGroupName=""):
6129 Create duplicates of given elements, i.e. create new elements based on the
6130 same nodes as the given ones.
6133 theElements: container of elements to duplicate. It can be a Mesh,
6134 sub-mesh, group, filter or a list of element IDs. If *theElements* is
6135 a Mesh, elements of highest dimension are duplicated
6136 theGroupName: a name of group to contain the generated elements.
6137 If a group with such a name already exists, the new elements
6138 are added to the existng group, else a new group is created.
6139 If *theGroupName* is empty, new elements are not added
6143 a group where the new elements are added. None if theGroupName == "".
6146 unRegister = genObjUnRegister()
6147 if isinstance( theElements, Mesh ):
6148 theElements = theElements.mesh
6149 elif isinstance( theElements, list ):
6150 theElements = self.GetIDSource( theElements, SMESH.ALL )
6151 unRegister.set( theElements )
6152 return self.editor.DoubleElements(theElements, theGroupName)
6154 def DoubleNodes(self, theNodes, theModifiedElems):
6156 Create a hole in a mesh by doubling the nodes of some particular elements
6159 theNodes: identifiers of nodes to be doubled
6160 theModifiedElems: identifiers of elements to be updated by the new (doubled)
6161 nodes. If list of element identifiers is empty then nodes are doubled but
6162 they not assigned to elements
6165 TRUE if operation has been completed successfully, FALSE otherwise
6168 return self.editor.DoubleNodes(theNodes, theModifiedElems)
6170 def DoubleNode(self, theNodeId, theModifiedElems):
6172 Create a hole in a mesh by doubling the nodes of some particular elements
6173 This method provided for convenience works as DoubleNodes() described above.
6176 theNodeId: identifiers of node to be doubled
6177 theModifiedElems: identifiers of elements to be updated
6180 TRUE if operation has been completed successfully, FALSE otherwise
6183 return self.editor.DoubleNode(theNodeId, theModifiedElems)
6185 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
6187 Create a hole in a mesh by doubling the nodes of some particular elements
6188 This method provided for convenience works as DoubleNodes() described above.
6191 theNodes: group of nodes to be doubled
6192 theModifiedElems: group of elements to be updated.
6193 theMakeGroup: forces the generation of a group containing new nodes.
6196 TRUE or a created group if operation has been completed successfully,
6197 FALSE or None otherwise
6201 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
6202 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
6204 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
6206 Create a hole in a mesh by doubling the nodes of some particular elements
6207 This method provided for convenience works as DoubleNodes() described above.
6210 theNodes: list of groups of nodes to be doubled
6211 theModifiedElems: list of groups of elements to be updated.
6212 theMakeGroup: forces the generation of a group containing new nodes.
6215 TRUE if operation has been completed successfully, FALSE otherwise
6219 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
6220 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
6222 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
6224 Create a hole in a mesh by doubling the nodes of some particular elements
6227 theElems: the list of elements (edges or faces) to be replicated
6228 The nodes for duplication could be found from these elements
6229 theNodesNot: list of nodes to NOT replicate
6230 theAffectedElems: the list of elements (cells and edges) to which the
6231 replicated nodes should be associated to.
6234 TRUE if operation has been completed successfully, FALSE otherwise
6237 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
6239 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
6241 Create a hole in a mesh by doubling the nodes of some particular elements
6244 theElems: the list of elements (edges or faces) to be replicated
6245 The nodes for duplication could be found from these elements
6246 theNodesNot: list of nodes to NOT replicate
6247 theShape: shape to detect affected elements (element which geometric center
6248 located on or inside shape).
6249 The replicated nodes should be associated to affected elements.
6252 TRUE if operation has been completed successfully, FALSE otherwise
6255 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
6257 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
6258 theMakeGroup=False, theMakeNodeGroup=False):
6260 Create a hole in a mesh by doubling the nodes of some particular elements
6261 This method provided for convenience works as DoubleNodes() described above.
6264 theElems: group of of elements (edges or faces) to be replicated
6265 theNodesNot: group of nodes not to replicated
6266 theAffectedElems: group of elements to which the replicated nodes
6267 should be associated to.
6268 theMakeGroup: forces the generation of a group containing new elements.
6269 theMakeNodeGroup: forces the generation of a group containing new nodes.
6272 TRUE or created groups (one or two) if operation has been completed successfully,
6273 FALSE or None otherwise
6276 if theMakeGroup or theMakeNodeGroup:
6277 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
6279 theMakeGroup, theMakeNodeGroup)
6280 if theMakeGroup and theMakeNodeGroup:
6283 return twoGroups[ int(theMakeNodeGroup) ]
6284 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
6286 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
6288 Create a hole in a mesh by doubling the nodes of some particular elements
6289 This method provided for convenience works as DoubleNodes() described above.
6292 theElems: group of of elements (edges or faces) to be replicated
6293 theNodesNot: group of nodes not to replicated
6294 theShape: shape to detect affected elements (element which geometric center
6295 located on or inside shape).
6296 The replicated nodes should be associated to affected elements.
6299 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
6301 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
6302 theMakeGroup=False, theMakeNodeGroup=False):
6304 Create a hole in a mesh by doubling the nodes of some particular elements
6305 This method provided for convenience works as DoubleNodes() described above.
6308 theElems: list of groups of elements (edges or faces) to be replicated
6309 theNodesNot: list of groups of nodes not to replicated
6310 theAffectedElems: group of elements to which the replicated nodes
6311 should be associated to.
6312 theMakeGroup: forces the generation of a group containing new elements.
6313 theMakeNodeGroup: forces the generation of a group containing new nodes.
6316 TRUE or created groups (one or two) if operation has been completed successfully,
6317 FALSE or None otherwise
6320 if theMakeGroup or theMakeNodeGroup:
6321 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
6323 theMakeGroup, theMakeNodeGroup)
6324 if theMakeGroup and theMakeNodeGroup:
6327 return twoGroups[ int(theMakeNodeGroup) ]
6328 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
6330 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
6332 Create a hole in a mesh by doubling the nodes of some particular elements
6333 This method provided for convenience works as DoubleNodes() described above.
6336 theElems: list of groups of elements (edges or faces) to be replicated
6337 theNodesNot: list of groups of nodes not to replicated
6338 theShape: shape to detect affected elements (element which geometric center
6339 located on or inside shape).
6340 The replicated nodes should be associated to affected elements.
6343 TRUE if operation has been completed successfully, FALSE otherwise
6346 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
6348 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
6350 Identify the elements that will be affected by node duplication (actual duplication is not performed.
6351 This method is the first step of DoubleNodeElemGroupsInRegion.
6354 theElems: list of groups of nodes or elements (edges or faces) to be replicated
6355 theNodesNot: list of groups of nodes not to replicated
6356 theShape: shape to detect affected elements (element which geometric center
6357 located on or inside shape).
6358 The replicated nodes should be associated to affected elements.
6361 groups of affected elements in order:: volumes, faces, edges
6364 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
6366 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
6368 Double nodes on shared faces between groups of volumes and create flat elements on demand.
6369 The list of groups must describe a partition of the mesh volumes.
6370 The nodes of the internal faces at the boundaries of the groups are doubled.
6371 In option, the internal faces are replaced by flat elements.
6372 Triangles are transformed in prisms, and quadrangles in hexahedrons.
6375 theDomains: list of groups of volumes
6376 createJointElems: if TRUE, create the elements
6377 onAllBoundaries: if TRUE, the nodes and elements are also created on
6378 the boundary between *theDomains* and the rest mesh
6381 TRUE if operation has been completed successfully, FALSE otherwise
6384 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
6386 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
6388 Double nodes on some external faces and create flat elements.
6389 Flat elements are mainly used by some types of mechanic calculations.
6391 Each group of the list must be constituted of faces.
6392 Triangles are transformed in prisms, and quadrangles in hexahedrons.
6395 theGroupsOfFaces: list of groups of faces
6398 TRUE if operation has been completed successfully, FALSE otherwise
6401 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
6403 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
6405 identify all the elements around a geom shape, get the faces delimiting the hole
6407 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
6409 def MakePolyLine(self, segments, groupName='', isPreview=False ):
6411 Create a polyline consisting of 1D mesh elements each lying on a 2D element of
6412 the initial mesh. Positions of new nodes are found by cutting the mesh by the
6413 plane passing through pairs of points specified by each PolySegment structure.
6414 If there are several paths connecting a pair of points, the shortest path is
6415 selected by the module. Position of the cutting plane is defined by the two
6416 points and an optional vector lying on the plane specified by a PolySegment.
6417 By default the vector is defined by Mesh module as following. A middle point
6418 of the two given points is computed. The middle point is projected to the mesh.
6419 The vector goes from the middle point to the projection point. In case of planar
6420 mesh, the vector is normal to the mesh.
6423 segments - PolySegment's defining positions of cutting planes.
6424 groupName - optional name of a group where created mesh segments will
6428 The used vector which goes from the middle point to its projection.
6430 editor = self.editor
6432 editor = self.mesh.GetMeshEditPreviewer()
6433 segmentsRes = editor.MakePolyLine( segments, groupName )
6434 for i, seg in enumerate( segmentsRes ):
6435 segments[i].vector = seg.vector
6437 return editor.GetPreviewData()
6440 def GetFunctor(self, funcType ):
6442 Return a cached numerical functor by its type.
6445 theCriterion functor type: an item of SMESH.FunctorType enumeration.
6446 Type SMESH.FunctorType._items in the Python Console to see all items.
6447 Note that not all items correspond to numerical functors.
6450 SMESH_NumericalFunctor. The functor is already initialized
6454 fn = self.functors[ funcType._v ]
6456 fn = self.smeshpyD.GetFunctor(funcType)
6457 fn.SetMesh(self.mesh)
6458 self.functors[ funcType._v ] = fn
6461 def FunctorValue(self, funcType, elemId, isElem=True):
6463 Return value of a functor for a given element
6466 funcType: an item of SMESH.FunctorType enum
6467 Type "SMESH.FunctorType._items" in the Python Console to see all items.
6468 elemId: element or node ID
6469 isElem: *elemId* is ID of element or node
6472 the functor value or zero in case of invalid arguments
6475 fn = self.GetFunctor( funcType )
6476 if fn.GetElementType() == self.GetElementType(elemId, isElem):
6477 val = fn.GetValue(elemId)
6482 def GetLength(self, elemId=None):
6484 Get length of 1D element or sum of lengths of all 1D mesh elements
6487 elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
6490 element's length value if *elemId* is specified or sum of all 1D mesh elements' lengths otherwise
6495 length = self.smeshpyD.GetLength(self)
6497 length = self.FunctorValue(SMESH.FT_Length, elemId)
6500 def GetArea(self, elemId=None):
6502 Get area of 2D element or sum of areas of all 2D mesh elements
6503 elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
6506 element's area value if *elemId* is specified or sum of all 2D mesh elements' areas otherwise
6511 area = self.smeshpyD.GetArea(self)
6513 area = self.FunctorValue(SMESH.FT_Area, elemId)
6516 def GetVolume(self, elemId=None):
6518 Get volume of 3D element or sum of volumes of all 3D mesh elements
6519 elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
6522 element's volume value if *elemId* is specified or sum of all 3D mesh elements' volumes otherwise
6527 volume = self.smeshpyD.GetVolume(self)
6529 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
6532 def GetMaxElementLength(self, elemId):
6534 Get maximum element length.
6537 elemId mesh element ID
6540 element's maximum length value
6543 if self.GetElementType(elemId, True) == SMESH.VOLUME:
6544 ftype = SMESH.FT_MaxElementLength3D
6546 ftype = SMESH.FT_MaxElementLength2D
6547 return self.FunctorValue(ftype, elemId)
6549 def GetAspectRatio(self, elemId):
6551 Get aspect ratio of 2D or 3D element.
6554 elemId mesh element ID
6557 element's aspect ratio value
6560 if self.GetElementType(elemId, True) == SMESH.VOLUME:
6561 ftype = SMESH.FT_AspectRatio3D
6563 ftype = SMESH.FT_AspectRatio
6564 return self.FunctorValue(ftype, elemId)
6566 def GetWarping(self, elemId):
6568 Get warping angle of 2D element.
6571 elemId mesh element ID
6574 element's warping angle value
6577 return self.FunctorValue(SMESH.FT_Warping, elemId)
6579 def GetMinimumAngle(self, elemId):
6581 Get minimum angle of 2D element.
6584 elemId mesh element ID
6587 element's minimum angle value
6590 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
6592 def GetTaper(self, elemId):
6594 Get taper of 2D element.
6597 elemId mesh element ID
6600 element's taper value
6603 return self.FunctorValue(SMESH.FT_Taper, elemId)
6605 def GetSkew(self, elemId):
6607 Get skew of 2D element.
6610 elemId mesh element ID
6613 element's skew value
6616 return self.FunctorValue(SMESH.FT_Skew, elemId)
6618 def GetMinMax(self, funType, meshPart=None):
6620 Return minimal and maximal value of a given functor.
6623 funType a functor type, an item of SMESH.FunctorType enum
6624 (one of SMESH.FunctorType._items)
6625 meshPart a part of mesh (group, sub-mesh) to treat
6631 unRegister = genObjUnRegister()
6632 if isinstance( meshPart, list ):
6633 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
6634 unRegister.set( meshPart )
6635 if isinstance( meshPart, Mesh ):
6636 meshPart = meshPart.mesh
6637 fun = self.GetFunctor( funType )
6640 if hasattr( meshPart, "SetMesh" ):
6641 meshPart.SetMesh( self.mesh ) # set mesh to filter
6642 hist = fun.GetLocalHistogram( 1, False, meshPart )
6644 hist = fun.GetHistogram( 1, False )
6646 return hist[0].min, hist[0].max
6649 pass # end of Mesh class
6652 class meshProxy(SMESH._objref_SMESH_Mesh):
6654 Private class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
6655 with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
6658 SMESH._objref_SMESH_Mesh.__init__(self)
6659 def __deepcopy__(self, memo=None):
6660 new = self.__class__()
6662 def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
6663 if len( args ) == 3:
6664 args += SMESH.ALL_NODES, True
6665 return SMESH._objref_SMESH_Mesh.CreateDimGroup( self, *args )
6667 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
6670 class submeshProxy(SMESH._objref_SMESH_subMesh):
6672 Private class wrapping SMESH.SMESH_SubMesh in order to add Compute()
6675 SMESH._objref_SMESH_subMesh.__init__(self)
6677 def __deepcopy__(self, memo=None):
6678 new = self.__class__()
6681 def Compute(self,refresh=False):
6683 Compute the sub-mesh and return the status of the computation
6684 refresh if *True*, Object browser is automatically updated (when running in GUI)
6688 This is a method of SMESH.SMESH_submesh that can be obtained via Mesh.GetSubMesh() or
6689 :meth:`smeshBuilder.Mesh.GetSubMesh`.
6693 self.mesh = Mesh( smeshBuilder(), None, self.GetMesh())
6695 ok = self.mesh.Compute( self.GetSubShape(),refresh=[] )
6697 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
6698 smeshgui = salome.ImportComponentGUI("SMESH")
6699 smeshgui.Init(self.mesh.GetStudyId())
6700 smeshgui.SetMeshIcon( salome.ObjectToID( self ), ok, (self.GetNumberOfElements()==0) )
6701 if refresh: salome.sg.updateObjBrowser(True)
6706 omniORB.registerObjref(SMESH._objref_SMESH_subMesh._NP_RepositoryId, submeshProxy)
6709 class meshEditor(SMESH._objref_SMESH_MeshEditor):
6711 Private class used to compensate change of CORBA API of SMESH_MeshEditor for backward
6712 compatibility with old dump scripts which call SMESH_MeshEditor directly and not via
6716 SMESH._objref_SMESH_MeshEditor.__init__(self)
6718 def __getattr__(self, name ): # method called if an attribute not found
6719 if not self.mesh: # look for name() method in Mesh class
6720 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
6721 if hasattr( self.mesh, name ):
6722 return getattr( self.mesh, name )
6723 if name == "ExtrusionAlongPathObjX":
6724 return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
6725 print "meshEditor: attribute '%s' NOT FOUND" % name
6727 def __deepcopy__(self, memo=None):
6728 new = self.__class__()
6730 def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
6731 if len( args ) == 1: args += False,
6732 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
6733 def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
6734 if len( args ) == 2: args += False,
6735 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
6736 def MergeNodes(self,*args): # 2 args added (NodesToKeep,AvoidMakingHoles)
6737 if len( args ) == 1:
6738 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [], False )
6739 NodesToKeep = args[1]
6740 AvoidMakingHoles = args[2] if len( args ) == 3 else False
6741 unRegister = genObjUnRegister()
6743 if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
6744 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
6745 if not isinstance( NodesToKeep, list ):
6746 NodesToKeep = [ NodesToKeep ]
6747 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep, AvoidMakingHoles )
6749 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
6751 class Pattern(SMESH._objref_SMESH_Pattern):
6753 Private class wrapping SMESH.SMESH_Pattern CORBA class in order to treat Notebook
6754 variables in some methods
6757 def LoadFromFile(self, patternTextOrFile ):
6758 text = patternTextOrFile
6759 if os.path.exists( text ):
6760 text = open( patternTextOrFile ).read()
6762 return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
6764 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
6765 decrFun = lambda i: i-1
6766 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
6767 theMesh.SetParameters(Parameters)
6768 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
6770 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
6771 decrFun = lambda i: i-1
6772 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
6773 theMesh.SetParameters(Parameters)
6774 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
6776 def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
6777 if isinstance( mesh, Mesh ):
6778 mesh = mesh.GetMesh()
6779 return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
6781 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
6783 Registering the new proxy for Pattern
6788 Private class used to bind methods creating algorithms to the class Mesh
6791 def __init__(self, method):
6793 self.defaultAlgoType = ""
6794 self.algoTypeToClass = {}
6795 self.method = method
6797 def add(self, algoClass):
6799 Store a python class of algorithm
6801 if type( algoClass ).__name__ == 'classobj' and \
6802 hasattr( algoClass, "algoType"):
6803 self.algoTypeToClass[ algoClass.algoType ] = algoClass
6804 if not self.defaultAlgoType and \
6805 hasattr( algoClass, "isDefault") and algoClass.isDefault:
6806 self.defaultAlgoType = algoClass.algoType
6807 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
6809 def copy(self, mesh):
6811 Create a copy of self and assign mesh to the copy
6814 other = algoCreator( self.method )
6815 other.defaultAlgoType = self.defaultAlgoType
6816 other.algoTypeToClass = self.algoTypeToClass
6820 def __call__(self,algo="",geom=0,*args):
6822 Create an instance of algorithm
6826 if isinstance( algo, str ):
6828 elif ( isinstance( algo, geomBuilder.GEOM._objref_GEOM_Object ) and \
6829 not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object )):
6834 if isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
6836 elif not algoType and isinstance( geom, str ):
6841 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ) and not shape:
6843 elif isinstance( arg, str ) and not algoType:
6846 import traceback, sys
6847 msg = "Warning. Unexpected argument in mesh.%s() ---> %s" % ( self.method, arg )
6848 sys.stderr.write( msg + '\n' )
6849 tb = traceback.extract_stack(None,2)
6850 traceback.print_list( [tb[0]] )
6852 algoType = self.defaultAlgoType
6853 if not algoType and self.algoTypeToClass:
6854 algoType = sorted( self.algoTypeToClass.keys() )[0]
6855 if self.algoTypeToClass.has_key( algoType ):
6856 #print "Create algo",algoType
6857 return self.algoTypeToClass[ algoType ]( self.mesh, shape )
6858 raise RuntimeError, "No class found for algo type %s" % algoType
6861 class hypMethodWrapper:
6863 Private class used to substitute and store variable parameters of hypotheses.
6866 def __init__(self, hyp, method):
6868 self.method = method
6869 #print "REBIND:", method.__name__
6872 def __call__(self,*args):
6874 call a method of hypothesis with calling SetVarParameter() before
6878 return self.method( self.hyp, *args ) # hypothesis method with no args
6880 #print "MethWrapper.__call__",self.method.__name__, args
6882 parsed = ParseParameters(*args) # replace variables with their values
6883 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
6884 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
6885 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
6886 # maybe there is a replaced string arg which is not variable
6887 result = self.method( self.hyp, *args )
6888 except ValueError, detail: # raised by ParseParameters()
6890 result = self.method( self.hyp, *args )
6891 except omniORB.CORBA.BAD_PARAM:
6892 raise ValueError, detail # wrong variable name
6897 class genObjUnRegister:
6899 A helper class that calls UnRegister() of SALOME.GenericObj'es stored in it
6902 def __init__(self, genObj=None):
6903 self.genObjList = []
6907 def set(self, genObj):
6908 "Store one or a list of of SALOME.GenericObj'es"
6909 if isinstance( genObj, list ):
6910 self.genObjList.extend( genObj )
6912 self.genObjList.append( genObj )
6916 for genObj in self.genObjList:
6917 if genObj and hasattr( genObj, "UnRegister" ):
6920 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
6922 Bind methods creating mesher plug-ins to the Mesh class
6925 # print "pluginName: ", pluginName
6926 pluginBuilderName = pluginName + "Builder"
6928 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
6929 except Exception, e:
6930 from salome_utils import verbose
6931 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
6933 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
6934 plugin = eval( pluginBuilderName )
6935 # print " plugin:" , str(plugin)
6937 # add methods creating algorithms to Mesh
6938 for k in dir( plugin ):
6939 if k[0] == '_': continue
6940 algo = getattr( plugin, k )
6941 # print " algo:", str(algo)
6942 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
6943 # print " meshMethod:" , str(algo.meshMethod)
6944 if not hasattr( Mesh, algo.meshMethod ):
6945 setattr( Mesh, algo.meshMethod, algoCreator( algo.meshMethod ))
6947 _mmethod = getattr( Mesh, algo.meshMethod )
6948 if hasattr( _mmethod, "add" ):