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)
1882 ## Creates a mesh group by the given conditions
1883 # @param groupName the name of the mesh group
1884 # @param elementType the type of elements in the group
1885 # @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1886 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1887 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
1888 # @param UnaryOp FT_LogicalNOT or FT_Undefined
1889 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1890 # FT_LyingOnGeom, FT_CoplanarFaces criteria
1891 # @return SMESH_GroupOnFilter
1892 # @ingroup l2_grps_create
1896 CritType=FT_Undefined,
1899 UnaryOp=FT_Undefined,
1901 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1902 group = self.MakeGroupByCriterion(groupName, aCriterion)
1905 ## Creates a mesh group by the given criterion
1906 # @param groupName the name of the mesh group
1907 # @param Criterion the instance of Criterion class
1908 # @return SMESH_GroupOnFilter
1909 # @ingroup l2_grps_create
1910 def MakeGroupByCriterion(self, groupName, Criterion):
1911 aFilterMgr = self.smeshpyD.CreateFilterManager()
1912 aFilter = aFilterMgr.CreateFilter()
1914 aCriteria.append(Criterion)
1915 aFilter.SetCriteria(aCriteria)
1916 group = self.MakeGroupByFilter(groupName, aFilter)
1917 aFilterMgr.UnRegister()
1920 ## Creates a mesh group by the given criteria (list of criteria)
1921 # @param groupName the name of the mesh group
1922 # @param theCriteria the list of criteria
1923 # @return SMESH_GroupOnFilter
1924 # @ingroup l2_grps_create
1925 def MakeGroupByCriteria(self, groupName, theCriteria):
1926 aFilterMgr = self.smeshpyD.CreateFilterManager()
1927 aFilter = aFilterMgr.CreateFilter()
1928 aFilter.SetCriteria(theCriteria)
1929 group = self.MakeGroupByFilter(groupName, aFilter)
1930 aFilterMgr.UnRegister()
1933 ## Creates a mesh group by the given filter
1934 # @param groupName the name of the mesh group
1935 # @param theFilter the instance of Filter class
1936 # @return SMESH_GroupOnFilter
1937 # @ingroup l2_grps_create
1938 def MakeGroupByFilter(self, groupName, theFilter):
1939 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1940 #theFilter.SetMesh( self.mesh )
1941 #group.AddFrom( theFilter )
1942 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
1946 # @ingroup l2_grps_delete
1947 def RemoveGroup(self, group):
1948 self.mesh.RemoveGroup(group)
1950 ## Removes a group with its contents
1951 # @ingroup l2_grps_delete
1952 def RemoveGroupWithContents(self, group):
1953 self.mesh.RemoveGroupWithContents(group)
1955 ## Gets the list of groups existing in the mesh in the order of creation (starting from the oldest one)
1956 # @return a sequence of SMESH_GroupBase
1957 # @ingroup l2_grps_create
1958 def GetGroups(self):
1959 return self.mesh.GetGroups()
1961 ## Gets the number of groups existing in the mesh
1962 # @return the quantity of groups as an integer value
1963 # @ingroup l2_grps_create
1965 return self.mesh.NbGroups()
1967 ## Gets the list of names of groups existing in the mesh
1968 # @return list of strings
1969 # @ingroup l2_grps_create
1970 def GetGroupNames(self):
1971 groups = self.GetGroups()
1973 for group in groups:
1974 names.append(group.GetName())
1977 ## Produces a union of two groups
1978 # A new group is created. All mesh elements that are
1979 # present in the initial groups are added to the new one
1980 # @return an instance of SMESH_Group
1981 # @ingroup l2_grps_operon
1982 def UnionGroups(self, group1, group2, name):
1983 return self.mesh.UnionGroups(group1, group2, name)
1985 ## Produces a union list of groups
1986 # New group is created. All mesh elements that are present in
1987 # initial groups are added to the new one
1988 # @return an instance of SMESH_Group
1989 # @ingroup l2_grps_operon
1990 def UnionListOfGroups(self, groups, name):
1991 return self.mesh.UnionListOfGroups(groups, name)
1993 ## Prodices an intersection of two groups
1994 # A new group is created. All mesh elements that are common
1995 # for the two initial groups are added to the new one.
1996 # @return an instance of SMESH_Group
1997 # @ingroup l2_grps_operon
1998 def IntersectGroups(self, group1, group2, name):
1999 return self.mesh.IntersectGroups(group1, group2, name)
2001 ## Produces an intersection of groups
2002 # New group is created. All mesh elements that are present in all
2003 # initial groups simultaneously are added to the new one
2004 # @return an instance of SMESH_Group
2005 # @ingroup l2_grps_operon
2006 def IntersectListOfGroups(self, groups, name):
2007 return self.mesh.IntersectListOfGroups(groups, name)
2009 ## Produces a cut of two groups
2010 # A new group is created. All mesh elements that are present in
2011 # the main group but are not present in the tool group are added to the new one
2012 # @return an instance of SMESH_Group
2013 # @ingroup l2_grps_operon
2014 def CutGroups(self, main_group, tool_group, name):
2015 return self.mesh.CutGroups(main_group, tool_group, name)
2017 ## Produces a cut of groups
2018 # A new group is created. All mesh elements that are present in main groups
2019 # but do not present in tool groups are added to the new one
2020 # @return an instance of SMESH_Group
2021 # @ingroup l2_grps_operon
2022 def CutListOfGroups(self, main_groups, tool_groups, name):
2023 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2025 ## Produces a group of elements of specified type using list of existing groups
2026 # A new group is created. System
2027 # 1) extracts all nodes on which groups elements are built
2028 # 2) combines all elements of specified dimension laying on these nodes
2029 # @return an instance of SMESH_Group
2030 # @ingroup l2_grps_operon
2031 def CreateDimGroup(self, groups, elem_type, name):
2032 return self.mesh.CreateDimGroup(groups, elem_type, name)
2035 ## Convert group on geom into standalone group
2036 # @ingroup l2_grps_delete
2037 def ConvertToStandalone(self, group):
2038 return self.mesh.ConvertToStandalone(group)
2040 # Get some info about mesh:
2041 # ------------------------
2043 ## Returns the log of nodes and elements added or removed
2044 # since the previous clear of the log.
2045 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2046 # @return list of log_block structures:
2051 # @ingroup l1_auxiliary
2052 def GetLog(self, clearAfterGet):
2053 return self.mesh.GetLog(clearAfterGet)
2055 ## Clears the log of nodes and elements added or removed since the previous
2056 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2057 # @ingroup l1_auxiliary
2059 self.mesh.ClearLog()
2061 ## Toggles auto color mode on the object.
2062 # @param theAutoColor the flag which toggles auto color mode.
2063 # @ingroup l1_auxiliary
2064 def SetAutoColor(self, theAutoColor):
2065 self.mesh.SetAutoColor(theAutoColor)
2067 ## Gets flag of object auto color mode.
2068 # @return True or False
2069 # @ingroup l1_auxiliary
2070 def GetAutoColor(self):
2071 return self.mesh.GetAutoColor()
2073 ## Gets the internal ID
2074 # @return integer value, which is the internal Id of the mesh
2075 # @ingroup l1_auxiliary
2077 return self.mesh.GetId()
2080 # @return integer value, which is the study Id of the mesh
2081 # @ingroup l1_auxiliary
2082 def GetStudyId(self):
2083 return self.mesh.GetStudyId()
2085 ## Checks the group names for duplications.
2086 # Consider the maximum group name length stored in MED file.
2087 # @return True or False
2088 # @ingroup l1_auxiliary
2089 def HasDuplicatedGroupNamesMED(self):
2090 return self.mesh.HasDuplicatedGroupNamesMED()
2092 ## Obtains the mesh editor tool
2093 # @return an instance of SMESH_MeshEditor
2094 # @ingroup l1_modifying
2095 def GetMeshEditor(self):
2098 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2099 # can be passed as argument to a method accepting mesh, group or sub-mesh
2100 # @return an instance of SMESH_IDSource
2101 # @ingroup l1_auxiliary
2102 def GetIDSource(self, ids, elemType):
2103 return self.editor.MakeIDSource(ids, elemType)
2106 # Get informations about mesh contents:
2107 # ------------------------------------
2109 ## Gets the mesh stattistic
2110 # @return dictionary type element - count of elements
2111 # @ingroup l1_meshinfo
2112 def GetMeshInfo(self, obj = None):
2113 if not obj: obj = self.mesh
2114 return self.smeshpyD.GetMeshInfo(obj)
2116 ## Returns the number of nodes in the mesh
2117 # @return an integer value
2118 # @ingroup l1_meshinfo
2120 return self.mesh.NbNodes()
2122 ## Returns the number of elements in the mesh
2123 # @return an integer value
2124 # @ingroup l1_meshinfo
2125 def NbElements(self):
2126 return self.mesh.NbElements()
2128 ## Returns the number of 0d elements in the mesh
2129 # @return an integer value
2130 # @ingroup l1_meshinfo
2131 def Nb0DElements(self):
2132 return self.mesh.Nb0DElements()
2134 ## Returns the number of ball discrete elements in the mesh
2135 # @return an integer value
2136 # @ingroup l1_meshinfo
2138 return self.mesh.NbBalls()
2140 ## Returns the number of edges in the mesh
2141 # @return an integer value
2142 # @ingroup l1_meshinfo
2144 return self.mesh.NbEdges()
2146 ## Returns the number of edges with the given order in the mesh
2147 # @param elementOrder the order of elements:
2148 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2149 # @return an integer value
2150 # @ingroup l1_meshinfo
2151 def NbEdgesOfOrder(self, elementOrder):
2152 return self.mesh.NbEdgesOfOrder(elementOrder)
2154 ## Returns the number of faces in the mesh
2155 # @return an integer value
2156 # @ingroup l1_meshinfo
2158 return self.mesh.NbFaces()
2160 ## Returns the number of faces with the given order in the mesh
2161 # @param elementOrder the order of elements:
2162 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2163 # @return an integer value
2164 # @ingroup l1_meshinfo
2165 def NbFacesOfOrder(self, elementOrder):
2166 return self.mesh.NbFacesOfOrder(elementOrder)
2168 ## Returns the number of triangles in the mesh
2169 # @return an integer value
2170 # @ingroup l1_meshinfo
2171 def NbTriangles(self):
2172 return self.mesh.NbTriangles()
2174 ## Returns the number of triangles with the given order in the mesh
2175 # @param elementOrder is the order of elements:
2176 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2177 # @return an integer value
2178 # @ingroup l1_meshinfo
2179 def NbTrianglesOfOrder(self, elementOrder):
2180 return self.mesh.NbTrianglesOfOrder(elementOrder)
2182 ## Returns the number of biquadratic triangles in the mesh
2183 # @return an integer value
2184 # @ingroup l1_meshinfo
2185 def NbBiQuadTriangles(self):
2186 return self.mesh.NbBiQuadTriangles()
2188 ## Returns the number of quadrangles in the mesh
2189 # @return an integer value
2190 # @ingroup l1_meshinfo
2191 def NbQuadrangles(self):
2192 return self.mesh.NbQuadrangles()
2194 ## Returns the number of quadrangles with the given order in the mesh
2195 # @param elementOrder the order of elements:
2196 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2197 # @return an integer value
2198 # @ingroup l1_meshinfo
2199 def NbQuadranglesOfOrder(self, elementOrder):
2200 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2202 ## Returns the number of biquadratic quadrangles in the mesh
2203 # @return an integer value
2204 # @ingroup l1_meshinfo
2205 def NbBiQuadQuadrangles(self):
2206 return self.mesh.NbBiQuadQuadrangles()
2208 ## Returns the number of polygons in the mesh
2209 # @return an integer value
2210 # @ingroup l1_meshinfo
2211 def NbPolygons(self):
2212 return self.mesh.NbPolygons()
2214 ## Returns the number of volumes in the mesh
2215 # @return an integer value
2216 # @ingroup l1_meshinfo
2217 def NbVolumes(self):
2218 return self.mesh.NbVolumes()
2220 ## Returns the number of volumes with the given order in the mesh
2221 # @param elementOrder the order of elements:
2222 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2223 # @return an integer value
2224 # @ingroup l1_meshinfo
2225 def NbVolumesOfOrder(self, elementOrder):
2226 return self.mesh.NbVolumesOfOrder(elementOrder)
2228 ## Returns the number of tetrahedrons in the mesh
2229 # @return an integer value
2230 # @ingroup l1_meshinfo
2232 return self.mesh.NbTetras()
2234 ## Returns the number of tetrahedrons with the given order in the mesh
2235 # @param elementOrder the order of elements:
2236 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2237 # @return an integer value
2238 # @ingroup l1_meshinfo
2239 def NbTetrasOfOrder(self, elementOrder):
2240 return self.mesh.NbTetrasOfOrder(elementOrder)
2242 ## Returns the number of hexahedrons in the mesh
2243 # @return an integer value
2244 # @ingroup l1_meshinfo
2246 return self.mesh.NbHexas()
2248 ## Returns the number of hexahedrons with the given order in the mesh
2249 # @param elementOrder the order of elements:
2250 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2251 # @return an integer value
2252 # @ingroup l1_meshinfo
2253 def NbHexasOfOrder(self, elementOrder):
2254 return self.mesh.NbHexasOfOrder(elementOrder)
2256 ## Returns the number of triquadratic hexahedrons in the mesh
2257 # @return an integer value
2258 # @ingroup l1_meshinfo
2259 def NbTriQuadraticHexas(self):
2260 return self.mesh.NbTriQuadraticHexas()
2262 ## Returns the number of pyramids in the mesh
2263 # @return an integer value
2264 # @ingroup l1_meshinfo
2265 def NbPyramids(self):
2266 return self.mesh.NbPyramids()
2268 ## Returns the number of pyramids with the given order in the mesh
2269 # @param elementOrder the order of elements:
2270 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2271 # @return an integer value
2272 # @ingroup l1_meshinfo
2273 def NbPyramidsOfOrder(self, elementOrder):
2274 return self.mesh.NbPyramidsOfOrder(elementOrder)
2276 ## Returns the number of prisms in the mesh
2277 # @return an integer value
2278 # @ingroup l1_meshinfo
2280 return self.mesh.NbPrisms()
2282 ## Returns the number of prisms with the given order in the mesh
2283 # @param elementOrder the order of elements:
2284 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2285 # @return an integer value
2286 # @ingroup l1_meshinfo
2287 def NbPrismsOfOrder(self, elementOrder):
2288 return self.mesh.NbPrismsOfOrder(elementOrder)
2290 ## Returns the number of hexagonal prisms in the mesh
2291 # @return an integer value
2292 # @ingroup l1_meshinfo
2293 def NbHexagonalPrisms(self):
2294 return self.mesh.NbHexagonalPrisms()
2296 ## Returns the number of polyhedrons in the mesh
2297 # @return an integer value
2298 # @ingroup l1_meshinfo
2299 def NbPolyhedrons(self):
2300 return self.mesh.NbPolyhedrons()
2302 ## Returns the number of submeshes in the mesh
2303 # @return an integer value
2304 # @ingroup l1_meshinfo
2305 def NbSubMesh(self):
2306 return self.mesh.NbSubMesh()
2308 ## Returns the list of mesh elements IDs
2309 # @return the list of integer values
2310 # @ingroup l1_meshinfo
2311 def GetElementsId(self):
2312 return self.mesh.GetElementsId()
2314 ## Returns the list of IDs of mesh elements with the given type
2315 # @param elementType the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2316 # @return list of integer values
2317 # @ingroup l1_meshinfo
2318 def GetElementsByType(self, elementType):
2319 return self.mesh.GetElementsByType(elementType)
2321 ## Returns the list of mesh nodes IDs
2322 # @return the list of integer values
2323 # @ingroup l1_meshinfo
2324 def GetNodesId(self):
2325 return self.mesh.GetNodesId()
2327 # Get the information about mesh elements:
2328 # ------------------------------------
2330 ## Returns the type of mesh element
2331 # @return the value from SMESH::ElementType enumeration
2332 # @ingroup l1_meshinfo
2333 def GetElementType(self, id, iselem):
2334 return self.mesh.GetElementType(id, iselem)
2336 ## Returns the geometric type of mesh element
2337 # @return the value from SMESH::EntityType enumeration
2338 # @ingroup l1_meshinfo
2339 def GetElementGeomType(self, id):
2340 return self.mesh.GetElementGeomType(id)
2342 ## Returns the shape type of mesh element
2343 # @return the value from SMESH::GeometryType enumeration
2344 # @ingroup l1_meshinfo
2345 def GetElementShape(self, id):
2346 return self.mesh.GetElementShape(id)
2348 ## Returns the list of submesh elements IDs
2349 # @param Shape a geom object(sub-shape) IOR
2350 # Shape must be the sub-shape of a ShapeToMesh()
2351 # @return the list of integer values
2352 # @ingroup l1_meshinfo
2353 def GetSubMeshElementsId(self, Shape):
2354 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2355 ShapeID = Shape.GetSubShapeIndices()[0]
2358 return self.mesh.GetSubMeshElementsId(ShapeID)
2360 ## Returns the list of submesh nodes IDs
2361 # @param Shape a geom object(sub-shape) IOR
2362 # Shape must be the sub-shape of a ShapeToMesh()
2363 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2364 # @return the list of integer values
2365 # @ingroup l1_meshinfo
2366 def GetSubMeshNodesId(self, Shape, all):
2367 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2368 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2371 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2373 ## Returns type of elements on given shape
2374 # @param Shape a geom object(sub-shape) IOR
2375 # Shape must be a sub-shape of a ShapeToMesh()
2376 # @return element type
2377 # @ingroup l1_meshinfo
2378 def GetSubMeshElementType(self, Shape):
2379 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2380 ShapeID = Shape.GetSubShapeIndices()[0]
2383 return self.mesh.GetSubMeshElementType(ShapeID)
2385 ## Gets the mesh description
2386 # @return string value
2387 # @ingroup l1_meshinfo
2389 return self.mesh.Dump()
2392 # Get the information about nodes and elements of a mesh by its IDs:
2393 # -----------------------------------------------------------
2395 ## Gets XYZ coordinates of a node
2396 # \n If there is no nodes for the given ID - returns an empty list
2397 # @return a list of double precision values
2398 # @ingroup l1_meshinfo
2399 def GetNodeXYZ(self, id):
2400 return self.mesh.GetNodeXYZ(id)
2402 ## Returns list of IDs of inverse elements for the given node
2403 # \n If there is no node for the given ID - returns an empty list
2404 # @return a list of integer values
2405 # @ingroup l1_meshinfo
2406 def GetNodeInverseElements(self, id):
2407 return self.mesh.GetNodeInverseElements(id)
2409 ## @brief Returns the position of a node on the shape
2410 # @return SMESH::NodePosition
2411 # @ingroup l1_meshinfo
2412 def GetNodePosition(self,NodeID):
2413 return self.mesh.GetNodePosition(NodeID)
2415 ## @brief Returns the position of an element on the shape
2416 # @return SMESH::ElementPosition
2417 # @ingroup l1_meshinfo
2418 def GetElementPosition(self,ElemID):
2419 return self.mesh.GetElementPosition(ElemID)
2421 ## If the given element is a node, returns the ID of shape
2422 # \n If there is no node for the given ID - returns -1
2423 # @return an integer value
2424 # @ingroup l1_meshinfo
2425 def GetShapeID(self, id):
2426 return self.mesh.GetShapeID(id)
2428 ## Returns the ID of the result shape after
2429 # FindShape() from SMESH_MeshEditor for the given element
2430 # \n If there is no element for the given ID - returns -1
2431 # @return an integer value
2432 # @ingroup l1_meshinfo
2433 def GetShapeIDForElem(self,id):
2434 return self.mesh.GetShapeIDForElem(id)
2436 ## Returns the number of nodes for the given element
2437 # \n If there is no element for the given ID - returns -1
2438 # @return an integer value
2439 # @ingroup l1_meshinfo
2440 def GetElemNbNodes(self, id):
2441 return self.mesh.GetElemNbNodes(id)
2443 ## Returns the node ID the given (zero based) index for the given element
2444 # \n If there is no element for the given ID - returns -1
2445 # \n If there is no node for the given index - returns -2
2446 # @return an integer value
2447 # @ingroup l1_meshinfo
2448 def GetElemNode(self, id, index):
2449 return self.mesh.GetElemNode(id, index)
2451 ## Returns the IDs of nodes of the given element
2452 # @return a list of integer values
2453 # @ingroup l1_meshinfo
2454 def GetElemNodes(self, id):
2455 return self.mesh.GetElemNodes(id)
2457 ## Returns true if the given node is the medium node in the given quadratic element
2458 # @ingroup l1_meshinfo
2459 def IsMediumNode(self, elementID, nodeID):
2460 return self.mesh.IsMediumNode(elementID, nodeID)
2462 ## Returns true if the given node is the medium node in one of quadratic elements
2463 # @ingroup l1_meshinfo
2464 def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2465 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2467 ## Returns the number of edges for the given element
2468 # @ingroup l1_meshinfo
2469 def ElemNbEdges(self, id):
2470 return self.mesh.ElemNbEdges(id)
2472 ## Returns the number of faces for the given element
2473 # @ingroup l1_meshinfo
2474 def ElemNbFaces(self, id):
2475 return self.mesh.ElemNbFaces(id)
2477 ## Returns nodes of given face (counted from zero) for given volumic element.
2478 # @ingroup l1_meshinfo
2479 def GetElemFaceNodes(self,elemId, faceIndex):
2480 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2482 ## Returns three components of normal of given mesh face
2483 # (or an empty array in KO case)
2484 # @ingroup l1_meshinfo
2485 def GetFaceNormal(self, faceId, normalized=False):
2486 return self.mesh.GetFaceNormal(faceId,normalized)
2488 ## Returns an element based on all given nodes.
2489 # @ingroup l1_meshinfo
2490 def FindElementByNodes(self,nodes):
2491 return self.mesh.FindElementByNodes(nodes)
2493 ## Returns true if the given element is a polygon
2494 # @ingroup l1_meshinfo
2495 def IsPoly(self, id):
2496 return self.mesh.IsPoly(id)
2498 ## Returns true if the given element is quadratic
2499 # @ingroup l1_meshinfo
2500 def IsQuadratic(self, id):
2501 return self.mesh.IsQuadratic(id)
2503 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2504 # @ingroup l1_meshinfo
2505 def GetBallDiameter(self, id):
2506 return self.mesh.GetBallDiameter(id)
2508 ## Returns XYZ coordinates of the barycenter of the given element
2509 # \n If there is no element for the given ID - returns an empty list
2510 # @return a list of three double values
2511 # @ingroup l1_meshinfo
2512 def BaryCenter(self, id):
2513 return self.mesh.BaryCenter(id)
2515 ## Passes mesh elements through the given filter and return IDs of fitting elements
2516 # @param theFilter SMESH_Filter
2517 # @return a list of ids
2518 # @ingroup l1_controls
2519 def GetIdsFromFilter(self, theFilter):
2520 theFilter.SetMesh( self.mesh )
2521 return theFilter.GetIDs()
2523 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2524 # Returns a list of special structures (borders).
2525 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2526 # @ingroup l1_controls
2527 def GetFreeBorders(self):
2528 aFilterMgr = self.smeshpyD.CreateFilterManager()
2529 aPredicate = aFilterMgr.CreateFreeEdges()
2530 aPredicate.SetMesh(self.mesh)
2531 aBorders = aPredicate.GetBorders()
2532 aFilterMgr.UnRegister()
2536 # Get mesh measurements information:
2537 # ------------------------------------
2539 ## Get minimum distance between two nodes, elements or distance to the origin
2540 # @param id1 first node/element id
2541 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2542 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2543 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2544 # @return minimum distance value
2545 # @sa GetMinDistance()
2546 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2547 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2548 return aMeasure.value
2550 ## Get measure structure specifying minimum distance data between two objects
2551 # @param id1 first node/element id
2552 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2553 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2554 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2555 # @return Measure structure
2557 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2559 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2561 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2564 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2566 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2571 aMeasurements = self.smeshpyD.CreateMeasurements()
2572 aMeasure = aMeasurements.MinDistance(id1, id2)
2573 genObjUnRegister([aMeasurements,id1, id2])
2576 ## Get bounding box of the specified object(s)
2577 # @param objects single source object or list of source objects or list of nodes/elements IDs
2578 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2579 # @c False specifies that @a objects are nodes
2580 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2581 # @sa GetBoundingBox()
2582 def BoundingBox(self, objects=None, isElem=False):
2583 result = self.GetBoundingBox(objects, isElem)
2587 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2590 ## Get measure structure specifying bounding box data of the specified object(s)
2591 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2592 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2593 # @c False specifies that @a objects are nodes
2594 # @return Measure structure
2596 def GetBoundingBox(self, IDs=None, isElem=False):
2599 elif isinstance(IDs, tuple):
2601 if not isinstance(IDs, list):
2603 if len(IDs) > 0 and isinstance(IDs[0], int):
2606 unRegister = genObjUnRegister()
2608 if isinstance(o, Mesh):
2609 srclist.append(o.mesh)
2610 elif hasattr(o, "_narrow"):
2611 src = o._narrow(SMESH.SMESH_IDSource)
2612 if src: srclist.append(src)
2614 elif isinstance(o, list):
2616 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2618 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2619 unRegister.set( srclist[-1] )
2622 aMeasurements = self.smeshpyD.CreateMeasurements()
2623 unRegister.set( aMeasurements )
2624 aMeasure = aMeasurements.BoundingBox(srclist)
2627 # Mesh edition (SMESH_MeshEditor functionality):
2628 # ---------------------------------------------
2630 ## Removes the elements from the mesh by ids
2631 # @param IDsOfElements is a list of ids of elements to remove
2632 # @return True or False
2633 # @ingroup l2_modif_del
2634 def RemoveElements(self, IDsOfElements):
2635 return self.editor.RemoveElements(IDsOfElements)
2637 ## Removes nodes from mesh by ids
2638 # @param IDsOfNodes is a list of ids of nodes to remove
2639 # @return True or False
2640 # @ingroup l2_modif_del
2641 def RemoveNodes(self, IDsOfNodes):
2642 return self.editor.RemoveNodes(IDsOfNodes)
2644 ## Removes all orphan (free) nodes from mesh
2645 # @return number of the removed nodes
2646 # @ingroup l2_modif_del
2647 def RemoveOrphanNodes(self):
2648 return self.editor.RemoveOrphanNodes()
2650 ## Add a node to the mesh by coordinates
2651 # @return Id of the new node
2652 # @ingroup l2_modif_add
2653 def AddNode(self, x, y, z):
2654 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2655 if hasVars: self.mesh.SetParameters(Parameters)
2656 return self.editor.AddNode( x, y, z)
2658 ## Creates a 0D element on a node with given number.
2659 # @param IDOfNode the ID of node for creation of the element.
2660 # @return the Id of the new 0D element
2661 # @ingroup l2_modif_add
2662 def Add0DElement(self, IDOfNode):
2663 return self.editor.Add0DElement(IDOfNode)
2665 ## Create 0D elements on all nodes of the given elements except those
2666 # nodes on which a 0D element already exists.
2667 # @param theObject an object on whose nodes 0D elements will be created.
2668 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2669 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2670 # @param theGroupName optional name of a group to add 0D elements created
2671 # and/or found on nodes of \a theObject.
2672 # @return an object (a new group or a temporary SMESH_IDSource) holding
2673 # IDs of new and/or found 0D elements. IDs of 0D elements
2674 # can be retrieved from the returned object by calling GetIDs()
2675 # @ingroup l2_modif_add
2676 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2677 unRegister = genObjUnRegister()
2678 if isinstance( theObject, Mesh ):
2679 theObject = theObject.GetMesh()
2680 if isinstance( theObject, list ):
2681 theObject = self.GetIDSource( theObject, SMESH.ALL )
2682 unRegister.set( theObject )
2683 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2685 ## Creates a ball element on a node with given ID.
2686 # @param IDOfNode the ID of node for creation of the element.
2687 # @param diameter the bal diameter.
2688 # @return the Id of the new ball element
2689 # @ingroup l2_modif_add
2690 def AddBall(self, IDOfNode, diameter):
2691 return self.editor.AddBall( IDOfNode, diameter )
2693 ## Creates a linear or quadratic edge (this is determined
2694 # by the number of given nodes).
2695 # @param IDsOfNodes the list of node IDs for creation of the element.
2696 # The order of nodes in this list should correspond to the description
2697 # of MED. \n This description is located by the following link:
2698 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2699 # @return the Id of the new edge
2700 # @ingroup l2_modif_add
2701 def AddEdge(self, IDsOfNodes):
2702 return self.editor.AddEdge(IDsOfNodes)
2704 ## Creates a linear or quadratic face (this is determined
2705 # by the number of given nodes).
2706 # @param IDsOfNodes the list of node IDs for creation of the element.
2707 # The order of nodes in this list should correspond to the description
2708 # of MED. \n This description is located by the following link:
2709 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2710 # @return the Id of the new face
2711 # @ingroup l2_modif_add
2712 def AddFace(self, IDsOfNodes):
2713 return self.editor.AddFace(IDsOfNodes)
2715 ## Adds a polygonal face to the mesh by the list of node IDs
2716 # @param IdsOfNodes the list of node IDs for creation of the element.
2717 # @return the Id of the new face
2718 # @ingroup l2_modif_add
2719 def AddPolygonalFace(self, IdsOfNodes):
2720 return self.editor.AddPolygonalFace(IdsOfNodes)
2722 ## Creates both simple and quadratic volume (this is determined
2723 # by the number of given nodes).
2724 # @param IDsOfNodes the list of node IDs for creation of the element.
2725 # The order of nodes in this list should correspond to the description
2726 # of MED. \n This description is located by the following link:
2727 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2728 # @return the Id of the new volumic element
2729 # @ingroup l2_modif_add
2730 def AddVolume(self, IDsOfNodes):
2731 return self.editor.AddVolume(IDsOfNodes)
2733 ## Creates a volume of many faces, giving nodes for each face.
2734 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2735 # @param Quantities the list of integer values, Quantities[i]
2736 # gives the quantity of nodes in face number i.
2737 # @return the Id of the new volumic element
2738 # @ingroup l2_modif_add
2739 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2740 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2742 ## Creates a volume of many faces, giving the IDs of the existing faces.
2743 # @param IdsOfFaces the list of face IDs for volume creation.
2745 # Note: The created volume will refer only to the nodes
2746 # of the given faces, not to the faces themselves.
2747 # @return the Id of the new volumic element
2748 # @ingroup l2_modif_add
2749 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2750 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2753 ## @brief Binds a node to a vertex
2754 # @param NodeID a node ID
2755 # @param Vertex a vertex or vertex ID
2756 # @return True if succeed else raises an exception
2757 # @ingroup l2_modif_add
2758 def SetNodeOnVertex(self, NodeID, Vertex):
2759 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2760 VertexID = Vertex.GetSubShapeIndices()[0]
2764 self.editor.SetNodeOnVertex(NodeID, VertexID)
2765 except SALOME.SALOME_Exception, inst:
2766 raise ValueError, inst.details.text
2770 ## @brief Stores the node position on an edge
2771 # @param NodeID a node ID
2772 # @param Edge an edge or edge ID
2773 # @param paramOnEdge a parameter on the edge where the node is located
2774 # @return True if succeed else raises an exception
2775 # @ingroup l2_modif_add
2776 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2777 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2778 EdgeID = Edge.GetSubShapeIndices()[0]
2782 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2783 except SALOME.SALOME_Exception, inst:
2784 raise ValueError, inst.details.text
2787 ## @brief Stores node position on a face
2788 # @param NodeID a node ID
2789 # @param Face a face or face ID
2790 # @param u U parameter on the face where the node is located
2791 # @param v V parameter on the face where the node is located
2792 # @return True if succeed else raises an exception
2793 # @ingroup l2_modif_add
2794 def SetNodeOnFace(self, NodeID, Face, u, v):
2795 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2796 FaceID = Face.GetSubShapeIndices()[0]
2800 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2801 except SALOME.SALOME_Exception, inst:
2802 raise ValueError, inst.details.text
2805 ## @brief Binds a node to a solid
2806 # @param NodeID a node ID
2807 # @param Solid a solid or solid ID
2808 # @return True if succeed else raises an exception
2809 # @ingroup l2_modif_add
2810 def SetNodeInVolume(self, NodeID, Solid):
2811 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2812 SolidID = Solid.GetSubShapeIndices()[0]
2816 self.editor.SetNodeInVolume(NodeID, SolidID)
2817 except SALOME.SALOME_Exception, inst:
2818 raise ValueError, inst.details.text
2821 ## @brief Bind an element to a shape
2822 # @param ElementID an element ID
2823 # @param Shape a shape or shape ID
2824 # @return True if succeed else raises an exception
2825 # @ingroup l2_modif_add
2826 def SetMeshElementOnShape(self, ElementID, Shape):
2827 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2828 ShapeID = Shape.GetSubShapeIndices()[0]
2832 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2833 except SALOME.SALOME_Exception, inst:
2834 raise ValueError, inst.details.text
2838 ## Moves the node with the given id
2839 # @param NodeID the id of the node
2840 # @param x a new X coordinate
2841 # @param y a new Y coordinate
2842 # @param z a new Z coordinate
2843 # @return True if succeed else False
2844 # @ingroup l2_modif_movenode
2845 def MoveNode(self, NodeID, x, y, z):
2846 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2847 if hasVars: self.mesh.SetParameters(Parameters)
2848 return self.editor.MoveNode(NodeID, x, y, z)
2850 ## Finds the node closest to a point and moves it to a point location
2851 # @param x the X coordinate of a point
2852 # @param y the Y coordinate of a point
2853 # @param z the Z coordinate of a point
2854 # @param NodeID if specified (>0), the node with this ID is moved,
2855 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
2856 # @return the ID of a node
2857 # @ingroup l2_modif_throughp
2858 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2859 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2860 if hasVars: self.mesh.SetParameters(Parameters)
2861 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2863 ## Finds the node closest to a point
2864 # @param x the X coordinate of a point
2865 # @param y the Y coordinate of a point
2866 # @param z the Z coordinate of a point
2867 # @return the ID of a node
2868 # @ingroup l2_modif_throughp
2869 def FindNodeClosestTo(self, x, y, z):
2870 #preview = self.mesh.GetMeshEditPreviewer()
2871 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2872 return self.editor.FindNodeClosestTo(x, y, z)
2874 ## Finds the elements where a point lays IN or ON
2875 # @param x the X coordinate of a point
2876 # @param y the Y coordinate of a point
2877 # @param z the Z coordinate of a point
2878 # @param elementType type of elements to find (SMESH.ALL type
2879 # means elements of any type excluding nodes, discrete and 0D elements)
2880 # @param meshPart a part of mesh (group, sub-mesh) to search within
2881 # @return list of IDs of found elements
2882 # @ingroup l2_modif_throughp
2883 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2885 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2887 return self.editor.FindElementsByPoint(x, y, z, elementType)
2889 # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2890 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2891 # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2893 def GetPointState(self, x, y, z):
2894 return self.editor.GetPointState(x, y, z)
2896 ## Finds the node closest to a point and moves it to a point location
2897 # @param x the X coordinate of a point
2898 # @param y the Y coordinate of a point
2899 # @param z the Z coordinate of a point
2900 # @return the ID of a moved node
2901 # @ingroup l2_modif_throughp
2902 def MeshToPassThroughAPoint(self, x, y, z):
2903 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2905 ## Replaces two neighbour triangles sharing Node1-Node2 link
2906 # with the triangles built on the same 4 nodes but having other common link.
2907 # @param NodeID1 the ID of the first node
2908 # @param NodeID2 the ID of the second node
2909 # @return false if proper faces were not found
2910 # @ingroup l2_modif_invdiag
2911 def InverseDiag(self, NodeID1, NodeID2):
2912 return self.editor.InverseDiag(NodeID1, NodeID2)
2914 ## Replaces two neighbour triangles sharing Node1-Node2 link
2915 # with a quadrangle built on the same 4 nodes.
2916 # @param NodeID1 the ID of the first node
2917 # @param NodeID2 the ID of the second node
2918 # @return false if proper faces were not found
2919 # @ingroup l2_modif_unitetri
2920 def DeleteDiag(self, NodeID1, NodeID2):
2921 return self.editor.DeleteDiag(NodeID1, NodeID2)
2923 ## Reorients elements by ids
2924 # @param IDsOfElements if undefined reorients all mesh elements
2925 # @return True if succeed else False
2926 # @ingroup l2_modif_changori
2927 def Reorient(self, IDsOfElements=None):
2928 if IDsOfElements == None:
2929 IDsOfElements = self.GetElementsId()
2930 return self.editor.Reorient(IDsOfElements)
2932 ## Reorients all elements of the object
2933 # @param theObject mesh, submesh or group
2934 # @return True if succeed else False
2935 # @ingroup l2_modif_changori
2936 def ReorientObject(self, theObject):
2937 if ( isinstance( theObject, Mesh )):
2938 theObject = theObject.GetMesh()
2939 return self.editor.ReorientObject(theObject)
2941 ## Reorient faces contained in \a the2DObject.
2942 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2943 # @param theDirection is a desired direction of normal of \a theFace.
2944 # It can be either a GEOM vector or a list of coordinates [x,y,z].
2945 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2946 # compared with theDirection. It can be either ID of face or a point
2947 # by which the face will be found. The point can be given as either
2948 # a GEOM vertex or a list of point coordinates.
2949 # @return number of reoriented faces
2950 # @ingroup l2_modif_changori
2951 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2952 unRegister = genObjUnRegister()
2954 if isinstance( the2DObject, Mesh ):
2955 the2DObject = the2DObject.GetMesh()
2956 if isinstance( the2DObject, list ):
2957 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2958 unRegister.set( the2DObject )
2959 # check theDirection
2960 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
2961 theDirection = self.smeshpyD.GetDirStruct( theDirection )
2962 if isinstance( theDirection, list ):
2963 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
2964 # prepare theFace and thePoint
2965 theFace = theFaceOrPoint
2966 thePoint = PointStruct(0,0,0)
2967 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
2968 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
2970 if isinstance( theFaceOrPoint, list ):
2971 thePoint = PointStruct( *theFaceOrPoint )
2973 if isinstance( theFaceOrPoint, PointStruct ):
2974 thePoint = theFaceOrPoint
2976 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
2978 ## Reorient faces according to adjacent volumes.
2979 # @param the2DObject is a mesh, sub-mesh, group or list of
2980 # either IDs of faces or face groups.
2981 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
2982 # @param theOutsideNormal to orient faces to have their normals
2983 # pointing either \a outside or \a inside the adjacent volumes.
2984 # @return number of reoriented faces.
2985 # @ingroup l2_modif_changori
2986 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
2987 unRegister = genObjUnRegister()
2989 if not isinstance( the2DObject, list ):
2990 the2DObject = [ the2DObject ]
2991 elif the2DObject and isinstance( the2DObject[0], int ):
2992 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2993 unRegister.set( the2DObject )
2994 the2DObject = [ the2DObject ]
2995 for i,obj2D in enumerate( the2DObject ):
2996 if isinstance( obj2D, Mesh ):
2997 the2DObject[i] = obj2D.GetMesh()
2998 if isinstance( obj2D, list ):
2999 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3000 unRegister.set( the2DObject[i] )
3002 if isinstance( the3DObject, Mesh ):
3003 the3DObject = the3DObject.GetMesh()
3004 if isinstance( the3DObject, list ):
3005 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3006 unRegister.set( the3DObject )
3007 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3009 ## Fuses the neighbouring triangles into quadrangles.
3010 # @param IDsOfElements The triangles to be fused,
3011 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3012 # choose a neighbour to fuse with.
3013 # @param MaxAngle is the maximum angle between element normals at which the fusion
3014 # is still performed; theMaxAngle is mesured in radians.
3015 # Also it could be a name of variable which defines angle in degrees.
3016 # @return TRUE in case of success, FALSE otherwise.
3017 # @ingroup l2_modif_unitetri
3018 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3019 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3020 self.mesh.SetParameters(Parameters)
3021 if not IDsOfElements:
3022 IDsOfElements = self.GetElementsId()
3023 Functor = self.smeshpyD.GetFunctor(theCriterion)
3024 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3026 ## Fuses the neighbouring triangles of the object into quadrangles
3027 # @param theObject is mesh, submesh or group
3028 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3029 # choose a neighbour to fuse with.
3030 # @param MaxAngle a max angle between element normals at which the fusion
3031 # is still performed; theMaxAngle is mesured in radians.
3032 # @return TRUE in case of success, FALSE otherwise.
3033 # @ingroup l2_modif_unitetri
3034 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3035 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3036 self.mesh.SetParameters(Parameters)
3037 if isinstance( theObject, Mesh ):
3038 theObject = theObject.GetMesh()
3039 Functor = self.smeshpyD.GetFunctor(theCriterion)
3040 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3042 ## Splits quadrangles into triangles.
3043 # @param IDsOfElements the faces to be splitted.
3044 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3045 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3046 # value, then quadrangles will be split by the smallest diagonal.
3047 # @return TRUE in case of success, FALSE otherwise.
3048 # @ingroup l2_modif_cutquadr
3049 def QuadToTri (self, IDsOfElements, theCriterion = None):
3050 if IDsOfElements == []:
3051 IDsOfElements = self.GetElementsId()
3052 if theCriterion is None:
3053 theCriterion = FT_MaxElementLength2D
3054 Functor = self.smeshpyD.GetFunctor(theCriterion)
3055 return self.editor.QuadToTri(IDsOfElements, Functor)
3057 ## Splits quadrangles into triangles.
3058 # @param theObject the object from which the list of elements is taken,
3059 # this is mesh, submesh or group
3060 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3061 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3062 # value, then quadrangles will be split by the smallest diagonal.
3063 # @return TRUE in case of success, FALSE otherwise.
3064 # @ingroup l2_modif_cutquadr
3065 def QuadToTriObject (self, theObject, theCriterion = None):
3066 if ( isinstance( theObject, Mesh )):
3067 theObject = theObject.GetMesh()
3068 if theCriterion is None:
3069 theCriterion = FT_MaxElementLength2D
3070 Functor = self.smeshpyD.GetFunctor(theCriterion)
3071 return self.editor.QuadToTriObject(theObject, Functor)
3073 ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3075 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3076 # group or a list of face IDs. By default all quadrangles are split
3077 # @ingroup l2_modif_cutquadr
3078 def QuadTo4Tri (self, theElements=[]):
3079 unRegister = genObjUnRegister()
3080 if isinstance( theElements, Mesh ):
3081 theElements = theElements.mesh
3082 elif not theElements:
3083 theElements = self.mesh
3084 elif isinstance( theElements, list ):
3085 theElements = self.GetIDSource( theElements, SMESH.FACE )
3086 unRegister.set( theElements )
3087 return self.editor.QuadTo4Tri( theElements )
3089 ## Splits quadrangles into triangles.
3090 # @param IDsOfElements the faces to be splitted
3091 # @param Diag13 is used to choose a diagonal for splitting.
3092 # @return TRUE in case of success, FALSE otherwise.
3093 # @ingroup l2_modif_cutquadr
3094 def SplitQuad (self, IDsOfElements, Diag13):
3095 if IDsOfElements == []:
3096 IDsOfElements = self.GetElementsId()
3097 return self.editor.SplitQuad(IDsOfElements, Diag13)
3099 ## Splits quadrangles into triangles.
3100 # @param theObject the object from which the list of elements is taken,
3101 # this is mesh, submesh or group
3102 # @param Diag13 is used to choose a diagonal for splitting.
3103 # @return TRUE in case of success, FALSE otherwise.
3104 # @ingroup l2_modif_cutquadr
3105 def SplitQuadObject (self, theObject, Diag13):
3106 if ( isinstance( theObject, Mesh )):
3107 theObject = theObject.GetMesh()
3108 return self.editor.SplitQuadObject(theObject, Diag13)
3110 ## Finds a better splitting of the given quadrangle.
3111 # @param IDOfQuad the ID of the quadrangle to be splitted.
3112 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3113 # choose a diagonal for splitting.
3114 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3115 # diagonal is better, 0 if error occurs.
3116 # @ingroup l2_modif_cutquadr
3117 def BestSplit (self, IDOfQuad, theCriterion):
3118 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3120 ## Splits volumic elements into tetrahedrons
3121 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3122 # @param method flags passing splitting method:
3123 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3124 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3125 # @ingroup l2_modif_cutquadr
3126 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3127 unRegister = genObjUnRegister()
3128 if isinstance( elems, Mesh ):
3129 elems = elems.GetMesh()
3130 if ( isinstance( elems, list )):
3131 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3132 unRegister.set( elems )
3133 self.editor.SplitVolumesIntoTetra(elems, method)
3135 ## Splits hexahedra into prisms
3136 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3137 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3138 # gives a normal vector defining facets to split into triangles.
3139 # @a startHexPoint can be either a triple of coordinates or a vertex.
3140 # @param facetNormal a normal to a facet to split into triangles of a
3141 # hexahedron found by @a startHexPoint.
3142 # @a facetNormal can be either a triple of coordinates or an edge.
3143 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3144 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3145 # @param allDomains if @c False, only hexahedra adjacent to one closest
3146 # to @a startHexPoint are split, else @a startHexPoint
3147 # is used to find the facet to split in all domains present in @a elems.
3148 # @ingroup l2_modif_cutquadr
3149 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3150 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3152 unRegister = genObjUnRegister()
3153 if isinstance( elems, Mesh ):
3154 elems = elems.GetMesh()
3155 if ( isinstance( elems, list )):
3156 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3157 unRegister.set( elems )
3160 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3161 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3162 elif isinstance( startHexPoint, list ):
3163 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3166 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3167 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3168 elif isinstance( facetNormal, list ):
3169 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3172 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3174 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3176 ## Splits quadrangle faces near triangular facets of volumes
3178 # @ingroup l1_auxiliary
3179 def SplitQuadsNearTriangularFacets(self):
3180 faces_array = self.GetElementsByType(SMESH.FACE)
3181 for face_id in faces_array:
3182 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3183 quad_nodes = self.mesh.GetElemNodes(face_id)
3184 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3185 isVolumeFound = False
3186 for node1_elem in node1_elems:
3187 if not isVolumeFound:
3188 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3189 nb_nodes = self.GetElemNbNodes(node1_elem)
3190 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3191 volume_elem = node1_elem
3192 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3193 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3194 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3195 isVolumeFound = True
3196 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3197 self.SplitQuad([face_id], False) # diagonal 2-4
3198 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3199 isVolumeFound = True
3200 self.SplitQuad([face_id], True) # diagonal 1-3
3201 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3202 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3203 isVolumeFound = True
3204 self.SplitQuad([face_id], True) # diagonal 1-3
3206 ## @brief Splits hexahedrons into tetrahedrons.
3208 # This operation uses pattern mapping functionality for splitting.
3209 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3210 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3211 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3212 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3213 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3214 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3215 # @return TRUE in case of success, FALSE otherwise.
3216 # @ingroup l1_auxiliary
3217 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3218 # Pattern: 5.---------.6
3223 # (0,0,1) 4.---------.7 * |
3230 # (0,0,0) 0.---------.3
3231 pattern_tetra = "!!! Nb of points: \n 8 \n\
3241 !!! Indices of points of 6 tetras: \n\
3249 pattern = self.smeshpyD.GetPattern()
3250 isDone = pattern.LoadFromFile(pattern_tetra)
3252 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3255 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3256 isDone = pattern.MakeMesh(self.mesh, False, False)
3257 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3259 # split quafrangle faces near triangular facets of volumes
3260 self.SplitQuadsNearTriangularFacets()
3264 ## @brief Split hexahedrons into prisms.
3266 # Uses the pattern mapping functionality for splitting.
3267 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3268 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3269 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3270 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3271 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3272 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3273 # @return TRUE in case of success, FALSE otherwise.
3274 # @ingroup l1_auxiliary
3275 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3276 # Pattern: 5.---------.6
3281 # (0,0,1) 4.---------.7 |
3288 # (0,0,0) 0.---------.3
3289 pattern_prism = "!!! Nb of points: \n 8 \n\
3299 !!! Indices of points of 2 prisms: \n\
3303 pattern = self.smeshpyD.GetPattern()
3304 isDone = pattern.LoadFromFile(pattern_prism)
3306 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3309 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3310 isDone = pattern.MakeMesh(self.mesh, False, False)
3311 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3313 # Splits quafrangle faces near triangular facets of volumes
3314 self.SplitQuadsNearTriangularFacets()
3318 ## Smoothes elements
3319 # @param IDsOfElements the list if ids of elements to smooth
3320 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3321 # Note that nodes built on edges and boundary nodes are always fixed.
3322 # @param MaxNbOfIterations the maximum number of iterations
3323 # @param MaxAspectRatio varies in range [1.0, inf]
3324 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3325 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3326 # @return TRUE in case of success, FALSE otherwise.
3327 # @ingroup l2_modif_smooth
3328 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3329 MaxNbOfIterations, MaxAspectRatio, Method):
3330 if IDsOfElements == []:
3331 IDsOfElements = self.GetElementsId()
3332 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3333 self.mesh.SetParameters(Parameters)
3334 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3335 MaxNbOfIterations, MaxAspectRatio, Method)
3337 ## Smoothes elements which belong to the given object
3338 # @param theObject the object to smooth
3339 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3340 # Note that nodes built on edges and boundary nodes are always fixed.
3341 # @param MaxNbOfIterations the maximum number of iterations
3342 # @param MaxAspectRatio varies in range [1.0, inf]
3343 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3344 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3345 # @return TRUE in case of success, FALSE otherwise.
3346 # @ingroup l2_modif_smooth
3347 def SmoothObject(self, theObject, IDsOfFixedNodes,
3348 MaxNbOfIterations, MaxAspectRatio, Method):
3349 if ( isinstance( theObject, Mesh )):
3350 theObject = theObject.GetMesh()
3351 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3352 MaxNbOfIterations, MaxAspectRatio, Method)
3354 ## Parametrically smoothes the given elements
3355 # @param IDsOfElements the list if ids of elements to smooth
3356 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3357 # Note that nodes built on edges and boundary nodes are always fixed.
3358 # @param MaxNbOfIterations the maximum number of iterations
3359 # @param MaxAspectRatio varies in range [1.0, inf]
3360 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3361 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3362 # @return TRUE in case of success, FALSE otherwise.
3363 # @ingroup l2_modif_smooth
3364 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3365 MaxNbOfIterations, MaxAspectRatio, Method):
3366 if IDsOfElements == []:
3367 IDsOfElements = self.GetElementsId()
3368 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3369 self.mesh.SetParameters(Parameters)
3370 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3371 MaxNbOfIterations, MaxAspectRatio, Method)
3373 ## Parametrically smoothes the elements which belong to the given object
3374 # @param theObject the object to smooth
3375 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3376 # Note that nodes built on edges and boundary nodes are always fixed.
3377 # @param MaxNbOfIterations the maximum number of iterations
3378 # @param MaxAspectRatio varies in range [1.0, inf]
3379 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3380 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3381 # @return TRUE in case of success, FALSE otherwise.
3382 # @ingroup l2_modif_smooth
3383 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3384 MaxNbOfIterations, MaxAspectRatio, Method):
3385 if ( isinstance( theObject, Mesh )):
3386 theObject = theObject.GetMesh()
3387 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3388 MaxNbOfIterations, MaxAspectRatio, Method)
3390 ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3391 # them with quadratic with the same id.
3392 # @param theForce3d new node creation method:
3393 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3394 # 1 - the medium node lies at the middle of the line segments connecting start and end node of a mesh element
3395 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3396 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3397 # @ingroup l2_modif_tofromqu
3398 def ConvertToQuadratic(self, theForce3d, theSubMesh=None, theToBiQuad=False):
3399 if isinstance( theSubMesh, Mesh ):
3400 theSubMesh = theSubMesh.mesh
3402 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3405 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3407 self.editor.ConvertToQuadratic(theForce3d)
3408 error = self.editor.GetLastError()
3409 if error and error.comment:
3412 ## Converts the mesh from quadratic to ordinary,
3413 # deletes old quadratic elements, \n replacing
3414 # them with ordinary mesh elements with the same id.
3415 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3416 # @ingroup l2_modif_tofromqu
3417 def ConvertFromQuadratic(self, theSubMesh=None):
3419 self.editor.ConvertFromQuadraticObject(theSubMesh)
3421 return self.editor.ConvertFromQuadratic()
3423 ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3424 # @return TRUE if operation has been completed successfully, FALSE otherwise
3425 # @ingroup l2_modif_edit
3426 def Make2DMeshFrom3D(self):
3427 return self.editor. Make2DMeshFrom3D()
3429 ## Creates missing boundary elements
3430 # @param elements - elements whose boundary is to be checked:
3431 # mesh, group, sub-mesh or list of elements
3432 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3433 # @param dimension - defines type of boundary elements to create:
3434 # SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D
3435 # SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3436 # @param groupName - a name of group to store created boundary elements in,
3437 # "" means not to create the group
3438 # @param meshName - a name of new mesh to store created boundary elements in,
3439 # "" means not to create the new mesh
3440 # @param toCopyElements - if true, the checked elements will be copied into
3441 # the new mesh else only boundary elements will be copied into the new mesh
3442 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3443 # boundary elements will be copied into the new mesh
3444 # @return tuple (mesh, group) where boundary elements were added to
3445 # @ingroup l2_modif_edit
3446 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3447 toCopyElements=False, toCopyExistingBondary=False):
3448 unRegister = genObjUnRegister()
3449 if isinstance( elements, Mesh ):
3450 elements = elements.GetMesh()
3451 if ( isinstance( elements, list )):
3452 elemType = SMESH.ALL
3453 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3454 elements = self.editor.MakeIDSource(elements, elemType)
3455 unRegister.set( elements )
3456 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3457 toCopyElements,toCopyExistingBondary)
3458 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3462 # @brief Creates missing boundary elements around either the whole mesh or
3463 # groups of 2D elements
3464 # @param dimension - defines type of boundary elements to create
3465 # @param groupName - a name of group to store all boundary elements in,
3466 # "" means not to create the group
3467 # @param meshName - a name of a new mesh, which is a copy of the initial
3468 # mesh + created boundary elements; "" means not to create the new mesh
3469 # @param toCopyAll - if true, the whole initial mesh will be copied into
3470 # the new mesh else only boundary elements will be copied into the new mesh
3471 # @param groups - groups of 2D elements to make boundary around
3472 # @retval tuple( long, mesh, groups )
3473 # long - number of added boundary elements
3474 # mesh - the mesh where elements were added to
3475 # group - the group of boundary elements or None
3477 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3478 toCopyAll=False, groups=[]):
3479 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3481 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3482 return nb, mesh, group
3484 ## Renumber mesh nodes
3485 # @ingroup l2_modif_renumber
3486 def RenumberNodes(self):
3487 self.editor.RenumberNodes()
3489 ## Renumber mesh elements
3490 # @ingroup l2_modif_renumber
3491 def RenumberElements(self):
3492 self.editor.RenumberElements()
3494 ## Generates new elements by rotation of the elements around the axis
3495 # @param IDsOfElements the list of ids of elements to sweep
3496 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3497 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3498 # @param NbOfSteps the number of steps
3499 # @param Tolerance tolerance
3500 # @param MakeGroups forces the generation of new groups from existing ones
3501 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3502 # of all steps, else - size of each step
3503 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3504 # @ingroup l2_modif_extrurev
3505 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3506 MakeGroups=False, TotalAngle=False):
3507 if IDsOfElements == []:
3508 IDsOfElements = self.GetElementsId()
3509 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3510 Axis = self.smeshpyD.GetAxisStruct(Axis)
3511 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3512 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3513 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3514 self.mesh.SetParameters(Parameters)
3515 if TotalAngle and NbOfSteps:
3516 AngleInRadians /= NbOfSteps
3518 return self.editor.RotationSweepMakeGroups(IDsOfElements, Axis,
3519 AngleInRadians, NbOfSteps, Tolerance)
3520 self.editor.RotationSweep(IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance)
3523 ## Generates new elements by rotation of the elements of object around the axis
3524 # @param theObject object which elements should be sweeped.
3525 # It can be a mesh, a sub mesh or a group.
3526 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3527 # @param AngleInRadians the angle of Rotation
3528 # @param NbOfSteps number of steps
3529 # @param Tolerance tolerance
3530 # @param MakeGroups forces the generation of new groups from existing ones
3531 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3532 # of all steps, else - size of each step
3533 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3534 # @ingroup l2_modif_extrurev
3535 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3536 MakeGroups=False, TotalAngle=False):
3537 if ( isinstance( theObject, Mesh )):
3538 theObject = theObject.GetMesh()
3539 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3540 Axis = self.smeshpyD.GetAxisStruct(Axis)
3541 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3542 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3543 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3544 self.mesh.SetParameters(Parameters)
3545 if TotalAngle and NbOfSteps:
3546 AngleInRadians /= NbOfSteps
3548 return self.editor.RotationSweepObjectMakeGroups(theObject, Axis, AngleInRadians,
3549 NbOfSteps, Tolerance)
3550 self.editor.RotationSweepObject(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3553 ## Generates new elements by rotation of the elements of object around the axis
3554 # @param theObject object which elements should be sweeped.
3555 # It can be a mesh, a sub mesh or a group.
3556 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3557 # @param AngleInRadians the angle of Rotation
3558 # @param NbOfSteps number of steps
3559 # @param Tolerance tolerance
3560 # @param MakeGroups forces the generation of new groups from existing ones
3561 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3562 # of all steps, else - size of each step
3563 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3564 # @ingroup l2_modif_extrurev
3565 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3566 MakeGroups=False, TotalAngle=False):
3567 if ( isinstance( theObject, Mesh )):
3568 theObject = theObject.GetMesh()
3569 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3570 Axis = self.smeshpyD.GetAxisStruct(Axis)
3571 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3572 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3573 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3574 self.mesh.SetParameters(Parameters)
3575 if TotalAngle and NbOfSteps:
3576 AngleInRadians /= NbOfSteps
3578 return self.editor.RotationSweepObject1DMakeGroups(theObject, Axis, AngleInRadians,
3579 NbOfSteps, Tolerance)
3580 self.editor.RotationSweepObject1D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3583 ## Generates new elements by rotation of the elements of object around the axis
3584 # @param theObject object which elements should be sweeped.
3585 # It can be a mesh, a sub mesh or a group.
3586 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3587 # @param AngleInRadians the angle of Rotation
3588 # @param NbOfSteps number of steps
3589 # @param Tolerance tolerance
3590 # @param MakeGroups forces the generation of new groups from existing ones
3591 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3592 # of all steps, else - size of each step
3593 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3594 # @ingroup l2_modif_extrurev
3595 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3596 MakeGroups=False, TotalAngle=False):
3597 if ( isinstance( theObject, Mesh )):
3598 theObject = theObject.GetMesh()
3599 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3600 Axis = self.smeshpyD.GetAxisStruct(Axis)
3601 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3602 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3603 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3604 self.mesh.SetParameters(Parameters)
3605 if TotalAngle and NbOfSteps:
3606 AngleInRadians /= NbOfSteps
3608 return self.editor.RotationSweepObject2DMakeGroups(theObject, Axis, AngleInRadians,
3609 NbOfSteps, Tolerance)
3610 self.editor.RotationSweepObject2D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3613 ## Generates new elements by extrusion of the elements with given ids
3614 # @param IDsOfElements the list of elements ids for extrusion
3615 # @param StepVector vector or DirStruct or 3 vector components, defining
3616 # the direction and value of extrusion for one step (the total extrusion
3617 # length will be NbOfSteps * ||StepVector||)
3618 # @param NbOfSteps the number of steps
3619 # @param MakeGroups forces the generation of new groups from existing ones
3620 # @param IsNodes is True if elements with given ids are nodes
3621 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3622 # @ingroup l2_modif_extrurev
3623 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3624 if IDsOfElements == []:
3625 IDsOfElements = self.GetElementsId()
3626 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3627 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3628 if isinstance( StepVector, list ):
3629 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3630 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3631 Parameters = StepVector.PS.parameters + var_separator + Parameters
3632 self.mesh.SetParameters(Parameters)
3635 return self.editor.ExtrusionSweepMakeGroups0D(IDsOfElements, StepVector, NbOfSteps)
3637 return self.editor.ExtrusionSweepMakeGroups(IDsOfElements, StepVector, NbOfSteps)
3639 self.editor.ExtrusionSweep0D(IDsOfElements, StepVector, NbOfSteps)
3641 self.editor.ExtrusionSweep(IDsOfElements, StepVector, NbOfSteps)
3644 ## Generates new elements by extrusion of the elements with given ids
3645 # @param IDsOfElements is ids of elements
3646 # @param StepVector vector or DirStruct or 3 vector components, defining
3647 # the direction and value of extrusion for one step (the total extrusion
3648 # length will be NbOfSteps * ||StepVector||)
3649 # @param NbOfSteps the number of steps
3650 # @param ExtrFlags sets flags for extrusion
3651 # @param SewTolerance uses for comparing locations of nodes if flag
3652 # EXTRUSION_FLAG_SEW is set
3653 # @param MakeGroups forces the generation of new groups from existing ones
3654 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3655 # @ingroup l2_modif_extrurev
3656 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3657 ExtrFlags, SewTolerance, MakeGroups=False):
3658 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3659 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3660 if isinstance( StepVector, list ):
3661 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3663 return self.editor.AdvancedExtrusionMakeGroups(IDsOfElements, StepVector, NbOfSteps,
3664 ExtrFlags, SewTolerance)
3665 self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3666 ExtrFlags, SewTolerance)
3669 ## Generates new elements by extrusion of the elements which belong to the object
3670 # @param theObject the object which elements should be processed.
3671 # It can be a mesh, a sub mesh or a group.
3672 # @param StepVector vector or DirStruct or 3 vector components, defining
3673 # the direction and value of extrusion for one step (the total extrusion
3674 # length will be NbOfSteps * ||StepVector||)
3675 # @param NbOfSteps the number of steps
3676 # @param MakeGroups forces the generation of new groups from existing ones
3677 # @param IsNodes is True if elements which belong to the object are nodes
3678 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3679 # @ingroup l2_modif_extrurev
3680 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3681 if ( isinstance( theObject, Mesh )):
3682 theObject = theObject.GetMesh()
3683 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3684 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3685 if isinstance( StepVector, list ):
3686 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3687 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3688 Parameters = StepVector.PS.parameters + var_separator + Parameters
3689 self.mesh.SetParameters(Parameters)
3692 return self.editor.ExtrusionSweepObject0DMakeGroups(theObject, StepVector, NbOfSteps)
3694 return self.editor.ExtrusionSweepObjectMakeGroups(theObject, StepVector, NbOfSteps)
3696 self.editor.ExtrusionSweepObject0D(theObject, StepVector, NbOfSteps)
3698 self.editor.ExtrusionSweepObject(theObject, StepVector, NbOfSteps)
3701 ## Generates new elements by extrusion of the elements which belong to the object
3702 # @param theObject object which elements should be processed.
3703 # It can be a mesh, a sub mesh or a group.
3704 # @param StepVector vector or DirStruct or 3 vector components, defining
3705 # the direction and value of extrusion for one step (the total extrusion
3706 # length will be NbOfSteps * ||StepVector||)
3707 # @param NbOfSteps the number of steps
3708 # @param MakeGroups to generate new groups from existing ones
3709 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3710 # @ingroup l2_modif_extrurev
3711 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3712 if ( isinstance( theObject, Mesh )):
3713 theObject = theObject.GetMesh()
3714 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3715 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3716 if isinstance( StepVector, list ):
3717 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3718 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3719 Parameters = StepVector.PS.parameters + var_separator + Parameters
3720 self.mesh.SetParameters(Parameters)
3722 return self.editor.ExtrusionSweepObject1DMakeGroups(theObject, StepVector, NbOfSteps)
3723 self.editor.ExtrusionSweepObject1D(theObject, StepVector, NbOfSteps)
3726 ## Generates new elements by extrusion of the elements which belong to the object
3727 # @param theObject object which elements should be processed.
3728 # It can be a mesh, a sub mesh or a group.
3729 # @param StepVector vector or DirStruct or 3 vector components, defining
3730 # the direction and value of extrusion for one step (the total extrusion
3731 # length will be NbOfSteps * ||StepVector||)
3732 # @param NbOfSteps the number of steps
3733 # @param MakeGroups forces the generation of new groups from existing ones
3734 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3735 # @ingroup l2_modif_extrurev
3736 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3737 if ( isinstance( theObject, Mesh )):
3738 theObject = theObject.GetMesh()
3739 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3740 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3741 if isinstance( StepVector, list ):
3742 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3743 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3744 Parameters = StepVector.PS.parameters + var_separator + Parameters
3745 self.mesh.SetParameters(Parameters)
3747 return self.editor.ExtrusionSweepObject2DMakeGroups(theObject, StepVector, NbOfSteps)
3748 self.editor.ExtrusionSweepObject2D(theObject, StepVector, NbOfSteps)
3753 ## Generates new elements by extrusion of the given elements
3754 # The path of extrusion must be a meshed edge.
3755 # @param Base mesh or group, or submesh, or list of ids of elements for extrusion
3756 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3757 # @param NodeStart the start node from Path. Defines the direction of extrusion
3758 # @param HasAngles allows the shape to be rotated around the path
3759 # to get the resulting mesh in a helical fashion
3760 # @param Angles list of angles in radians
3761 # @param LinearVariation forces the computation of rotation angles as linear
3762 # variation of the given Angles along path steps
3763 # @param HasRefPoint allows using the reference point
3764 # @param RefPoint the point around which the elements are rotated (the mass
3765 # center of the elements by default).
3766 # The User can specify any point as the Reference Point.
3767 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
3768 # @param MakeGroups forces the generation of new groups from existing ones
3769 # @param ElemType type of elements for extrusion (if param Base is a mesh)
3770 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3771 # only SMESH::Extrusion_Error otherwise
3772 # @ingroup l2_modif_extrurev
3773 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
3774 HasAngles, Angles, LinearVariation,
3775 HasRefPoint, RefPoint, MakeGroups, ElemType):
3776 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3777 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3779 elif isinstance( RefPoint, list ):
3780 RefPoint = PointStruct(*RefPoint)
3782 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3783 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3784 self.mesh.SetParameters(Parameters)
3786 if (isinstance(Path, Mesh)): Path = Path.GetMesh()
3788 if isinstance(Base, list):
3790 if Base == []: IDsOfElements = self.GetElementsId()
3791 else: IDsOfElements = Base
3792 return self.editor.ExtrusionAlongPathX(IDsOfElements, Path, NodeStart,
3793 HasAngles, Angles, LinearVariation,
3794 HasRefPoint, RefPoint, MakeGroups, ElemType)
3796 if isinstance(Base, Mesh): Base = Base.GetMesh()
3797 if isinstance(Base, SMESH._objref_SMESH_Mesh) or isinstance(Base, SMESH._objref_SMESH_Group) or isinstance(Base, SMESH._objref_SMESH_subMesh):
3798 return self.editor.ExtrusionAlongPathObjX(Base, Path, NodeStart,
3799 HasAngles, Angles, LinearVariation,
3800 HasRefPoint, RefPoint, MakeGroups, ElemType)
3802 raise RuntimeError, "Invalid Base for ExtrusionAlongPathX"
3805 ## Generates new elements by extrusion of the given elements
3806 # The path of extrusion must be a meshed edge.
3807 # @param IDsOfElements ids of elements
3808 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
3809 # @param PathShape shape(edge) defines the sub-mesh for the path
3810 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3811 # @param HasAngles allows the shape to be rotated around the path
3812 # to get the resulting mesh in a helical fashion
3813 # @param Angles list of angles in radians
3814 # @param HasRefPoint allows using the reference point
3815 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3816 # The User can specify any point as the Reference Point.
3817 # @param MakeGroups forces the generation of new groups from existing ones
3818 # @param LinearVariation forces the computation of rotation angles as linear
3819 # variation of the given Angles along path steps
3820 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3821 # only SMESH::Extrusion_Error otherwise
3822 # @ingroup l2_modif_extrurev
3823 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
3824 HasAngles, Angles, HasRefPoint, RefPoint,
3825 MakeGroups=False, LinearVariation=False):
3826 if IDsOfElements == []:
3827 IDsOfElements = self.GetElementsId()
3828 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3829 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3831 if ( isinstance( PathMesh, Mesh )):
3832 PathMesh = PathMesh.GetMesh()
3833 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3834 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3835 self.mesh.SetParameters(Parameters)
3836 if HasAngles and Angles and LinearVariation:
3837 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3840 return self.editor.ExtrusionAlongPathMakeGroups(IDsOfElements, PathMesh,
3841 PathShape, NodeStart, HasAngles,
3842 Angles, HasRefPoint, RefPoint)
3843 return self.editor.ExtrusionAlongPath(IDsOfElements, PathMesh, PathShape,
3844 NodeStart, HasAngles, Angles, HasRefPoint, RefPoint)
3846 ## Generates new elements by extrusion of the elements which belong to the object
3847 # The path of extrusion must be a meshed edge.
3848 # @param theObject the object which elements should be processed.
3849 # It can be a mesh, a sub mesh or a group.
3850 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3851 # @param PathShape shape(edge) defines the sub-mesh for the path
3852 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3853 # @param HasAngles allows the shape to be rotated around the path
3854 # to get the resulting mesh in a helical fashion
3855 # @param Angles list of angles
3856 # @param HasRefPoint allows using the reference point
3857 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3858 # The User can specify any point as the Reference Point.
3859 # @param MakeGroups forces the generation of new groups from existing ones
3860 # @param LinearVariation forces the computation of rotation angles as linear
3861 # variation of the given Angles along path steps
3862 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3863 # only SMESH::Extrusion_Error otherwise
3864 # @ingroup l2_modif_extrurev
3865 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
3866 HasAngles, Angles, HasRefPoint, RefPoint,
3867 MakeGroups=False, LinearVariation=False):
3868 if ( isinstance( theObject, Mesh )):
3869 theObject = theObject.GetMesh()
3870 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3871 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3872 if ( isinstance( PathMesh, Mesh )):
3873 PathMesh = PathMesh.GetMesh()
3874 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3875 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3876 self.mesh.SetParameters(Parameters)
3877 if HasAngles and Angles and LinearVariation:
3878 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3881 return self.editor.ExtrusionAlongPathObjectMakeGroups(theObject, PathMesh,
3882 PathShape, NodeStart, HasAngles,
3883 Angles, HasRefPoint, RefPoint)
3884 return self.editor.ExtrusionAlongPathObject(theObject, PathMesh, PathShape,
3885 NodeStart, HasAngles, Angles, HasRefPoint,
3888 ## Generates new elements by extrusion of the elements which belong to the object
3889 # The path of extrusion must be a meshed edge.
3890 # @param theObject the object which elements should be processed.
3891 # It can be a mesh, a sub mesh or a group.
3892 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3893 # @param PathShape shape(edge) defines the sub-mesh for the path
3894 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3895 # @param HasAngles allows the shape to be rotated around the path
3896 # to get the resulting mesh in a helical fashion
3897 # @param Angles list of angles
3898 # @param HasRefPoint allows using the reference point
3899 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3900 # The User can specify any point as the Reference Point.
3901 # @param MakeGroups forces the generation of new groups from existing ones
3902 # @param LinearVariation forces the computation of rotation angles as linear
3903 # variation of the given Angles along path steps
3904 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3905 # only SMESH::Extrusion_Error otherwise
3906 # @ingroup l2_modif_extrurev
3907 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
3908 HasAngles, Angles, HasRefPoint, RefPoint,
3909 MakeGroups=False, LinearVariation=False):
3910 if ( isinstance( theObject, Mesh )):
3911 theObject = theObject.GetMesh()
3912 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3913 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3914 if ( isinstance( PathMesh, Mesh )):
3915 PathMesh = PathMesh.GetMesh()
3916 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3917 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3918 self.mesh.SetParameters(Parameters)
3919 if HasAngles and Angles and LinearVariation:
3920 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3923 return self.editor.ExtrusionAlongPathObject1DMakeGroups(theObject, PathMesh,
3924 PathShape, NodeStart, HasAngles,
3925 Angles, HasRefPoint, RefPoint)
3926 return self.editor.ExtrusionAlongPathObject1D(theObject, PathMesh, PathShape,
3927 NodeStart, HasAngles, Angles, HasRefPoint,
3930 ## Generates new elements by extrusion of the elements which belong to the object
3931 # The path of extrusion must be a meshed edge.
3932 # @param theObject the object which elements should be processed.
3933 # It can be a mesh, a sub mesh or a group.
3934 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3935 # @param PathShape shape(edge) defines the sub-mesh for the path
3936 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3937 # @param HasAngles allows the shape to be rotated around the path
3938 # to get the resulting mesh in a helical fashion
3939 # @param Angles list of angles
3940 # @param HasRefPoint allows using the reference point
3941 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3942 # The User can specify any point as the Reference Point.
3943 # @param MakeGroups forces the generation of new groups from existing ones
3944 # @param LinearVariation forces the computation of rotation angles as linear
3945 # variation of the given Angles along path steps
3946 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3947 # only SMESH::Extrusion_Error otherwise
3948 # @ingroup l2_modif_extrurev
3949 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
3950 HasAngles, Angles, HasRefPoint, RefPoint,
3951 MakeGroups=False, LinearVariation=False):
3952 if ( isinstance( theObject, Mesh )):
3953 theObject = theObject.GetMesh()
3954 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3955 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3956 if ( isinstance( PathMesh, Mesh )):
3957 PathMesh = PathMesh.GetMesh()
3958 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3959 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3960 self.mesh.SetParameters(Parameters)
3961 if HasAngles and Angles and LinearVariation:
3962 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3965 return self.editor.ExtrusionAlongPathObject2DMakeGroups(theObject, PathMesh,
3966 PathShape, NodeStart, HasAngles,
3967 Angles, HasRefPoint, RefPoint)
3968 return self.editor.ExtrusionAlongPathObject2D(theObject, PathMesh, PathShape,
3969 NodeStart, HasAngles, Angles, HasRefPoint,
3972 ## Creates a symmetrical copy of mesh elements
3973 # @param IDsOfElements list of elements ids
3974 # @param Mirror is AxisStruct or geom object(point, line, plane)
3975 # @param theMirrorType is POINT, AXIS or PLANE
3976 # If the Mirror is a geom object this parameter is unnecessary
3977 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
3978 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3979 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3980 # @ingroup l2_modif_trsf
3981 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
3982 if IDsOfElements == []:
3983 IDsOfElements = self.GetElementsId()
3984 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3985 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3986 theMirrorType = Mirror._mirrorType
3988 self.mesh.SetParameters(Mirror.parameters)
3989 if Copy and MakeGroups:
3990 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
3991 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
3994 ## Creates a new mesh by a symmetrical copy of mesh elements
3995 # @param IDsOfElements the list of elements ids
3996 # @param Mirror is AxisStruct or geom object (point, line, plane)
3997 # @param theMirrorType is POINT, AXIS or PLANE
3998 # If the Mirror is a geom object this parameter is unnecessary
3999 # @param MakeGroups to generate new groups from existing ones
4000 # @param NewMeshName a name of the new mesh to create
4001 # @return instance of Mesh class
4002 # @ingroup l2_modif_trsf
4003 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4004 if IDsOfElements == []:
4005 IDsOfElements = self.GetElementsId()
4006 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4007 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4008 theMirrorType = Mirror._mirrorType
4010 self.mesh.SetParameters(Mirror.parameters)
4011 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4012 MakeGroups, NewMeshName)
4013 return Mesh(self.smeshpyD,self.geompyD,mesh)
4015 ## Creates a symmetrical copy of the object
4016 # @param theObject mesh, submesh or group
4017 # @param Mirror AxisStruct or geom object (point, line, plane)
4018 # @param theMirrorType is POINT, AXIS or PLANE
4019 # If the Mirror is a geom object this parameter is unnecessary
4020 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4021 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4022 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4023 # @ingroup l2_modif_trsf
4024 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4025 if ( isinstance( theObject, Mesh )):
4026 theObject = theObject.GetMesh()
4027 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4028 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4029 theMirrorType = Mirror._mirrorType
4031 self.mesh.SetParameters(Mirror.parameters)
4032 if Copy and MakeGroups:
4033 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4034 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4037 ## Creates a new mesh by a symmetrical copy of the object
4038 # @param theObject mesh, submesh or group
4039 # @param Mirror AxisStruct or geom object (point, line, plane)
4040 # @param theMirrorType POINT, AXIS or PLANE
4041 # If the Mirror is a geom object this parameter is unnecessary
4042 # @param MakeGroups forces the generation of new groups from existing ones
4043 # @param NewMeshName the name of the new mesh to create
4044 # @return instance of Mesh class
4045 # @ingroup l2_modif_trsf
4046 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4047 if ( isinstance( theObject, Mesh )):
4048 theObject = theObject.GetMesh()
4049 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4050 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4051 theMirrorType = Mirror._mirrorType
4053 self.mesh.SetParameters(Mirror.parameters)
4054 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4055 MakeGroups, NewMeshName)
4056 return Mesh( self.smeshpyD,self.geompyD,mesh )
4058 ## Translates the elements
4059 # @param IDsOfElements list of elements ids
4060 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4061 # @param Copy allows copying the translated elements
4062 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4063 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4064 # @ingroup l2_modif_trsf
4065 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4066 if IDsOfElements == []:
4067 IDsOfElements = self.GetElementsId()
4068 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4069 Vector = self.smeshpyD.GetDirStruct(Vector)
4070 if isinstance( Vector, list ):
4071 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4072 self.mesh.SetParameters(Vector.PS.parameters)
4073 if Copy and MakeGroups:
4074 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4075 self.editor.Translate(IDsOfElements, Vector, Copy)
4078 ## Creates a new mesh of translated elements
4079 # @param IDsOfElements list of elements ids
4080 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4081 # @param MakeGroups forces the generation of new groups from existing ones
4082 # @param NewMeshName the name of the newly created mesh
4083 # @return instance of Mesh class
4084 # @ingroup l2_modif_trsf
4085 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4086 if IDsOfElements == []:
4087 IDsOfElements = self.GetElementsId()
4088 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4089 Vector = self.smeshpyD.GetDirStruct(Vector)
4090 if isinstance( Vector, list ):
4091 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4092 self.mesh.SetParameters(Vector.PS.parameters)
4093 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4094 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4096 ## Translates the object
4097 # @param theObject the object to translate (mesh, submesh, or group)
4098 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4099 # @param Copy allows copying the translated elements
4100 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4101 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4102 # @ingroup l2_modif_trsf
4103 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4104 if ( isinstance( theObject, Mesh )):
4105 theObject = theObject.GetMesh()
4106 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4107 Vector = self.smeshpyD.GetDirStruct(Vector)
4108 if isinstance( Vector, list ):
4109 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4110 self.mesh.SetParameters(Vector.PS.parameters)
4111 if Copy and MakeGroups:
4112 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4113 self.editor.TranslateObject(theObject, Vector, Copy)
4116 ## Creates a new mesh from the translated object
4117 # @param theObject the object to translate (mesh, submesh, or group)
4118 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4119 # @param MakeGroups forces the generation of new groups from existing ones
4120 # @param NewMeshName the name of the newly created mesh
4121 # @return instance of Mesh class
4122 # @ingroup l2_modif_trsf
4123 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4124 if isinstance( theObject, Mesh ):
4125 theObject = theObject.GetMesh()
4126 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4127 Vector = self.smeshpyD.GetDirStruct(Vector)
4128 if isinstance( Vector, list ):
4129 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4130 self.mesh.SetParameters(Vector.PS.parameters)
4131 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4132 return Mesh( self.smeshpyD, self.geompyD, mesh )
4136 ## Scales the object
4137 # @param theObject - the object to translate (mesh, submesh, or group)
4138 # @param thePoint - base point for scale
4139 # @param theScaleFact - list of 1-3 scale factors for axises
4140 # @param Copy - allows copying the translated elements
4141 # @param MakeGroups - forces the generation of new groups from existing
4143 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4144 # empty list otherwise
4145 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4146 unRegister = genObjUnRegister()
4147 if ( isinstance( theObject, Mesh )):
4148 theObject = theObject.GetMesh()
4149 if ( isinstance( theObject, list )):
4150 theObject = self.GetIDSource(theObject, SMESH.ALL)
4151 unRegister.set( theObject )
4152 if ( isinstance( theScaleFact, float )):
4153 theScaleFact = [theScaleFact]
4154 if ( isinstance( theScaleFact, int )):
4155 theScaleFact = [ float(theScaleFact)]
4157 self.mesh.SetParameters(thePoint.parameters)
4159 if Copy and MakeGroups:
4160 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4161 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4164 ## Creates a new mesh from the translated object
4165 # @param theObject - the object to translate (mesh, submesh, or group)
4166 # @param thePoint - base point for scale
4167 # @param theScaleFact - list of 1-3 scale factors for axises
4168 # @param MakeGroups - forces the generation of new groups from existing ones
4169 # @param NewMeshName - the name of the newly created mesh
4170 # @return instance of Mesh class
4171 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4172 unRegister = genObjUnRegister()
4173 if (isinstance(theObject, Mesh)):
4174 theObject = theObject.GetMesh()
4175 if ( isinstance( theObject, list )):
4176 theObject = self.GetIDSource(theObject,SMESH.ALL)
4177 unRegister.set( theObject )
4178 if ( isinstance( theScaleFact, float )):
4179 theScaleFact = [theScaleFact]
4180 if ( isinstance( theScaleFact, int )):
4181 theScaleFact = [ float(theScaleFact)]
4183 self.mesh.SetParameters(thePoint.parameters)
4184 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4185 MakeGroups, NewMeshName)
4186 return Mesh( self.smeshpyD, self.geompyD, mesh )
4190 ## Rotates the elements
4191 # @param IDsOfElements list of elements ids
4192 # @param Axis the axis of rotation (AxisStruct or geom line)
4193 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4194 # @param Copy allows copying the rotated elements
4195 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4196 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4197 # @ingroup l2_modif_trsf
4198 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4199 if IDsOfElements == []:
4200 IDsOfElements = self.GetElementsId()
4201 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4202 Axis = self.smeshpyD.GetAxisStruct(Axis)
4203 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4204 Parameters = Axis.parameters + var_separator + Parameters
4205 self.mesh.SetParameters(Parameters)
4206 if Copy and MakeGroups:
4207 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4208 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4211 ## Creates a new mesh of rotated elements
4212 # @param IDsOfElements list of element ids
4213 # @param Axis the axis of rotation (AxisStruct or geom line)
4214 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4215 # @param MakeGroups forces the generation of new groups from existing ones
4216 # @param NewMeshName the name of the newly created mesh
4217 # @return instance of Mesh class
4218 # @ingroup l2_modif_trsf
4219 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4220 if IDsOfElements == []:
4221 IDsOfElements = self.GetElementsId()
4222 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4223 Axis = self.smeshpyD.GetAxisStruct(Axis)
4224 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4225 Parameters = Axis.parameters + var_separator + Parameters
4226 self.mesh.SetParameters(Parameters)
4227 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4228 MakeGroups, NewMeshName)
4229 return Mesh( self.smeshpyD, self.geompyD, mesh )
4231 ## Rotates the object
4232 # @param theObject the object to rotate( mesh, submesh, or group)
4233 # @param Axis the axis of rotation (AxisStruct or geom line)
4234 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4235 # @param Copy allows copying the rotated elements
4236 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4237 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4238 # @ingroup l2_modif_trsf
4239 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4240 if (isinstance(theObject, Mesh)):
4241 theObject = theObject.GetMesh()
4242 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4243 Axis = self.smeshpyD.GetAxisStruct(Axis)
4244 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4245 Parameters = Axis.parameters + ":" + Parameters
4246 self.mesh.SetParameters(Parameters)
4247 if Copy and MakeGroups:
4248 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4249 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4252 ## Creates a new mesh from the rotated object
4253 # @param theObject the object to rotate (mesh, submesh, or group)
4254 # @param Axis the axis of rotation (AxisStruct or geom line)
4255 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4256 # @param MakeGroups forces the generation of new groups from existing ones
4257 # @param NewMeshName the name of the newly created mesh
4258 # @return instance of Mesh class
4259 # @ingroup l2_modif_trsf
4260 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4261 if (isinstance( theObject, Mesh )):
4262 theObject = theObject.GetMesh()
4263 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4264 Axis = self.smeshpyD.GetAxisStruct(Axis)
4265 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4266 Parameters = Axis.parameters + ":" + Parameters
4267 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4268 MakeGroups, NewMeshName)
4269 self.mesh.SetParameters(Parameters)
4270 return Mesh( self.smeshpyD, self.geompyD, mesh )
4272 ## Finds groups of adjacent nodes within Tolerance.
4273 # @param Tolerance the value of tolerance
4274 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4275 # @ingroup l2_modif_trsf
4276 def FindCoincidentNodes (self, Tolerance):
4277 return self.editor.FindCoincidentNodes(Tolerance)
4279 ## Finds groups of ajacent nodes within Tolerance.
4280 # @param Tolerance the value of tolerance
4281 # @param SubMeshOrGroup SubMesh or Group
4282 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4283 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4284 # @ingroup l2_modif_trsf
4285 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance, exceptNodes=[]):
4286 unRegister = genObjUnRegister()
4287 if (isinstance( SubMeshOrGroup, Mesh )):
4288 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4289 if not isinstance( exceptNodes, list):
4290 exceptNodes = [ exceptNodes ]
4291 if exceptNodes and isinstance( exceptNodes[0], int):
4292 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE)]
4293 unRegister.set( exceptNodes )
4294 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,exceptNodes)
4297 # @param GroupsOfNodes a list of pairs of nodes IDs for merging (e.g. [[1,12],[25,4]])
4298 # @ingroup l2_modif_trsf
4299 def MergeNodes (self, GroupsOfNodes):
4300 self.editor.MergeNodes(GroupsOfNodes)
4302 ## Finds the elements built on the same nodes.
4303 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4304 # @return the list of pairs of equal elements IDs (e.g. [[1,12],[25,4]])
4305 # @ingroup l2_modif_trsf
4306 def FindEqualElements (self, MeshOrSubMeshOrGroup):
4307 if ( isinstance( MeshOrSubMeshOrGroup, Mesh )):
4308 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4309 return self.editor.FindEqualElements(MeshOrSubMeshOrGroup)
4311 ## Merges elements in each given group.
4312 # @param GroupsOfElementsID a list of pairs of elements IDs for merging (e.g. [[1,12],[25,4]])
4313 # @ingroup l2_modif_trsf
4314 def MergeElements(self, GroupsOfElementsID):
4315 self.editor.MergeElements(GroupsOfElementsID)
4317 ## Leaves one element and removes all other elements built on the same nodes.
4318 # @ingroup l2_modif_trsf
4319 def MergeEqualElements(self):
4320 self.editor.MergeEqualElements()
4322 ## Sews free borders
4323 # @return SMESH::Sew_Error
4324 # @ingroup l2_modif_trsf
4325 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4326 FirstNodeID2, SecondNodeID2, LastNodeID2,
4327 CreatePolygons, CreatePolyedrs):
4328 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4329 FirstNodeID2, SecondNodeID2, LastNodeID2,
4330 CreatePolygons, CreatePolyedrs)
4332 ## Sews conform free borders
4333 # @return SMESH::Sew_Error
4334 # @ingroup l2_modif_trsf
4335 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4336 FirstNodeID2, SecondNodeID2):
4337 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4338 FirstNodeID2, SecondNodeID2)
4340 ## Sews border to side
4341 # @return SMESH::Sew_Error
4342 # @ingroup l2_modif_trsf
4343 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4344 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4345 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4346 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4348 ## Sews two sides of a mesh. The nodes belonging to Side1 are
4349 # merged with the nodes of elements of Side2.
4350 # The number of elements in theSide1 and in theSide2 must be
4351 # equal and they should have similar nodal connectivity.
4352 # The nodes to merge should belong to side borders and
4353 # the first node should be linked to the second.
4354 # @return SMESH::Sew_Error
4355 # @ingroup l2_modif_trsf
4356 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4357 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4358 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4359 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4360 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4361 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4363 ## Sets new nodes for the given element.
4364 # @param ide the element id
4365 # @param newIDs nodes ids
4366 # @return If the number of nodes does not correspond to the type of element - returns false
4367 # @ingroup l2_modif_edit
4368 def ChangeElemNodes(self, ide, newIDs):
4369 return self.editor.ChangeElemNodes(ide, newIDs)
4371 ## If during the last operation of MeshEditor some nodes were
4372 # created, this method returns the list of their IDs, \n
4373 # if new nodes were not created - returns empty list
4374 # @return the list of integer values (can be empty)
4375 # @ingroup l1_auxiliary
4376 def GetLastCreatedNodes(self):
4377 return self.editor.GetLastCreatedNodes()
4379 ## If during the last operation of MeshEditor some elements were
4380 # created this method returns the list of their IDs, \n
4381 # if new elements were not created - returns empty list
4382 # @return the list of integer values (can be empty)
4383 # @ingroup l1_auxiliary
4384 def GetLastCreatedElems(self):
4385 return self.editor.GetLastCreatedElems()
4387 ## Clears sequences of nodes and elements created by mesh edition oparations
4388 # @ingroup l1_auxiliary
4389 def ClearLastCreated(self):
4390 self.editor.ClearLastCreated()
4392 ## Creates Duplicates given elements, i.e. creates new elements based on the
4393 # same nodes as the given ones.
4394 # @param theElements - container of elements to duplicate. It can be a Mesh,
4395 # sub-mesh, group, filter or a list of element IDs.
4396 # @param theGroupName - a name of group to contain the generated elements.
4397 # If a group with such a name already exists, the new elements
4398 # are added to the existng group, else a new group is created.
4399 # If \a theGroupName is empty, new elements are not added
4401 # @return a group where the new elements are added. None if theGroupName == "".
4402 # @ingroup l2_modif_edit
4403 def DoubleElements(self, theElements, theGroupName=""):
4404 unRegister = genObjUnRegister()
4405 if isinstance( theElements, Mesh ):
4406 theElements = theElements.mesh
4407 elif isinstance( theElements, list ):
4408 theElements = self.GetIDSource( theElements, SMESH.ALL )
4409 unRegister.set( theElements )
4410 return self.editor.DoubleElements(theElements, theGroupName)
4412 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4413 # @param theNodes identifiers of nodes to be doubled
4414 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4415 # nodes. If list of element identifiers is empty then nodes are doubled but
4416 # they not assigned to elements
4417 # @return TRUE if operation has been completed successfully, FALSE otherwise
4418 # @ingroup l2_modif_edit
4419 def DoubleNodes(self, theNodes, theModifiedElems):
4420 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4422 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4423 # This method provided for convenience works as DoubleNodes() described above.
4424 # @param theNodeId identifiers of node to be doubled
4425 # @param theModifiedElems identifiers of elements to be updated
4426 # @return TRUE if operation has been completed successfully, FALSE otherwise
4427 # @ingroup l2_modif_edit
4428 def DoubleNode(self, theNodeId, theModifiedElems):
4429 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4431 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4432 # This method provided for convenience works as DoubleNodes() described above.
4433 # @param theNodes group of nodes to be doubled
4434 # @param theModifiedElems group of elements to be updated.
4435 # @param theMakeGroup forces the generation of a group containing new nodes.
4436 # @return TRUE or a created group if operation has been completed successfully,
4437 # FALSE or None otherwise
4438 # @ingroup l2_modif_edit
4439 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4441 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4442 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4444 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4445 # This method provided for convenience works as DoubleNodes() described above.
4446 # @param theNodes list of groups of nodes to be doubled
4447 # @param theModifiedElems list of groups of elements to be updated.
4448 # @param theMakeGroup forces the generation of a group containing new nodes.
4449 # @return TRUE if operation has been completed successfully, FALSE otherwise
4450 # @ingroup l2_modif_edit
4451 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4453 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4454 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4456 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4457 # @param theElems - the list of elements (edges or faces) to be replicated
4458 # The nodes for duplication could be found from these elements
4459 # @param theNodesNot - list of nodes to NOT replicate
4460 # @param theAffectedElems - the list of elements (cells and edges) to which the
4461 # replicated nodes should be associated to.
4462 # @return TRUE if operation has been completed successfully, FALSE otherwise
4463 # @ingroup l2_modif_edit
4464 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4465 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4467 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4468 # @param theElems - the list of elements (edges or faces) to be replicated
4469 # The nodes for duplication could be found from these elements
4470 # @param theNodesNot - list of nodes to NOT replicate
4471 # @param theShape - shape to detect affected elements (element which geometric center
4472 # located on or inside shape).
4473 # The replicated nodes should be associated to affected elements.
4474 # @return TRUE if operation has been completed successfully, FALSE otherwise
4475 # @ingroup l2_modif_edit
4476 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4477 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4479 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4480 # This method provided for convenience works as DoubleNodes() described above.
4481 # @param theElems - group of of elements (edges or faces) to be replicated
4482 # @param theNodesNot - group of nodes not to replicated
4483 # @param theAffectedElems - group of elements to which the replicated nodes
4484 # should be associated to.
4485 # @param theMakeGroup forces the generation of a group containing new elements.
4486 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4487 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4488 # FALSE or None otherwise
4489 # @ingroup l2_modif_edit
4490 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4491 theMakeGroup=False, theMakeNodeGroup=False):
4492 if theMakeGroup or theMakeNodeGroup:
4493 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4495 theMakeGroup, theMakeNodeGroup)
4496 if theMakeGroup and theMakeNodeGroup:
4499 return twoGroups[ int(theMakeNodeGroup) ]
4500 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4502 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4503 # This method provided for convenience works as DoubleNodes() described above.
4504 # @param theElems - group of of elements (edges or faces) to be replicated
4505 # @param theNodesNot - group of nodes not to replicated
4506 # @param theShape - shape to detect affected elements (element which geometric center
4507 # located on or inside shape).
4508 # The replicated nodes should be associated to affected elements.
4509 # @ingroup l2_modif_edit
4510 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4511 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4513 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4514 # This method provided for convenience works as DoubleNodes() described above.
4515 # @param theElems - list of groups of elements (edges or faces) to be replicated
4516 # @param theNodesNot - list of groups of nodes not to replicated
4517 # @param theAffectedElems - group of elements to which the replicated nodes
4518 # should be associated to.
4519 # @param theMakeGroup forces the generation of a group containing new elements.
4520 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4521 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4522 # FALSE or None otherwise
4523 # @ingroup l2_modif_edit
4524 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4525 theMakeGroup=False, theMakeNodeGroup=False):
4526 if theMakeGroup or theMakeNodeGroup:
4527 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4529 theMakeGroup, theMakeNodeGroup)
4530 if theMakeGroup and theMakeNodeGroup:
4533 return twoGroups[ int(theMakeNodeGroup) ]
4534 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4536 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4537 # This method provided for convenience works as DoubleNodes() described above.
4538 # @param theElems - list of groups of elements (edges or faces) to be replicated
4539 # @param theNodesNot - list of groups of nodes not to replicated
4540 # @param theShape - shape to detect affected elements (element which geometric center
4541 # located on or inside shape).
4542 # The replicated nodes should be associated to affected elements.
4543 # @return TRUE if operation has been completed successfully, FALSE otherwise
4544 # @ingroup l2_modif_edit
4545 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4546 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4548 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4549 # This method is the first step of DoubleNodeElemGroupsInRegion.
4550 # @param theElems - list of groups of elements (edges or faces) to be replicated
4551 # @param theNodesNot - list of groups of nodes not to replicated
4552 # @param theShape - shape to detect affected elements (element which geometric center
4553 # located on or inside shape).
4554 # The replicated nodes should be associated to affected elements.
4555 # @return groups of affected elements
4556 # @ingroup l2_modif_edit
4557 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4558 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4560 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4561 # The list of groups must describe a partition of the mesh volumes.
4562 # The nodes of the internal faces at the boundaries of the groups are doubled.
4563 # In option, the internal faces are replaced by flat elements.
4564 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4565 # @param theDomains - list of groups of volumes
4566 # @param createJointElems - if TRUE, create the elements
4567 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4568 # the boundary between \a theDomains and the rest mesh
4569 # @return TRUE if operation has been completed successfully, FALSE otherwise
4570 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4571 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4573 ## Double nodes on some external faces and create flat elements.
4574 # Flat elements are mainly used by some types of mechanic calculations.
4576 # Each group of the list must be constituted of faces.
4577 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4578 # @param theGroupsOfFaces - list of groups of faces
4579 # @return TRUE if operation has been completed successfully, FALSE otherwise
4580 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4581 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4583 ## identify all the elements around a geom shape, get the faces delimiting the hole
4585 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4586 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4588 def _getFunctor(self, funcType ):
4589 fn = self.functors[ funcType._v ]
4591 fn = self.smeshpyD.GetFunctor(funcType)
4592 fn.SetMesh(self.mesh)
4593 self.functors[ funcType._v ] = fn
4596 def _valueFromFunctor(self, funcType, elemId):
4597 fn = self._getFunctor( funcType )
4598 if fn.GetElementType() == self.GetElementType(elemId, True):
4599 val = fn.GetValue(elemId)
4604 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4605 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4606 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4607 # @ingroup l1_measurements
4608 def GetLength(self, elemId=None):
4611 length = self.smeshpyD.GetLength(self)
4613 length = self._valueFromFunctor(SMESH.FT_Length, elemId)
4616 ## Get area of 2D element or sum of areas of all 2D mesh elements
4617 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4618 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4619 # @ingroup l1_measurements
4620 def GetArea(self, elemId=None):
4623 area = self.smeshpyD.GetArea(self)
4625 area = self._valueFromFunctor(SMESH.FT_Area, elemId)
4628 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4629 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4630 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4631 # @ingroup l1_measurements
4632 def GetVolume(self, elemId=None):
4635 volume = self.smeshpyD.GetVolume(self)
4637 volume = self._valueFromFunctor(SMESH.FT_Volume3D, elemId)
4640 ## Get maximum element length.
4641 # @param elemId mesh element ID
4642 # @return element's maximum length value
4643 # @ingroup l1_measurements
4644 def GetMaxElementLength(self, elemId):
4645 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4646 ftype = SMESH.FT_MaxElementLength3D
4648 ftype = SMESH.FT_MaxElementLength2D
4649 return self._valueFromFunctor(ftype, elemId)
4651 ## Get aspect ratio of 2D or 3D element.
4652 # @param elemId mesh element ID
4653 # @return element's aspect ratio value
4654 # @ingroup l1_measurements
4655 def GetAspectRatio(self, elemId):
4656 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4657 ftype = SMESH.FT_AspectRatio3D
4659 ftype = SMESH.FT_AspectRatio
4660 return self._valueFromFunctor(ftype, elemId)
4662 ## Get warping angle of 2D element.
4663 # @param elemId mesh element ID
4664 # @return element's warping angle value
4665 # @ingroup l1_measurements
4666 def GetWarping(self, elemId):
4667 return self._valueFromFunctor(SMESH.FT_Warping, elemId)
4669 ## Get minimum angle of 2D element.
4670 # @param elemId mesh element ID
4671 # @return element's minimum angle value
4672 # @ingroup l1_measurements
4673 def GetMinimumAngle(self, elemId):
4674 return self._valueFromFunctor(SMESH.FT_MinimumAngle, elemId)
4676 ## Get taper of 2D element.
4677 # @param elemId mesh element ID
4678 # @return element's taper value
4679 # @ingroup l1_measurements
4680 def GetTaper(self, elemId):
4681 return self._valueFromFunctor(SMESH.FT_Taper, elemId)
4683 ## Get skew of 2D element.
4684 # @param elemId mesh element ID
4685 # @return element's skew value
4686 # @ingroup l1_measurements
4687 def GetSkew(self, elemId):
4688 return self._valueFromFunctor(SMESH.FT_Skew, elemId)
4690 ## Return minimal and maximal value of a given functor.
4691 # @param funType a functor type, an item of SMESH.FunctorType enum
4692 # (one of SMESH.FunctorType._items)
4693 # @param meshPart a part of mesh (group, sub-mesh) to treat
4694 # @return tuple (min,max)
4695 # @ingroup l1_measurements
4696 def GetMinMax(self, funType, meshPart=None):
4697 unRegister = genObjUnRegister()
4698 if isinstance( meshPart, list ):
4699 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
4700 unRegister.set( meshPart )
4701 if isinstance( meshPart, Mesh ):
4702 meshPart = meshPart.mesh
4703 fun = self._getFunctor( funType )
4706 hist = fun.GetLocalHistogram( 1, False, meshPart )
4708 hist = fun.GetHistogram( 1, False )
4710 return hist[0].min, hist[0].max
4713 pass # end of Mesh class
4715 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
4717 class Pattern(SMESH._objref_SMESH_Pattern):
4719 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4720 decrFun = lambda i: i-1
4721 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4722 theMesh.SetParameters(Parameters)
4723 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4725 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4726 decrFun = lambda i: i-1
4727 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4728 theMesh.SetParameters(Parameters)
4729 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4731 # Registering the new proxy for Pattern
4732 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4734 ## Private class used to bind methods creating algorithms to the class Mesh
4739 self.defaultAlgoType = ""
4740 self.algoTypeToClass = {}
4742 # Stores a python class of algorithm
4743 def add(self, algoClass):
4744 if type( algoClass ).__name__ == 'classobj' and \
4745 hasattr( algoClass, "algoType"):
4746 self.algoTypeToClass[ algoClass.algoType ] = algoClass
4747 if not self.defaultAlgoType and \
4748 hasattr( algoClass, "isDefault") and algoClass.isDefault:
4749 self.defaultAlgoType = algoClass.algoType
4750 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
4752 # creates a copy of self and assign mesh to the copy
4753 def copy(self, mesh):
4754 other = algoCreator()
4755 other.defaultAlgoType = self.defaultAlgoType
4756 other.algoTypeToClass = self.algoTypeToClass
4760 # creates an instance of algorithm
4761 def __call__(self,algo="",geom=0,*args):
4762 algoType = self.defaultAlgoType
4763 for arg in args + (algo,geom):
4764 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
4766 if isinstance( arg, str ) and arg:
4768 if not algoType and self.algoTypeToClass:
4769 algoType = self.algoTypeToClass.keys()[0]
4770 if self.algoTypeToClass.has_key( algoType ):
4771 #print "Create algo",algoType
4772 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
4773 raise RuntimeError, "No class found for algo type %s" % algoType
4776 # Private class used to substitute and store variable parameters of hypotheses.
4778 class hypMethodWrapper:
4779 def __init__(self, hyp, method):
4781 self.method = method
4782 #print "REBIND:", method.__name__
4785 # call a method of hypothesis with calling SetVarParameter() before
4786 def __call__(self,*args):
4788 return self.method( self.hyp, *args ) # hypothesis method with no args
4790 #print "MethWrapper.__call__",self.method.__name__, args
4792 parsed = ParseParameters(*args) # replace variables with their values
4793 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
4794 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
4795 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
4796 # maybe there is a replaced string arg which is not variable
4797 result = self.method( self.hyp, *args )
4798 except ValueError, detail: # raised by ParseParameters()
4800 result = self.method( self.hyp, *args )
4801 except omniORB.CORBA.BAD_PARAM:
4802 raise ValueError, detail # wrong variable name
4807 # A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
4808 class genObjUnRegister:
4810 def __init__(self, genObj=None):
4811 self.genObjList = []
4815 def set(self, genObj):
4816 "Store one or a list of of SALOME.GenericObj'es"
4817 if isinstance( genObj, list ):
4818 self.genObjList.extend( genObj )
4820 self.genObjList.append( genObj )
4824 for genObj in self.genObjList:
4825 if genObj and hasattr( genObj, "UnRegister" ):
4828 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
4830 #print "pluginName: ", pluginName
4831 pluginBuilderName = pluginName + "Builder"
4833 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
4834 except Exception, e:
4835 from salome_utils import verbose
4836 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
4838 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
4839 plugin = eval( pluginBuilderName )
4840 #print " plugin:" , str(plugin)
4842 # add methods creating algorithms to Mesh
4843 for k in dir( plugin ):
4844 if k[0] == '_': continue
4845 algo = getattr( plugin, k )
4846 #print " algo:", str(algo)
4847 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
4848 #print " meshMethod:" , str(algo.meshMethod)
4849 if not hasattr( Mesh, algo.meshMethod ):
4850 setattr( Mesh, algo.meshMethod, algoCreator() )
4852 getattr( Mesh, algo.meshMethod ).add( algo )