1 # Copyright (C) 2007-2014 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
23 ## @package smeshBuilder
24 # Python API for SALOME %Mesh module
26 ## @defgroup l1_auxiliary Auxiliary methods and structures
27 ## @defgroup l1_creating Creating meshes
29 ## @defgroup l2_impexp Importing and exporting meshes
30 ## @defgroup l2_construct Constructing meshes
31 ## @defgroup l2_algorithms Defining Algorithms
33 ## @defgroup l3_algos_basic Basic meshing algorithms
34 ## @defgroup l3_algos_proj Projection Algorithms
35 ## @defgroup l3_algos_radialp Radial Prism
36 ## @defgroup l3_algos_segmarv Segments around Vertex
37 ## @defgroup l3_algos_3dextr 3D extrusion meshing algorithm
40 ## @defgroup l2_hypotheses Defining hypotheses
42 ## @defgroup l3_hypos_1dhyps 1D Meshing Hypotheses
43 ## @defgroup l3_hypos_2dhyps 2D Meshing Hypotheses
44 ## @defgroup l3_hypos_maxvol Max Element Volume hypothesis
45 ## @defgroup l3_hypos_quad Quadrangle Parameters hypothesis
46 ## @defgroup l3_hypos_additi Additional Hypotheses
49 ## @defgroup l2_submeshes Constructing submeshes
50 ## @defgroup l2_compounds Building Compounds
51 ## @defgroup l2_editing Editing Meshes
54 ## @defgroup l1_meshinfo Mesh Information
55 ## @defgroup l1_controls Quality controls and Filtering
56 ## @defgroup l1_grouping Grouping elements
58 ## @defgroup l2_grps_create Creating groups
59 ## @defgroup l2_grps_edit Editing groups
60 ## @defgroup l2_grps_operon Using operations on groups
61 ## @defgroup l2_grps_delete Deleting Groups
64 ## @defgroup l1_modifying Modifying meshes
66 ## @defgroup l2_modif_add Adding nodes and elements
67 ## @defgroup l2_modif_del Removing nodes and elements
68 ## @defgroup l2_modif_edit Modifying nodes and elements
69 ## @defgroup l2_modif_renumber Renumbering nodes and elements
70 ## @defgroup l2_modif_trsf Transforming meshes (Translation, Rotation, Symmetry, Sewing, Merging)
71 ## @defgroup l2_modif_movenode Moving nodes
72 ## @defgroup l2_modif_throughp Mesh through point
73 ## @defgroup l2_modif_invdiag Diagonal inversion of elements
74 ## @defgroup l2_modif_unitetri Uniting triangles
75 ## @defgroup l2_modif_changori Changing orientation of elements
76 ## @defgroup l2_modif_cutquadr Cutting elements
77 ## @defgroup l2_modif_smooth Smoothing
78 ## @defgroup l2_modif_extrurev Extrusion and Revolution
79 ## @defgroup l2_modif_patterns Pattern mapping
80 ## @defgroup l2_modif_tofromqu Convert to/from Quadratic Mesh
83 ## @defgroup l1_measurements Measurements
86 from salome.geom import geomBuilder
88 import SMESH # This is necessary for back compatibility
90 from salome.smesh.smesh_algorithm import Mesh_Algorithm
97 def __instancecheck__(cls, inst):
98 """Implement isinstance(inst, cls)."""
99 return any(cls.__subclasscheck__(c)
100 for c in {type(inst), inst.__class__})
102 def __subclasscheck__(cls, sub):
103 """Implement issubclass(sub, cls)."""
104 return type.__subclasscheck__(cls, sub) or (cls.__name__ == sub.__name__ and cls.__module__ == sub.__module__)
106 ## @addtogroup l1_auxiliary
109 ## Converts an angle from degrees to radians
110 def DegreesToRadians(AngleInDegrees):
112 return AngleInDegrees * pi / 180.0
114 import salome_notebook
115 notebook = salome_notebook.notebook
116 # Salome notebook variable separator
119 ## Return list of variable values from salome notebook.
120 # The last argument, if is callable, is used to modify values got from notebook
121 def ParseParameters(*args):
126 if args and callable( args[-1] ):
127 args, varModifFun = args[:-1], args[-1]
128 for parameter in args:
130 Parameters += str(parameter) + var_separator
132 if isinstance(parameter,str):
133 # check if there is an inexistent variable name
134 if not notebook.isVariable(parameter):
135 raise ValueError, "Variable with name '" + parameter + "' doesn't exist!!!"
136 parameter = notebook.get(parameter)
139 parameter = varModifFun(parameter)
142 Result.append(parameter)
145 Parameters = Parameters[:-1]
146 Result.append( Parameters )
147 Result.append( hasVariables )
150 # Parse parameters converting variables to radians
151 def ParseAngles(*args):
152 return ParseParameters( *( args + (DegreesToRadians, )))
154 # Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
155 # Parameters are stored in PointStruct.parameters attribute
156 def __initPointStruct(point,*args):
157 point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
159 SMESH.PointStruct.__init__ = __initPointStruct
161 # Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
162 # Parameters are stored in AxisStruct.parameters attribute
163 def __initAxisStruct(ax,*args):
164 ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
166 SMESH.AxisStruct.__init__ = __initAxisStruct
168 smeshPrecisionConfusion = 1.e-07
169 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
170 if abs(val1 - val2) < tol:
180 if isinstance(obj, SALOMEDS._objref_SObject):
184 ior = salome.orb.object_to_string(obj)
189 studies = salome.myStudyManager.GetOpenStudies()
190 for sname in studies:
191 s = salome.myStudyManager.GetStudyByName(sname)
193 sobj = s.FindObjectIOR(ior)
194 if not sobj: continue
195 return sobj.GetName()
196 if hasattr(obj, "GetName"):
197 # unknown CORBA object, having GetName() method
200 # unknown CORBA object, no GetName() method
203 if hasattr(obj, "GetName"):
204 # unknown non-CORBA object, having GetName() method
207 raise RuntimeError, "Null or invalid object"
209 ## Prints error message if a hypothesis was not assigned.
210 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
212 hypType = "algorithm"
214 hypType = "hypothesis"
217 if hasattr( status, "__getitem__" ):
218 status,reason = status[0],status[1]
219 if status == HYP_UNKNOWN_FATAL :
220 reason = "for unknown reason"
221 elif status == HYP_INCOMPATIBLE :
222 reason = "this hypothesis mismatches the algorithm"
223 elif status == HYP_NOTCONFORM :
224 reason = "a non-conform mesh would be built"
225 elif status == HYP_ALREADY_EXIST :
226 if isAlgo: return # it does not influence anything
227 reason = hypType + " of the same dimension is already assigned to this shape"
228 elif status == HYP_BAD_DIM :
229 reason = hypType + " mismatches the shape"
230 elif status == HYP_CONCURENT :
231 reason = "there are concurrent hypotheses on sub-shapes"
232 elif status == HYP_BAD_SUBSHAPE :
233 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
234 elif status == HYP_BAD_GEOMETRY:
235 reason = "geometry mismatches the expectation of the algorithm"
236 elif status == HYP_HIDDEN_ALGO:
237 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
238 elif status == HYP_HIDING_ALGO:
239 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
240 elif status == HYP_NEED_SHAPE:
241 reason = "algorithm can't work without shape"
242 elif status == HYP_INCOMPAT_HYPS:
248 where = '"%s"' % geomName
250 meshName = GetName( mesh )
251 if meshName and meshName != NO_NAME:
252 where = '"%s" in "%s"' % ( geomName, meshName )
253 if status < HYP_UNKNOWN_FATAL and where:
254 print '"%s" was assigned to %s but %s' %( hypName, where, reason )
256 print '"%s" was not assigned to %s : %s' %( hypName, where, reason )
258 print '"%s" was not assigned : %s' %( hypName, reason )
261 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
262 def AssureGeomPublished(mesh, geom, name=''):
263 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
265 if not geom.GetStudyEntry() and \
266 mesh.smeshpyD.GetCurrentStudy():
268 studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
269 if studyID != mesh.geompyD.myStudyId:
270 mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
272 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
273 # for all groups SubShapeName() returns "Compound_-1"
274 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
276 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
278 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
281 ## Return the first vertex of a geometrical edge by ignoring orientation
282 def FirstVertexOnCurve(mesh, edge):
283 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
285 raise TypeError, "Given object has no vertices"
286 if len( vv ) == 1: return vv[0]
287 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
288 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
289 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
290 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
293 dist1 += abs( xyz[i] - xyz1[i] )
294 dist2 += abs( xyz[i] - xyz2[i] )
300 # end of l1_auxiliary
304 # Warning: smeshInst is a singleton
310 ## This class allows to create, load or manipulate meshes
311 # It has a set of methods to create load or copy meshes, to combine several meshes.
312 # It also has methods to get infos on meshes.
313 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
315 # MirrorType enumeration
316 POINT = SMESH_MeshEditor.POINT
317 AXIS = SMESH_MeshEditor.AXIS
318 PLANE = SMESH_MeshEditor.PLANE
320 # Smooth_Method enumeration
321 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
322 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
324 PrecisionConfusion = smeshPrecisionConfusion
326 # TopAbs_State enumeration
327 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
329 # Methods of splitting a hexahedron into tetrahedra
330 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
336 #print "==== __new__", engine, smeshInst, doLcc
338 if smeshInst is None:
339 # smesh engine is either retrieved from engine, or created
341 # Following test avoids a recursive loop
343 if smeshInst is not None:
344 # smesh engine not created: existing engine found
348 # FindOrLoadComponent called:
349 # 1. CORBA resolution of server
350 # 2. the __new__ method is called again
351 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
352 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
354 # FindOrLoadComponent not called
355 if smeshInst is None:
356 # smeshBuilder instance is created from lcc.FindOrLoadComponent
357 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
358 smeshInst = super(smeshBuilder,cls).__new__(cls)
360 # smesh engine not created: existing engine found
361 #print "==== existing ", engine, smeshInst, doLcc
363 #print "====1 ", smeshInst
366 #print "====2 ", smeshInst
371 #print "--------------- smeshbuilder __init__ ---", created
374 SMESH._objref_SMESH_Gen.__init__(self)
376 ## Dump component to the Python script
377 # This method overrides IDL function to allow default values for the parameters.
378 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
379 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
381 ## Set mode of DumpPython(), \a historical or \a snapshot.
382 # In the \a historical mode, the Python Dump script includes all commands
383 # performed by SMESH engine. In the \a snapshot mode, commands
384 # relating to objects removed from the Study are excluded from the script
385 # as well as commands not influencing the current state of meshes
386 def SetDumpPythonHistorical(self, isHistorical):
387 if isHistorical: val = "true"
389 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
391 ## Sets the current study and Geometry component
392 # @ingroup l1_auxiliary
393 def init_smesh(self,theStudy,geompyD = None):
395 self.SetCurrentStudy(theStudy,geompyD)
398 notebook.myStudy = theStudy
400 ## Creates a mesh. This can be either an empty mesh, possibly having an underlying geometry,
401 # or a mesh wrapping a CORBA mesh given as a parameter.
402 # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
403 # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
404 # (2) a Geometrical object for meshing or
406 # @param name the name for the new mesh.
407 # @return an instance of Mesh class.
408 # @ingroup l2_construct
409 def Mesh(self, obj=0, name=0):
410 if isinstance(obj,str):
412 return Mesh(self,self.geompyD,obj,name)
414 ## Returns a long value from enumeration
415 # @ingroup l1_controls
416 def EnumToLong(self,theItem):
419 ## Returns a string representation of the color.
420 # To be used with filters.
421 # @param c color value (SALOMEDS.Color)
422 # @ingroup l1_controls
423 def ColorToString(self,c):
425 if isinstance(c, SALOMEDS.Color):
426 val = "%s;%s;%s" % (c.R, c.G, c.B)
427 elif isinstance(c, str):
430 raise ValueError, "Color value should be of string or SALOMEDS.Color type"
433 ## Gets PointStruct from vertex
434 # @param theVertex a GEOM object(vertex)
435 # @return SMESH.PointStruct
436 # @ingroup l1_auxiliary
437 def GetPointStruct(self,theVertex):
438 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
439 return PointStruct(x,y,z)
441 ## Gets DirStruct from vector
442 # @param theVector a GEOM object(vector)
443 # @return SMESH.DirStruct
444 # @ingroup l1_auxiliary
445 def GetDirStruct(self,theVector):
446 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
447 if(len(vertices) != 2):
448 print "Error: vector object is incorrect."
450 p1 = self.geompyD.PointCoordinates(vertices[0])
451 p2 = self.geompyD.PointCoordinates(vertices[1])
452 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
453 dirst = DirStruct(pnt)
456 ## Makes DirStruct from a triplet
457 # @param x,y,z vector components
458 # @return SMESH.DirStruct
459 # @ingroup l1_auxiliary
460 def MakeDirStruct(self,x,y,z):
461 pnt = PointStruct(x,y,z)
462 return DirStruct(pnt)
464 ## Get AxisStruct from object
465 # @param theObj a GEOM object (line or plane)
466 # @return SMESH.AxisStruct
467 # @ingroup l1_auxiliary
468 def GetAxisStruct(self,theObj):
470 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
473 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
474 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
475 vertex1 = self.geompyD.PointCoordinates(vertex1)
476 vertex2 = self.geompyD.PointCoordinates(vertex2)
477 vertex3 = self.geompyD.PointCoordinates(vertex3)
478 vertex4 = self.geompyD.PointCoordinates(vertex4)
479 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
480 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
481 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] ]
482 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
483 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
484 elif len(edges) == 1:
485 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
486 p1 = self.geompyD.PointCoordinates( vertex1 )
487 p2 = self.geompyD.PointCoordinates( vertex2 )
488 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
489 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
490 elif theObj.GetShapeType() == GEOM.VERTEX:
491 x,y,z = self.geompyD.PointCoordinates( theObj )
492 axis = AxisStruct( x,y,z, 1,0,0,)
493 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
496 # From SMESH_Gen interface:
497 # ------------------------
499 ## Sets the given name to the object
500 # @param obj the object to rename
501 # @param name a new object name
502 # @ingroup l1_auxiliary
503 def SetName(self, obj, name):
504 if isinstance( obj, Mesh ):
506 elif isinstance( obj, Mesh_Algorithm ):
507 obj = obj.GetAlgorithm()
508 ior = salome.orb.object_to_string(obj)
509 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
511 ## Sets the current mode
512 # @ingroup l1_auxiliary
513 def SetEmbeddedMode( self,theMode ):
514 #self.SetEmbeddedMode(theMode)
515 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
517 ## Gets the current mode
518 # @ingroup l1_auxiliary
519 def IsEmbeddedMode(self):
520 #return self.IsEmbeddedMode()
521 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
523 ## Sets the current study
524 # @ingroup l1_auxiliary
525 def SetCurrentStudy( self, theStudy, geompyD = None ):
526 #self.SetCurrentStudy(theStudy)
528 from salome.geom import geomBuilder
529 geompyD = geomBuilder.geom
532 self.SetGeomEngine(geompyD)
533 SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
536 notebook = salome_notebook.NoteBook( theStudy )
538 notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
540 ## Gets the current study
541 # @ingroup l1_auxiliary
542 def GetCurrentStudy(self):
543 #return self.GetCurrentStudy()
544 return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
546 ## Creates a Mesh object importing data from the given UNV file
547 # @return an instance of Mesh class
549 def CreateMeshesFromUNV( self,theFileName ):
550 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
551 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
554 ## Creates a Mesh object(s) importing data from the given MED file
555 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
557 def CreateMeshesFromMED( self,theFileName ):
558 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
559 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
560 return aMeshes, aStatus
562 ## Creates a Mesh object(s) importing data from the given SAUV file
563 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
565 def CreateMeshesFromSAUV( self,theFileName ):
566 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
567 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
568 return aMeshes, aStatus
570 ## Creates a Mesh object importing data from the given STL file
571 # @return an instance of Mesh class
573 def CreateMeshesFromSTL( self, theFileName ):
574 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
575 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
578 ## Creates Mesh objects importing data from the given CGNS file
579 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
581 def CreateMeshesFromCGNS( self, theFileName ):
582 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
583 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
584 return aMeshes, aStatus
586 ## Creates a Mesh object importing data from the given GMF file.
587 # GMF files must have .mesh extension for the ASCII format and .meshb for
589 # @return [ an instance of Mesh class, SMESH.ComputeError ]
591 def CreateMeshesFromGMF( self, theFileName ):
592 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
595 if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
596 return Mesh(self, self.geompyD, aSmeshMesh), error
598 ## Concatenate the given meshes into one mesh.
599 # @return an instance of Mesh class
600 # @param meshes the meshes to combine into one mesh
601 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
602 # @param mergeNodesAndElements if true, equal nodes and elements aremerged
603 # @param mergeTolerance tolerance for merging nodes
604 # @param allGroups forces creation of groups of all elements
605 # @param name name of a new mesh
606 def Concatenate( self, meshes, uniteIdenticalGroups,
607 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
609 if not meshes: return None
610 for i,m in enumerate(meshes):
611 if isinstance(m, Mesh):
612 meshes[i] = m.GetMesh()
613 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
614 meshes[0].SetParameters(Parameters)
616 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
617 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
619 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
620 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
621 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
624 ## Create a mesh by copying a part of another mesh.
625 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
626 # to copy nodes or elements not contained in any mesh object,
627 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
628 # @param meshName a name of the new mesh
629 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
630 # @param toKeepIDs to preserve IDs of the copied elements or not
631 # @return an instance of Mesh class
632 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
633 if (isinstance( meshPart, Mesh )):
634 meshPart = meshPart.GetMesh()
635 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
636 return Mesh(self, self.geompyD, mesh)
638 ## From SMESH_Gen interface
639 # @return the list of integer values
640 # @ingroup l1_auxiliary
641 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
642 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
644 ## From SMESH_Gen interface. Creates a pattern
645 # @return an instance of SMESH_Pattern
647 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
648 # @ingroup l2_modif_patterns
649 def GetPattern(self):
650 return SMESH._objref_SMESH_Gen.GetPattern(self)
652 ## Sets number of segments per diagonal of boundary box of geometry by which
653 # default segment length of appropriate 1D hypotheses is defined.
654 # Default value is 10
655 # @ingroup l1_auxiliary
656 def SetBoundaryBoxSegmentation(self, nbSegments):
657 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
659 # Filtering. Auxiliary functions:
660 # ------------------------------
662 ## Creates an empty criterion
663 # @return SMESH.Filter.Criterion
664 # @ingroup l1_controls
665 def GetEmptyCriterion(self):
666 Type = self.EnumToLong(FT_Undefined)
667 Compare = self.EnumToLong(FT_Undefined)
671 UnaryOp = self.EnumToLong(FT_Undefined)
672 BinaryOp = self.EnumToLong(FT_Undefined)
675 Precision = -1 ##@1e-07
676 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
677 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
679 ## Creates a criterion by the given parameters
680 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
681 # @param elementType the type of elements(NODE, EDGE, FACE, VOLUME)
682 # @param CritType the type of criterion (FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc.)
683 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
684 # @param Threshold the threshold value (range of ids as string, shape, numeric)
685 # @param UnaryOp FT_LogicalNOT or FT_Undefined
686 # @param BinaryOp a binary logical operation FT_LogicalAND, FT_LogicalOR or
687 # FT_Undefined (must be for the last criterion of all criteria)
688 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
689 # FT_LyingOnGeom, FT_CoplanarFaces criteria
690 # @return SMESH.Filter.Criterion
692 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
693 # @ingroup l1_controls
694 def GetCriterion(self,elementType,
696 Compare = FT_EqualTo,
698 UnaryOp=FT_Undefined,
699 BinaryOp=FT_Undefined,
701 if not CritType in SMESH.FunctorType._items:
702 raise TypeError, "CritType should be of SMESH.FunctorType"
703 aCriterion = self.GetEmptyCriterion()
704 aCriterion.TypeOfElement = elementType
705 aCriterion.Type = self.EnumToLong(CritType)
706 aCriterion.Tolerance = Tolerance
708 aThreshold = Threshold
710 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
711 aCriterion.Compare = self.EnumToLong(Compare)
712 elif Compare == "=" or Compare == "==":
713 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
715 aCriterion.Compare = self.EnumToLong(FT_LessThan)
717 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
718 elif Compare != FT_Undefined:
719 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
722 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
723 FT_BelongToCylinder, FT_LyingOnGeom]:
724 # Checks that Threshold is GEOM object
725 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
726 aCriterion.ThresholdStr = GetName(aThreshold)
727 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
728 if not aCriterion.ThresholdID:
729 name = aCriterion.ThresholdStr
731 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
732 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
733 #raise RuntimeError, "Threshold shape must be published"
735 print "Error: The Threshold should be a shape."
737 if isinstance(UnaryOp,float):
738 aCriterion.Tolerance = UnaryOp
739 UnaryOp = FT_Undefined
741 elif CritType == FT_RangeOfIds:
742 # Checks that Threshold is string
743 if isinstance(aThreshold, str):
744 aCriterion.ThresholdStr = aThreshold
746 print "Error: The Threshold should be a string."
748 elif CritType == FT_CoplanarFaces:
749 # Checks the Threshold
750 if isinstance(aThreshold, int):
751 aCriterion.ThresholdID = str(aThreshold)
752 elif isinstance(aThreshold, str):
755 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
756 aCriterion.ThresholdID = aThreshold
759 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
760 elif CritType == FT_ConnectedElements:
761 # Checks the Threshold
762 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
763 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
764 if not aCriterion.ThresholdID:
765 name = aThreshold.GetName()
767 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
768 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
769 elif isinstance(aThreshold, int): # node id
770 aCriterion.Threshold = aThreshold
771 elif isinstance(aThreshold, list): # 3 point coordinates
772 if len( aThreshold ) < 3:
773 raise ValueError, "too few point coordinates, must be 3"
774 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
775 elif isinstance(aThreshold, str):
776 if aThreshold.isdigit():
777 aCriterion.Threshold = aThreshold # node id
779 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
782 "The Threshold should either a VERTEX, or a node ID, "\
783 "or a list of point coordinates and not '%s'"%aThreshold
784 elif CritType == FT_ElemGeomType:
785 # Checks the Threshold
787 aCriterion.Threshold = self.EnumToLong(aThreshold)
788 assert( aThreshold in SMESH.GeometryType._items )
790 if isinstance(aThreshold, int):
791 aCriterion.Threshold = aThreshold
793 print "Error: The Threshold should be an integer or SMESH.GeometryType."
797 elif CritType == FT_EntityType:
798 # Checks the Threshold
800 aCriterion.Threshold = self.EnumToLong(aThreshold)
801 assert( aThreshold in SMESH.EntityType._items )
803 if isinstance(aThreshold, int):
804 aCriterion.Threshold = aThreshold
806 print "Error: The Threshold should be an integer or SMESH.EntityType."
811 elif CritType == FT_GroupColor:
812 # Checks the Threshold
814 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
816 print "Error: The threshold value should be of SALOMEDS.Color type"
819 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
820 FT_LinearOrQuadratic, FT_BadOrientedVolume,
821 FT_BareBorderFace, FT_BareBorderVolume,
822 FT_OverConstrainedFace, FT_OverConstrainedVolume,
823 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
824 # At this point the Threshold is unnecessary
825 if aThreshold == FT_LogicalNOT:
826 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
827 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
828 aCriterion.BinaryOp = aThreshold
832 aThreshold = float(aThreshold)
833 aCriterion.Threshold = aThreshold
835 print "Error: The Threshold should be a number."
838 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
839 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
841 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
842 aCriterion.BinaryOp = self.EnumToLong(Threshold)
844 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
845 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
847 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
848 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
852 ## Creates a filter with the given parameters
853 # @param elementType the type of elements in the group
854 # @param CritType the type of criterion ( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
855 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
856 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
857 # @param UnaryOp FT_LogicalNOT or FT_Undefined
858 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
859 # FT_LyingOnGeom, FT_CoplanarFaces and FT_EqualNodes criteria
860 # @param mesh the mesh to initialize the filter with
861 # @return SMESH_Filter
863 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
864 # @ingroup l1_controls
865 def GetFilter(self,elementType,
866 CritType=FT_Undefined,
869 UnaryOp=FT_Undefined,
872 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
873 aFilterMgr = self.CreateFilterManager()
874 aFilter = aFilterMgr.CreateFilter()
876 aCriteria.append(aCriterion)
877 aFilter.SetCriteria(aCriteria)
879 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
880 else : aFilter.SetMesh( mesh )
881 aFilterMgr.UnRegister()
884 ## Creates a filter from criteria
885 # @param criteria a list of criteria
886 # @param binOp binary operator used when binary operator of criteria is undefined
887 # @return SMESH_Filter
889 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
890 # @ingroup l1_controls
891 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
892 for i in range( len( criteria ) - 1 ):
893 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
894 criteria[i].BinaryOp = self.EnumToLong( binOp )
895 aFilterMgr = self.CreateFilterManager()
896 aFilter = aFilterMgr.CreateFilter()
897 aFilter.SetCriteria(criteria)
898 aFilterMgr.UnRegister()
901 ## Creates a numerical functor by its type
902 # @param theCriterion FT_...; functor type
903 # @return SMESH_NumericalFunctor
904 # @ingroup l1_controls
905 def GetFunctor(self,theCriterion):
906 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
908 aFilterMgr = self.CreateFilterManager()
910 if theCriterion == FT_AspectRatio:
911 functor = aFilterMgr.CreateAspectRatio()
912 elif theCriterion == FT_AspectRatio3D:
913 functor = aFilterMgr.CreateAspectRatio3D()
914 elif theCriterion == FT_Warping:
915 functor = aFilterMgr.CreateWarping()
916 elif theCriterion == FT_MinimumAngle:
917 functor = aFilterMgr.CreateMinimumAngle()
918 elif theCriterion == FT_Taper:
919 functor = aFilterMgr.CreateTaper()
920 elif theCriterion == FT_Skew:
921 functor = aFilterMgr.CreateSkew()
922 elif theCriterion == FT_Area:
923 functor = aFilterMgr.CreateArea()
924 elif theCriterion == FT_Volume3D:
925 functor = aFilterMgr.CreateVolume3D()
926 elif theCriterion == FT_MaxElementLength2D:
927 functor = aFilterMgr.CreateMaxElementLength2D()
928 elif theCriterion == FT_MaxElementLength3D:
929 functor = aFilterMgr.CreateMaxElementLength3D()
930 elif theCriterion == FT_MultiConnection:
931 functor = aFilterMgr.CreateMultiConnection()
932 elif theCriterion == FT_MultiConnection2D:
933 functor = aFilterMgr.CreateMultiConnection2D()
934 elif theCriterion == FT_Length:
935 functor = aFilterMgr.CreateLength()
936 elif theCriterion == FT_Length2D:
937 functor = aFilterMgr.CreateLength2D()
939 print "Error: given parameter is not numerical functor type."
940 aFilterMgr.UnRegister()
943 ## Creates hypothesis
944 # @param theHType mesh hypothesis type (string)
945 # @param theLibName mesh plug-in library name
946 # @return created hypothesis instance
947 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
948 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
950 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
953 # wrap hypothesis methods
954 #print "HYPOTHESIS", theHType
955 for meth_name in dir( hyp.__class__ ):
956 if not meth_name.startswith("Get") and \
957 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
958 method = getattr ( hyp.__class__, meth_name )
960 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
964 ## Gets the mesh statistic
965 # @return dictionary "element type" - "count of elements"
966 # @ingroup l1_meshinfo
967 def GetMeshInfo(self, obj):
968 if isinstance( obj, Mesh ):
971 if hasattr(obj, "GetMeshInfo"):
972 values = obj.GetMeshInfo()
973 for i in range(SMESH.Entity_Last._v):
974 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
978 ## Get minimum distance between two objects
980 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
981 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
983 # @param src1 first source object
984 # @param src2 second source object
985 # @param id1 node/element id from the first source
986 # @param id2 node/element id from the second (or first) source
987 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
988 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
989 # @return minimum distance value
990 # @sa GetMinDistance()
991 # @ingroup l1_measurements
992 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
993 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
997 result = result.value
1000 ## Get measure structure specifying minimum distance data between two objects
1002 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1003 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1005 # @param src1 first source object
1006 # @param src2 second source object
1007 # @param id1 node/element id from the first source
1008 # @param id2 node/element id from the second (or first) source
1009 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1010 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1011 # @return Measure structure or None if input data is invalid
1013 # @ingroup l1_measurements
1014 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1015 if isinstance(src1, Mesh): src1 = src1.mesh
1016 if isinstance(src2, Mesh): src2 = src2.mesh
1017 if src2 is None and id2 != 0: src2 = src1
1018 if not hasattr(src1, "_narrow"): return None
1019 src1 = src1._narrow(SMESH.SMESH_IDSource)
1020 if not src1: return None
1021 unRegister = genObjUnRegister()
1024 e = m.GetMeshEditor()
1026 src1 = e.MakeIDSource([id1], SMESH.FACE)
1028 src1 = e.MakeIDSource([id1], SMESH.NODE)
1029 unRegister.set( src1 )
1031 if hasattr(src2, "_narrow"):
1032 src2 = src2._narrow(SMESH.SMESH_IDSource)
1033 if src2 and id2 != 0:
1035 e = m.GetMeshEditor()
1037 src2 = e.MakeIDSource([id2], SMESH.FACE)
1039 src2 = e.MakeIDSource([id2], SMESH.NODE)
1040 unRegister.set( src2 )
1043 aMeasurements = self.CreateMeasurements()
1044 unRegister.set( aMeasurements )
1045 result = aMeasurements.MinDistance(src1, src2)
1048 ## Get bounding box of the specified object(s)
1049 # @param objects single source object or list of source objects
1050 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1051 # @sa GetBoundingBox()
1052 # @ingroup l1_measurements
1053 def BoundingBox(self, objects):
1054 result = self.GetBoundingBox(objects)
1058 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1061 ## Get measure structure specifying bounding box data of the specified object(s)
1062 # @param objects single source object or list of source objects
1063 # @return Measure structure
1065 # @ingroup l1_measurements
1066 def GetBoundingBox(self, objects):
1067 if isinstance(objects, tuple):
1068 objects = list(objects)
1069 if not isinstance(objects, list):
1073 if isinstance(o, Mesh):
1074 srclist.append(o.mesh)
1075 elif hasattr(o, "_narrow"):
1076 src = o._narrow(SMESH.SMESH_IDSource)
1077 if src: srclist.append(src)
1080 aMeasurements = self.CreateMeasurements()
1081 result = aMeasurements.BoundingBox(srclist)
1082 aMeasurements.UnRegister()
1085 ## Get sum of lengths of all 1D elements in the mesh object.
1086 # @param obj mesh, submesh or group
1087 # @return sum of lengths of all 1D elements
1088 # @ingroup l1_measurements
1089 def GetLength(self, obj):
1090 if isinstance(obj, Mesh): obj = obj.mesh
1091 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1092 aMeasurements = self.CreateMeasurements()
1093 value = aMeasurements.Length(obj)
1094 aMeasurements.UnRegister()
1097 ## Get sum of areas of all 2D elements in the mesh object.
1098 # @param obj mesh, submesh or group
1099 # @return sum of areas of all 2D elements
1100 # @ingroup l1_measurements
1101 def GetArea(self, obj):
1102 if isinstance(obj, Mesh): obj = obj.mesh
1103 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1104 aMeasurements = self.CreateMeasurements()
1105 value = aMeasurements.Area(obj)
1106 aMeasurements.UnRegister()
1109 ## Get sum of volumes of all 3D elements in the mesh object.
1110 # @param obj mesh, submesh or group
1111 # @return sum of volumes of all 3D elements
1112 # @ingroup l1_measurements
1113 def GetVolume(self, obj):
1114 if isinstance(obj, Mesh): obj = obj.mesh
1115 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1116 aMeasurements = self.CreateMeasurements()
1117 value = aMeasurements.Volume(obj)
1118 aMeasurements.UnRegister()
1121 pass # end of class smeshBuilder
1124 #Registering the new proxy for SMESH_Gen
1125 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1127 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1128 # interface to create or load meshes.
1133 # salome.salome_init()
1134 # from salome.smesh import smeshBuilder
1135 # smesh = smeshBuilder.New(theStudy)
1137 # @param study SALOME study, generally obtained by salome.myStudy.
1138 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1139 # @return smeshBuilder instance
1141 def New( study, instance=None):
1143 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1144 interface to create or load meshes.
1148 salome.salome_init()
1149 from salome.smesh import smeshBuilder
1150 smesh = smeshBuilder.New(theStudy)
1153 study SALOME study, generally obtained by salome.myStudy.
1154 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1156 smeshBuilder instance
1164 smeshInst = smeshBuilder()
1165 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1166 smeshInst.init_smesh(study)
1170 # Public class: Mesh
1171 # ==================
1173 ## This class allows defining and managing a mesh.
1174 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1175 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1176 # new nodes and elements and by changing the existing entities), to get information
1177 # about a mesh and to export a mesh into different formats.
1179 __metaclass__ = MeshMeta
1187 # Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1188 # sets the GUI name of this mesh to \a name.
1189 # @param smeshpyD an instance of smeshBuilder class
1190 # @param geompyD an instance of geomBuilder class
1191 # @param obj Shape to be meshed or SMESH_Mesh object
1192 # @param name Study name of the mesh
1193 # @ingroup l2_construct
1194 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1195 self.smeshpyD=smeshpyD
1196 self.geompyD=geompyD
1201 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1204 # publish geom of mesh (issue 0021122)
1205 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1207 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1208 if studyID != geompyD.myStudyId:
1209 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1212 geo_name = name + " shape"
1214 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1215 geompyD.addToStudy( self.geom, geo_name )
1216 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1218 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1221 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1223 self.smeshpyD.SetName(self.mesh, name)
1225 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1228 self.geom = self.mesh.GetShapeToMesh()
1230 self.editor = self.mesh.GetMeshEditor()
1231 self.functors = [None] * SMESH.FT_Undefined._v
1233 # set self to algoCreator's
1234 for attrName in dir(self):
1235 attr = getattr( self, attrName )
1236 if isinstance( attr, algoCreator ):
1237 #print "algoCreator ", attrName
1238 setattr( self, attrName, attr.copy( self ))
1243 ## Destructor. Clean-up resources
1246 #self.mesh.UnRegister()
1250 ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1251 # @param theMesh a SMESH_Mesh object
1252 # @ingroup l2_construct
1253 def SetMesh(self, theMesh):
1254 # do not call Register() as this prevents mesh servant deletion at closing study
1255 #if self.mesh: self.mesh.UnRegister()
1258 #self.mesh.Register()
1259 self.geom = self.mesh.GetShapeToMesh()
1262 ## Returns the mesh, that is an instance of SMESH_Mesh interface
1263 # @return a SMESH_Mesh object
1264 # @ingroup l2_construct
1268 ## Gets the name of the mesh
1269 # @return the name of the mesh as a string
1270 # @ingroup l2_construct
1272 name = GetName(self.GetMesh())
1275 ## Sets a name to the mesh
1276 # @param name a new name of the mesh
1277 # @ingroup l2_construct
1278 def SetName(self, name):
1279 self.smeshpyD.SetName(self.GetMesh(), name)
1281 ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1282 # The subMesh object gives access to the IDs of nodes and elements.
1283 # @param geom a geometrical object (shape)
1284 # @param name a name for the submesh
1285 # @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1286 # @ingroup l2_submeshes
1287 def GetSubMesh(self, geom, name):
1288 AssureGeomPublished( self, geom, name )
1289 submesh = self.mesh.GetSubMesh( geom, name )
1292 ## Returns the shape associated to the mesh
1293 # @return a GEOM_Object
1294 # @ingroup l2_construct
1298 ## Associates the given shape to the mesh (entails the recreation of the mesh)
1299 # @param geom the shape to be meshed (GEOM_Object)
1300 # @ingroup l2_construct
1301 def SetShape(self, geom):
1302 self.mesh = self.smeshpyD.CreateMesh(geom)
1304 ## Loads mesh from the study after opening the study
1308 ## Returns true if the hypotheses are defined well
1309 # @param theSubObject a sub-shape of a mesh shape
1310 # @return True or False
1311 # @ingroup l2_construct
1312 def IsReadyToCompute(self, theSubObject):
1313 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1315 ## Returns errors of hypotheses definition.
1316 # The list of errors is empty if everything is OK.
1317 # @param theSubObject a sub-shape of a mesh shape
1318 # @return a list of errors
1319 # @ingroup l2_construct
1320 def GetAlgoState(self, theSubObject):
1321 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1323 ## Returns a geometrical object on which the given element was built.
1324 # The returned geometrical object, if not nil, is either found in the
1325 # study or published by this method with the given name
1326 # @param theElementID the id of the mesh element
1327 # @param theGeomName the user-defined name of the geometrical object
1328 # @return GEOM::GEOM_Object instance
1329 # @ingroup l2_construct
1330 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1331 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1333 ## Returns the mesh dimension depending on the dimension of the underlying shape
1334 # or, if the mesh is not based on any shape, basing on deimension of elements
1335 # @return mesh dimension as an integer value [0,3]
1336 # @ingroup l1_auxiliary
1337 def MeshDimension(self):
1338 if self.mesh.HasShapeToMesh():
1339 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1340 if len( shells ) > 0 :
1342 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1344 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1349 if self.NbVolumes() > 0: return 3
1350 if self.NbFaces() > 0: return 2
1351 if self.NbEdges() > 0: return 1
1354 ## Evaluates size of prospective mesh on a shape
1355 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1356 # To know predicted number of e.g. edges, inquire it this way
1357 # Evaluate()[ EnumToLong( Entity_Edge )]
1358 def Evaluate(self, geom=0):
1359 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1361 geom = self.mesh.GetShapeToMesh()
1364 return self.smeshpyD.Evaluate(self.mesh, geom)
1367 ## Computes the mesh and returns the status of the computation
1368 # @param geom geomtrical shape on which mesh data should be computed
1369 # @param discardModifs if True and the mesh has been edited since
1370 # a last total re-compute and that may prevent successful partial re-compute,
1371 # then the mesh is cleaned before Compute()
1372 # @return True or False
1373 # @ingroup l2_construct
1374 def Compute(self, geom=0, discardModifs=False):
1375 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1377 geom = self.mesh.GetShapeToMesh()
1382 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1384 ok = self.smeshpyD.Compute(self.mesh, geom)
1385 except SALOME.SALOME_Exception, ex:
1386 print "Mesh computation failed, exception caught:"
1387 print " ", ex.details.text
1390 print "Mesh computation failed, exception caught:"
1391 traceback.print_exc()
1395 # Treat compute errors
1396 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1397 for err in computeErrors:
1399 if self.mesh.HasShapeToMesh():
1401 mainIOR = salome.orb.object_to_string(geom)
1402 for sname in salome.myStudyManager.GetOpenStudies():
1403 s = salome.myStudyManager.GetStudyByName(sname)
1405 mainSO = s.FindObjectIOR(mainIOR)
1406 if not mainSO: continue
1407 if err.subShapeID == 1:
1408 shapeText = ' on "%s"' % mainSO.GetName()
1409 subIt = s.NewChildIterator(mainSO)
1411 subSO = subIt.Value()
1413 obj = subSO.GetObject()
1414 if not obj: continue
1415 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1417 ids = go.GetSubShapeIndices()
1418 if len(ids) == 1 and ids[0] == err.subShapeID:
1419 shapeText = ' on "%s"' % subSO.GetName()
1422 shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1424 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1426 shapeText = " on subshape #%s" % (err.subShapeID)
1428 shapeText = " on subshape #%s" % (err.subShapeID)
1430 stdErrors = ["OK", #COMPERR_OK
1431 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1432 "std::exception", #COMPERR_STD_EXCEPTION
1433 "OCC exception", #COMPERR_OCC_EXCEPTION
1434 "..", #COMPERR_SLM_EXCEPTION
1435 "Unknown exception", #COMPERR_EXCEPTION
1436 "Memory allocation problem", #COMPERR_MEMORY_PB
1437 "Algorithm failed", #COMPERR_ALGO_FAILED
1438 "Unexpected geometry", #COMPERR_BAD_SHAPE
1439 "Warning", #COMPERR_WARNING
1440 "Computation cancelled",#COMPERR_CANCELED
1441 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1443 if err.code < len(stdErrors): errText = stdErrors[err.code]
1445 errText = "code %s" % -err.code
1446 if errText: errText += ". "
1447 errText += err.comment
1448 if allReasons != "":allReasons += "\n"
1450 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1452 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1456 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1458 if err.isGlobalAlgo:
1466 reason = '%s %sD algorithm is missing' % (glob, dim)
1467 elif err.state == HYP_MISSING:
1468 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1469 % (glob, dim, name, dim))
1470 elif err.state == HYP_NOTCONFORM:
1471 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1472 elif err.state == HYP_BAD_PARAMETER:
1473 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1474 % ( glob, dim, name ))
1475 elif err.state == HYP_BAD_GEOMETRY:
1476 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1477 'geometry' % ( glob, dim, name ))
1478 elif err.state == HYP_HIDDEN_ALGO:
1479 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1480 'algorithm of upper dimension generating %sD mesh'
1481 % ( glob, dim, name, glob, dim ))
1483 reason = ("For unknown reason. "
1484 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1486 if allReasons != "":allReasons += "\n"
1487 allReasons += "- " + reason
1489 if not ok or allReasons != "":
1490 msg = '"' + GetName(self.mesh) + '"'
1491 if ok: msg += " has been computed with warnings"
1492 else: msg += " has not been computed"
1493 if allReasons != "": msg += ":"
1498 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1499 smeshgui = salome.ImportComponentGUI("SMESH")
1500 smeshgui.Init(self.mesh.GetStudyId())
1501 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1502 salome.sg.updateObjBrowser(1)
1506 ## Return submesh objects list in meshing order
1507 # @return list of list of submesh objects
1508 # @ingroup l2_construct
1509 def GetMeshOrder(self):
1510 return self.mesh.GetMeshOrder()
1512 ## Return submesh objects list in meshing order
1513 # @return list of list of submesh objects
1514 # @ingroup l2_construct
1515 def SetMeshOrder(self, submeshes):
1516 return self.mesh.SetMeshOrder(submeshes)
1518 ## Removes all nodes and elements
1519 # @ingroup l2_construct
1522 if ( salome.sg.hasDesktop() and
1523 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() )):
1524 smeshgui = salome.ImportComponentGUI("SMESH")
1525 smeshgui.Init(self.mesh.GetStudyId())
1526 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1527 salome.sg.updateObjBrowser(1)
1529 ## Removes all nodes and elements of indicated shape
1530 # @ingroup l2_construct
1531 def ClearSubMesh(self, geomId):
1532 self.mesh.ClearSubMesh(geomId)
1533 if salome.sg.hasDesktop():
1534 smeshgui = salome.ImportComponentGUI("SMESH")
1535 smeshgui.Init(self.mesh.GetStudyId())
1536 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1537 salome.sg.updateObjBrowser(1)
1539 ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1540 # @param fineness [0.0,1.0] defines mesh fineness
1541 # @return True or False
1542 # @ingroup l3_algos_basic
1543 def AutomaticTetrahedralization(self, fineness=0):
1544 dim = self.MeshDimension()
1546 self.RemoveGlobalHypotheses()
1547 self.Segment().AutomaticLength(fineness)
1549 self.Triangle().LengthFromEdges()
1554 return self.Compute()
1556 ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1557 # @param fineness [0.0, 1.0] defines mesh fineness
1558 # @return True or False
1559 # @ingroup l3_algos_basic
1560 def AutomaticHexahedralization(self, fineness=0):
1561 dim = self.MeshDimension()
1562 # assign the hypotheses
1563 self.RemoveGlobalHypotheses()
1564 self.Segment().AutomaticLength(fineness)
1571 return self.Compute()
1573 ## Assigns a hypothesis
1574 # @param hyp a hypothesis to assign
1575 # @param geom a subhape of mesh geometry
1576 # @return SMESH.Hypothesis_Status
1577 # @ingroup l2_hypotheses
1578 def AddHypothesis(self, hyp, geom=0):
1579 if isinstance( hyp, Mesh_Algorithm ):
1580 hyp = hyp.GetAlgorithm()
1585 geom = self.mesh.GetShapeToMesh()
1588 if self.mesh.HasShapeToMesh():
1589 hyp_type = hyp.GetName()
1590 lib_name = hyp.GetLibName()
1591 checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1592 if checkAll and geom:
1593 checkAll = geom.GetType() == 37
1594 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1596 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1597 status = self.mesh.AddHypothesis(geom, hyp)
1599 status = HYP_BAD_GEOMETRY,""
1600 hyp_name = GetName( hyp )
1603 geom_name = geom.GetName()
1604 isAlgo = hyp._narrow( SMESH_Algo )
1605 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1608 ## Return True if an algorithm of hypothesis is assigned to a given shape
1609 # @param hyp a hypothesis to check
1610 # @param geom a subhape of mesh geometry
1611 # @return True of False
1612 # @ingroup l2_hypotheses
1613 def IsUsedHypothesis(self, hyp, geom):
1614 if not hyp: # or not geom
1616 if isinstance( hyp, Mesh_Algorithm ):
1617 hyp = hyp.GetAlgorithm()
1619 hyps = self.GetHypothesisList(geom)
1621 if h.GetId() == hyp.GetId():
1625 ## Unassigns a hypothesis
1626 # @param hyp a hypothesis to unassign
1627 # @param geom a sub-shape of mesh geometry
1628 # @return SMESH.Hypothesis_Status
1629 # @ingroup l2_hypotheses
1630 def RemoveHypothesis(self, hyp, geom=0):
1633 if isinstance( hyp, Mesh_Algorithm ):
1634 hyp = hyp.GetAlgorithm()
1640 if self.IsUsedHypothesis( hyp, shape ):
1641 return self.mesh.RemoveHypothesis( shape, hyp )
1642 hypName = GetName( hyp )
1643 geoName = GetName( shape )
1644 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1647 ## Gets the list of hypotheses added on a geometry
1648 # @param geom a sub-shape of mesh geometry
1649 # @return the sequence of SMESH_Hypothesis
1650 # @ingroup l2_hypotheses
1651 def GetHypothesisList(self, geom):
1652 return self.mesh.GetHypothesisList( geom )
1654 ## Removes all global hypotheses
1655 # @ingroup l2_hypotheses
1656 def RemoveGlobalHypotheses(self):
1657 current_hyps = self.mesh.GetHypothesisList( self.geom )
1658 for hyp in current_hyps:
1659 self.mesh.RemoveHypothesis( self.geom, hyp )
1663 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1664 ## allowing to overwrite the file if it exists or add the exported data to its contents
1665 # @param f is the file name
1666 # @param auto_groups boolean parameter for creating/not creating
1667 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1668 # the typical use is auto_groups=false.
1669 # @param version MED format version(MED_V2_1 or MED_V2_2)
1670 # @param overwrite boolean parameter for overwriting/not overwriting the file
1671 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1672 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1673 # - 1D if all mesh nodes lie on OX coordinate axis, or
1674 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1675 # - 3D in the rest cases.
1676 # If @a autoDimension is @c False, the space dimension is always 3.
1677 # @param fields : list of GEOM fields defined on the shape to mesh.
1678 # @param geomAssocFields : each character of this string means a need to export a
1679 # corresponding field; correspondence between fields and characters is following:
1680 # - 'v' stands for _vertices_ field;
1681 # - 'e' stands for _edges_ field;
1682 # - 'f' stands for _faces_ field;
1683 # - 's' stands for _solids_ field.
1684 # @ingroup l2_impexp
1685 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1686 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1687 if meshPart or fields or geomAssocFields:
1688 unRegister = genObjUnRegister()
1689 if isinstance( meshPart, list ):
1690 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1691 unRegister.set( meshPart )
1692 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1693 fields, geomAssocFields)
1695 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1697 ## Exports the mesh in a file in SAUV format
1698 # @param f is the file name
1699 # @param auto_groups boolean parameter for creating/not creating
1700 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1701 # the typical use is auto_groups=false.
1702 # @ingroup l2_impexp
1703 def ExportSAUV(self, f, auto_groups=0):
1704 self.mesh.ExportSAUV(f, auto_groups)
1706 ## Exports the mesh in a file in DAT format
1707 # @param f the file name
1708 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1709 # @ingroup l2_impexp
1710 def ExportDAT(self, f, meshPart=None):
1712 unRegister = genObjUnRegister()
1713 if isinstance( meshPart, list ):
1714 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1715 unRegister.set( meshPart )
1716 self.mesh.ExportPartToDAT( meshPart, f )
1718 self.mesh.ExportDAT(f)
1720 ## Exports the mesh in a file in UNV format
1721 # @param f the file name
1722 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1723 # @ingroup l2_impexp
1724 def ExportUNV(self, f, meshPart=None):
1726 unRegister = genObjUnRegister()
1727 if isinstance( meshPart, list ):
1728 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1729 unRegister.set( meshPart )
1730 self.mesh.ExportPartToUNV( meshPart, f )
1732 self.mesh.ExportUNV(f)
1734 ## Export the mesh in a file in STL format
1735 # @param f the file name
1736 # @param ascii defines the file encoding
1737 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1738 # @ingroup l2_impexp
1739 def ExportSTL(self, f, ascii=1, meshPart=None):
1741 unRegister = genObjUnRegister()
1742 if isinstance( meshPart, list ):
1743 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1744 unRegister.set( meshPart )
1745 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1747 self.mesh.ExportSTL(f, ascii)
1749 ## Exports the mesh in a file in CGNS format
1750 # @param f is the file name
1751 # @param overwrite boolean parameter for overwriting/not overwriting the file
1752 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1753 # @ingroup l2_impexp
1754 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1755 unRegister = genObjUnRegister()
1756 if isinstance( meshPart, list ):
1757 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1758 unRegister.set( meshPart )
1759 if isinstance( meshPart, Mesh ):
1760 meshPart = meshPart.mesh
1762 meshPart = self.mesh
1763 self.mesh.ExportCGNS(meshPart, f, overwrite)
1765 ## Exports the mesh in a file in GMF format.
1766 # GMF files must have .mesh extension for the ASCII format and .meshb for
1767 # the bynary format. Other extensions are not allowed.
1768 # @param f is the file name
1769 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1770 # @ingroup l2_impexp
1771 def ExportGMF(self, f, meshPart=None):
1772 unRegister = genObjUnRegister()
1773 if isinstance( meshPart, list ):
1774 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1775 unRegister.set( meshPart )
1776 if isinstance( meshPart, Mesh ):
1777 meshPart = meshPart.mesh
1779 meshPart = self.mesh
1780 self.mesh.ExportGMF(meshPart, f, True)
1782 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1783 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1784 ## allowing to overwrite the file if it exists or add the exported data to its contents
1785 # @param f the file name
1786 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1787 # @param opt boolean parameter for creating/not creating
1788 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1789 # @param overwrite boolean parameter for overwriting/not overwriting the file
1790 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1791 # - 1D if all mesh nodes lie on OX coordinate axis, or
1792 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1793 # - 3D in the rest cases.
1795 # If @a autoDimension is @c False, the space dimension is always 3.
1796 # @ingroup l2_impexp
1797 def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1798 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1800 # Operations with groups:
1801 # ----------------------
1803 ## Creates an empty mesh group
1804 # @param elementType the type of elements in the group
1805 # @param name the name of the mesh group
1806 # @return SMESH_Group
1807 # @ingroup l2_grps_create
1808 def CreateEmptyGroup(self, elementType, name):
1809 return self.mesh.CreateGroup(elementType, name)
1811 ## Creates a mesh group based on the geometric object \a grp
1812 # and gives a \a name, \n if this parameter is not defined
1813 # the name is the same as the geometric group name \n
1814 # Note: Works like GroupOnGeom().
1815 # @param grp a geometric group, a vertex, an edge, a face or a solid
1816 # @param name the name of the mesh group
1817 # @return SMESH_GroupOnGeom
1818 # @ingroup l2_grps_create
1819 def Group(self, grp, name=""):
1820 return self.GroupOnGeom(grp, name)
1822 ## Creates a mesh group based on the geometrical object \a grp
1823 # and gives a \a name, \n if this parameter is not defined
1824 # the name is the same as the geometrical group name
1825 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1826 # @param name the name of the mesh group
1827 # @param typ the type of elements in the group. If not set, it is
1828 # automatically detected by the type of the geometry
1829 # @return SMESH_GroupOnGeom
1830 # @ingroup l2_grps_create
1831 def GroupOnGeom(self, grp, name="", typ=None):
1832 AssureGeomPublished( self, grp, name )
1834 name = grp.GetName()
1836 typ = self._groupTypeFromShape( grp )
1837 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1839 ## Pivate method to get a type of group on geometry
1840 def _groupTypeFromShape( self, shape ):
1841 tgeo = str(shape.GetShapeType())
1842 if tgeo == "VERTEX":
1844 elif tgeo == "EDGE":
1846 elif tgeo == "FACE" or tgeo == "SHELL":
1848 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1850 elif tgeo == "COMPOUND":
1851 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1853 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1854 return self._groupTypeFromShape( sub[0] )
1857 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1860 ## Creates a mesh group with given \a name based on the \a filter which
1861 ## is a special type of group dynamically updating it's contents during
1862 ## mesh modification
1863 # @param typ the type of elements in the group
1864 # @param name the name of the mesh group
1865 # @param filter the filter defining group contents
1866 # @return SMESH_GroupOnFilter
1867 # @ingroup l2_grps_create
1868 def GroupOnFilter(self, typ, name, filter):
1869 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1871 ## Creates a mesh group by the given ids of elements
1872 # @param groupName the name of the mesh group
1873 # @param elementType the type of elements in the group
1874 # @param elemIDs the list of ids
1875 # @return SMESH_Group
1876 # @ingroup l2_grps_create
1877 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1878 group = self.mesh.CreateGroup(elementType, groupName)
1879 if hasattr( elemIDs, "GetIDs" ):
1880 if hasattr( elemIDs, "SetMesh" ):
1881 elemIDs.SetMesh( self.GetMesh() )
1882 group.AddFrom( elemIDs )
1887 ## Creates a mesh group by the given conditions
1888 # @param groupName the name of the mesh group
1889 # @param elementType the type of elements in the group
1890 # @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1891 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1892 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
1893 # @param UnaryOp FT_LogicalNOT or FT_Undefined
1894 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1895 # FT_LyingOnGeom, FT_CoplanarFaces criteria
1896 # @return SMESH_GroupOnFilter
1897 # @ingroup l2_grps_create
1901 CritType=FT_Undefined,
1904 UnaryOp=FT_Undefined,
1906 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1907 group = self.MakeGroupByCriterion(groupName, aCriterion)
1910 ## Creates a mesh group by the given criterion
1911 # @param groupName the name of the mesh group
1912 # @param Criterion the instance of Criterion class
1913 # @return SMESH_GroupOnFilter
1914 # @ingroup l2_grps_create
1915 def MakeGroupByCriterion(self, groupName, Criterion):
1916 return self.MakeGroupByCriteria( groupName, [Criterion] )
1918 ## Creates a mesh group by the given criteria (list of criteria)
1919 # @param groupName the name of the mesh group
1920 # @param theCriteria the list of criteria
1921 # @param binOp binary operator used when binary operator of criteria is undefined
1922 # @return SMESH_GroupOnFilter
1923 # @ingroup l2_grps_create
1924 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
1925 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
1926 group = self.MakeGroupByFilter(groupName, aFilter)
1929 ## Creates a mesh group by the given filter
1930 # @param groupName the name of the mesh group
1931 # @param theFilter the instance of Filter class
1932 # @return SMESH_GroupOnFilter
1933 # @ingroup l2_grps_create
1934 def MakeGroupByFilter(self, groupName, theFilter):
1935 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1936 #theFilter.SetMesh( self.mesh )
1937 #group.AddFrom( theFilter )
1938 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
1942 # @ingroup l2_grps_delete
1943 def RemoveGroup(self, group):
1944 self.mesh.RemoveGroup(group)
1946 ## Removes a group with its contents
1947 # @ingroup l2_grps_delete
1948 def RemoveGroupWithContents(self, group):
1949 self.mesh.RemoveGroupWithContents(group)
1951 ## Gets the list of groups existing in the mesh in the order of creation (starting from the oldest one)
1952 # @return a sequence of SMESH_GroupBase
1953 # @ingroup l2_grps_create
1954 def GetGroups(self):
1955 return self.mesh.GetGroups()
1957 ## Gets the number of groups existing in the mesh
1958 # @return the quantity of groups as an integer value
1959 # @ingroup l2_grps_create
1961 return self.mesh.NbGroups()
1963 ## Gets the list of names of groups existing in the mesh
1964 # @return list of strings
1965 # @ingroup l2_grps_create
1966 def GetGroupNames(self):
1967 groups = self.GetGroups()
1969 for group in groups:
1970 names.append(group.GetName())
1973 ## Produces a union of two groups
1974 # A new group is created. All mesh elements that are
1975 # present in the initial groups are added to the new one
1976 # @return an instance of SMESH_Group
1977 # @ingroup l2_grps_operon
1978 def UnionGroups(self, group1, group2, name):
1979 return self.mesh.UnionGroups(group1, group2, name)
1981 ## Produces a union list of groups
1982 # New group is created. All mesh elements that are present in
1983 # initial groups are added to the new one
1984 # @return an instance of SMESH_Group
1985 # @ingroup l2_grps_operon
1986 def UnionListOfGroups(self, groups, name):
1987 return self.mesh.UnionListOfGroups(groups, name)
1989 ## Prodices an intersection of two groups
1990 # A new group is created. All mesh elements that are common
1991 # for the two initial groups are added to the new one.
1992 # @return an instance of SMESH_Group
1993 # @ingroup l2_grps_operon
1994 def IntersectGroups(self, group1, group2, name):
1995 return self.mesh.IntersectGroups(group1, group2, name)
1997 ## Produces an intersection of groups
1998 # New group is created. All mesh elements that are present in all
1999 # initial groups simultaneously are added to the new one
2000 # @return an instance of SMESH_Group
2001 # @ingroup l2_grps_operon
2002 def IntersectListOfGroups(self, groups, name):
2003 return self.mesh.IntersectListOfGroups(groups, name)
2005 ## Produces a cut of two groups
2006 # A new group is created. All mesh elements that are present in
2007 # the main group but are not present in the tool group are added to the new one
2008 # @return an instance of SMESH_Group
2009 # @ingroup l2_grps_operon
2010 def CutGroups(self, main_group, tool_group, name):
2011 return self.mesh.CutGroups(main_group, tool_group, name)
2013 ## Produces a cut of groups
2014 # A new group is created. All mesh elements that are present in main groups
2015 # but do not present in tool groups are added to the new one
2016 # @return an instance of SMESH_Group
2017 # @ingroup l2_grps_operon
2018 def CutListOfGroups(self, main_groups, tool_groups, name):
2019 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2021 ## Produces a group of elements of specified type using list of existing groups
2022 # A new group is created. System
2023 # 1) extracts all nodes on which groups elements are built
2024 # 2) combines all elements of specified dimension laying on these nodes
2025 # @return an instance of SMESH_Group
2026 # @ingroup l2_grps_operon
2027 def CreateDimGroup(self, groups, elem_type, name):
2028 return self.mesh.CreateDimGroup(groups, elem_type, name)
2031 ## Convert group on geom into standalone group
2032 # @ingroup l2_grps_delete
2033 def ConvertToStandalone(self, group):
2034 return self.mesh.ConvertToStandalone(group)
2036 # Get some info about mesh:
2037 # ------------------------
2039 ## Returns the log of nodes and elements added or removed
2040 # since the previous clear of the log.
2041 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2042 # @return list of log_block structures:
2047 # @ingroup l1_auxiliary
2048 def GetLog(self, clearAfterGet):
2049 return self.mesh.GetLog(clearAfterGet)
2051 ## Clears the log of nodes and elements added or removed since the previous
2052 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2053 # @ingroup l1_auxiliary
2055 self.mesh.ClearLog()
2057 ## Toggles auto color mode on the object.
2058 # @param theAutoColor the flag which toggles auto color mode.
2059 # @ingroup l1_auxiliary
2060 def SetAutoColor(self, theAutoColor):
2061 self.mesh.SetAutoColor(theAutoColor)
2063 ## Gets flag of object auto color mode.
2064 # @return True or False
2065 # @ingroup l1_auxiliary
2066 def GetAutoColor(self):
2067 return self.mesh.GetAutoColor()
2069 ## Gets the internal ID
2070 # @return integer value, which is the internal Id of the mesh
2071 # @ingroup l1_auxiliary
2073 return self.mesh.GetId()
2076 # @return integer value, which is the study Id of the mesh
2077 # @ingroup l1_auxiliary
2078 def GetStudyId(self):
2079 return self.mesh.GetStudyId()
2081 ## Checks the group names for duplications.
2082 # Consider the maximum group name length stored in MED file.
2083 # @return True or False
2084 # @ingroup l1_auxiliary
2085 def HasDuplicatedGroupNamesMED(self):
2086 return self.mesh.HasDuplicatedGroupNamesMED()
2088 ## Obtains the mesh editor tool
2089 # @return an instance of SMESH_MeshEditor
2090 # @ingroup l1_modifying
2091 def GetMeshEditor(self):
2094 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2095 # can be passed as argument to a method accepting mesh, group or sub-mesh
2096 # @return an instance of SMESH_IDSource
2097 # @ingroup l1_auxiliary
2098 def GetIDSource(self, ids, elemType):
2099 return self.editor.MakeIDSource(ids, elemType)
2102 # Get informations about mesh contents:
2103 # ------------------------------------
2105 ## Gets the mesh stattistic
2106 # @return dictionary type element - count of elements
2107 # @ingroup l1_meshinfo
2108 def GetMeshInfo(self, obj = None):
2109 if not obj: obj = self.mesh
2110 return self.smeshpyD.GetMeshInfo(obj)
2112 ## Returns the number of nodes in the mesh
2113 # @return an integer value
2114 # @ingroup l1_meshinfo
2116 return self.mesh.NbNodes()
2118 ## Returns the number of elements in the mesh
2119 # @return an integer value
2120 # @ingroup l1_meshinfo
2121 def NbElements(self):
2122 return self.mesh.NbElements()
2124 ## Returns the number of 0d elements in the mesh
2125 # @return an integer value
2126 # @ingroup l1_meshinfo
2127 def Nb0DElements(self):
2128 return self.mesh.Nb0DElements()
2130 ## Returns the number of ball discrete elements in the mesh
2131 # @return an integer value
2132 # @ingroup l1_meshinfo
2134 return self.mesh.NbBalls()
2136 ## Returns the number of edges in the mesh
2137 # @return an integer value
2138 # @ingroup l1_meshinfo
2140 return self.mesh.NbEdges()
2142 ## Returns the number of edges with the given order in the mesh
2143 # @param elementOrder the order of elements:
2144 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2145 # @return an integer value
2146 # @ingroup l1_meshinfo
2147 def NbEdgesOfOrder(self, elementOrder):
2148 return self.mesh.NbEdgesOfOrder(elementOrder)
2150 ## Returns the number of faces in the mesh
2151 # @return an integer value
2152 # @ingroup l1_meshinfo
2154 return self.mesh.NbFaces()
2156 ## Returns the number of faces with the given order in the mesh
2157 # @param elementOrder the order of elements:
2158 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2159 # @return an integer value
2160 # @ingroup l1_meshinfo
2161 def NbFacesOfOrder(self, elementOrder):
2162 return self.mesh.NbFacesOfOrder(elementOrder)
2164 ## Returns the number of triangles in the mesh
2165 # @return an integer value
2166 # @ingroup l1_meshinfo
2167 def NbTriangles(self):
2168 return self.mesh.NbTriangles()
2170 ## Returns the number of triangles with the given order in the mesh
2171 # @param elementOrder is the order of elements:
2172 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2173 # @return an integer value
2174 # @ingroup l1_meshinfo
2175 def NbTrianglesOfOrder(self, elementOrder):
2176 return self.mesh.NbTrianglesOfOrder(elementOrder)
2178 ## Returns the number of biquadratic triangles in the mesh
2179 # @return an integer value
2180 # @ingroup l1_meshinfo
2181 def NbBiQuadTriangles(self):
2182 return self.mesh.NbBiQuadTriangles()
2184 ## Returns the number of quadrangles in the mesh
2185 # @return an integer value
2186 # @ingroup l1_meshinfo
2187 def NbQuadrangles(self):
2188 return self.mesh.NbQuadrangles()
2190 ## Returns the number of quadrangles with the given order in the mesh
2191 # @param elementOrder the order of elements:
2192 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2193 # @return an integer value
2194 # @ingroup l1_meshinfo
2195 def NbQuadranglesOfOrder(self, elementOrder):
2196 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2198 ## Returns the number of biquadratic quadrangles in the mesh
2199 # @return an integer value
2200 # @ingroup l1_meshinfo
2201 def NbBiQuadQuadrangles(self):
2202 return self.mesh.NbBiQuadQuadrangles()
2204 ## Returns the number of polygons in the mesh
2205 # @return an integer value
2206 # @ingroup l1_meshinfo
2207 def NbPolygons(self):
2208 return self.mesh.NbPolygons()
2210 ## Returns the number of volumes in the mesh
2211 # @return an integer value
2212 # @ingroup l1_meshinfo
2213 def NbVolumes(self):
2214 return self.mesh.NbVolumes()
2216 ## Returns the number of volumes with the given order in the mesh
2217 # @param elementOrder the order of elements:
2218 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2219 # @return an integer value
2220 # @ingroup l1_meshinfo
2221 def NbVolumesOfOrder(self, elementOrder):
2222 return self.mesh.NbVolumesOfOrder(elementOrder)
2224 ## Returns the number of tetrahedrons in the mesh
2225 # @return an integer value
2226 # @ingroup l1_meshinfo
2228 return self.mesh.NbTetras()
2230 ## Returns the number of tetrahedrons with the given order in the mesh
2231 # @param elementOrder the order of elements:
2232 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2233 # @return an integer value
2234 # @ingroup l1_meshinfo
2235 def NbTetrasOfOrder(self, elementOrder):
2236 return self.mesh.NbTetrasOfOrder(elementOrder)
2238 ## Returns the number of hexahedrons in the mesh
2239 # @return an integer value
2240 # @ingroup l1_meshinfo
2242 return self.mesh.NbHexas()
2244 ## Returns the number of hexahedrons with the given order in the mesh
2245 # @param elementOrder the order of elements:
2246 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2247 # @return an integer value
2248 # @ingroup l1_meshinfo
2249 def NbHexasOfOrder(self, elementOrder):
2250 return self.mesh.NbHexasOfOrder(elementOrder)
2252 ## Returns the number of triquadratic hexahedrons in the mesh
2253 # @return an integer value
2254 # @ingroup l1_meshinfo
2255 def NbTriQuadraticHexas(self):
2256 return self.mesh.NbTriQuadraticHexas()
2258 ## Returns the number of pyramids in the mesh
2259 # @return an integer value
2260 # @ingroup l1_meshinfo
2261 def NbPyramids(self):
2262 return self.mesh.NbPyramids()
2264 ## Returns the number of pyramids with the given order in the mesh
2265 # @param elementOrder the order of elements:
2266 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2267 # @return an integer value
2268 # @ingroup l1_meshinfo
2269 def NbPyramidsOfOrder(self, elementOrder):
2270 return self.mesh.NbPyramidsOfOrder(elementOrder)
2272 ## Returns the number of prisms in the mesh
2273 # @return an integer value
2274 # @ingroup l1_meshinfo
2276 return self.mesh.NbPrisms()
2278 ## Returns the number of prisms with the given order in the mesh
2279 # @param elementOrder the order of elements:
2280 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2281 # @return an integer value
2282 # @ingroup l1_meshinfo
2283 def NbPrismsOfOrder(self, elementOrder):
2284 return self.mesh.NbPrismsOfOrder(elementOrder)
2286 ## Returns the number of hexagonal prisms in the mesh
2287 # @return an integer value
2288 # @ingroup l1_meshinfo
2289 def NbHexagonalPrisms(self):
2290 return self.mesh.NbHexagonalPrisms()
2292 ## Returns the number of polyhedrons in the mesh
2293 # @return an integer value
2294 # @ingroup l1_meshinfo
2295 def NbPolyhedrons(self):
2296 return self.mesh.NbPolyhedrons()
2298 ## Returns the number of submeshes in the mesh
2299 # @return an integer value
2300 # @ingroup l1_meshinfo
2301 def NbSubMesh(self):
2302 return self.mesh.NbSubMesh()
2304 ## Returns the list of mesh elements IDs
2305 # @return the list of integer values
2306 # @ingroup l1_meshinfo
2307 def GetElementsId(self):
2308 return self.mesh.GetElementsId()
2310 ## Returns the list of IDs of mesh elements with the given type
2311 # @param elementType the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2312 # @return list of integer values
2313 # @ingroup l1_meshinfo
2314 def GetElementsByType(self, elementType):
2315 return self.mesh.GetElementsByType(elementType)
2317 ## Returns the list of mesh nodes IDs
2318 # @return the list of integer values
2319 # @ingroup l1_meshinfo
2320 def GetNodesId(self):
2321 return self.mesh.GetNodesId()
2323 # Get the information about mesh elements:
2324 # ------------------------------------
2326 ## Returns the type of mesh element
2327 # @return the value from SMESH::ElementType enumeration
2328 # @ingroup l1_meshinfo
2329 def GetElementType(self, id, iselem):
2330 return self.mesh.GetElementType(id, iselem)
2332 ## Returns the geometric type of mesh element
2333 # @return the value from SMESH::EntityType enumeration
2334 # @ingroup l1_meshinfo
2335 def GetElementGeomType(self, id):
2336 return self.mesh.GetElementGeomType(id)
2338 ## Returns the shape type of mesh element
2339 # @return the value from SMESH::GeometryType enumeration
2340 # @ingroup l1_meshinfo
2341 def GetElementShape(self, id):
2342 return self.mesh.GetElementShape(id)
2344 ## Returns the list of submesh elements IDs
2345 # @param Shape a geom object(sub-shape) IOR
2346 # Shape must be the sub-shape of a ShapeToMesh()
2347 # @return the list of integer values
2348 # @ingroup l1_meshinfo
2349 def GetSubMeshElementsId(self, Shape):
2350 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2351 ShapeID = Shape.GetSubShapeIndices()[0]
2354 return self.mesh.GetSubMeshElementsId(ShapeID)
2356 ## Returns the list of submesh nodes IDs
2357 # @param Shape a geom object(sub-shape) IOR
2358 # Shape must be the sub-shape of a ShapeToMesh()
2359 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2360 # @return the list of integer values
2361 # @ingroup l1_meshinfo
2362 def GetSubMeshNodesId(self, Shape, all):
2363 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2364 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2367 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2369 ## Returns type of elements on given shape
2370 # @param Shape a geom object(sub-shape) IOR
2371 # Shape must be a sub-shape of a ShapeToMesh()
2372 # @return element type
2373 # @ingroup l1_meshinfo
2374 def GetSubMeshElementType(self, Shape):
2375 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2376 ShapeID = Shape.GetSubShapeIndices()[0]
2379 return self.mesh.GetSubMeshElementType(ShapeID)
2381 ## Gets the mesh description
2382 # @return string value
2383 # @ingroup l1_meshinfo
2385 return self.mesh.Dump()
2388 # Get the information about nodes and elements of a mesh by its IDs:
2389 # -----------------------------------------------------------
2391 ## Gets XYZ coordinates of a node
2392 # \n If there is no nodes for the given ID - returns an empty list
2393 # @return a list of double precision values
2394 # @ingroup l1_meshinfo
2395 def GetNodeXYZ(self, id):
2396 return self.mesh.GetNodeXYZ(id)
2398 ## Returns list of IDs of inverse elements for the given node
2399 # \n If there is no node for the given ID - returns an empty list
2400 # @return a list of integer values
2401 # @ingroup l1_meshinfo
2402 def GetNodeInverseElements(self, id):
2403 return self.mesh.GetNodeInverseElements(id)
2405 ## @brief Returns the position of a node on the shape
2406 # @return SMESH::NodePosition
2407 # @ingroup l1_meshinfo
2408 def GetNodePosition(self,NodeID):
2409 return self.mesh.GetNodePosition(NodeID)
2411 ## @brief Returns the position of an element on the shape
2412 # @return SMESH::ElementPosition
2413 # @ingroup l1_meshinfo
2414 def GetElementPosition(self,ElemID):
2415 return self.mesh.GetElementPosition(ElemID)
2417 ## If the given element is a node, returns the ID of shape
2418 # \n If there is no node for the given ID - returns -1
2419 # @return an integer value
2420 # @ingroup l1_meshinfo
2421 def GetShapeID(self, id):
2422 return self.mesh.GetShapeID(id)
2424 ## Returns the ID of the result shape after
2425 # FindShape() from SMESH_MeshEditor for the given element
2426 # \n If there is no element for the given ID - returns -1
2427 # @return an integer value
2428 # @ingroup l1_meshinfo
2429 def GetShapeIDForElem(self,id):
2430 return self.mesh.GetShapeIDForElem(id)
2432 ## Returns the number of nodes for the given element
2433 # \n If there is no element for the given ID - returns -1
2434 # @return an integer value
2435 # @ingroup l1_meshinfo
2436 def GetElemNbNodes(self, id):
2437 return self.mesh.GetElemNbNodes(id)
2439 ## Returns the node ID the given (zero based) index for the given element
2440 # \n If there is no element for the given ID - returns -1
2441 # \n If there is no node for the given index - returns -2
2442 # @return an integer value
2443 # @ingroup l1_meshinfo
2444 def GetElemNode(self, id, index):
2445 return self.mesh.GetElemNode(id, index)
2447 ## Returns the IDs of nodes of the given element
2448 # @return a list of integer values
2449 # @ingroup l1_meshinfo
2450 def GetElemNodes(self, id):
2451 return self.mesh.GetElemNodes(id)
2453 ## Returns true if the given node is the medium node in the given quadratic element
2454 # @ingroup l1_meshinfo
2455 def IsMediumNode(self, elementID, nodeID):
2456 return self.mesh.IsMediumNode(elementID, nodeID)
2458 ## Returns true if the given node is the medium node in one of quadratic elements
2459 # @ingroup l1_meshinfo
2460 def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2461 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2463 ## Returns the number of edges for the given element
2464 # @ingroup l1_meshinfo
2465 def ElemNbEdges(self, id):
2466 return self.mesh.ElemNbEdges(id)
2468 ## Returns the number of faces for the given element
2469 # @ingroup l1_meshinfo
2470 def ElemNbFaces(self, id):
2471 return self.mesh.ElemNbFaces(id)
2473 ## Returns nodes of given face (counted from zero) for given volumic element.
2474 # @ingroup l1_meshinfo
2475 def GetElemFaceNodes(self,elemId, faceIndex):
2476 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2478 ## Returns three components of normal of given mesh face
2479 # (or an empty array in KO case)
2480 # @ingroup l1_meshinfo
2481 def GetFaceNormal(self, faceId, normalized=False):
2482 return self.mesh.GetFaceNormal(faceId,normalized)
2484 ## Returns an element based on all given nodes.
2485 # @ingroup l1_meshinfo
2486 def FindElementByNodes(self,nodes):
2487 return self.mesh.FindElementByNodes(nodes)
2489 ## Returns true if the given element is a polygon
2490 # @ingroup l1_meshinfo
2491 def IsPoly(self, id):
2492 return self.mesh.IsPoly(id)
2494 ## Returns true if the given element is quadratic
2495 # @ingroup l1_meshinfo
2496 def IsQuadratic(self, id):
2497 return self.mesh.IsQuadratic(id)
2499 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2500 # @ingroup l1_meshinfo
2501 def GetBallDiameter(self, id):
2502 return self.mesh.GetBallDiameter(id)
2504 ## Returns XYZ coordinates of the barycenter of the given element
2505 # \n If there is no element for the given ID - returns an empty list
2506 # @return a list of three double values
2507 # @ingroup l1_meshinfo
2508 def BaryCenter(self, id):
2509 return self.mesh.BaryCenter(id)
2511 ## Passes mesh elements through the given filter and return IDs of fitting elements
2512 # @param theFilter SMESH_Filter
2513 # @return a list of ids
2514 # @ingroup l1_controls
2515 def GetIdsFromFilter(self, theFilter):
2516 theFilter.SetMesh( self.mesh )
2517 return theFilter.GetIDs()
2519 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2520 # Returns a list of special structures (borders).
2521 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2522 # @ingroup l1_controls
2523 def GetFreeBorders(self):
2524 aFilterMgr = self.smeshpyD.CreateFilterManager()
2525 aPredicate = aFilterMgr.CreateFreeEdges()
2526 aPredicate.SetMesh(self.mesh)
2527 aBorders = aPredicate.GetBorders()
2528 aFilterMgr.UnRegister()
2532 # Get mesh measurements information:
2533 # ------------------------------------
2535 ## Get minimum distance between two nodes, elements or distance to the origin
2536 # @param id1 first node/element id
2537 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2538 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2539 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2540 # @return minimum distance value
2541 # @sa GetMinDistance()
2542 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2543 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2544 return aMeasure.value
2546 ## Get measure structure specifying minimum distance data between two objects
2547 # @param id1 first node/element id
2548 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2549 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2550 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2551 # @return Measure structure
2553 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2555 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2557 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2560 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2562 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2567 aMeasurements = self.smeshpyD.CreateMeasurements()
2568 aMeasure = aMeasurements.MinDistance(id1, id2)
2569 genObjUnRegister([aMeasurements,id1, id2])
2572 ## Get bounding box of the specified object(s)
2573 # @param objects single source object or list of source objects or list of nodes/elements IDs
2574 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2575 # @c False specifies that @a objects are nodes
2576 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2577 # @sa GetBoundingBox()
2578 def BoundingBox(self, objects=None, isElem=False):
2579 result = self.GetBoundingBox(objects, isElem)
2583 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2586 ## Get measure structure specifying bounding box data of the specified object(s)
2587 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2588 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2589 # @c False specifies that @a objects are nodes
2590 # @return Measure structure
2592 def GetBoundingBox(self, IDs=None, isElem=False):
2595 elif isinstance(IDs, tuple):
2597 if not isinstance(IDs, list):
2599 if len(IDs) > 0 and isinstance(IDs[0], int):
2602 unRegister = genObjUnRegister()
2604 if isinstance(o, Mesh):
2605 srclist.append(o.mesh)
2606 elif hasattr(o, "_narrow"):
2607 src = o._narrow(SMESH.SMESH_IDSource)
2608 if src: srclist.append(src)
2610 elif isinstance(o, list):
2612 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2614 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2615 unRegister.set( srclist[-1] )
2618 aMeasurements = self.smeshpyD.CreateMeasurements()
2619 unRegister.set( aMeasurements )
2620 aMeasure = aMeasurements.BoundingBox(srclist)
2623 # Mesh edition (SMESH_MeshEditor functionality):
2624 # ---------------------------------------------
2626 ## Removes the elements from the mesh by ids
2627 # @param IDsOfElements is a list of ids of elements to remove
2628 # @return True or False
2629 # @ingroup l2_modif_del
2630 def RemoveElements(self, IDsOfElements):
2631 return self.editor.RemoveElements(IDsOfElements)
2633 ## Removes nodes from mesh by ids
2634 # @param IDsOfNodes is a list of ids of nodes to remove
2635 # @return True or False
2636 # @ingroup l2_modif_del
2637 def RemoveNodes(self, IDsOfNodes):
2638 return self.editor.RemoveNodes(IDsOfNodes)
2640 ## Removes all orphan (free) nodes from mesh
2641 # @return number of the removed nodes
2642 # @ingroup l2_modif_del
2643 def RemoveOrphanNodes(self):
2644 return self.editor.RemoveOrphanNodes()
2646 ## Add a node to the mesh by coordinates
2647 # @return Id of the new node
2648 # @ingroup l2_modif_add
2649 def AddNode(self, x, y, z):
2650 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2651 if hasVars: self.mesh.SetParameters(Parameters)
2652 return self.editor.AddNode( x, y, z)
2654 ## Creates a 0D element on a node with given number.
2655 # @param IDOfNode the ID of node for creation of the element.
2656 # @return the Id of the new 0D element
2657 # @ingroup l2_modif_add
2658 def Add0DElement(self, IDOfNode):
2659 return self.editor.Add0DElement(IDOfNode)
2661 ## Create 0D elements on all nodes of the given elements except those
2662 # nodes on which a 0D element already exists.
2663 # @param theObject an object on whose nodes 0D elements will be created.
2664 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2665 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2666 # @param theGroupName optional name of a group to add 0D elements created
2667 # and/or found on nodes of \a theObject.
2668 # @return an object (a new group or a temporary SMESH_IDSource) holding
2669 # IDs of new and/or found 0D elements. IDs of 0D elements
2670 # can be retrieved from the returned object by calling GetIDs()
2671 # @ingroup l2_modif_add
2672 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2673 unRegister = genObjUnRegister()
2674 if isinstance( theObject, Mesh ):
2675 theObject = theObject.GetMesh()
2676 if isinstance( theObject, list ):
2677 theObject = self.GetIDSource( theObject, SMESH.ALL )
2678 unRegister.set( theObject )
2679 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2681 ## Creates a ball element on a node with given ID.
2682 # @param IDOfNode the ID of node for creation of the element.
2683 # @param diameter the bal diameter.
2684 # @return the Id of the new ball element
2685 # @ingroup l2_modif_add
2686 def AddBall(self, IDOfNode, diameter):
2687 return self.editor.AddBall( IDOfNode, diameter )
2689 ## Creates a linear or quadratic edge (this is determined
2690 # by the number of given nodes).
2691 # @param IDsOfNodes the list of node IDs for creation of the element.
2692 # The order of nodes in this list should correspond to the description
2693 # of MED. \n This description is located by the following link:
2694 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2695 # @return the Id of the new edge
2696 # @ingroup l2_modif_add
2697 def AddEdge(self, IDsOfNodes):
2698 return self.editor.AddEdge(IDsOfNodes)
2700 ## Creates a linear or quadratic face (this is determined
2701 # by the number of given nodes).
2702 # @param IDsOfNodes the list of node IDs for creation of the element.
2703 # The order of nodes in this list should correspond to the description
2704 # of MED. \n This description is located by the following link:
2705 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2706 # @return the Id of the new face
2707 # @ingroup l2_modif_add
2708 def AddFace(self, IDsOfNodes):
2709 return self.editor.AddFace(IDsOfNodes)
2711 ## Adds a polygonal face to the mesh by the list of node IDs
2712 # @param IdsOfNodes the list of node IDs for creation of the element.
2713 # @return the Id of the new face
2714 # @ingroup l2_modif_add
2715 def AddPolygonalFace(self, IdsOfNodes):
2716 return self.editor.AddPolygonalFace(IdsOfNodes)
2718 ## Creates both simple and quadratic volume (this is determined
2719 # by the number of given nodes).
2720 # @param IDsOfNodes the list of node IDs for creation of the element.
2721 # The order of nodes in this list should correspond to the description
2722 # of MED. \n This description is located by the following link:
2723 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2724 # @return the Id of the new volumic element
2725 # @ingroup l2_modif_add
2726 def AddVolume(self, IDsOfNodes):
2727 return self.editor.AddVolume(IDsOfNodes)
2729 ## Creates a volume of many faces, giving nodes for each face.
2730 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2731 # @param Quantities the list of integer values, Quantities[i]
2732 # gives the quantity of nodes in face number i.
2733 # @return the Id of the new volumic element
2734 # @ingroup l2_modif_add
2735 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2736 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2738 ## Creates a volume of many faces, giving the IDs of the existing faces.
2739 # @param IdsOfFaces the list of face IDs for volume creation.
2741 # Note: The created volume will refer only to the nodes
2742 # of the given faces, not to the faces themselves.
2743 # @return the Id of the new volumic element
2744 # @ingroup l2_modif_add
2745 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2746 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2749 ## @brief Binds a node to a vertex
2750 # @param NodeID a node ID
2751 # @param Vertex a vertex or vertex ID
2752 # @return True if succeed else raises an exception
2753 # @ingroup l2_modif_add
2754 def SetNodeOnVertex(self, NodeID, Vertex):
2755 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2756 VertexID = Vertex.GetSubShapeIndices()[0]
2760 self.editor.SetNodeOnVertex(NodeID, VertexID)
2761 except SALOME.SALOME_Exception, inst:
2762 raise ValueError, inst.details.text
2766 ## @brief Stores the node position on an edge
2767 # @param NodeID a node ID
2768 # @param Edge an edge or edge ID
2769 # @param paramOnEdge a parameter on the edge where the node is located
2770 # @return True if succeed else raises an exception
2771 # @ingroup l2_modif_add
2772 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2773 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2774 EdgeID = Edge.GetSubShapeIndices()[0]
2778 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2779 except SALOME.SALOME_Exception, inst:
2780 raise ValueError, inst.details.text
2783 ## @brief Stores node position on a face
2784 # @param NodeID a node ID
2785 # @param Face a face or face ID
2786 # @param u U parameter on the face where the node is located
2787 # @param v V parameter on the face where the node is located
2788 # @return True if succeed else raises an exception
2789 # @ingroup l2_modif_add
2790 def SetNodeOnFace(self, NodeID, Face, u, v):
2791 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2792 FaceID = Face.GetSubShapeIndices()[0]
2796 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2797 except SALOME.SALOME_Exception, inst:
2798 raise ValueError, inst.details.text
2801 ## @brief Binds a node to a solid
2802 # @param NodeID a node ID
2803 # @param Solid a solid or solid ID
2804 # @return True if succeed else raises an exception
2805 # @ingroup l2_modif_add
2806 def SetNodeInVolume(self, NodeID, Solid):
2807 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2808 SolidID = Solid.GetSubShapeIndices()[0]
2812 self.editor.SetNodeInVolume(NodeID, SolidID)
2813 except SALOME.SALOME_Exception, inst:
2814 raise ValueError, inst.details.text
2817 ## @brief Bind an element to a shape
2818 # @param ElementID an element ID
2819 # @param Shape a shape or shape ID
2820 # @return True if succeed else raises an exception
2821 # @ingroup l2_modif_add
2822 def SetMeshElementOnShape(self, ElementID, Shape):
2823 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2824 ShapeID = Shape.GetSubShapeIndices()[0]
2828 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2829 except SALOME.SALOME_Exception, inst:
2830 raise ValueError, inst.details.text
2834 ## Moves the node with the given id
2835 # @param NodeID the id of the node
2836 # @param x a new X coordinate
2837 # @param y a new Y coordinate
2838 # @param z a new Z coordinate
2839 # @return True if succeed else False
2840 # @ingroup l2_modif_movenode
2841 def MoveNode(self, NodeID, x, y, z):
2842 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2843 if hasVars: self.mesh.SetParameters(Parameters)
2844 return self.editor.MoveNode(NodeID, x, y, z)
2846 ## Finds the node closest to a point and moves it to a point location
2847 # @param x the X coordinate of a point
2848 # @param y the Y coordinate of a point
2849 # @param z the Z coordinate of a point
2850 # @param NodeID if specified (>0), the node with this ID is moved,
2851 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
2852 # @return the ID of a node
2853 # @ingroup l2_modif_throughp
2854 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2855 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2856 if hasVars: self.mesh.SetParameters(Parameters)
2857 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2859 ## Finds the node closest to a point
2860 # @param x the X coordinate of a point
2861 # @param y the Y coordinate of a point
2862 # @param z the Z coordinate of a point
2863 # @return the ID of a node
2864 # @ingroup l2_modif_throughp
2865 def FindNodeClosestTo(self, x, y, z):
2866 #preview = self.mesh.GetMeshEditPreviewer()
2867 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2868 return self.editor.FindNodeClosestTo(x, y, z)
2870 ## Finds the elements where a point lays IN or ON
2871 # @param x the X coordinate of a point
2872 # @param y the Y coordinate of a point
2873 # @param z the Z coordinate of a point
2874 # @param elementType type of elements to find (SMESH.ALL type
2875 # means elements of any type excluding nodes, discrete and 0D elements)
2876 # @param meshPart a part of mesh (group, sub-mesh) to search within
2877 # @return list of IDs of found elements
2878 # @ingroup l2_modif_throughp
2879 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2881 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2883 return self.editor.FindElementsByPoint(x, y, z, elementType)
2885 # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2886 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2887 # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2889 def GetPointState(self, x, y, z):
2890 return self.editor.GetPointState(x, y, z)
2892 ## Finds the node closest to a point and moves it to a point location
2893 # @param x the X coordinate of a point
2894 # @param y the Y coordinate of a point
2895 # @param z the Z coordinate of a point
2896 # @return the ID of a moved node
2897 # @ingroup l2_modif_throughp
2898 def MeshToPassThroughAPoint(self, x, y, z):
2899 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2901 ## Replaces two neighbour triangles sharing Node1-Node2 link
2902 # with the triangles built on the same 4 nodes but having other common link.
2903 # @param NodeID1 the ID of the first node
2904 # @param NodeID2 the ID of the second node
2905 # @return false if proper faces were not found
2906 # @ingroup l2_modif_invdiag
2907 def InverseDiag(self, NodeID1, NodeID2):
2908 return self.editor.InverseDiag(NodeID1, NodeID2)
2910 ## Replaces two neighbour triangles sharing Node1-Node2 link
2911 # with a quadrangle built on the same 4 nodes.
2912 # @param NodeID1 the ID of the first node
2913 # @param NodeID2 the ID of the second node
2914 # @return false if proper faces were not found
2915 # @ingroup l2_modif_unitetri
2916 def DeleteDiag(self, NodeID1, NodeID2):
2917 return self.editor.DeleteDiag(NodeID1, NodeID2)
2919 ## Reorients elements by ids
2920 # @param IDsOfElements if undefined reorients all mesh elements
2921 # @return True if succeed else False
2922 # @ingroup l2_modif_changori
2923 def Reorient(self, IDsOfElements=None):
2924 if IDsOfElements == None:
2925 IDsOfElements = self.GetElementsId()
2926 return self.editor.Reorient(IDsOfElements)
2928 ## Reorients all elements of the object
2929 # @param theObject mesh, submesh or group
2930 # @return True if succeed else False
2931 # @ingroup l2_modif_changori
2932 def ReorientObject(self, theObject):
2933 if ( isinstance( theObject, Mesh )):
2934 theObject = theObject.GetMesh()
2935 return self.editor.ReorientObject(theObject)
2937 ## Reorient faces contained in \a the2DObject.
2938 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2939 # @param theDirection is a desired direction of normal of \a theFace.
2940 # It can be either a GEOM vector or a list of coordinates [x,y,z].
2941 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2942 # compared with theDirection. It can be either ID of face or a point
2943 # by which the face will be found. The point can be given as either
2944 # a GEOM vertex or a list of point coordinates.
2945 # @return number of reoriented faces
2946 # @ingroup l2_modif_changori
2947 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2948 unRegister = genObjUnRegister()
2950 if isinstance( the2DObject, Mesh ):
2951 the2DObject = the2DObject.GetMesh()
2952 if isinstance( the2DObject, list ):
2953 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2954 unRegister.set( the2DObject )
2955 # check theDirection
2956 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
2957 theDirection = self.smeshpyD.GetDirStruct( theDirection )
2958 if isinstance( theDirection, list ):
2959 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
2960 # prepare theFace and thePoint
2961 theFace = theFaceOrPoint
2962 thePoint = PointStruct(0,0,0)
2963 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
2964 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
2966 if isinstance( theFaceOrPoint, list ):
2967 thePoint = PointStruct( *theFaceOrPoint )
2969 if isinstance( theFaceOrPoint, PointStruct ):
2970 thePoint = theFaceOrPoint
2972 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
2974 ## Reorient faces according to adjacent volumes.
2975 # @param the2DObject is a mesh, sub-mesh, group or list of
2976 # either IDs of faces or face groups.
2977 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
2978 # @param theOutsideNormal to orient faces to have their normals
2979 # pointing either \a outside or \a inside the adjacent volumes.
2980 # @return number of reoriented faces.
2981 # @ingroup l2_modif_changori
2982 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
2983 unRegister = genObjUnRegister()
2985 if not isinstance( the2DObject, list ):
2986 the2DObject = [ the2DObject ]
2987 elif the2DObject and isinstance( the2DObject[0], int ):
2988 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2989 unRegister.set( the2DObject )
2990 the2DObject = [ the2DObject ]
2991 for i,obj2D in enumerate( the2DObject ):
2992 if isinstance( obj2D, Mesh ):
2993 the2DObject[i] = obj2D.GetMesh()
2994 if isinstance( obj2D, list ):
2995 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
2996 unRegister.set( the2DObject[i] )
2998 if isinstance( the3DObject, Mesh ):
2999 the3DObject = the3DObject.GetMesh()
3000 if isinstance( the3DObject, list ):
3001 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3002 unRegister.set( the3DObject )
3003 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3005 ## Fuses the neighbouring triangles into quadrangles.
3006 # @param IDsOfElements The triangles to be fused,
3007 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3008 # choose a neighbour to fuse with.
3009 # @param MaxAngle is the maximum angle between element normals at which the fusion
3010 # is still performed; theMaxAngle is mesured in radians.
3011 # Also it could be a name of variable which defines angle in degrees.
3012 # @return TRUE in case of success, FALSE otherwise.
3013 # @ingroup l2_modif_unitetri
3014 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3015 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3016 self.mesh.SetParameters(Parameters)
3017 if not IDsOfElements:
3018 IDsOfElements = self.GetElementsId()
3019 Functor = self.smeshpyD.GetFunctor(theCriterion)
3020 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3022 ## Fuses the neighbouring triangles of the object into quadrangles
3023 # @param theObject is mesh, submesh or group
3024 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3025 # choose a neighbour to fuse with.
3026 # @param MaxAngle a max angle between element normals at which the fusion
3027 # is still performed; theMaxAngle is mesured in radians.
3028 # @return TRUE in case of success, FALSE otherwise.
3029 # @ingroup l2_modif_unitetri
3030 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3031 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3032 self.mesh.SetParameters(Parameters)
3033 if isinstance( theObject, Mesh ):
3034 theObject = theObject.GetMesh()
3035 Functor = self.smeshpyD.GetFunctor(theCriterion)
3036 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3038 ## Splits quadrangles into triangles.
3039 # @param IDsOfElements the faces to be splitted.
3040 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3041 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3042 # value, then quadrangles will be split by the smallest diagonal.
3043 # @return TRUE in case of success, FALSE otherwise.
3044 # @ingroup l2_modif_cutquadr
3045 def QuadToTri (self, IDsOfElements, theCriterion = None):
3046 if IDsOfElements == []:
3047 IDsOfElements = self.GetElementsId()
3048 if theCriterion is None:
3049 theCriterion = FT_MaxElementLength2D
3050 Functor = self.smeshpyD.GetFunctor(theCriterion)
3051 return self.editor.QuadToTri(IDsOfElements, Functor)
3053 ## Splits quadrangles into triangles.
3054 # @param theObject the object from which the list of elements is taken,
3055 # this is mesh, submesh or group
3056 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3057 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3058 # value, then quadrangles will be split by the smallest diagonal.
3059 # @return TRUE in case of success, FALSE otherwise.
3060 # @ingroup l2_modif_cutquadr
3061 def QuadToTriObject (self, theObject, theCriterion = None):
3062 if ( isinstance( theObject, Mesh )):
3063 theObject = theObject.GetMesh()
3064 if theCriterion is None:
3065 theCriterion = FT_MaxElementLength2D
3066 Functor = self.smeshpyD.GetFunctor(theCriterion)
3067 return self.editor.QuadToTriObject(theObject, Functor)
3069 ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3071 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3072 # group or a list of face IDs. By default all quadrangles are split
3073 # @ingroup l2_modif_cutquadr
3074 def QuadTo4Tri (self, theElements=[]):
3075 unRegister = genObjUnRegister()
3076 if isinstance( theElements, Mesh ):
3077 theElements = theElements.mesh
3078 elif not theElements:
3079 theElements = self.mesh
3080 elif isinstance( theElements, list ):
3081 theElements = self.GetIDSource( theElements, SMESH.FACE )
3082 unRegister.set( theElements )
3083 return self.editor.QuadTo4Tri( theElements )
3085 ## Splits quadrangles into triangles.
3086 # @param IDsOfElements the faces to be splitted
3087 # @param Diag13 is used to choose a diagonal for splitting.
3088 # @return TRUE in case of success, FALSE otherwise.
3089 # @ingroup l2_modif_cutquadr
3090 def SplitQuad (self, IDsOfElements, Diag13):
3091 if IDsOfElements == []:
3092 IDsOfElements = self.GetElementsId()
3093 return self.editor.SplitQuad(IDsOfElements, Diag13)
3095 ## Splits quadrangles into triangles.
3096 # @param theObject the object from which the list of elements is taken,
3097 # this is mesh, submesh or group
3098 # @param Diag13 is used to choose a diagonal for splitting.
3099 # @return TRUE in case of success, FALSE otherwise.
3100 # @ingroup l2_modif_cutquadr
3101 def SplitQuadObject (self, theObject, Diag13):
3102 if ( isinstance( theObject, Mesh )):
3103 theObject = theObject.GetMesh()
3104 return self.editor.SplitQuadObject(theObject, Diag13)
3106 ## Finds a better splitting of the given quadrangle.
3107 # @param IDOfQuad the ID of the quadrangle to be splitted.
3108 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3109 # choose a diagonal for splitting.
3110 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3111 # diagonal is better, 0 if error occurs.
3112 # @ingroup l2_modif_cutquadr
3113 def BestSplit (self, IDOfQuad, theCriterion):
3114 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3116 ## Splits volumic elements into tetrahedrons
3117 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3118 # @param method flags passing splitting method:
3119 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3120 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3121 # @ingroup l2_modif_cutquadr
3122 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3123 unRegister = genObjUnRegister()
3124 if isinstance( elems, Mesh ):
3125 elems = elems.GetMesh()
3126 if ( isinstance( elems, list )):
3127 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3128 unRegister.set( elems )
3129 self.editor.SplitVolumesIntoTetra(elems, method)
3131 ## Splits hexahedra into prisms
3132 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3133 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3134 # gives a normal vector defining facets to split into triangles.
3135 # @a startHexPoint can be either a triple of coordinates or a vertex.
3136 # @param facetNormal a normal to a facet to split into triangles of a
3137 # hexahedron found by @a startHexPoint.
3138 # @a facetNormal can be either a triple of coordinates or an edge.
3139 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3140 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3141 # @param allDomains if @c False, only hexahedra adjacent to one closest
3142 # to @a startHexPoint are split, else @a startHexPoint
3143 # is used to find the facet to split in all domains present in @a elems.
3144 # @ingroup l2_modif_cutquadr
3145 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3146 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3148 unRegister = genObjUnRegister()
3149 if isinstance( elems, Mesh ):
3150 elems = elems.GetMesh()
3151 if ( isinstance( elems, list )):
3152 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3153 unRegister.set( elems )
3156 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3157 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3158 elif isinstance( startHexPoint, list ):
3159 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3162 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3163 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3164 elif isinstance( facetNormal, list ):
3165 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3168 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3170 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3172 ## Splits quadrangle faces near triangular facets of volumes
3174 # @ingroup l1_auxiliary
3175 def SplitQuadsNearTriangularFacets(self):
3176 faces_array = self.GetElementsByType(SMESH.FACE)
3177 for face_id in faces_array:
3178 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3179 quad_nodes = self.mesh.GetElemNodes(face_id)
3180 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3181 isVolumeFound = False
3182 for node1_elem in node1_elems:
3183 if not isVolumeFound:
3184 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3185 nb_nodes = self.GetElemNbNodes(node1_elem)
3186 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3187 volume_elem = node1_elem
3188 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3189 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3190 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3191 isVolumeFound = True
3192 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3193 self.SplitQuad([face_id], False) # diagonal 2-4
3194 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3195 isVolumeFound = True
3196 self.SplitQuad([face_id], True) # diagonal 1-3
3197 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3198 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3199 isVolumeFound = True
3200 self.SplitQuad([face_id], True) # diagonal 1-3
3202 ## @brief Splits hexahedrons into tetrahedrons.
3204 # This operation uses pattern mapping functionality for splitting.
3205 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3206 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3207 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3208 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3209 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3210 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3211 # @return TRUE in case of success, FALSE otherwise.
3212 # @ingroup l1_auxiliary
3213 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3214 # Pattern: 5.---------.6
3219 # (0,0,1) 4.---------.7 * |
3226 # (0,0,0) 0.---------.3
3227 pattern_tetra = "!!! Nb of points: \n 8 \n\
3237 !!! Indices of points of 6 tetras: \n\
3245 pattern = self.smeshpyD.GetPattern()
3246 isDone = pattern.LoadFromFile(pattern_tetra)
3248 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3251 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3252 isDone = pattern.MakeMesh(self.mesh, False, False)
3253 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3255 # split quafrangle faces near triangular facets of volumes
3256 self.SplitQuadsNearTriangularFacets()
3260 ## @brief Split hexahedrons into prisms.
3262 # Uses the pattern mapping functionality for splitting.
3263 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3264 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3265 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3266 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3267 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3268 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3269 # @return TRUE in case of success, FALSE otherwise.
3270 # @ingroup l1_auxiliary
3271 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3272 # Pattern: 5.---------.6
3277 # (0,0,1) 4.---------.7 |
3284 # (0,0,0) 0.---------.3
3285 pattern_prism = "!!! Nb of points: \n 8 \n\
3295 !!! Indices of points of 2 prisms: \n\
3299 pattern = self.smeshpyD.GetPattern()
3300 isDone = pattern.LoadFromFile(pattern_prism)
3302 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3305 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3306 isDone = pattern.MakeMesh(self.mesh, False, False)
3307 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3309 # Splits quafrangle faces near triangular facets of volumes
3310 self.SplitQuadsNearTriangularFacets()
3314 ## Smoothes elements
3315 # @param IDsOfElements the list if ids of elements to smooth
3316 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3317 # Note that nodes built on edges and boundary nodes are always fixed.
3318 # @param MaxNbOfIterations the maximum number of iterations
3319 # @param MaxAspectRatio varies in range [1.0, inf]
3320 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3321 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3322 # @return TRUE in case of success, FALSE otherwise.
3323 # @ingroup l2_modif_smooth
3324 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3325 MaxNbOfIterations, MaxAspectRatio, Method):
3326 if IDsOfElements == []:
3327 IDsOfElements = self.GetElementsId()
3328 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3329 self.mesh.SetParameters(Parameters)
3330 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3331 MaxNbOfIterations, MaxAspectRatio, Method)
3333 ## Smoothes elements which belong to the given object
3334 # @param theObject the object to smooth
3335 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3336 # Note that nodes built on edges and boundary nodes are always fixed.
3337 # @param MaxNbOfIterations the maximum number of iterations
3338 # @param MaxAspectRatio varies in range [1.0, inf]
3339 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3340 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3341 # @return TRUE in case of success, FALSE otherwise.
3342 # @ingroup l2_modif_smooth
3343 def SmoothObject(self, theObject, IDsOfFixedNodes,
3344 MaxNbOfIterations, MaxAspectRatio, Method):
3345 if ( isinstance( theObject, Mesh )):
3346 theObject = theObject.GetMesh()
3347 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3348 MaxNbOfIterations, MaxAspectRatio, Method)
3350 ## Parametrically smoothes the given elements
3351 # @param IDsOfElements the list if ids of elements to smooth
3352 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3353 # Note that nodes built on edges and boundary nodes are always fixed.
3354 # @param MaxNbOfIterations the maximum number of iterations
3355 # @param MaxAspectRatio varies in range [1.0, inf]
3356 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3357 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3358 # @return TRUE in case of success, FALSE otherwise.
3359 # @ingroup l2_modif_smooth
3360 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3361 MaxNbOfIterations, MaxAspectRatio, Method):
3362 if IDsOfElements == []:
3363 IDsOfElements = self.GetElementsId()
3364 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3365 self.mesh.SetParameters(Parameters)
3366 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3367 MaxNbOfIterations, MaxAspectRatio, Method)
3369 ## Parametrically smoothes the elements which belong to the given object
3370 # @param theObject the object to smooth
3371 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3372 # Note that nodes built on edges and boundary nodes are always fixed.
3373 # @param MaxNbOfIterations the maximum number of iterations
3374 # @param MaxAspectRatio varies in range [1.0, inf]
3375 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3376 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3377 # @return TRUE in case of success, FALSE otherwise.
3378 # @ingroup l2_modif_smooth
3379 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3380 MaxNbOfIterations, MaxAspectRatio, Method):
3381 if ( isinstance( theObject, Mesh )):
3382 theObject = theObject.GetMesh()
3383 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3384 MaxNbOfIterations, MaxAspectRatio, Method)
3386 ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3387 # them with quadratic with the same id.
3388 # @param theForce3d new node creation method:
3389 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3390 # 1 - the medium node lies at the middle of the line segments connecting start and end node of a mesh element
3391 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3392 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3393 # @ingroup l2_modif_tofromqu
3394 def ConvertToQuadratic(self, theForce3d, theSubMesh=None, theToBiQuad=False):
3395 if isinstance( theSubMesh, Mesh ):
3396 theSubMesh = theSubMesh.mesh
3398 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3401 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3403 self.editor.ConvertToQuadratic(theForce3d)
3404 error = self.editor.GetLastError()
3405 if error and error.comment:
3408 ## Converts the mesh from quadratic to ordinary,
3409 # deletes old quadratic elements, \n replacing
3410 # them with ordinary mesh elements with the same id.
3411 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3412 # @ingroup l2_modif_tofromqu
3413 def ConvertFromQuadratic(self, theSubMesh=None):
3415 self.editor.ConvertFromQuadraticObject(theSubMesh)
3417 return self.editor.ConvertFromQuadratic()
3419 ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3420 # @return TRUE if operation has been completed successfully, FALSE otherwise
3421 # @ingroup l2_modif_edit
3422 def Make2DMeshFrom3D(self):
3423 return self.editor. Make2DMeshFrom3D()
3425 ## Creates missing boundary elements
3426 # @param elements - elements whose boundary is to be checked:
3427 # mesh, group, sub-mesh or list of elements
3428 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3429 # @param dimension - defines type of boundary elements to create:
3430 # SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D
3431 # SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3432 # @param groupName - a name of group to store created boundary elements in,
3433 # "" means not to create the group
3434 # @param meshName - a name of new mesh to store created boundary elements in,
3435 # "" means not to create the new mesh
3436 # @param toCopyElements - if true, the checked elements will be copied into
3437 # the new mesh else only boundary elements will be copied into the new mesh
3438 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3439 # boundary elements will be copied into the new mesh
3440 # @return tuple (mesh, group) where boundary elements were added to
3441 # @ingroup l2_modif_edit
3442 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3443 toCopyElements=False, toCopyExistingBondary=False):
3444 unRegister = genObjUnRegister()
3445 if isinstance( elements, Mesh ):
3446 elements = elements.GetMesh()
3447 if ( isinstance( elements, list )):
3448 elemType = SMESH.ALL
3449 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3450 elements = self.editor.MakeIDSource(elements, elemType)
3451 unRegister.set( elements )
3452 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3453 toCopyElements,toCopyExistingBondary)
3454 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3458 # @brief Creates missing boundary elements around either the whole mesh or
3459 # groups of 2D elements
3460 # @param dimension - defines type of boundary elements to create
3461 # @param groupName - a name of group to store all boundary elements in,
3462 # "" means not to create the group
3463 # @param meshName - a name of a new mesh, which is a copy of the initial
3464 # mesh + created boundary elements; "" means not to create the new mesh
3465 # @param toCopyAll - if true, the whole initial mesh will be copied into
3466 # the new mesh else only boundary elements will be copied into the new mesh
3467 # @param groups - groups of 2D elements to make boundary around
3468 # @retval tuple( long, mesh, groups )
3469 # long - number of added boundary elements
3470 # mesh - the mesh where elements were added to
3471 # group - the group of boundary elements or None
3473 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3474 toCopyAll=False, groups=[]):
3475 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3477 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3478 return nb, mesh, group
3480 ## Renumber mesh nodes
3481 # @ingroup l2_modif_renumber
3482 def RenumberNodes(self):
3483 self.editor.RenumberNodes()
3485 ## Renumber mesh elements
3486 # @ingroup l2_modif_renumber
3487 def RenumberElements(self):
3488 self.editor.RenumberElements()
3490 ## Generates new elements by rotation of the elements around the axis
3491 # @param IDsOfElements the list of ids of elements to sweep
3492 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3493 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3494 # @param NbOfSteps the number of steps
3495 # @param Tolerance tolerance
3496 # @param MakeGroups forces the generation of new groups from existing ones
3497 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3498 # of all steps, else - size of each step
3499 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3500 # @ingroup l2_modif_extrurev
3501 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3502 MakeGroups=False, TotalAngle=False):
3503 if IDsOfElements == []:
3504 IDsOfElements = self.GetElementsId()
3505 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3506 Axis = self.smeshpyD.GetAxisStruct(Axis)
3507 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3508 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3509 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3510 self.mesh.SetParameters(Parameters)
3511 if TotalAngle and NbOfSteps:
3512 AngleInRadians /= NbOfSteps
3514 return self.editor.RotationSweepMakeGroups(IDsOfElements, Axis,
3515 AngleInRadians, NbOfSteps, Tolerance)
3516 self.editor.RotationSweep(IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance)
3519 ## Generates new elements by rotation of the elements of object around the axis
3520 # @param theObject object which elements should be sweeped.
3521 # It can be a mesh, a sub mesh or a group.
3522 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3523 # @param AngleInRadians the angle of Rotation
3524 # @param NbOfSteps number of steps
3525 # @param Tolerance tolerance
3526 # @param MakeGroups forces the generation of new groups from existing ones
3527 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3528 # of all steps, else - size of each step
3529 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3530 # @ingroup l2_modif_extrurev
3531 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3532 MakeGroups=False, TotalAngle=False):
3533 if ( isinstance( theObject, Mesh )):
3534 theObject = theObject.GetMesh()
3535 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3536 Axis = self.smeshpyD.GetAxisStruct(Axis)
3537 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3538 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3539 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3540 self.mesh.SetParameters(Parameters)
3541 if TotalAngle and NbOfSteps:
3542 AngleInRadians /= NbOfSteps
3544 return self.editor.RotationSweepObjectMakeGroups(theObject, Axis, AngleInRadians,
3545 NbOfSteps, Tolerance)
3546 self.editor.RotationSweepObject(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3549 ## Generates new elements by rotation of the elements of object around the axis
3550 # @param theObject object which elements should be sweeped.
3551 # It can be a mesh, a sub mesh or a group.
3552 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3553 # @param AngleInRadians the angle of Rotation
3554 # @param NbOfSteps number of steps
3555 # @param Tolerance tolerance
3556 # @param MakeGroups forces the generation of new groups from existing ones
3557 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3558 # of all steps, else - size of each step
3559 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3560 # @ingroup l2_modif_extrurev
3561 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3562 MakeGroups=False, TotalAngle=False):
3563 if ( isinstance( theObject, Mesh )):
3564 theObject = theObject.GetMesh()
3565 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3566 Axis = self.smeshpyD.GetAxisStruct(Axis)
3567 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3568 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3569 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3570 self.mesh.SetParameters(Parameters)
3571 if TotalAngle and NbOfSteps:
3572 AngleInRadians /= NbOfSteps
3574 return self.editor.RotationSweepObject1DMakeGroups(theObject, Axis, AngleInRadians,
3575 NbOfSteps, Tolerance)
3576 self.editor.RotationSweepObject1D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3579 ## Generates new elements by rotation of the elements of object around the axis
3580 # @param theObject object which elements should be sweeped.
3581 # It can be a mesh, a sub mesh or a group.
3582 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3583 # @param AngleInRadians the angle of Rotation
3584 # @param NbOfSteps number of steps
3585 # @param Tolerance tolerance
3586 # @param MakeGroups forces the generation of new groups from existing ones
3587 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3588 # of all steps, else - size of each step
3589 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3590 # @ingroup l2_modif_extrurev
3591 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3592 MakeGroups=False, TotalAngle=False):
3593 if ( isinstance( theObject, Mesh )):
3594 theObject = theObject.GetMesh()
3595 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3596 Axis = self.smeshpyD.GetAxisStruct(Axis)
3597 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3598 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3599 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3600 self.mesh.SetParameters(Parameters)
3601 if TotalAngle and NbOfSteps:
3602 AngleInRadians /= NbOfSteps
3604 return self.editor.RotationSweepObject2DMakeGroups(theObject, Axis, AngleInRadians,
3605 NbOfSteps, Tolerance)
3606 self.editor.RotationSweepObject2D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3609 ## Generates new elements by extrusion of the elements with given ids
3610 # @param IDsOfElements the list of elements ids for extrusion
3611 # @param StepVector vector or DirStruct or 3 vector components, defining
3612 # the direction and value of extrusion for one step (the total extrusion
3613 # length will be NbOfSteps * ||StepVector||)
3614 # @param NbOfSteps the number of steps
3615 # @param MakeGroups forces the generation of new groups from existing ones
3616 # @param IsNodes is True if elements with given ids are nodes
3617 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3618 # @ingroup l2_modif_extrurev
3619 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3620 if IDsOfElements == []:
3621 IDsOfElements = self.GetElementsId()
3622 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3623 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3624 if isinstance( StepVector, list ):
3625 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3626 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3627 Parameters = StepVector.PS.parameters + var_separator + Parameters
3628 self.mesh.SetParameters(Parameters)
3631 return self.editor.ExtrusionSweepMakeGroups0D(IDsOfElements, StepVector, NbOfSteps)
3633 return self.editor.ExtrusionSweepMakeGroups(IDsOfElements, StepVector, NbOfSteps)
3635 self.editor.ExtrusionSweep0D(IDsOfElements, StepVector, NbOfSteps)
3637 self.editor.ExtrusionSweep(IDsOfElements, StepVector, NbOfSteps)
3640 ## Generates new elements by extrusion of the elements with given ids
3641 # @param IDsOfElements is ids of elements
3642 # @param StepVector vector or DirStruct or 3 vector components, defining
3643 # the direction and value of extrusion for one step (the total extrusion
3644 # length will be NbOfSteps * ||StepVector||)
3645 # @param NbOfSteps the number of steps
3646 # @param ExtrFlags sets flags for extrusion
3647 # @param SewTolerance uses for comparing locations of nodes if flag
3648 # EXTRUSION_FLAG_SEW is set
3649 # @param MakeGroups forces the generation of new groups from existing ones
3650 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3651 # @ingroup l2_modif_extrurev
3652 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3653 ExtrFlags, SewTolerance, MakeGroups=False):
3654 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3655 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3656 if isinstance( StepVector, list ):
3657 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3659 return self.editor.AdvancedExtrusionMakeGroups(IDsOfElements, StepVector, NbOfSteps,
3660 ExtrFlags, SewTolerance)
3661 self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3662 ExtrFlags, SewTolerance)
3665 ## Generates new elements by extrusion of the elements which belong to the object
3666 # @param theObject the object which elements should be processed.
3667 # It can be a mesh, a sub mesh or a group.
3668 # @param StepVector vector or DirStruct or 3 vector components, defining
3669 # the direction and value of extrusion for one step (the total extrusion
3670 # length will be NbOfSteps * ||StepVector||)
3671 # @param NbOfSteps the number of steps
3672 # @param MakeGroups forces the generation of new groups from existing ones
3673 # @param IsNodes is True if elements which belong to the object are nodes
3674 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3675 # @ingroup l2_modif_extrurev
3676 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3677 if ( isinstance( theObject, Mesh )):
3678 theObject = theObject.GetMesh()
3679 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3680 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3681 if isinstance( StepVector, list ):
3682 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3683 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3684 Parameters = StepVector.PS.parameters + var_separator + Parameters
3685 self.mesh.SetParameters(Parameters)
3688 return self.editor.ExtrusionSweepObject0DMakeGroups(theObject, StepVector, NbOfSteps)
3690 return self.editor.ExtrusionSweepObjectMakeGroups(theObject, StepVector, NbOfSteps)
3692 self.editor.ExtrusionSweepObject0D(theObject, StepVector, NbOfSteps)
3694 self.editor.ExtrusionSweepObject(theObject, StepVector, NbOfSteps)
3697 ## Generates new elements by extrusion of the elements which belong to the object
3698 # @param theObject object which elements should be processed.
3699 # It can be a mesh, a sub mesh or a group.
3700 # @param StepVector vector or DirStruct or 3 vector components, defining
3701 # the direction and value of extrusion for one step (the total extrusion
3702 # length will be NbOfSteps * ||StepVector||)
3703 # @param NbOfSteps the number of steps
3704 # @param MakeGroups to generate new groups from existing ones
3705 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3706 # @ingroup l2_modif_extrurev
3707 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3708 if ( isinstance( theObject, Mesh )):
3709 theObject = theObject.GetMesh()
3710 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3711 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3712 if isinstance( StepVector, list ):
3713 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3714 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3715 Parameters = StepVector.PS.parameters + var_separator + Parameters
3716 self.mesh.SetParameters(Parameters)
3718 return self.editor.ExtrusionSweepObject1DMakeGroups(theObject, StepVector, NbOfSteps)
3719 self.editor.ExtrusionSweepObject1D(theObject, StepVector, NbOfSteps)
3722 ## Generates new elements by extrusion of the elements which belong to the object
3723 # @param theObject object which elements should be processed.
3724 # It can be a mesh, a sub mesh or a group.
3725 # @param StepVector vector or DirStruct or 3 vector components, defining
3726 # the direction and value of extrusion for one step (the total extrusion
3727 # length will be NbOfSteps * ||StepVector||)
3728 # @param NbOfSteps the number of steps
3729 # @param MakeGroups forces the generation of new groups from existing ones
3730 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3731 # @ingroup l2_modif_extrurev
3732 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3733 if ( isinstance( theObject, Mesh )):
3734 theObject = theObject.GetMesh()
3735 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3736 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3737 if isinstance( StepVector, list ):
3738 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3739 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3740 Parameters = StepVector.PS.parameters + var_separator + Parameters
3741 self.mesh.SetParameters(Parameters)
3743 return self.editor.ExtrusionSweepObject2DMakeGroups(theObject, StepVector, NbOfSteps)
3744 self.editor.ExtrusionSweepObject2D(theObject, StepVector, NbOfSteps)
3749 ## Generates new elements by extrusion of the given elements
3750 # The path of extrusion must be a meshed edge.
3751 # @param Base mesh or group, or submesh, or list of ids of elements for extrusion
3752 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3753 # @param NodeStart the start node from Path. Defines the direction of extrusion
3754 # @param HasAngles allows the shape to be rotated around the path
3755 # to get the resulting mesh in a helical fashion
3756 # @param Angles list of angles in radians
3757 # @param LinearVariation forces the computation of rotation angles as linear
3758 # variation of the given Angles along path steps
3759 # @param HasRefPoint allows using the reference point
3760 # @param RefPoint the point around which the elements are rotated (the mass
3761 # center of the elements by default).
3762 # The User can specify any point as the Reference Point.
3763 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
3764 # @param MakeGroups forces the generation of new groups from existing ones
3765 # @param ElemType type of elements for extrusion (if param Base is a mesh)
3766 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3767 # only SMESH::Extrusion_Error otherwise
3768 # @ingroup l2_modif_extrurev
3769 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
3770 HasAngles, Angles, LinearVariation,
3771 HasRefPoint, RefPoint, MakeGroups, ElemType):
3772 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3773 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3775 elif isinstance( RefPoint, list ):
3776 RefPoint = PointStruct(*RefPoint)
3778 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3779 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3780 self.mesh.SetParameters(Parameters)
3782 if (isinstance(Path, Mesh)): Path = Path.GetMesh()
3784 if isinstance(Base, list):
3786 if Base == []: IDsOfElements = self.GetElementsId()
3787 else: IDsOfElements = Base
3788 return self.editor.ExtrusionAlongPathX(IDsOfElements, Path, NodeStart,
3789 HasAngles, Angles, LinearVariation,
3790 HasRefPoint, RefPoint, MakeGroups, ElemType)
3792 if isinstance(Base, Mesh): Base = Base.GetMesh()
3793 if isinstance(Base, SMESH._objref_SMESH_Mesh) or isinstance(Base, SMESH._objref_SMESH_Group) or isinstance(Base, SMESH._objref_SMESH_subMesh):
3794 return self.editor.ExtrusionAlongPathObjX(Base, Path, NodeStart,
3795 HasAngles, Angles, LinearVariation,
3796 HasRefPoint, RefPoint, MakeGroups, ElemType)
3798 raise RuntimeError, "Invalid Base for ExtrusionAlongPathX"
3801 ## Generates new elements by extrusion of the given elements
3802 # The path of extrusion must be a meshed edge.
3803 # @param IDsOfElements ids of elements
3804 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
3805 # @param PathShape shape(edge) defines the sub-mesh for the path
3806 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3807 # @param HasAngles allows the shape to be rotated around the path
3808 # to get the resulting mesh in a helical fashion
3809 # @param Angles list of angles in radians
3810 # @param HasRefPoint allows using the reference point
3811 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3812 # The User can specify any point as the Reference Point.
3813 # @param MakeGroups forces the generation of new groups from existing ones
3814 # @param LinearVariation forces the computation of rotation angles as linear
3815 # variation of the given Angles along path steps
3816 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3817 # only SMESH::Extrusion_Error otherwise
3818 # @ingroup l2_modif_extrurev
3819 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
3820 HasAngles, Angles, HasRefPoint, RefPoint,
3821 MakeGroups=False, LinearVariation=False):
3822 if IDsOfElements == []:
3823 IDsOfElements = self.GetElementsId()
3824 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3825 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3827 if ( isinstance( PathMesh, Mesh )):
3828 PathMesh = PathMesh.GetMesh()
3829 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3830 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3831 self.mesh.SetParameters(Parameters)
3832 if HasAngles and Angles and LinearVariation:
3833 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3836 return self.editor.ExtrusionAlongPathMakeGroups(IDsOfElements, PathMesh,
3837 PathShape, NodeStart, HasAngles,
3838 Angles, HasRefPoint, RefPoint)
3839 return self.editor.ExtrusionAlongPath(IDsOfElements, PathMesh, PathShape,
3840 NodeStart, HasAngles, Angles, HasRefPoint, RefPoint)
3842 ## Generates new elements by extrusion of the elements which belong to the object
3843 # The path of extrusion must be a meshed edge.
3844 # @param theObject the object which elements should be processed.
3845 # It can be a mesh, a sub mesh or a group.
3846 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3847 # @param PathShape shape(edge) defines the sub-mesh for the path
3848 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3849 # @param HasAngles allows the shape to be rotated around the path
3850 # to get the resulting mesh in a helical fashion
3851 # @param Angles list of angles
3852 # @param HasRefPoint allows using the reference point
3853 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3854 # The User can specify any point as the Reference Point.
3855 # @param MakeGroups forces the generation of new groups from existing ones
3856 # @param LinearVariation forces the computation of rotation angles as linear
3857 # variation of the given Angles along path steps
3858 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3859 # only SMESH::Extrusion_Error otherwise
3860 # @ingroup l2_modif_extrurev
3861 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
3862 HasAngles, Angles, HasRefPoint, RefPoint,
3863 MakeGroups=False, LinearVariation=False):
3864 if ( isinstance( theObject, Mesh )):
3865 theObject = theObject.GetMesh()
3866 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3867 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3868 if ( isinstance( PathMesh, Mesh )):
3869 PathMesh = PathMesh.GetMesh()
3870 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3871 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3872 self.mesh.SetParameters(Parameters)
3873 if HasAngles and Angles and LinearVariation:
3874 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3877 return self.editor.ExtrusionAlongPathObjectMakeGroups(theObject, PathMesh,
3878 PathShape, NodeStart, HasAngles,
3879 Angles, HasRefPoint, RefPoint)
3880 return self.editor.ExtrusionAlongPathObject(theObject, PathMesh, PathShape,
3881 NodeStart, HasAngles, Angles, HasRefPoint,
3884 ## Generates new elements by extrusion of the elements which belong to the object
3885 # The path of extrusion must be a meshed edge.
3886 # @param theObject the object which elements should be processed.
3887 # It can be a mesh, a sub mesh or a group.
3888 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3889 # @param PathShape shape(edge) defines the sub-mesh for the path
3890 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3891 # @param HasAngles allows the shape to be rotated around the path
3892 # to get the resulting mesh in a helical fashion
3893 # @param Angles list of angles
3894 # @param HasRefPoint allows using the reference point
3895 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3896 # The User can specify any point as the Reference Point.
3897 # @param MakeGroups forces the generation of new groups from existing ones
3898 # @param LinearVariation forces the computation of rotation angles as linear
3899 # variation of the given Angles along path steps
3900 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3901 # only SMESH::Extrusion_Error otherwise
3902 # @ingroup l2_modif_extrurev
3903 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
3904 HasAngles, Angles, HasRefPoint, RefPoint,
3905 MakeGroups=False, LinearVariation=False):
3906 if ( isinstance( theObject, Mesh )):
3907 theObject = theObject.GetMesh()
3908 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3909 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3910 if ( isinstance( PathMesh, Mesh )):
3911 PathMesh = PathMesh.GetMesh()
3912 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3913 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3914 self.mesh.SetParameters(Parameters)
3915 if HasAngles and Angles and LinearVariation:
3916 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3919 return self.editor.ExtrusionAlongPathObject1DMakeGroups(theObject, PathMesh,
3920 PathShape, NodeStart, HasAngles,
3921 Angles, HasRefPoint, RefPoint)
3922 return self.editor.ExtrusionAlongPathObject1D(theObject, PathMesh, PathShape,
3923 NodeStart, HasAngles, Angles, HasRefPoint,
3926 ## Generates new elements by extrusion of the elements which belong to the object
3927 # The path of extrusion must be a meshed edge.
3928 # @param theObject the object which elements should be processed.
3929 # It can be a mesh, a sub mesh or a group.
3930 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3931 # @param PathShape shape(edge) defines the sub-mesh for the path
3932 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3933 # @param HasAngles allows the shape to be rotated around the path
3934 # to get the resulting mesh in a helical fashion
3935 # @param Angles list of angles
3936 # @param HasRefPoint allows using the reference point
3937 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3938 # The User can specify any point as the Reference Point.
3939 # @param MakeGroups forces the generation of new groups from existing ones
3940 # @param LinearVariation forces the computation of rotation angles as linear
3941 # variation of the given Angles along path steps
3942 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3943 # only SMESH::Extrusion_Error otherwise
3944 # @ingroup l2_modif_extrurev
3945 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
3946 HasAngles, Angles, HasRefPoint, RefPoint,
3947 MakeGroups=False, LinearVariation=False):
3948 if ( isinstance( theObject, Mesh )):
3949 theObject = theObject.GetMesh()
3950 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3951 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3952 if ( isinstance( PathMesh, Mesh )):
3953 PathMesh = PathMesh.GetMesh()
3954 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3955 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3956 self.mesh.SetParameters(Parameters)
3957 if HasAngles and Angles and LinearVariation:
3958 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3961 return self.editor.ExtrusionAlongPathObject2DMakeGroups(theObject, PathMesh,
3962 PathShape, NodeStart, HasAngles,
3963 Angles, HasRefPoint, RefPoint)
3964 return self.editor.ExtrusionAlongPathObject2D(theObject, PathMesh, PathShape,
3965 NodeStart, HasAngles, Angles, HasRefPoint,
3968 ## Creates a symmetrical copy of mesh elements
3969 # @param IDsOfElements list of elements ids
3970 # @param Mirror is AxisStruct or geom object(point, line, plane)
3971 # @param theMirrorType is POINT, AXIS or PLANE
3972 # If the Mirror is a geom object this parameter is unnecessary
3973 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
3974 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3975 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3976 # @ingroup l2_modif_trsf
3977 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
3978 if IDsOfElements == []:
3979 IDsOfElements = self.GetElementsId()
3980 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3981 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3982 theMirrorType = Mirror._mirrorType
3984 self.mesh.SetParameters(Mirror.parameters)
3985 if Copy and MakeGroups:
3986 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
3987 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
3990 ## Creates a new mesh by a symmetrical copy of mesh elements
3991 # @param IDsOfElements the list of elements ids
3992 # @param Mirror is AxisStruct or geom object (point, line, plane)
3993 # @param theMirrorType is POINT, AXIS or PLANE
3994 # If the Mirror is a geom object this parameter is unnecessary
3995 # @param MakeGroups to generate new groups from existing ones
3996 # @param NewMeshName a name of the new mesh to create
3997 # @return instance of Mesh class
3998 # @ingroup l2_modif_trsf
3999 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4000 if IDsOfElements == []:
4001 IDsOfElements = self.GetElementsId()
4002 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4003 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4004 theMirrorType = Mirror._mirrorType
4006 self.mesh.SetParameters(Mirror.parameters)
4007 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4008 MakeGroups, NewMeshName)
4009 return Mesh(self.smeshpyD,self.geompyD,mesh)
4011 ## Creates a symmetrical copy of the object
4012 # @param theObject mesh, submesh or group
4013 # @param Mirror AxisStruct or geom object (point, line, plane)
4014 # @param theMirrorType is POINT, AXIS or PLANE
4015 # If the Mirror is a geom object this parameter is unnecessary
4016 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4017 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4018 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4019 # @ingroup l2_modif_trsf
4020 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4021 if ( isinstance( theObject, Mesh )):
4022 theObject = theObject.GetMesh()
4023 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4024 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4025 theMirrorType = Mirror._mirrorType
4027 self.mesh.SetParameters(Mirror.parameters)
4028 if Copy and MakeGroups:
4029 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4030 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4033 ## Creates a new mesh by a symmetrical copy of the object
4034 # @param theObject mesh, submesh or group
4035 # @param Mirror AxisStruct or geom object (point, line, plane)
4036 # @param theMirrorType POINT, AXIS or PLANE
4037 # If the Mirror is a geom object this parameter is unnecessary
4038 # @param MakeGroups forces the generation of new groups from existing ones
4039 # @param NewMeshName the name of the new mesh to create
4040 # @return instance of Mesh class
4041 # @ingroup l2_modif_trsf
4042 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4043 if ( isinstance( theObject, Mesh )):
4044 theObject = theObject.GetMesh()
4045 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4046 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4047 theMirrorType = Mirror._mirrorType
4049 self.mesh.SetParameters(Mirror.parameters)
4050 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4051 MakeGroups, NewMeshName)
4052 return Mesh( self.smeshpyD,self.geompyD,mesh )
4054 ## Translates the elements
4055 # @param IDsOfElements list of elements ids
4056 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4057 # @param Copy allows copying the translated elements
4058 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4059 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4060 # @ingroup l2_modif_trsf
4061 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4062 if IDsOfElements == []:
4063 IDsOfElements = self.GetElementsId()
4064 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4065 Vector = self.smeshpyD.GetDirStruct(Vector)
4066 if isinstance( Vector, list ):
4067 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4068 self.mesh.SetParameters(Vector.PS.parameters)
4069 if Copy and MakeGroups:
4070 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4071 self.editor.Translate(IDsOfElements, Vector, Copy)
4074 ## Creates a new mesh of translated elements
4075 # @param IDsOfElements list of elements ids
4076 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4077 # @param MakeGroups forces the generation of new groups from existing ones
4078 # @param NewMeshName the name of the newly created mesh
4079 # @return instance of Mesh class
4080 # @ingroup l2_modif_trsf
4081 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4082 if IDsOfElements == []:
4083 IDsOfElements = self.GetElementsId()
4084 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4085 Vector = self.smeshpyD.GetDirStruct(Vector)
4086 if isinstance( Vector, list ):
4087 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4088 self.mesh.SetParameters(Vector.PS.parameters)
4089 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4090 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4092 ## Translates the object
4093 # @param theObject the object to translate (mesh, submesh, or group)
4094 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4095 # @param Copy allows copying the translated elements
4096 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4097 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4098 # @ingroup l2_modif_trsf
4099 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4100 if ( isinstance( theObject, Mesh )):
4101 theObject = theObject.GetMesh()
4102 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4103 Vector = self.smeshpyD.GetDirStruct(Vector)
4104 if isinstance( Vector, list ):
4105 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4106 self.mesh.SetParameters(Vector.PS.parameters)
4107 if Copy and MakeGroups:
4108 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4109 self.editor.TranslateObject(theObject, Vector, Copy)
4112 ## Creates a new mesh from the translated object
4113 # @param theObject the object to translate (mesh, submesh, or group)
4114 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4115 # @param MakeGroups forces the generation of new groups from existing ones
4116 # @param NewMeshName the name of the newly created mesh
4117 # @return instance of Mesh class
4118 # @ingroup l2_modif_trsf
4119 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4120 if isinstance( theObject, Mesh ):
4121 theObject = theObject.GetMesh()
4122 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4123 Vector = self.smeshpyD.GetDirStruct(Vector)
4124 if isinstance( Vector, list ):
4125 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4126 self.mesh.SetParameters(Vector.PS.parameters)
4127 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4128 return Mesh( self.smeshpyD, self.geompyD, mesh )
4132 ## Scales the object
4133 # @param theObject - the object to translate (mesh, submesh, or group)
4134 # @param thePoint - base point for scale
4135 # @param theScaleFact - list of 1-3 scale factors for axises
4136 # @param Copy - allows copying the translated elements
4137 # @param MakeGroups - forces the generation of new groups from existing
4139 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4140 # empty list otherwise
4141 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4142 unRegister = genObjUnRegister()
4143 if ( isinstance( theObject, Mesh )):
4144 theObject = theObject.GetMesh()
4145 if ( isinstance( theObject, list )):
4146 theObject = self.GetIDSource(theObject, SMESH.ALL)
4147 unRegister.set( theObject )
4148 if ( isinstance( theScaleFact, float )):
4149 theScaleFact = [theScaleFact]
4150 if ( isinstance( theScaleFact, int )):
4151 theScaleFact = [ float(theScaleFact)]
4153 self.mesh.SetParameters(thePoint.parameters)
4155 if Copy and MakeGroups:
4156 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4157 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4160 ## Creates a new mesh from the translated object
4161 # @param theObject - the object to translate (mesh, submesh, or group)
4162 # @param thePoint - base point for scale
4163 # @param theScaleFact - list of 1-3 scale factors for axises
4164 # @param MakeGroups - forces the generation of new groups from existing ones
4165 # @param NewMeshName - the name of the newly created mesh
4166 # @return instance of Mesh class
4167 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4168 unRegister = genObjUnRegister()
4169 if (isinstance(theObject, Mesh)):
4170 theObject = theObject.GetMesh()
4171 if ( isinstance( theObject, list )):
4172 theObject = self.GetIDSource(theObject,SMESH.ALL)
4173 unRegister.set( theObject )
4174 if ( isinstance( theScaleFact, float )):
4175 theScaleFact = [theScaleFact]
4176 if ( isinstance( theScaleFact, int )):
4177 theScaleFact = [ float(theScaleFact)]
4179 self.mesh.SetParameters(thePoint.parameters)
4180 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4181 MakeGroups, NewMeshName)
4182 return Mesh( self.smeshpyD, self.geompyD, mesh )
4186 ## Rotates the elements
4187 # @param IDsOfElements list of elements ids
4188 # @param Axis the axis of rotation (AxisStruct or geom line)
4189 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4190 # @param Copy allows copying the rotated elements
4191 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4192 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4193 # @ingroup l2_modif_trsf
4194 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4195 if IDsOfElements == []:
4196 IDsOfElements = self.GetElementsId()
4197 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4198 Axis = self.smeshpyD.GetAxisStruct(Axis)
4199 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4200 Parameters = Axis.parameters + var_separator + Parameters
4201 self.mesh.SetParameters(Parameters)
4202 if Copy and MakeGroups:
4203 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4204 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4207 ## Creates a new mesh of rotated elements
4208 # @param IDsOfElements list of element ids
4209 # @param Axis the axis of rotation (AxisStruct or geom line)
4210 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4211 # @param MakeGroups forces the generation of new groups from existing ones
4212 # @param NewMeshName the name of the newly created mesh
4213 # @return instance of Mesh class
4214 # @ingroup l2_modif_trsf
4215 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4216 if IDsOfElements == []:
4217 IDsOfElements = self.GetElementsId()
4218 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4219 Axis = self.smeshpyD.GetAxisStruct(Axis)
4220 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4221 Parameters = Axis.parameters + var_separator + Parameters
4222 self.mesh.SetParameters(Parameters)
4223 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4224 MakeGroups, NewMeshName)
4225 return Mesh( self.smeshpyD, self.geompyD, mesh )
4227 ## Rotates the object
4228 # @param theObject the object to rotate( mesh, submesh, or group)
4229 # @param Axis the axis of rotation (AxisStruct or geom line)
4230 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4231 # @param Copy allows copying the rotated elements
4232 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4233 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4234 # @ingroup l2_modif_trsf
4235 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4236 if (isinstance(theObject, Mesh)):
4237 theObject = theObject.GetMesh()
4238 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4239 Axis = self.smeshpyD.GetAxisStruct(Axis)
4240 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4241 Parameters = Axis.parameters + ":" + Parameters
4242 self.mesh.SetParameters(Parameters)
4243 if Copy and MakeGroups:
4244 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4245 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4248 ## Creates a new mesh from the rotated object
4249 # @param theObject the object to rotate (mesh, submesh, or group)
4250 # @param Axis the axis of rotation (AxisStruct or geom line)
4251 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4252 # @param MakeGroups forces the generation of new groups from existing ones
4253 # @param NewMeshName the name of the newly created mesh
4254 # @return instance of Mesh class
4255 # @ingroup l2_modif_trsf
4256 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4257 if (isinstance( theObject, Mesh )):
4258 theObject = theObject.GetMesh()
4259 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4260 Axis = self.smeshpyD.GetAxisStruct(Axis)
4261 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4262 Parameters = Axis.parameters + ":" + Parameters
4263 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4264 MakeGroups, NewMeshName)
4265 self.mesh.SetParameters(Parameters)
4266 return Mesh( self.smeshpyD, self.geompyD, mesh )
4268 ## Finds groups of adjacent nodes within Tolerance.
4269 # @param Tolerance the value of tolerance
4270 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4271 # @ingroup l2_modif_trsf
4272 def FindCoincidentNodes (self, Tolerance):
4273 return self.editor.FindCoincidentNodes(Tolerance)
4275 ## Finds groups of ajacent nodes within Tolerance.
4276 # @param Tolerance the value of tolerance
4277 # @param SubMeshOrGroup SubMesh or Group
4278 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4279 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4280 # @ingroup l2_modif_trsf
4281 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance, exceptNodes=[]):
4282 unRegister = genObjUnRegister()
4283 if (isinstance( SubMeshOrGroup, Mesh )):
4284 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4285 if not isinstance( exceptNodes, list):
4286 exceptNodes = [ exceptNodes ]
4287 if exceptNodes and isinstance( exceptNodes[0], int):
4288 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE)]
4289 unRegister.set( exceptNodes )
4290 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,exceptNodes)
4293 # @param GroupsOfNodes a list of pairs of nodes IDs for merging (e.g. [[1,12],[25,4]])
4294 # @ingroup l2_modif_trsf
4295 def MergeNodes (self, GroupsOfNodes):
4296 self.editor.MergeNodes(GroupsOfNodes)
4298 ## Finds the elements built on the same nodes.
4299 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4300 # @return the list of pairs of equal elements IDs (e.g. [[1,12],[25,4]])
4301 # @ingroup l2_modif_trsf
4302 def FindEqualElements (self, MeshOrSubMeshOrGroup):
4303 if ( isinstance( MeshOrSubMeshOrGroup, Mesh )):
4304 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4305 return self.editor.FindEqualElements(MeshOrSubMeshOrGroup)
4307 ## Merges elements in each given group.
4308 # @param GroupsOfElementsID a list of pairs of elements IDs for merging (e.g. [[1,12],[25,4]])
4309 # @ingroup l2_modif_trsf
4310 def MergeElements(self, GroupsOfElementsID):
4311 self.editor.MergeElements(GroupsOfElementsID)
4313 ## Leaves one element and removes all other elements built on the same nodes.
4314 # @ingroup l2_modif_trsf
4315 def MergeEqualElements(self):
4316 self.editor.MergeEqualElements()
4318 ## Sews free borders
4319 # @return SMESH::Sew_Error
4320 # @ingroup l2_modif_trsf
4321 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4322 FirstNodeID2, SecondNodeID2, LastNodeID2,
4323 CreatePolygons, CreatePolyedrs):
4324 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4325 FirstNodeID2, SecondNodeID2, LastNodeID2,
4326 CreatePolygons, CreatePolyedrs)
4328 ## Sews conform free borders
4329 # @return SMESH::Sew_Error
4330 # @ingroup l2_modif_trsf
4331 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4332 FirstNodeID2, SecondNodeID2):
4333 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4334 FirstNodeID2, SecondNodeID2)
4336 ## Sews border to side
4337 # @return SMESH::Sew_Error
4338 # @ingroup l2_modif_trsf
4339 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4340 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4341 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4342 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4344 ## Sews two sides of a mesh. The nodes belonging to Side1 are
4345 # merged with the nodes of elements of Side2.
4346 # The number of elements in theSide1 and in theSide2 must be
4347 # equal and they should have similar nodal connectivity.
4348 # The nodes to merge should belong to side borders and
4349 # the first node should be linked to the second.
4350 # @return SMESH::Sew_Error
4351 # @ingroup l2_modif_trsf
4352 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4353 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4354 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4355 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4356 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4357 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4359 ## Sets new nodes for the given element.
4360 # @param ide the element id
4361 # @param newIDs nodes ids
4362 # @return If the number of nodes does not correspond to the type of element - returns false
4363 # @ingroup l2_modif_edit
4364 def ChangeElemNodes(self, ide, newIDs):
4365 return self.editor.ChangeElemNodes(ide, newIDs)
4367 ## If during the last operation of MeshEditor some nodes were
4368 # created, this method returns the list of their IDs, \n
4369 # if new nodes were not created - returns empty list
4370 # @return the list of integer values (can be empty)
4371 # @ingroup l1_auxiliary
4372 def GetLastCreatedNodes(self):
4373 return self.editor.GetLastCreatedNodes()
4375 ## If during the last operation of MeshEditor some elements were
4376 # created this method returns the list of their IDs, \n
4377 # if new elements were not created - returns empty list
4378 # @return the list of integer values (can be empty)
4379 # @ingroup l1_auxiliary
4380 def GetLastCreatedElems(self):
4381 return self.editor.GetLastCreatedElems()
4383 ## Clears sequences of nodes and elements created by mesh edition oparations
4384 # @ingroup l1_auxiliary
4385 def ClearLastCreated(self):
4386 self.editor.ClearLastCreated()
4388 ## Creates Duplicates given elements, i.e. creates new elements based on the
4389 # same nodes as the given ones.
4390 # @param theElements - container of elements to duplicate. It can be a Mesh,
4391 # sub-mesh, group, filter or a list of element IDs.
4392 # @param theGroupName - a name of group to contain the generated elements.
4393 # If a group with such a name already exists, the new elements
4394 # are added to the existng group, else a new group is created.
4395 # If \a theGroupName is empty, new elements are not added
4397 # @return a group where the new elements are added. None if theGroupName == "".
4398 # @ingroup l2_modif_edit
4399 def DoubleElements(self, theElements, theGroupName=""):
4400 unRegister = genObjUnRegister()
4401 if isinstance( theElements, Mesh ):
4402 theElements = theElements.mesh
4403 elif isinstance( theElements, list ):
4404 theElements = self.GetIDSource( theElements, SMESH.ALL )
4405 unRegister.set( theElements )
4406 return self.editor.DoubleElements(theElements, theGroupName)
4408 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4409 # @param theNodes identifiers of nodes to be doubled
4410 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4411 # nodes. If list of element identifiers is empty then nodes are doubled but
4412 # they not assigned to elements
4413 # @return TRUE if operation has been completed successfully, FALSE otherwise
4414 # @ingroup l2_modif_edit
4415 def DoubleNodes(self, theNodes, theModifiedElems):
4416 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4418 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4419 # This method provided for convenience works as DoubleNodes() described above.
4420 # @param theNodeId identifiers of node to be doubled
4421 # @param theModifiedElems identifiers of elements to be updated
4422 # @return TRUE if operation has been completed successfully, FALSE otherwise
4423 # @ingroup l2_modif_edit
4424 def DoubleNode(self, theNodeId, theModifiedElems):
4425 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4427 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4428 # This method provided for convenience works as DoubleNodes() described above.
4429 # @param theNodes group of nodes to be doubled
4430 # @param theModifiedElems group of elements to be updated.
4431 # @param theMakeGroup forces the generation of a group containing new nodes.
4432 # @return TRUE or a created group if operation has been completed successfully,
4433 # FALSE or None otherwise
4434 # @ingroup l2_modif_edit
4435 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4437 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4438 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4440 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4441 # This method provided for convenience works as DoubleNodes() described above.
4442 # @param theNodes list of groups of nodes to be doubled
4443 # @param theModifiedElems list of groups of elements to be updated.
4444 # @param theMakeGroup forces the generation of a group containing new nodes.
4445 # @return TRUE if operation has been completed successfully, FALSE otherwise
4446 # @ingroup l2_modif_edit
4447 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4449 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4450 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4452 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4453 # @param theElems - the list of elements (edges or faces) to be replicated
4454 # The nodes for duplication could be found from these elements
4455 # @param theNodesNot - list of nodes to NOT replicate
4456 # @param theAffectedElems - the list of elements (cells and edges) to which the
4457 # replicated nodes should be associated to.
4458 # @return TRUE if operation has been completed successfully, FALSE otherwise
4459 # @ingroup l2_modif_edit
4460 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4461 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4463 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4464 # @param theElems - the list of elements (edges or faces) to be replicated
4465 # The nodes for duplication could be found from these elements
4466 # @param theNodesNot - list of nodes to NOT replicate
4467 # @param theShape - shape to detect affected elements (element which geometric center
4468 # located on or inside shape).
4469 # The replicated nodes should be associated to affected elements.
4470 # @return TRUE if operation has been completed successfully, FALSE otherwise
4471 # @ingroup l2_modif_edit
4472 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4473 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4475 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4476 # This method provided for convenience works as DoubleNodes() described above.
4477 # @param theElems - group of of elements (edges or faces) to be replicated
4478 # @param theNodesNot - group of nodes not to replicated
4479 # @param theAffectedElems - group of elements to which the replicated nodes
4480 # should be associated to.
4481 # @param theMakeGroup forces the generation of a group containing new elements.
4482 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4483 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4484 # FALSE or None otherwise
4485 # @ingroup l2_modif_edit
4486 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4487 theMakeGroup=False, theMakeNodeGroup=False):
4488 if theMakeGroup or theMakeNodeGroup:
4489 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4491 theMakeGroup, theMakeNodeGroup)
4492 if theMakeGroup and theMakeNodeGroup:
4495 return twoGroups[ int(theMakeNodeGroup) ]
4496 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4498 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4499 # This method provided for convenience works as DoubleNodes() described above.
4500 # @param theElems - group of of elements (edges or faces) to be replicated
4501 # @param theNodesNot - group of nodes not to replicated
4502 # @param theShape - shape to detect affected elements (element which geometric center
4503 # located on or inside shape).
4504 # The replicated nodes should be associated to affected elements.
4505 # @ingroup l2_modif_edit
4506 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4507 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4509 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4510 # This method provided for convenience works as DoubleNodes() described above.
4511 # @param theElems - list of groups of elements (edges or faces) to be replicated
4512 # @param theNodesNot - list of groups of nodes not to replicated
4513 # @param theAffectedElems - group of elements to which the replicated nodes
4514 # should be associated to.
4515 # @param theMakeGroup forces the generation of a group containing new elements.
4516 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4517 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4518 # FALSE or None otherwise
4519 # @ingroup l2_modif_edit
4520 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4521 theMakeGroup=False, theMakeNodeGroup=False):
4522 if theMakeGroup or theMakeNodeGroup:
4523 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4525 theMakeGroup, theMakeNodeGroup)
4526 if theMakeGroup and theMakeNodeGroup:
4529 return twoGroups[ int(theMakeNodeGroup) ]
4530 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4532 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4533 # This method provided for convenience works as DoubleNodes() described above.
4534 # @param theElems - list of groups of elements (edges or faces) to be replicated
4535 # @param theNodesNot - list of groups of nodes not to replicated
4536 # @param theShape - shape to detect affected elements (element which geometric center
4537 # located on or inside shape).
4538 # The replicated nodes should be associated to affected elements.
4539 # @return TRUE if operation has been completed successfully, FALSE otherwise
4540 # @ingroup l2_modif_edit
4541 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4542 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4544 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4545 # This method is the first step of DoubleNodeElemGroupsInRegion.
4546 # @param theElems - list of groups of elements (edges or faces) to be replicated
4547 # @param theNodesNot - list of groups of nodes not to replicated
4548 # @param theShape - shape to detect affected elements (element which geometric center
4549 # located on or inside shape).
4550 # The replicated nodes should be associated to affected elements.
4551 # @return groups of affected elements
4552 # @ingroup l2_modif_edit
4553 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4554 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4556 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4557 # The list of groups must describe a partition of the mesh volumes.
4558 # The nodes of the internal faces at the boundaries of the groups are doubled.
4559 # In option, the internal faces are replaced by flat elements.
4560 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4561 # @param theDomains - list of groups of volumes
4562 # @param createJointElems - if TRUE, create the elements
4563 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4564 # the boundary between \a theDomains and the rest mesh
4565 # @return TRUE if operation has been completed successfully, FALSE otherwise
4566 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4567 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4569 ## Double nodes on some external faces and create flat elements.
4570 # Flat elements are mainly used by some types of mechanic calculations.
4572 # Each group of the list must be constituted of faces.
4573 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4574 # @param theGroupsOfFaces - list of groups of faces
4575 # @return TRUE if operation has been completed successfully, FALSE otherwise
4576 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4577 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4579 ## identify all the elements around a geom shape, get the faces delimiting the hole
4581 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4582 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4584 def _getFunctor(self, funcType ):
4585 fn = self.functors[ funcType._v ]
4587 fn = self.smeshpyD.GetFunctor(funcType)
4588 fn.SetMesh(self.mesh)
4589 self.functors[ funcType._v ] = fn
4592 def _valueFromFunctor(self, funcType, elemId):
4593 fn = self._getFunctor( funcType )
4594 if fn.GetElementType() == self.GetElementType(elemId, True):
4595 val = fn.GetValue(elemId)
4600 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4601 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4602 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4603 # @ingroup l1_measurements
4604 def GetLength(self, elemId=None):
4607 length = self.smeshpyD.GetLength(self)
4609 length = self._valueFromFunctor(SMESH.FT_Length, elemId)
4612 ## Get area of 2D element or sum of areas of all 2D mesh elements
4613 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4614 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4615 # @ingroup l1_measurements
4616 def GetArea(self, elemId=None):
4619 area = self.smeshpyD.GetArea(self)
4621 area = self._valueFromFunctor(SMESH.FT_Area, elemId)
4624 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4625 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4626 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4627 # @ingroup l1_measurements
4628 def GetVolume(self, elemId=None):
4631 volume = self.smeshpyD.GetVolume(self)
4633 volume = self._valueFromFunctor(SMESH.FT_Volume3D, elemId)
4636 ## Get maximum element length.
4637 # @param elemId mesh element ID
4638 # @return element's maximum length value
4639 # @ingroup l1_measurements
4640 def GetMaxElementLength(self, elemId):
4641 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4642 ftype = SMESH.FT_MaxElementLength3D
4644 ftype = SMESH.FT_MaxElementLength2D
4645 return self._valueFromFunctor(ftype, elemId)
4647 ## Get aspect ratio of 2D or 3D element.
4648 # @param elemId mesh element ID
4649 # @return element's aspect ratio value
4650 # @ingroup l1_measurements
4651 def GetAspectRatio(self, elemId):
4652 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4653 ftype = SMESH.FT_AspectRatio3D
4655 ftype = SMESH.FT_AspectRatio
4656 return self._valueFromFunctor(ftype, elemId)
4658 ## Get warping angle of 2D element.
4659 # @param elemId mesh element ID
4660 # @return element's warping angle value
4661 # @ingroup l1_measurements
4662 def GetWarping(self, elemId):
4663 return self._valueFromFunctor(SMESH.FT_Warping, elemId)
4665 ## Get minimum angle of 2D element.
4666 # @param elemId mesh element ID
4667 # @return element's minimum angle value
4668 # @ingroup l1_measurements
4669 def GetMinimumAngle(self, elemId):
4670 return self._valueFromFunctor(SMESH.FT_MinimumAngle, elemId)
4672 ## Get taper of 2D element.
4673 # @param elemId mesh element ID
4674 # @return element's taper value
4675 # @ingroup l1_measurements
4676 def GetTaper(self, elemId):
4677 return self._valueFromFunctor(SMESH.FT_Taper, elemId)
4679 ## Get skew of 2D element.
4680 # @param elemId mesh element ID
4681 # @return element's skew value
4682 # @ingroup l1_measurements
4683 def GetSkew(self, elemId):
4684 return self._valueFromFunctor(SMESH.FT_Skew, elemId)
4686 ## Return minimal and maximal value of a given functor.
4687 # @param funType a functor type, an item of SMESH.FunctorType enum
4688 # (one of SMESH.FunctorType._items)
4689 # @param meshPart a part of mesh (group, sub-mesh) to treat
4690 # @return tuple (min,max)
4691 # @ingroup l1_measurements
4692 def GetMinMax(self, funType, meshPart=None):
4693 unRegister = genObjUnRegister()
4694 if isinstance( meshPart, list ):
4695 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
4696 unRegister.set( meshPart )
4697 if isinstance( meshPart, Mesh ):
4698 meshPart = meshPart.mesh
4699 fun = self._getFunctor( funType )
4702 hist = fun.GetLocalHistogram( 1, False, meshPart )
4704 hist = fun.GetHistogram( 1, False )
4706 return hist[0].min, hist[0].max
4709 pass # end of Mesh class
4711 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
4713 class Pattern(SMESH._objref_SMESH_Pattern):
4715 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4716 decrFun = lambda i: i-1
4717 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4718 theMesh.SetParameters(Parameters)
4719 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4721 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4722 decrFun = lambda i: i-1
4723 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4724 theMesh.SetParameters(Parameters)
4725 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4727 # Registering the new proxy for Pattern
4728 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4730 ## Private class used to bind methods creating algorithms to the class Mesh
4735 self.defaultAlgoType = ""
4736 self.algoTypeToClass = {}
4738 # Stores a python class of algorithm
4739 def add(self, algoClass):
4740 if type( algoClass ).__name__ == 'classobj' and \
4741 hasattr( algoClass, "algoType"):
4742 self.algoTypeToClass[ algoClass.algoType ] = algoClass
4743 if not self.defaultAlgoType and \
4744 hasattr( algoClass, "isDefault") and algoClass.isDefault:
4745 self.defaultAlgoType = algoClass.algoType
4746 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
4748 # creates a copy of self and assign mesh to the copy
4749 def copy(self, mesh):
4750 other = algoCreator()
4751 other.defaultAlgoType = self.defaultAlgoType
4752 other.algoTypeToClass = self.algoTypeToClass
4756 # creates an instance of algorithm
4757 def __call__(self,algo="",geom=0,*args):
4758 algoType = self.defaultAlgoType
4759 for arg in args + (algo,geom):
4760 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
4762 if isinstance( arg, str ) and arg:
4764 if not algoType and self.algoTypeToClass:
4765 algoType = self.algoTypeToClass.keys()[0]
4766 if self.algoTypeToClass.has_key( algoType ):
4767 #print "Create algo",algoType
4768 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
4769 raise RuntimeError, "No class found for algo type %s" % algoType
4772 # Private class used to substitute and store variable parameters of hypotheses.
4774 class hypMethodWrapper:
4775 def __init__(self, hyp, method):
4777 self.method = method
4778 #print "REBIND:", method.__name__
4781 # call a method of hypothesis with calling SetVarParameter() before
4782 def __call__(self,*args):
4784 return self.method( self.hyp, *args ) # hypothesis method with no args
4786 #print "MethWrapper.__call__",self.method.__name__, args
4788 parsed = ParseParameters(*args) # replace variables with their values
4789 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
4790 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
4791 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
4792 # maybe there is a replaced string arg which is not variable
4793 result = self.method( self.hyp, *args )
4794 except ValueError, detail: # raised by ParseParameters()
4796 result = self.method( self.hyp, *args )
4797 except omniORB.CORBA.BAD_PARAM:
4798 raise ValueError, detail # wrong variable name
4803 # A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
4804 class genObjUnRegister:
4806 def __init__(self, genObj=None):
4807 self.genObjList = []
4811 def set(self, genObj):
4812 "Store one or a list of of SALOME.GenericObj'es"
4813 if isinstance( genObj, list ):
4814 self.genObjList.extend( genObj )
4816 self.genObjList.append( genObj )
4820 for genObj in self.genObjList:
4821 if genObj and hasattr( genObj, "UnRegister" ):
4824 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
4826 #print "pluginName: ", pluginName
4827 pluginBuilderName = pluginName + "Builder"
4829 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
4830 except Exception, e:
4831 from salome_utils import verbose
4832 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
4834 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
4835 plugin = eval( pluginBuilderName )
4836 #print " plugin:" , str(plugin)
4838 # add methods creating algorithms to Mesh
4839 for k in dir( plugin ):
4840 if k[0] == '_': continue
4841 algo = getattr( plugin, k )
4842 #print " algo:", str(algo)
4843 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
4844 #print " meshMethod:" , str(algo.meshMethod)
4845 if not hasattr( Mesh, algo.meshMethod ):
4846 setattr( Mesh, algo.meshMethod, algoCreator() )
4848 getattr( Mesh, algo.meshMethod ).add( algo )