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):
212 hypType = "algorithm"
214 hypType = "hypothesis"
216 if status == HYP_UNKNOWN_FATAL :
217 reason = "for unknown reason"
218 elif status == HYP_INCOMPATIBLE :
219 reason = "this hypothesis mismatches the algorithm"
220 elif status == HYP_NOTCONFORM :
221 reason = "a non-conform mesh would be built"
222 elif status == HYP_ALREADY_EXIST :
223 if isAlgo: return # it does not influence anything
224 reason = hypType + " of the same dimension is already assigned to this shape"
225 elif status == HYP_BAD_DIM :
226 reason = hypType + " mismatches the shape"
227 elif status == HYP_CONCURENT :
228 reason = "there are concurrent hypotheses on sub-shapes"
229 elif status == HYP_BAD_SUBSHAPE :
230 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
231 elif status == HYP_BAD_GEOMETRY:
232 reason = "geometry mismatches the expectation of the algorithm"
233 elif status == HYP_HIDDEN_ALGO:
234 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
235 elif status == HYP_HIDING_ALGO:
236 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
237 elif status == HYP_NEED_SHAPE:
238 reason = "Algorithm can't work without shape"
241 hypName = '"' + hypName + '"'
242 geomName= '"' + geomName+ '"'
243 if status < HYP_UNKNOWN_FATAL and not geomName =='""':
244 print hypName, "was assigned to", geomName,"but", reason
245 elif not geomName == '""':
246 print hypName, "was not assigned to",geomName,":", reason
248 print hypName, "was not assigned:", reason
251 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
252 def AssureGeomPublished(mesh, geom, name=''):
253 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
255 if not geom.GetStudyEntry() and \
256 mesh.smeshpyD.GetCurrentStudy():
258 studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
259 if studyID != mesh.geompyD.myStudyId:
260 mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
262 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
263 # for all groups SubShapeName() returns "Compound_-1"
264 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
266 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
268 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
271 ## Return the first vertex of a geometrical edge by ignoring orientation
272 def FirstVertexOnCurve(mesh, edge):
273 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
275 raise TypeError, "Given object has no vertices"
276 if len( vv ) == 1: return vv[0]
277 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
278 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
279 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
280 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
283 dist1 += abs( xyz[i] - xyz1[i] )
284 dist2 += abs( xyz[i] - xyz2[i] )
290 # end of l1_auxiliary
294 # Warning: smeshInst is a singleton
300 ## This class allows to create, load or manipulate meshes
301 # It has a set of methods to create load or copy meshes, to combine several meshes.
302 # It also has methods to get infos on meshes.
303 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
305 # MirrorType enumeration
306 POINT = SMESH_MeshEditor.POINT
307 AXIS = SMESH_MeshEditor.AXIS
308 PLANE = SMESH_MeshEditor.PLANE
310 # Smooth_Method enumeration
311 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
312 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
314 PrecisionConfusion = smeshPrecisionConfusion
316 # TopAbs_State enumeration
317 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
319 # Methods of splitting a hexahedron into tetrahedra
320 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
326 #print "==== __new__", engine, smeshInst, doLcc
328 if smeshInst is None:
329 # smesh engine is either retrieved from engine, or created
331 # Following test avoids a recursive loop
333 if smeshInst is not None:
334 # smesh engine not created: existing engine found
338 # FindOrLoadComponent called:
339 # 1. CORBA resolution of server
340 # 2. the __new__ method is called again
341 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
342 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
344 # FindOrLoadComponent not called
345 if smeshInst is None:
346 # smeshBuilder instance is created from lcc.FindOrLoadComponent
347 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
348 smeshInst = super(smeshBuilder,cls).__new__(cls)
350 # smesh engine not created: existing engine found
351 #print "==== existing ", engine, smeshInst, doLcc
353 #print "====1 ", smeshInst
356 #print "====2 ", smeshInst
361 #print "--------------- smeshbuilder __init__ ---", created
364 SMESH._objref_SMESH_Gen.__init__(self)
366 ## Dump component to the Python script
367 # This method overrides IDL function to allow default values for the parameters.
368 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
369 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
371 ## Set mode of DumpPython(), \a historical or \a snapshot.
372 # In the \a historical mode, the Python Dump script includes all commands
373 # performed by SMESH engine. In the \a snapshot mode, commands
374 # relating to objects removed from the Study are excluded from the script
375 # as well as commands not influencing the current state of meshes
376 def SetDumpPythonHistorical(self, isHistorical):
377 if isHistorical: val = "true"
379 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
381 ## Sets the current study and Geometry component
382 # @ingroup l1_auxiliary
383 def init_smesh(self,theStudy,geompyD = None):
385 self.SetCurrentStudy(theStudy,geompyD)
387 ## Creates an empty Mesh. This mesh can have an underlying geometry.
388 # @param obj the Geometrical object on which the mesh is built. If not defined,
389 # the mesh will have no underlying geometry.
390 # @param name the name for the new mesh.
391 # @return an instance of Mesh class.
392 # @ingroup l2_construct
393 def Mesh(self, obj=0, name=0):
394 if isinstance(obj,str):
396 return Mesh(self,self.geompyD,obj,name)
398 ## Returns a long value from enumeration
399 # @ingroup l1_controls
400 def EnumToLong(self,theItem):
403 ## Returns a string representation of the color.
404 # To be used with filters.
405 # @param c color value (SALOMEDS.Color)
406 # @ingroup l1_controls
407 def ColorToString(self,c):
409 if isinstance(c, SALOMEDS.Color):
410 val = "%s;%s;%s" % (c.R, c.G, c.B)
411 elif isinstance(c, str):
414 raise ValueError, "Color value should be of string or SALOMEDS.Color type"
417 ## Gets PointStruct from vertex
418 # @param theVertex a GEOM object(vertex)
419 # @return SMESH.PointStruct
420 # @ingroup l1_auxiliary
421 def GetPointStruct(self,theVertex):
422 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
423 return PointStruct(x,y,z)
425 ## Gets DirStruct from vector
426 # @param theVector a GEOM object(vector)
427 # @return SMESH.DirStruct
428 # @ingroup l1_auxiliary
429 def GetDirStruct(self,theVector):
430 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
431 if(len(vertices) != 2):
432 print "Error: vector object is incorrect."
434 p1 = self.geompyD.PointCoordinates(vertices[0])
435 p2 = self.geompyD.PointCoordinates(vertices[1])
436 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
437 dirst = DirStruct(pnt)
440 ## Makes DirStruct from a triplet
441 # @param x,y,z vector components
442 # @return SMESH.DirStruct
443 # @ingroup l1_auxiliary
444 def MakeDirStruct(self,x,y,z):
445 pnt = PointStruct(x,y,z)
446 return DirStruct(pnt)
448 ## Get AxisStruct from object
449 # @param theObj a GEOM object (line or plane)
450 # @return SMESH.AxisStruct
451 # @ingroup l1_auxiliary
452 def GetAxisStruct(self,theObj):
453 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
455 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
456 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
457 vertex1 = self.geompyD.PointCoordinates(vertex1)
458 vertex2 = self.geompyD.PointCoordinates(vertex2)
459 vertex3 = self.geompyD.PointCoordinates(vertex3)
460 vertex4 = self.geompyD.PointCoordinates(vertex4)
461 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
462 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
463 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] ]
464 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
466 elif len(edges) == 1:
467 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
468 p1 = self.geompyD.PointCoordinates( vertex1 )
469 p2 = self.geompyD.PointCoordinates( vertex2 )
470 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
474 # From SMESH_Gen interface:
475 # ------------------------
477 ## Sets the given name to the object
478 # @param obj the object to rename
479 # @param name a new object name
480 # @ingroup l1_auxiliary
481 def SetName(self, obj, name):
482 if isinstance( obj, Mesh ):
484 elif isinstance( obj, Mesh_Algorithm ):
485 obj = obj.GetAlgorithm()
486 ior = salome.orb.object_to_string(obj)
487 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
489 ## Sets the current mode
490 # @ingroup l1_auxiliary
491 def SetEmbeddedMode( self,theMode ):
492 #self.SetEmbeddedMode(theMode)
493 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
495 ## Gets the current mode
496 # @ingroup l1_auxiliary
497 def IsEmbeddedMode(self):
498 #return self.IsEmbeddedMode()
499 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
501 ## Sets the current study
502 # @ingroup l1_auxiliary
503 def SetCurrentStudy( self, theStudy, geompyD = None ):
504 #self.SetCurrentStudy(theStudy)
506 from salome.geom import geomBuilder
507 geompyD = geomBuilder.geom
510 self.SetGeomEngine(geompyD)
511 SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
514 notebook = salome_notebook.NoteBook( theStudy )
516 notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
518 ## Gets the current study
519 # @ingroup l1_auxiliary
520 def GetCurrentStudy(self):
521 #return self.GetCurrentStudy()
522 return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
524 ## Creates a Mesh object importing data from the given UNV file
525 # @return an instance of Mesh class
527 def CreateMeshesFromUNV( self,theFileName ):
528 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
529 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
532 ## Creates a Mesh object(s) importing data from the given MED file
533 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
535 def CreateMeshesFromMED( self,theFileName ):
536 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
537 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
538 return aMeshes, aStatus
540 ## Creates a Mesh object(s) importing data from the given SAUV file
541 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
543 def CreateMeshesFromSAUV( self,theFileName ):
544 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
545 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
546 return aMeshes, aStatus
548 ## Creates a Mesh object importing data from the given STL file
549 # @return an instance of Mesh class
551 def CreateMeshesFromSTL( self, theFileName ):
552 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
553 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
556 ## Creates Mesh objects importing data from the given CGNS file
557 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
559 def CreateMeshesFromCGNS( self, theFileName ):
560 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
561 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
562 return aMeshes, aStatus
564 ## Creates a Mesh object importing data from the given GMF file.
565 # GMF files must have .mesh extension for the ASCII format and .meshb for
567 # @return [ an instance of Mesh class, SMESH.ComputeError ]
569 def CreateMeshesFromGMF( self, theFileName ):
570 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
573 if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
574 return Mesh(self, self.geompyD, aSmeshMesh), error
576 ## Concatenate the given meshes into one mesh.
577 # @return an instance of Mesh class
578 # @param meshes the meshes to combine into one mesh
579 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
580 # @param mergeNodesAndElements if true, equal nodes and elements aremerged
581 # @param mergeTolerance tolerance for merging nodes
582 # @param allGroups forces creation of groups of all elements
583 # @param name name of a new mesh
584 def Concatenate( self, meshes, uniteIdenticalGroups,
585 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
587 if not meshes: return None
588 for i,m in enumerate(meshes):
589 if isinstance(m, Mesh):
590 meshes[i] = m.GetMesh()
591 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
592 meshes[0].SetParameters(Parameters)
594 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
595 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
597 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
598 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
599 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
602 ## Create a mesh by copying a part of another mesh.
603 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
604 # to copy nodes or elements not contained in any mesh object,
605 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
606 # @param meshName a name of the new mesh
607 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
608 # @param toKeepIDs to preserve IDs of the copied elements or not
609 # @return an instance of Mesh class
610 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
611 if (isinstance( meshPart, Mesh )):
612 meshPart = meshPart.GetMesh()
613 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
614 return Mesh(self, self.geompyD, mesh)
616 ## From SMESH_Gen interface
617 # @return the list of integer values
618 # @ingroup l1_auxiliary
619 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
620 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
622 ## From SMESH_Gen interface. Creates a pattern
623 # @return an instance of SMESH_Pattern
625 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
626 # @ingroup l2_modif_patterns
627 def GetPattern(self):
628 return SMESH._objref_SMESH_Gen.GetPattern(self)
630 ## Sets number of segments per diagonal of boundary box of geometry by which
631 # default segment length of appropriate 1D hypotheses is defined.
632 # Default value is 10
633 # @ingroup l1_auxiliary
634 def SetBoundaryBoxSegmentation(self, nbSegments):
635 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
637 # Filtering. Auxiliary functions:
638 # ------------------------------
640 ## Creates an empty criterion
641 # @return SMESH.Filter.Criterion
642 # @ingroup l1_controls
643 def GetEmptyCriterion(self):
644 Type = self.EnumToLong(FT_Undefined)
645 Compare = self.EnumToLong(FT_Undefined)
649 UnaryOp = self.EnumToLong(FT_Undefined)
650 BinaryOp = self.EnumToLong(FT_Undefined)
653 Precision = -1 ##@1e-07
654 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
655 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
657 ## Creates a criterion by the given parameters
658 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
659 # @param elementType the type of elements(NODE, EDGE, FACE, VOLUME)
660 # @param CritType the type of criterion (FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc.)
661 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
662 # @param Threshold the threshold value (range of ids as string, shape, numeric)
663 # @param UnaryOp FT_LogicalNOT or FT_Undefined
664 # @param BinaryOp a binary logical operation FT_LogicalAND, FT_LogicalOR or
665 # FT_Undefined (must be for the last criterion of all criteria)
666 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
667 # FT_LyingOnGeom, FT_CoplanarFaces criteria
668 # @return SMESH.Filter.Criterion
670 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
671 # @ingroup l1_controls
672 def GetCriterion(self,elementType,
674 Compare = FT_EqualTo,
676 UnaryOp=FT_Undefined,
677 BinaryOp=FT_Undefined,
679 if not CritType in SMESH.FunctorType._items:
680 raise TypeError, "CritType should be of SMESH.FunctorType"
681 aCriterion = self.GetEmptyCriterion()
682 aCriterion.TypeOfElement = elementType
683 aCriterion.Type = self.EnumToLong(CritType)
684 aCriterion.Tolerance = Tolerance
686 aThreshold = Threshold
688 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
689 aCriterion.Compare = self.EnumToLong(Compare)
690 elif Compare == "=" or Compare == "==":
691 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
693 aCriterion.Compare = self.EnumToLong(FT_LessThan)
695 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
696 elif Compare != FT_Undefined:
697 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
700 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
701 FT_BelongToCylinder, FT_LyingOnGeom]:
702 # Checks that Threshold is GEOM object
703 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
704 aCriterion.ThresholdStr = GetName(aThreshold)
705 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
706 if not aCriterion.ThresholdID:
707 name = aCriterion.ThresholdStr
709 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
710 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
711 #raise RuntimeError, "Threshold shape must be published"
713 print "Error: The Threshold should be a shape."
715 if isinstance(UnaryOp,float):
716 aCriterion.Tolerance = UnaryOp
717 UnaryOp = FT_Undefined
719 elif CritType == FT_RangeOfIds:
720 # Checks that Threshold is string
721 if isinstance(aThreshold, str):
722 aCriterion.ThresholdStr = aThreshold
724 print "Error: The Threshold should be a string."
726 elif CritType == FT_CoplanarFaces:
727 # Checks the Threshold
728 if isinstance(aThreshold, int):
729 aCriterion.ThresholdID = str(aThreshold)
730 elif isinstance(aThreshold, str):
733 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
734 aCriterion.ThresholdID = aThreshold
737 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
738 elif CritType == FT_ConnectedElements:
739 # Checks the Threshold
740 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
741 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
742 if not aCriterion.ThresholdID:
743 name = aThreshold.GetName()
745 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
746 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
747 elif isinstance(aThreshold, int): # node id
748 aCriterion.Threshold = aThreshold
749 elif isinstance(aThreshold, list): # 3 point coordinates
750 if len( aThreshold ) < 3:
751 raise ValueError, "too few point coordinates, must be 3"
752 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
753 elif isinstance(aThreshold, str):
754 if aThreshold.isdigit():
755 aCriterion.Threshold = aThreshold # node id
757 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
760 "The Threshold should either a VERTEX, or a node ID, "\
761 "or a list of point coordinates and not '%s'"%aThreshold
762 elif CritType == FT_ElemGeomType:
763 # Checks the Threshold
765 aCriterion.Threshold = self.EnumToLong(aThreshold)
766 assert( aThreshold in SMESH.GeometryType._items )
768 if isinstance(aThreshold, int):
769 aCriterion.Threshold = aThreshold
771 print "Error: The Threshold should be an integer or SMESH.GeometryType."
775 elif CritType == FT_EntityType:
776 # Checks the Threshold
778 aCriterion.Threshold = self.EnumToLong(aThreshold)
779 assert( aThreshold in SMESH.EntityType._items )
781 if isinstance(aThreshold, int):
782 aCriterion.Threshold = aThreshold
784 print "Error: The Threshold should be an integer or SMESH.EntityType."
789 elif CritType == FT_GroupColor:
790 # Checks the Threshold
792 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
794 print "Error: The threshold value should be of SALOMEDS.Color type"
797 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
798 FT_LinearOrQuadratic, FT_BadOrientedVolume,
799 FT_BareBorderFace, FT_BareBorderVolume,
800 FT_OverConstrainedFace, FT_OverConstrainedVolume,
801 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
802 # At this point the Threshold is unnecessary
803 if aThreshold == FT_LogicalNOT:
804 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
805 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
806 aCriterion.BinaryOp = aThreshold
810 aThreshold = float(aThreshold)
811 aCriterion.Threshold = aThreshold
813 print "Error: The Threshold should be a number."
816 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
817 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
819 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
820 aCriterion.BinaryOp = self.EnumToLong(Threshold)
822 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
823 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
825 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
826 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
830 ## Creates a filter with the given parameters
831 # @param elementType the type of elements in the group
832 # @param CritType the type of criterion ( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
833 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
834 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
835 # @param UnaryOp FT_LogicalNOT or FT_Undefined
836 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
837 # FT_LyingOnGeom, FT_CoplanarFaces and FT_EqualNodes criteria
838 # @param mesh the mesh to initialize the filter with
839 # @return SMESH_Filter
841 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
842 # @ingroup l1_controls
843 def GetFilter(self,elementType,
844 CritType=FT_Undefined,
847 UnaryOp=FT_Undefined,
850 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
851 aFilterMgr = self.CreateFilterManager()
852 aFilter = aFilterMgr.CreateFilter()
854 aCriteria.append(aCriterion)
855 aFilter.SetCriteria(aCriteria)
857 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
858 else : aFilter.SetMesh( mesh )
859 aFilterMgr.UnRegister()
862 ## Creates a filter from criteria
863 # @param criteria a list of criteria
864 # @param binOp binary operator used when binary operator of criteria is undefined
865 # @return SMESH_Filter
867 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
868 # @ingroup l1_controls
869 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
870 for i in range( len( criteria ) - 1 ):
871 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
872 criteria[i].BinaryOp = self.EnumToLong( binOp )
873 aFilterMgr = self.CreateFilterManager()
874 aFilter = aFilterMgr.CreateFilter()
875 aFilter.SetCriteria(criteria)
876 aFilterMgr.UnRegister()
879 ## Creates a numerical functor by its type
880 # @param theCriterion FT_...; functor type
881 # @return SMESH_NumericalFunctor
882 # @ingroup l1_controls
883 def GetFunctor(self,theCriterion):
884 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
886 aFilterMgr = self.CreateFilterManager()
888 if theCriterion == FT_AspectRatio:
889 functor = aFilterMgr.CreateAspectRatio()
890 elif theCriterion == FT_AspectRatio3D:
891 functor = aFilterMgr.CreateAspectRatio3D()
892 elif theCriterion == FT_Warping:
893 functor = aFilterMgr.CreateWarping()
894 elif theCriterion == FT_MinimumAngle:
895 functor = aFilterMgr.CreateMinimumAngle()
896 elif theCriterion == FT_Taper:
897 functor = aFilterMgr.CreateTaper()
898 elif theCriterion == FT_Skew:
899 functor = aFilterMgr.CreateSkew()
900 elif theCriterion == FT_Area:
901 functor = aFilterMgr.CreateArea()
902 elif theCriterion == FT_Volume3D:
903 functor = aFilterMgr.CreateVolume3D()
904 elif theCriterion == FT_MaxElementLength2D:
905 functor = aFilterMgr.CreateMaxElementLength2D()
906 elif theCriterion == FT_MaxElementLength3D:
907 functor = aFilterMgr.CreateMaxElementLength3D()
908 elif theCriterion == FT_MultiConnection:
909 functor = aFilterMgr.CreateMultiConnection()
910 elif theCriterion == FT_MultiConnection2D:
911 functor = aFilterMgr.CreateMultiConnection2D()
912 elif theCriterion == FT_Length:
913 functor = aFilterMgr.CreateLength()
914 elif theCriterion == FT_Length2D:
915 functor = aFilterMgr.CreateLength2D()
917 print "Error: given parameter is not numerical functor type."
918 aFilterMgr.UnRegister()
921 ## Creates hypothesis
922 # @param theHType mesh hypothesis type (string)
923 # @param theLibName mesh plug-in library name
924 # @return created hypothesis instance
925 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
926 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
928 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
931 # wrap hypothesis methods
932 #print "HYPOTHESIS", theHType
933 for meth_name in dir( hyp.__class__ ):
934 if not meth_name.startswith("Get") and \
935 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
936 method = getattr ( hyp.__class__, meth_name )
938 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
942 ## Gets the mesh statistic
943 # @return dictionary "element type" - "count of elements"
944 # @ingroup l1_meshinfo
945 def GetMeshInfo(self, obj):
946 if isinstance( obj, Mesh ):
949 if hasattr(obj, "GetMeshInfo"):
950 values = obj.GetMeshInfo()
951 for i in range(SMESH.Entity_Last._v):
952 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
956 ## Get minimum distance between two objects
958 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
959 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
961 # @param src1 first source object
962 # @param src2 second source object
963 # @param id1 node/element id from the first source
964 # @param id2 node/element id from the second (or first) source
965 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
966 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
967 # @return minimum distance value
968 # @sa GetMinDistance()
969 # @ingroup l1_measurements
970 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
971 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
975 result = result.value
978 ## Get measure structure specifying minimum distance data 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 Measure structure or None if input data is invalid
991 # @ingroup l1_measurements
992 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
993 if isinstance(src1, Mesh): src1 = src1.mesh
994 if isinstance(src2, Mesh): src2 = src2.mesh
995 if src2 is None and id2 != 0: src2 = src1
996 if not hasattr(src1, "_narrow"): return None
997 src1 = src1._narrow(SMESH.SMESH_IDSource)
998 if not src1: return None
999 unRegister = genObjUnRegister()
1002 e = m.GetMeshEditor()
1004 src1 = e.MakeIDSource([id1], SMESH.FACE)
1006 src1 = e.MakeIDSource([id1], SMESH.NODE)
1007 unRegister.set( src1 )
1009 if hasattr(src2, "_narrow"):
1010 src2 = src2._narrow(SMESH.SMESH_IDSource)
1011 if src2 and id2 != 0:
1013 e = m.GetMeshEditor()
1015 src2 = e.MakeIDSource([id2], SMESH.FACE)
1017 src2 = e.MakeIDSource([id2], SMESH.NODE)
1018 unRegister.set( src2 )
1021 aMeasurements = self.CreateMeasurements()
1022 unRegister.set( aMeasurements )
1023 result = aMeasurements.MinDistance(src1, src2)
1026 ## Get bounding box of the specified object(s)
1027 # @param objects single source object or list of source objects
1028 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1029 # @sa GetBoundingBox()
1030 # @ingroup l1_measurements
1031 def BoundingBox(self, objects):
1032 result = self.GetBoundingBox(objects)
1036 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1039 ## Get measure structure specifying bounding box data of the specified object(s)
1040 # @param objects single source object or list of source objects
1041 # @return Measure structure
1043 # @ingroup l1_measurements
1044 def GetBoundingBox(self, objects):
1045 if isinstance(objects, tuple):
1046 objects = list(objects)
1047 if not isinstance(objects, list):
1051 if isinstance(o, Mesh):
1052 srclist.append(o.mesh)
1053 elif hasattr(o, "_narrow"):
1054 src = o._narrow(SMESH.SMESH_IDSource)
1055 if src: srclist.append(src)
1058 aMeasurements = self.CreateMeasurements()
1059 result = aMeasurements.BoundingBox(srclist)
1060 aMeasurements.UnRegister()
1063 ## Get sum of lengths of all 1D elements in the mesh object.
1064 # @param obj mesh, submesh or group
1065 # @return sum of lengths of all 1D elements
1066 # @ingroup l1_measurements
1067 def GetLength(self, obj):
1068 if isinstance(obj, Mesh): obj = obj.mesh
1069 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1070 aMeasurements = self.CreateMeasurements()
1071 value = aMeasurements.Length(obj)
1072 aMeasurements.UnRegister()
1075 ## Get sum of areas of all 2D elements in the mesh object.
1076 # @param obj mesh, submesh or group
1077 # @return sum of areas of all 2D elements
1078 # @ingroup l1_measurements
1079 def GetArea(self, obj):
1080 if isinstance(obj, Mesh): obj = obj.mesh
1081 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1082 aMeasurements = self.CreateMeasurements()
1083 value = aMeasurements.Area(obj)
1084 aMeasurements.UnRegister()
1087 ## Get sum of volumes of all 3D elements in the mesh object.
1088 # @param obj mesh, submesh or group
1089 # @return sum of volumes of all 3D elements
1090 # @ingroup l1_measurements
1091 def GetVolume(self, obj):
1092 if isinstance(obj, Mesh): obj = obj.mesh
1093 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1094 aMeasurements = self.CreateMeasurements()
1095 value = aMeasurements.Volume(obj)
1096 aMeasurements.UnRegister()
1099 pass # end of class smeshBuilder
1102 #Registering the new proxy for SMESH_Gen
1103 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1105 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1106 # interface to create or load meshes.
1111 # salome.salome_init()
1112 # from salome.smesh import smeshBuilder
1113 # smesh = smeshBuilder.New(theStudy)
1115 # @param study SALOME study, generally obtained by salome.myStudy.
1116 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1117 # @return smeshBuilder instance
1119 def New( study, instance=None):
1121 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1122 interface to create or load meshes.
1126 salome.salome_init()
1127 from salome.smesh import smeshBuilder
1128 smesh = smeshBuilder.New(theStudy)
1131 study SALOME study, generally obtained by salome.myStudy.
1132 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1134 smeshBuilder instance
1142 smeshInst = smeshBuilder()
1143 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1144 smeshInst.init_smesh(study)
1148 # Public class: Mesh
1149 # ==================
1151 ## This class allows defining and managing a mesh.
1152 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1153 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1154 # new nodes and elements and by changing the existing entities), to get information
1155 # about a mesh and to export a mesh into different formats.
1157 __metaclass__ = MeshMeta
1165 # Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1166 # sets the GUI name of this mesh to \a name.
1167 # @param smeshpyD an instance of smeshBuilder class
1168 # @param geompyD an instance of geomBuilder class
1169 # @param obj Shape to be meshed or SMESH_Mesh object
1170 # @param name Study name of the mesh
1171 # @ingroup l2_construct
1172 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1173 self.smeshpyD=smeshpyD
1174 self.geompyD=geompyD
1179 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1182 # publish geom of mesh (issue 0021122)
1183 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1185 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1186 if studyID != geompyD.myStudyId:
1187 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1190 geo_name = name + " shape"
1192 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1193 geompyD.addToStudy( self.geom, geo_name )
1194 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1196 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1199 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1201 self.smeshpyD.SetName(self.mesh, name)
1203 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1206 self.geom = self.mesh.GetShapeToMesh()
1208 self.editor = self.mesh.GetMeshEditor()
1209 self.functors = [None] * SMESH.FT_Undefined._v
1211 # set self to algoCreator's
1212 for attrName in dir(self):
1213 attr = getattr( self, attrName )
1214 if isinstance( attr, algoCreator ):
1215 #print "algoCreator ", attrName
1216 setattr( self, attrName, attr.copy( self ))
1221 ## Destructor. Clean-up resources
1224 #self.mesh.UnRegister()
1228 ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1229 # @param theMesh a SMESH_Mesh object
1230 # @ingroup l2_construct
1231 def SetMesh(self, theMesh):
1232 # do not call Register() as this prevents mesh servant deletion at closing study
1233 #if self.mesh: self.mesh.UnRegister()
1236 #self.mesh.Register()
1237 self.geom = self.mesh.GetShapeToMesh()
1240 ## Returns the mesh, that is an instance of SMESH_Mesh interface
1241 # @return a SMESH_Mesh object
1242 # @ingroup l2_construct
1246 ## Gets the name of the mesh
1247 # @return the name of the mesh as a string
1248 # @ingroup l2_construct
1250 name = GetName(self.GetMesh())
1253 ## Sets a name to the mesh
1254 # @param name a new name of the mesh
1255 # @ingroup l2_construct
1256 def SetName(self, name):
1257 self.smeshpyD.SetName(self.GetMesh(), name)
1259 ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1260 # The subMesh object gives access to the IDs of nodes and elements.
1261 # @param geom a geometrical object (shape)
1262 # @param name a name for the submesh
1263 # @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1264 # @ingroup l2_submeshes
1265 def GetSubMesh(self, geom, name):
1266 AssureGeomPublished( self, geom, name )
1267 submesh = self.mesh.GetSubMesh( geom, name )
1270 ## Returns the shape associated to the mesh
1271 # @return a GEOM_Object
1272 # @ingroup l2_construct
1276 ## Associates the given shape to the mesh (entails the recreation of the mesh)
1277 # @param geom the shape to be meshed (GEOM_Object)
1278 # @ingroup l2_construct
1279 def SetShape(self, geom):
1280 self.mesh = self.smeshpyD.CreateMesh(geom)
1282 ## Loads mesh from the study after opening the study
1286 ## Returns true if the hypotheses are defined well
1287 # @param theSubObject a sub-shape of a mesh shape
1288 # @return True or False
1289 # @ingroup l2_construct
1290 def IsReadyToCompute(self, theSubObject):
1291 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1293 ## Returns errors of hypotheses definition.
1294 # The list of errors is empty if everything is OK.
1295 # @param theSubObject a sub-shape of a mesh shape
1296 # @return a list of errors
1297 # @ingroup l2_construct
1298 def GetAlgoState(self, theSubObject):
1299 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1301 ## Returns a geometrical object on which the given element was built.
1302 # The returned geometrical object, if not nil, is either found in the
1303 # study or published by this method with the given name
1304 # @param theElementID the id of the mesh element
1305 # @param theGeomName the user-defined name of the geometrical object
1306 # @return GEOM::GEOM_Object instance
1307 # @ingroup l2_construct
1308 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1309 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1311 ## Returns the mesh dimension depending on the dimension of the underlying shape
1312 # or, if the mesh is not based on any shape, basing on deimension of elements
1313 # @return mesh dimension as an integer value [0,3]
1314 # @ingroup l1_auxiliary
1315 def MeshDimension(self):
1316 if self.mesh.HasShapeToMesh():
1317 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1318 if len( shells ) > 0 :
1320 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1322 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1327 if self.NbVolumes() > 0: return 3
1328 if self.NbFaces() > 0: return 2
1329 if self.NbEdges() > 0: return 1
1332 ## Evaluates size of prospective mesh on a shape
1333 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1334 # To know predicted number of e.g. edges, inquire it this way
1335 # Evaluate()[ EnumToLong( Entity_Edge )]
1336 def Evaluate(self, geom=0):
1337 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1339 geom = self.mesh.GetShapeToMesh()
1342 return self.smeshpyD.Evaluate(self.mesh, geom)
1345 ## Computes the mesh and returns the status of the computation
1346 # @param geom geomtrical shape on which mesh data should be computed
1347 # @param discardModifs if True and the mesh has been edited since
1348 # a last total re-compute and that may prevent successful partial re-compute,
1349 # then the mesh is cleaned before Compute()
1350 # @return True or False
1351 # @ingroup l2_construct
1352 def Compute(self, geom=0, discardModifs=False):
1353 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1355 geom = self.mesh.GetShapeToMesh()
1360 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1362 ok = self.smeshpyD.Compute(self.mesh, geom)
1363 except SALOME.SALOME_Exception, ex:
1364 print "Mesh computation failed, exception caught:"
1365 print " ", ex.details.text
1368 print "Mesh computation failed, exception caught:"
1369 traceback.print_exc()
1373 # Treat compute errors
1374 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1375 for err in computeErrors:
1377 if self.mesh.HasShapeToMesh():
1379 mainIOR = salome.orb.object_to_string(geom)
1380 for sname in salome.myStudyManager.GetOpenStudies():
1381 s = salome.myStudyManager.GetStudyByName(sname)
1383 mainSO = s.FindObjectIOR(mainIOR)
1384 if not mainSO: continue
1385 if err.subShapeID == 1:
1386 shapeText = ' on "%s"' % mainSO.GetName()
1387 subIt = s.NewChildIterator(mainSO)
1389 subSO = subIt.Value()
1391 obj = subSO.GetObject()
1392 if not obj: continue
1393 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1395 ids = go.GetSubShapeIndices()
1396 if len(ids) == 1 and ids[0] == err.subShapeID:
1397 shapeText = ' on "%s"' % subSO.GetName()
1400 shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1402 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1404 shapeText = " on subshape #%s" % (err.subShapeID)
1406 shapeText = " on subshape #%s" % (err.subShapeID)
1408 stdErrors = ["OK", #COMPERR_OK
1409 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1410 "std::exception", #COMPERR_STD_EXCEPTION
1411 "OCC exception", #COMPERR_OCC_EXCEPTION
1412 "..", #COMPERR_SLM_EXCEPTION
1413 "Unknown exception", #COMPERR_EXCEPTION
1414 "Memory allocation problem", #COMPERR_MEMORY_PB
1415 "Algorithm failed", #COMPERR_ALGO_FAILED
1416 "Unexpected geometry", #COMPERR_BAD_SHAPE
1417 "Warning", #COMPERR_WARNING
1418 "Computation cancelled",#COMPERR_CANCELED
1419 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1421 if err.code < len(stdErrors): errText = stdErrors[err.code]
1423 errText = "code %s" % -err.code
1424 if errText: errText += ". "
1425 errText += err.comment
1426 if allReasons != "":allReasons += "\n"
1428 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1430 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1434 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1436 if err.isGlobalAlgo:
1444 reason = '%s %sD algorithm is missing' % (glob, dim)
1445 elif err.state == HYP_MISSING:
1446 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1447 % (glob, dim, name, dim))
1448 elif err.state == HYP_NOTCONFORM:
1449 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1450 elif err.state == HYP_BAD_PARAMETER:
1451 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1452 % ( glob, dim, name ))
1453 elif err.state == HYP_BAD_GEOMETRY:
1454 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1455 'geometry' % ( glob, dim, name ))
1456 elif err.state == HYP_HIDDEN_ALGO:
1457 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1458 'algorithm of upper dimension generating %sD mesh'
1459 % ( glob, dim, name, glob, dim ))
1461 reason = ("For unknown reason. "
1462 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1464 if allReasons != "":allReasons += "\n"
1465 allReasons += "- " + reason
1467 if not ok or allReasons != "":
1468 msg = '"' + GetName(self.mesh) + '"'
1469 if ok: msg += " has been computed with warnings"
1470 else: msg += " has not been computed"
1471 if allReasons != "": msg += ":"
1476 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1477 smeshgui = salome.ImportComponentGUI("SMESH")
1478 smeshgui.Init(self.mesh.GetStudyId())
1479 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1480 salome.sg.updateObjBrowser(1)
1484 ## Return submesh objects list in meshing order
1485 # @return list of list of submesh objects
1486 # @ingroup l2_construct
1487 def GetMeshOrder(self):
1488 return self.mesh.GetMeshOrder()
1490 ## Return submesh objects list in meshing order
1491 # @return list of list of submesh objects
1492 # @ingroup l2_construct
1493 def SetMeshOrder(self, submeshes):
1494 return self.mesh.SetMeshOrder(submeshes)
1496 ## Removes all nodes and elements
1497 # @ingroup l2_construct
1500 if ( salome.sg.hasDesktop() and
1501 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() )):
1502 smeshgui = salome.ImportComponentGUI("SMESH")
1503 smeshgui.Init(self.mesh.GetStudyId())
1504 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1505 salome.sg.updateObjBrowser(1)
1507 ## Removes all nodes and elements of indicated shape
1508 # @ingroup l2_construct
1509 def ClearSubMesh(self, geomId):
1510 self.mesh.ClearSubMesh(geomId)
1511 if salome.sg.hasDesktop():
1512 smeshgui = salome.ImportComponentGUI("SMESH")
1513 smeshgui.Init(self.mesh.GetStudyId())
1514 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1515 salome.sg.updateObjBrowser(1)
1517 ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + NETGEN
1518 # @param fineness [0.0,1.0] defines mesh fineness
1519 # @return True or False
1520 # @ingroup l3_algos_basic
1521 def AutomaticTetrahedralization(self, fineness=0):
1522 dim = self.MeshDimension()
1524 self.RemoveGlobalHypotheses()
1525 self.Segment().AutomaticLength(fineness)
1527 self.Triangle().LengthFromEdges()
1530 from salome.NETGENPlugin.NETGENPluginBuilder import NETGEN
1531 self.Tetrahedron(NETGEN)
1533 return self.Compute()
1535 ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1536 # @param fineness [0.0, 1.0] defines mesh fineness
1537 # @return True or False
1538 # @ingroup l3_algos_basic
1539 def AutomaticHexahedralization(self, fineness=0):
1540 dim = self.MeshDimension()
1541 # assign the hypotheses
1542 self.RemoveGlobalHypotheses()
1543 self.Segment().AutomaticLength(fineness)
1550 return self.Compute()
1552 ## Assigns a hypothesis
1553 # @param hyp a hypothesis to assign
1554 # @param geom a subhape of mesh geometry
1555 # @return SMESH.Hypothesis_Status
1556 # @ingroup l2_hypotheses
1557 def AddHypothesis(self, hyp, geom=0):
1558 if isinstance( hyp, Mesh_Algorithm ):
1559 hyp = hyp.GetAlgorithm()
1564 geom = self.mesh.GetShapeToMesh()
1567 if self.mesh.HasShapeToMesh():
1568 hyp_type = hyp.GetName()
1569 lib_name = hyp.GetLibName()
1570 isSubMesh = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1571 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, isSubMesh)
1573 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1574 status = self.mesh.AddHypothesis(geom, hyp)
1576 status = HYP_BAD_GEOMETRY
1577 hyp_name = GetName( hyp )
1580 geom_name = geom.GetName()
1581 isAlgo = hyp._narrow( SMESH_Algo )
1582 TreatHypoStatus( status, hyp_name, geom_name, isAlgo )
1585 ## Return True if an algorithm of hypothesis is assigned to a given shape
1586 # @param hyp a hypothesis to check
1587 # @param geom a subhape of mesh geometry
1588 # @return True of False
1589 # @ingroup l2_hypotheses
1590 def IsUsedHypothesis(self, hyp, geom):
1591 if not hyp: # or not geom
1593 if isinstance( hyp, Mesh_Algorithm ):
1594 hyp = hyp.GetAlgorithm()
1596 hyps = self.GetHypothesisList(geom)
1598 if h.GetId() == hyp.GetId():
1602 ## Unassigns a hypothesis
1603 # @param hyp a hypothesis to unassign
1604 # @param geom a sub-shape of mesh geometry
1605 # @return SMESH.Hypothesis_Status
1606 # @ingroup l2_hypotheses
1607 def RemoveHypothesis(self, hyp, geom=0):
1610 if isinstance( hyp, Mesh_Algorithm ):
1611 hyp = hyp.GetAlgorithm()
1617 if self.IsUsedHypothesis( hyp, shape ):
1618 return self.mesh.RemoveHypothesis( shape, hyp )
1619 hypName = GetName( hyp )
1620 geoName = GetName( shape )
1621 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1624 ## Gets the list of hypotheses added on a geometry
1625 # @param geom a sub-shape of mesh geometry
1626 # @return the sequence of SMESH_Hypothesis
1627 # @ingroup l2_hypotheses
1628 def GetHypothesisList(self, geom):
1629 return self.mesh.GetHypothesisList( geom )
1631 ## Removes all global hypotheses
1632 # @ingroup l2_hypotheses
1633 def RemoveGlobalHypotheses(self):
1634 current_hyps = self.mesh.GetHypothesisList( self.geom )
1635 for hyp in current_hyps:
1636 self.mesh.RemoveHypothesis( self.geom, hyp )
1640 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1641 ## allowing to overwrite the file if it exists or add the exported data to its contents
1642 # @param f is the file name
1643 # @param auto_groups boolean parameter for creating/not creating
1644 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1645 # the typical use is auto_groups=false.
1646 # @param version MED format version(MED_V2_1 or MED_V2_2)
1647 # @param overwrite boolean parameter for overwriting/not overwriting the file
1648 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1649 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1650 # - 1D if all mesh nodes lie on OX coordinate axis, or
1651 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1652 # - 3D in the rest cases.
1653 # If @a autoDimension is @c False, the space dimension is always 3.
1654 # @param fields : list of GEOM fields defined on the shape to mesh.
1655 # @param geomAssocFields : each character of this string means a need to export a
1656 # corresponding field; correspondence between fields and characters is following:
1657 # - 'v' stands for _vertices_ field;
1658 # - 'e' stands for _edges_ field;
1659 # - 'f' stands for _faces_ field;
1660 # - 's' stands for _solids_ field.
1661 # @ingroup l2_impexp
1662 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1663 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1664 if meshPart or fields or geomAssocFields:
1665 unRegister = genObjUnRegister()
1666 if isinstance( meshPart, list ):
1667 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1668 unRegister.set( meshPart )
1669 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1670 fields, geomAssocFields)
1672 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1674 ## Exports the mesh in a file in SAUV format
1675 # @param f is the file name
1676 # @param auto_groups boolean parameter for creating/not creating
1677 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1678 # the typical use is auto_groups=false.
1679 # @ingroup l2_impexp
1680 def ExportSAUV(self, f, auto_groups=0):
1681 self.mesh.ExportSAUV(f, auto_groups)
1683 ## Exports the mesh in a file in DAT format
1684 # @param f the file name
1685 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1686 # @ingroup l2_impexp
1687 def ExportDAT(self, f, meshPart=None):
1689 unRegister = genObjUnRegister()
1690 if isinstance( meshPart, list ):
1691 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1692 unRegister.set( meshPart )
1693 self.mesh.ExportPartToDAT( meshPart, f )
1695 self.mesh.ExportDAT(f)
1697 ## Exports the mesh in a file in UNV format
1698 # @param f the file name
1699 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1700 # @ingroup l2_impexp
1701 def ExportUNV(self, f, meshPart=None):
1703 unRegister = genObjUnRegister()
1704 if isinstance( meshPart, list ):
1705 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1706 unRegister.set( meshPart )
1707 self.mesh.ExportPartToUNV( meshPart, f )
1709 self.mesh.ExportUNV(f)
1711 ## Export the mesh in a file in STL format
1712 # @param f the file name
1713 # @param ascii defines the file encoding
1714 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1715 # @ingroup l2_impexp
1716 def ExportSTL(self, f, ascii=1, meshPart=None):
1718 unRegister = genObjUnRegister()
1719 if isinstance( meshPart, list ):
1720 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1721 unRegister.set( meshPart )
1722 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1724 self.mesh.ExportSTL(f, ascii)
1726 ## Exports the mesh in a file in CGNS format
1727 # @param f is the file name
1728 # @param overwrite boolean parameter for overwriting/not overwriting the file
1729 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1730 # @ingroup l2_impexp
1731 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1732 unRegister = genObjUnRegister()
1733 if isinstance( meshPart, list ):
1734 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1735 unRegister.set( meshPart )
1736 if isinstance( meshPart, Mesh ):
1737 meshPart = meshPart.mesh
1739 meshPart = self.mesh
1740 self.mesh.ExportCGNS(meshPart, f, overwrite)
1742 ## Exports the mesh in a file in GMF format.
1743 # GMF files must have .mesh extension for the ASCII format and .meshb for
1744 # the bynary format. Other extensions are not allowed.
1745 # @param f is the file name
1746 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1747 # @ingroup l2_impexp
1748 def ExportGMF(self, f, meshPart=None):
1749 unRegister = genObjUnRegister()
1750 if isinstance( meshPart, list ):
1751 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1752 unRegister.set( meshPart )
1753 if isinstance( meshPart, Mesh ):
1754 meshPart = meshPart.mesh
1756 meshPart = self.mesh
1757 self.mesh.ExportGMF(meshPart, f, True)
1759 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1760 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1761 ## allowing to overwrite the file if it exists or add the exported data to its contents
1762 # @param f the file name
1763 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1764 # @param opt boolean parameter for creating/not creating
1765 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1766 # @param overwrite boolean parameter for overwriting/not overwriting the file
1767 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1768 # - 1D if all mesh nodes lie on OX coordinate axis, or
1769 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1770 # - 3D in the rest cases.
1772 # If @a autoDimension is @c False, the space dimension is always 3.
1773 # @ingroup l2_impexp
1774 def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1775 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1777 # Operations with groups:
1778 # ----------------------
1780 ## Creates an empty mesh group
1781 # @param elementType the type of elements in the group
1782 # @param name the name of the mesh group
1783 # @return SMESH_Group
1784 # @ingroup l2_grps_create
1785 def CreateEmptyGroup(self, elementType, name):
1786 return self.mesh.CreateGroup(elementType, name)
1788 ## Creates a mesh group based on the geometric object \a grp
1789 # and gives a \a name, \n if this parameter is not defined
1790 # the name is the same as the geometric group name \n
1791 # Note: Works like GroupOnGeom().
1792 # @param grp a geometric group, a vertex, an edge, a face or a solid
1793 # @param name the name of the mesh group
1794 # @return SMESH_GroupOnGeom
1795 # @ingroup l2_grps_create
1796 def Group(self, grp, name=""):
1797 return self.GroupOnGeom(grp, name)
1799 ## Creates a mesh group based on the geometrical object \a grp
1800 # and gives a \a name, \n if this parameter is not defined
1801 # the name is the same as the geometrical group name
1802 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1803 # @param name the name of the mesh group
1804 # @param typ the type of elements in the group. If not set, it is
1805 # automatically detected by the type of the geometry
1806 # @return SMESH_GroupOnGeom
1807 # @ingroup l2_grps_create
1808 def GroupOnGeom(self, grp, name="", typ=None):
1809 AssureGeomPublished( self, grp, name )
1811 name = grp.GetName()
1813 typ = self._groupTypeFromShape( grp )
1814 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1816 ## Pivate method to get a type of group on geometry
1817 def _groupTypeFromShape( self, shape ):
1818 tgeo = str(shape.GetShapeType())
1819 if tgeo == "VERTEX":
1821 elif tgeo == "EDGE":
1823 elif tgeo == "FACE" or tgeo == "SHELL":
1825 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1827 elif tgeo == "COMPOUND":
1828 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1830 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1831 return self._groupTypeFromShape( sub[0] )
1834 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1837 ## Creates a mesh group with given \a name based on the \a filter which
1838 ## is a special type of group dynamically updating it's contents during
1839 ## mesh modification
1840 # @param typ the type of elements in the group
1841 # @param name the name of the mesh group
1842 # @param filter the filter defining group contents
1843 # @return SMESH_GroupOnFilter
1844 # @ingroup l2_grps_create
1845 def GroupOnFilter(self, typ, name, filter):
1846 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1848 ## Creates a mesh group by the given ids of elements
1849 # @param groupName the name of the mesh group
1850 # @param elementType the type of elements in the group
1851 # @param elemIDs the list of ids
1852 # @return SMESH_Group
1853 # @ingroup l2_grps_create
1854 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1855 group = self.mesh.CreateGroup(elementType, groupName)
1859 ## Creates a mesh group by the given conditions
1860 # @param groupName the name of the mesh group
1861 # @param elementType the type of elements in the group
1862 # @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1863 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1864 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
1865 # @param UnaryOp FT_LogicalNOT or FT_Undefined
1866 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1867 # FT_LyingOnGeom, FT_CoplanarFaces criteria
1868 # @return SMESH_Group
1869 # @ingroup l2_grps_create
1873 CritType=FT_Undefined,
1876 UnaryOp=FT_Undefined,
1878 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1879 group = self.MakeGroupByCriterion(groupName, aCriterion)
1882 ## Creates a mesh group by the given criterion
1883 # @param groupName the name of the mesh group
1884 # @param Criterion the instance of Criterion class
1885 # @return SMESH_Group
1886 # @ingroup l2_grps_create
1887 def MakeGroupByCriterion(self, groupName, Criterion):
1888 aFilterMgr = self.smeshpyD.CreateFilterManager()
1889 aFilter = aFilterMgr.CreateFilter()
1891 aCriteria.append(Criterion)
1892 aFilter.SetCriteria(aCriteria)
1893 group = self.MakeGroupByFilter(groupName, aFilter)
1894 aFilterMgr.UnRegister()
1897 ## Creates a mesh group by the given criteria (list of criteria)
1898 # @param groupName the name of the mesh group
1899 # @param theCriteria the list of criteria
1900 # @return SMESH_Group
1901 # @ingroup l2_grps_create
1902 def MakeGroupByCriteria(self, groupName, theCriteria):
1903 aFilterMgr = self.smeshpyD.CreateFilterManager()
1904 aFilter = aFilterMgr.CreateFilter()
1905 aFilter.SetCriteria(theCriteria)
1906 group = self.MakeGroupByFilter(groupName, aFilter)
1907 aFilterMgr.UnRegister()
1910 ## Creates a mesh group by the given filter
1911 # @param groupName the name of the mesh group
1912 # @param theFilter the instance of Filter class
1913 # @return SMESH_Group
1914 # @ingroup l2_grps_create
1915 def MakeGroupByFilter(self, groupName, theFilter):
1916 group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1917 theFilter.SetMesh( self.mesh )
1918 group.AddFrom( theFilter )
1922 # @ingroup l2_grps_delete
1923 def RemoveGroup(self, group):
1924 self.mesh.RemoveGroup(group)
1926 ## Removes a group with its contents
1927 # @ingroup l2_grps_delete
1928 def RemoveGroupWithContents(self, group):
1929 self.mesh.RemoveGroupWithContents(group)
1931 ## Gets the list of groups existing in the mesh in the order of creation (starting from the oldest one)
1932 # @return a sequence of SMESH_GroupBase
1933 # @ingroup l2_grps_create
1934 def GetGroups(self):
1935 return self.mesh.GetGroups()
1937 ## Gets the number of groups existing in the mesh
1938 # @return the quantity of groups as an integer value
1939 # @ingroup l2_grps_create
1941 return self.mesh.NbGroups()
1943 ## Gets the list of names of groups existing in the mesh
1944 # @return list of strings
1945 # @ingroup l2_grps_create
1946 def GetGroupNames(self):
1947 groups = self.GetGroups()
1949 for group in groups:
1950 names.append(group.GetName())
1953 ## Produces a union of two groups
1954 # A new group is created. All mesh elements that are
1955 # present in the initial groups are added to the new one
1956 # @return an instance of SMESH_Group
1957 # @ingroup l2_grps_operon
1958 def UnionGroups(self, group1, group2, name):
1959 return self.mesh.UnionGroups(group1, group2, name)
1961 ## Produces a union list of groups
1962 # New group is created. All mesh elements that are present in
1963 # initial groups are added to the new one
1964 # @return an instance of SMESH_Group
1965 # @ingroup l2_grps_operon
1966 def UnionListOfGroups(self, groups, name):
1967 return self.mesh.UnionListOfGroups(groups, name)
1969 ## Prodices an intersection of two groups
1970 # A new group is created. All mesh elements that are common
1971 # for the two initial groups are added to the new one.
1972 # @return an instance of SMESH_Group
1973 # @ingroup l2_grps_operon
1974 def IntersectGroups(self, group1, group2, name):
1975 return self.mesh.IntersectGroups(group1, group2, name)
1977 ## Produces an intersection of groups
1978 # New group is created. All mesh elements that are present in all
1979 # initial groups simultaneously are added to the new one
1980 # @return an instance of SMESH_Group
1981 # @ingroup l2_grps_operon
1982 def IntersectListOfGroups(self, groups, name):
1983 return self.mesh.IntersectListOfGroups(groups, name)
1985 ## Produces a cut of two groups
1986 # A new group is created. All mesh elements that are present in
1987 # the main group but are not present in the tool group are added to the new one
1988 # @return an instance of SMESH_Group
1989 # @ingroup l2_grps_operon
1990 def CutGroups(self, main_group, tool_group, name):
1991 return self.mesh.CutGroups(main_group, tool_group, name)
1993 ## Produces a cut of groups
1994 # A new group is created. All mesh elements that are present in main groups
1995 # but do not present in tool groups are added to the new one
1996 # @return an instance of SMESH_Group
1997 # @ingroup l2_grps_operon
1998 def CutListOfGroups(self, main_groups, tool_groups, name):
1999 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2001 ## Produces a group of elements of specified type using list of existing groups
2002 # A new group is created. System
2003 # 1) extracts all nodes on which groups elements are built
2004 # 2) combines all elements of specified dimension laying on these nodes
2005 # @return an instance of SMESH_Group
2006 # @ingroup l2_grps_operon
2007 def CreateDimGroup(self, groups, elem_type, name):
2008 return self.mesh.CreateDimGroup(groups, elem_type, name)
2011 ## Convert group on geom into standalone group
2012 # @ingroup l2_grps_delete
2013 def ConvertToStandalone(self, group):
2014 return self.mesh.ConvertToStandalone(group)
2016 # Get some info about mesh:
2017 # ------------------------
2019 ## Returns the log of nodes and elements added or removed
2020 # since the previous clear of the log.
2021 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2022 # @return list of log_block structures:
2027 # @ingroup l1_auxiliary
2028 def GetLog(self, clearAfterGet):
2029 return self.mesh.GetLog(clearAfterGet)
2031 ## Clears the log of nodes and elements added or removed since the previous
2032 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2033 # @ingroup l1_auxiliary
2035 self.mesh.ClearLog()
2037 ## Toggles auto color mode on the object.
2038 # @param theAutoColor the flag which toggles auto color mode.
2039 # @ingroup l1_auxiliary
2040 def SetAutoColor(self, theAutoColor):
2041 self.mesh.SetAutoColor(theAutoColor)
2043 ## Gets flag of object auto color mode.
2044 # @return True or False
2045 # @ingroup l1_auxiliary
2046 def GetAutoColor(self):
2047 return self.mesh.GetAutoColor()
2049 ## Gets the internal ID
2050 # @return integer value, which is the internal Id of the mesh
2051 # @ingroup l1_auxiliary
2053 return self.mesh.GetId()
2056 # @return integer value, which is the study Id of the mesh
2057 # @ingroup l1_auxiliary
2058 def GetStudyId(self):
2059 return self.mesh.GetStudyId()
2061 ## Checks the group names for duplications.
2062 # Consider the maximum group name length stored in MED file.
2063 # @return True or False
2064 # @ingroup l1_auxiliary
2065 def HasDuplicatedGroupNamesMED(self):
2066 return self.mesh.HasDuplicatedGroupNamesMED()
2068 ## Obtains the mesh editor tool
2069 # @return an instance of SMESH_MeshEditor
2070 # @ingroup l1_modifying
2071 def GetMeshEditor(self):
2074 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2075 # can be passed as argument to a method accepting mesh, group or sub-mesh
2076 # @return an instance of SMESH_IDSource
2077 # @ingroup l1_auxiliary
2078 def GetIDSource(self, ids, elemType):
2079 return self.editor.MakeIDSource(ids, elemType)
2082 # Get informations about mesh contents:
2083 # ------------------------------------
2085 ## Gets the mesh stattistic
2086 # @return dictionary type element - count of elements
2087 # @ingroup l1_meshinfo
2088 def GetMeshInfo(self, obj = None):
2089 if not obj: obj = self.mesh
2090 return self.smeshpyD.GetMeshInfo(obj)
2092 ## Returns the number of nodes in the mesh
2093 # @return an integer value
2094 # @ingroup l1_meshinfo
2096 return self.mesh.NbNodes()
2098 ## Returns the number of elements in the mesh
2099 # @return an integer value
2100 # @ingroup l1_meshinfo
2101 def NbElements(self):
2102 return self.mesh.NbElements()
2104 ## Returns the number of 0d elements in the mesh
2105 # @return an integer value
2106 # @ingroup l1_meshinfo
2107 def Nb0DElements(self):
2108 return self.mesh.Nb0DElements()
2110 ## Returns the number of ball discrete elements in the mesh
2111 # @return an integer value
2112 # @ingroup l1_meshinfo
2114 return self.mesh.NbBalls()
2116 ## Returns the number of edges in the mesh
2117 # @return an integer value
2118 # @ingroup l1_meshinfo
2120 return self.mesh.NbEdges()
2122 ## Returns the number of edges with the given order in the mesh
2123 # @param elementOrder the order of elements:
2124 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2125 # @return an integer value
2126 # @ingroup l1_meshinfo
2127 def NbEdgesOfOrder(self, elementOrder):
2128 return self.mesh.NbEdgesOfOrder(elementOrder)
2130 ## Returns the number of faces in the mesh
2131 # @return an integer value
2132 # @ingroup l1_meshinfo
2134 return self.mesh.NbFaces()
2136 ## Returns the number of faces with the given order in the mesh
2137 # @param elementOrder the order of elements:
2138 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2139 # @return an integer value
2140 # @ingroup l1_meshinfo
2141 def NbFacesOfOrder(self, elementOrder):
2142 return self.mesh.NbFacesOfOrder(elementOrder)
2144 ## Returns the number of triangles in the mesh
2145 # @return an integer value
2146 # @ingroup l1_meshinfo
2147 def NbTriangles(self):
2148 return self.mesh.NbTriangles()
2150 ## Returns the number of triangles with the given order in the mesh
2151 # @param elementOrder is the order of elements:
2152 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2153 # @return an integer value
2154 # @ingroup l1_meshinfo
2155 def NbTrianglesOfOrder(self, elementOrder):
2156 return self.mesh.NbTrianglesOfOrder(elementOrder)
2158 ## Returns the number of biquadratic triangles in the mesh
2159 # @return an integer value
2160 # @ingroup l1_meshinfo
2161 def NbBiQuadTriangles(self):
2162 return self.mesh.NbBiQuadTriangles()
2164 ## Returns the number of quadrangles in the mesh
2165 # @return an integer value
2166 # @ingroup l1_meshinfo
2167 def NbQuadrangles(self):
2168 return self.mesh.NbQuadrangles()
2170 ## Returns the number of quadrangles with the given order in the mesh
2171 # @param elementOrder the order of elements:
2172 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2173 # @return an integer value
2174 # @ingroup l1_meshinfo
2175 def NbQuadranglesOfOrder(self, elementOrder):
2176 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2178 ## Returns the number of biquadratic quadrangles in the mesh
2179 # @return an integer value
2180 # @ingroup l1_meshinfo
2181 def NbBiQuadQuadrangles(self):
2182 return self.mesh.NbBiQuadQuadrangles()
2184 ## Returns the number of polygons in the mesh
2185 # @return an integer value
2186 # @ingroup l1_meshinfo
2187 def NbPolygons(self):
2188 return self.mesh.NbPolygons()
2190 ## Returns the number of volumes in the mesh
2191 # @return an integer value
2192 # @ingroup l1_meshinfo
2193 def NbVolumes(self):
2194 return self.mesh.NbVolumes()
2196 ## Returns the number of volumes with the given order in the mesh
2197 # @param elementOrder the order of elements:
2198 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2199 # @return an integer value
2200 # @ingroup l1_meshinfo
2201 def NbVolumesOfOrder(self, elementOrder):
2202 return self.mesh.NbVolumesOfOrder(elementOrder)
2204 ## Returns the number of tetrahedrons in the mesh
2205 # @return an integer value
2206 # @ingroup l1_meshinfo
2208 return self.mesh.NbTetras()
2210 ## Returns the number of tetrahedrons with the given order in the mesh
2211 # @param elementOrder the order of elements:
2212 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2213 # @return an integer value
2214 # @ingroup l1_meshinfo
2215 def NbTetrasOfOrder(self, elementOrder):
2216 return self.mesh.NbTetrasOfOrder(elementOrder)
2218 ## Returns the number of hexahedrons in the mesh
2219 # @return an integer value
2220 # @ingroup l1_meshinfo
2222 return self.mesh.NbHexas()
2224 ## Returns the number of hexahedrons with the given order in the mesh
2225 # @param elementOrder the order of elements:
2226 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2227 # @return an integer value
2228 # @ingroup l1_meshinfo
2229 def NbHexasOfOrder(self, elementOrder):
2230 return self.mesh.NbHexasOfOrder(elementOrder)
2232 ## Returns the number of triquadratic hexahedrons in the mesh
2233 # @return an integer value
2234 # @ingroup l1_meshinfo
2235 def NbTriQuadraticHexas(self):
2236 return self.mesh.NbTriQuadraticHexas()
2238 ## Returns the number of pyramids in the mesh
2239 # @return an integer value
2240 # @ingroup l1_meshinfo
2241 def NbPyramids(self):
2242 return self.mesh.NbPyramids()
2244 ## Returns the number of pyramids with the given order in the mesh
2245 # @param elementOrder the order of elements:
2246 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2247 # @return an integer value
2248 # @ingroup l1_meshinfo
2249 def NbPyramidsOfOrder(self, elementOrder):
2250 return self.mesh.NbPyramidsOfOrder(elementOrder)
2252 ## Returns the number of prisms in the mesh
2253 # @return an integer value
2254 # @ingroup l1_meshinfo
2256 return self.mesh.NbPrisms()
2258 ## Returns the number of prisms with the given order in the mesh
2259 # @param elementOrder the order of elements:
2260 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2261 # @return an integer value
2262 # @ingroup l1_meshinfo
2263 def NbPrismsOfOrder(self, elementOrder):
2264 return self.mesh.NbPrismsOfOrder(elementOrder)
2266 ## Returns the number of hexagonal prisms in the mesh
2267 # @return an integer value
2268 # @ingroup l1_meshinfo
2269 def NbHexagonalPrisms(self):
2270 return self.mesh.NbHexagonalPrisms()
2272 ## Returns the number of polyhedrons in the mesh
2273 # @return an integer value
2274 # @ingroup l1_meshinfo
2275 def NbPolyhedrons(self):
2276 return self.mesh.NbPolyhedrons()
2278 ## Returns the number of submeshes in the mesh
2279 # @return an integer value
2280 # @ingroup l1_meshinfo
2281 def NbSubMesh(self):
2282 return self.mesh.NbSubMesh()
2284 ## Returns the list of mesh elements IDs
2285 # @return the list of integer values
2286 # @ingroup l1_meshinfo
2287 def GetElementsId(self):
2288 return self.mesh.GetElementsId()
2290 ## Returns the list of IDs of mesh elements with the given type
2291 # @param elementType the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2292 # @return list of integer values
2293 # @ingroup l1_meshinfo
2294 def GetElementsByType(self, elementType):
2295 return self.mesh.GetElementsByType(elementType)
2297 ## Returns the list of mesh nodes IDs
2298 # @return the list of integer values
2299 # @ingroup l1_meshinfo
2300 def GetNodesId(self):
2301 return self.mesh.GetNodesId()
2303 # Get the information about mesh elements:
2304 # ------------------------------------
2306 ## Returns the type of mesh element
2307 # @return the value from SMESH::ElementType enumeration
2308 # @ingroup l1_meshinfo
2309 def GetElementType(self, id, iselem):
2310 return self.mesh.GetElementType(id, iselem)
2312 ## Returns the geometric type of mesh element
2313 # @return the value from SMESH::EntityType enumeration
2314 # @ingroup l1_meshinfo
2315 def GetElementGeomType(self, id):
2316 return self.mesh.GetElementGeomType(id)
2318 ## Returns the shape type of mesh element
2319 # @return the value from SMESH::GeometryType enumeration
2320 # @ingroup l1_meshinfo
2321 def GetElementShape(self, id):
2322 return self.mesh.GetElementShape(id)
2324 ## Returns the list of submesh elements IDs
2325 # @param Shape a geom object(sub-shape) IOR
2326 # Shape must be the sub-shape of a ShapeToMesh()
2327 # @return the list of integer values
2328 # @ingroup l1_meshinfo
2329 def GetSubMeshElementsId(self, Shape):
2330 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2331 ShapeID = Shape.GetSubShapeIndices()[0]
2334 return self.mesh.GetSubMeshElementsId(ShapeID)
2336 ## Returns the list of submesh nodes IDs
2337 # @param Shape a geom object(sub-shape) IOR
2338 # Shape must be the sub-shape of a ShapeToMesh()
2339 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2340 # @return the list of integer values
2341 # @ingroup l1_meshinfo
2342 def GetSubMeshNodesId(self, Shape, all):
2343 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2344 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2347 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2349 ## Returns type of elements on given shape
2350 # @param Shape a geom object(sub-shape) IOR
2351 # Shape must be a sub-shape of a ShapeToMesh()
2352 # @return element type
2353 # @ingroup l1_meshinfo
2354 def GetSubMeshElementType(self, Shape):
2355 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2356 ShapeID = Shape.GetSubShapeIndices()[0]
2359 return self.mesh.GetSubMeshElementType(ShapeID)
2361 ## Gets the mesh description
2362 # @return string value
2363 # @ingroup l1_meshinfo
2365 return self.mesh.Dump()
2368 # Get the information about nodes and elements of a mesh by its IDs:
2369 # -----------------------------------------------------------
2371 ## Gets XYZ coordinates of a node
2372 # \n If there is no nodes for the given ID - returns an empty list
2373 # @return a list of double precision values
2374 # @ingroup l1_meshinfo
2375 def GetNodeXYZ(self, id):
2376 return self.mesh.GetNodeXYZ(id)
2378 ## Returns list of IDs of inverse elements for the given node
2379 # \n If there is no node for the given ID - returns an empty list
2380 # @return a list of integer values
2381 # @ingroup l1_meshinfo
2382 def GetNodeInverseElements(self, id):
2383 return self.mesh.GetNodeInverseElements(id)
2385 ## @brief Returns the position of a node on the shape
2386 # @return SMESH::NodePosition
2387 # @ingroup l1_meshinfo
2388 def GetNodePosition(self,NodeID):
2389 return self.mesh.GetNodePosition(NodeID)
2391 ## @brief Returns the position of an element on the shape
2392 # @return SMESH::ElementPosition
2393 # @ingroup l1_meshinfo
2394 def GetElementPosition(self,ElemID):
2395 return self.mesh.GetElementPosition(ElemID)
2397 ## If the given element is a node, returns the ID of shape
2398 # \n If there is no node for the given ID - returns -1
2399 # @return an integer value
2400 # @ingroup l1_meshinfo
2401 def GetShapeID(self, id):
2402 return self.mesh.GetShapeID(id)
2404 ## Returns the ID of the result shape after
2405 # FindShape() from SMESH_MeshEditor for the given element
2406 # \n If there is no element for the given ID - returns -1
2407 # @return an integer value
2408 # @ingroup l1_meshinfo
2409 def GetShapeIDForElem(self,id):
2410 return self.mesh.GetShapeIDForElem(id)
2412 ## Returns the number of nodes for the given element
2413 # \n If there is no element for the given ID - returns -1
2414 # @return an integer value
2415 # @ingroup l1_meshinfo
2416 def GetElemNbNodes(self, id):
2417 return self.mesh.GetElemNbNodes(id)
2419 ## Returns the node ID the given (zero based) index for the given element
2420 # \n If there is no element for the given ID - returns -1
2421 # \n If there is no node for the given index - returns -2
2422 # @return an integer value
2423 # @ingroup l1_meshinfo
2424 def GetElemNode(self, id, index):
2425 return self.mesh.GetElemNode(id, index)
2427 ## Returns the IDs of nodes of the given element
2428 # @return a list of integer values
2429 # @ingroup l1_meshinfo
2430 def GetElemNodes(self, id):
2431 return self.mesh.GetElemNodes(id)
2433 ## Returns true if the given node is the medium node in the given quadratic element
2434 # @ingroup l1_meshinfo
2435 def IsMediumNode(self, elementID, nodeID):
2436 return self.mesh.IsMediumNode(elementID, nodeID)
2438 ## Returns true if the given node is the medium node in one of quadratic elements
2439 # @ingroup l1_meshinfo
2440 def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2441 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2443 ## Returns the number of edges for the given element
2444 # @ingroup l1_meshinfo
2445 def ElemNbEdges(self, id):
2446 return self.mesh.ElemNbEdges(id)
2448 ## Returns the number of faces for the given element
2449 # @ingroup l1_meshinfo
2450 def ElemNbFaces(self, id):
2451 return self.mesh.ElemNbFaces(id)
2453 ## Returns nodes of given face (counted from zero) for given volumic element.
2454 # @ingroup l1_meshinfo
2455 def GetElemFaceNodes(self,elemId, faceIndex):
2456 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2458 ## Returns three components of normal of given mesh face
2459 # (or an empty array in KO case)
2460 # @ingroup l1_meshinfo
2461 def GetFaceNormal(self, faceId, normalized=False):
2462 return self.mesh.GetFaceNormal(faceId,normalized)
2464 ## Returns an element based on all given nodes.
2465 # @ingroup l1_meshinfo
2466 def FindElementByNodes(self,nodes):
2467 return self.mesh.FindElementByNodes(nodes)
2469 ## Returns true if the given element is a polygon
2470 # @ingroup l1_meshinfo
2471 def IsPoly(self, id):
2472 return self.mesh.IsPoly(id)
2474 ## Returns true if the given element is quadratic
2475 # @ingroup l1_meshinfo
2476 def IsQuadratic(self, id):
2477 return self.mesh.IsQuadratic(id)
2479 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2480 # @ingroup l1_meshinfo
2481 def GetBallDiameter(self, id):
2482 return self.mesh.GetBallDiameter(id)
2484 ## Returns XYZ coordinates of the barycenter of the given element
2485 # \n If there is no element for the given ID - returns an empty list
2486 # @return a list of three double values
2487 # @ingroup l1_meshinfo
2488 def BaryCenter(self, id):
2489 return self.mesh.BaryCenter(id)
2491 ## Passes mesh elements through the given filter and return IDs of fitting elements
2492 # @param theFilter SMESH_Filter
2493 # @return a list of ids
2494 # @ingroup l1_controls
2495 def GetIdsFromFilter(self, theFilter):
2496 theFilter.SetMesh( self.mesh )
2497 return theFilter.GetIDs()
2499 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2500 # Returns a list of special structures (borders).
2501 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2502 # @ingroup l1_controls
2503 def GetFreeBorders(self):
2504 aFilterMgr = self.smeshpyD.CreateFilterManager()
2505 aPredicate = aFilterMgr.CreateFreeEdges()
2506 aPredicate.SetMesh(self.mesh)
2507 aBorders = aPredicate.GetBorders()
2508 aFilterMgr.UnRegister()
2512 # Get mesh measurements information:
2513 # ------------------------------------
2515 ## Get minimum distance between two nodes, elements or distance to the origin
2516 # @param id1 first node/element id
2517 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2518 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2519 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2520 # @return minimum distance value
2521 # @sa GetMinDistance()
2522 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2523 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2524 return aMeasure.value
2526 ## Get measure structure specifying minimum distance data between two objects
2527 # @param id1 first node/element id
2528 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2529 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2530 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2531 # @return Measure structure
2533 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2535 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2537 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2540 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2542 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2547 aMeasurements = self.smeshpyD.CreateMeasurements()
2548 aMeasure = aMeasurements.MinDistance(id1, id2)
2549 genObjUnRegister([aMeasurements,id1, id2])
2552 ## Get bounding box of the specified object(s)
2553 # @param objects single source object or list of source objects or list of nodes/elements IDs
2554 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2555 # @c False specifies that @a objects are nodes
2556 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2557 # @sa GetBoundingBox()
2558 def BoundingBox(self, objects=None, isElem=False):
2559 result = self.GetBoundingBox(objects, isElem)
2563 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2566 ## Get measure structure specifying bounding box data of the specified object(s)
2567 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2568 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2569 # @c False specifies that @a objects are nodes
2570 # @return Measure structure
2572 def GetBoundingBox(self, IDs=None, isElem=False):
2575 elif isinstance(IDs, tuple):
2577 if not isinstance(IDs, list):
2579 if len(IDs) > 0 and isinstance(IDs[0], int):
2582 unRegister = genObjUnRegister()
2584 if isinstance(o, Mesh):
2585 srclist.append(o.mesh)
2586 elif hasattr(o, "_narrow"):
2587 src = o._narrow(SMESH.SMESH_IDSource)
2588 if src: srclist.append(src)
2590 elif isinstance(o, list):
2592 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2594 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2595 unRegister.set( srclist[-1] )
2598 aMeasurements = self.smeshpyD.CreateMeasurements()
2599 unRegister.set( aMeasurements )
2600 aMeasure = aMeasurements.BoundingBox(srclist)
2603 # Mesh edition (SMESH_MeshEditor functionality):
2604 # ---------------------------------------------
2606 ## Removes the elements from the mesh by ids
2607 # @param IDsOfElements is a list of ids of elements to remove
2608 # @return True or False
2609 # @ingroup l2_modif_del
2610 def RemoveElements(self, IDsOfElements):
2611 return self.editor.RemoveElements(IDsOfElements)
2613 ## Removes nodes from mesh by ids
2614 # @param IDsOfNodes is a list of ids of nodes to remove
2615 # @return True or False
2616 # @ingroup l2_modif_del
2617 def RemoveNodes(self, IDsOfNodes):
2618 return self.editor.RemoveNodes(IDsOfNodes)
2620 ## Removes all orphan (free) nodes from mesh
2621 # @return number of the removed nodes
2622 # @ingroup l2_modif_del
2623 def RemoveOrphanNodes(self):
2624 return self.editor.RemoveOrphanNodes()
2626 ## Add a node to the mesh by coordinates
2627 # @return Id of the new node
2628 # @ingroup l2_modif_add
2629 def AddNode(self, x, y, z):
2630 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2631 if hasVars: self.mesh.SetParameters(Parameters)
2632 return self.editor.AddNode( x, y, z)
2634 ## Creates a 0D element on a node with given number.
2635 # @param IDOfNode the ID of node for creation of the element.
2636 # @return the Id of the new 0D element
2637 # @ingroup l2_modif_add
2638 def Add0DElement(self, IDOfNode):
2639 return self.editor.Add0DElement(IDOfNode)
2641 ## Create 0D elements on all nodes of the given elements except those
2642 # nodes on which a 0D element already exists.
2643 # @param theObject an object on whose nodes 0D elements will be created.
2644 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2645 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2646 # @param theGroupName optional name of a group to add 0D elements created
2647 # and/or found on nodes of \a theObject.
2648 # @return an object (a new group or a temporary SMESH_IDSource) holding
2649 # IDs of new and/or found 0D elements. IDs of 0D elements
2650 # can be retrieved from the returned object by calling GetIDs()
2651 # @ingroup l2_modif_add
2652 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2653 unRegister = genObjUnRegister()
2654 if isinstance( theObject, Mesh ):
2655 theObject = theObject.GetMesh()
2656 if isinstance( theObject, list ):
2657 theObject = self.GetIDSource( theObject, SMESH.ALL )
2658 unRegister.set( theObject )
2659 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2661 ## Creates a ball element on a node with given ID.
2662 # @param IDOfNode the ID of node for creation of the element.
2663 # @param diameter the bal diameter.
2664 # @return the Id of the new ball element
2665 # @ingroup l2_modif_add
2666 def AddBall(self, IDOfNode, diameter):
2667 return self.editor.AddBall( IDOfNode, diameter )
2669 ## Creates a linear or quadratic edge (this is determined
2670 # by the number of given nodes).
2671 # @param IDsOfNodes the list of node IDs for creation of the element.
2672 # The order of nodes in this list should correspond to the description
2673 # of MED. \n This description is located by the following link:
2674 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2675 # @return the Id of the new edge
2676 # @ingroup l2_modif_add
2677 def AddEdge(self, IDsOfNodes):
2678 return self.editor.AddEdge(IDsOfNodes)
2680 ## Creates a linear or quadratic face (this is determined
2681 # by the number of given nodes).
2682 # @param IDsOfNodes the list of node IDs for creation of the element.
2683 # The order of nodes in this list should correspond to the description
2684 # of MED. \n This description is located by the following link:
2685 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2686 # @return the Id of the new face
2687 # @ingroup l2_modif_add
2688 def AddFace(self, IDsOfNodes):
2689 return self.editor.AddFace(IDsOfNodes)
2691 ## Adds a polygonal face to the mesh by the list of node IDs
2692 # @param IdsOfNodes the list of node IDs for creation of the element.
2693 # @return the Id of the new face
2694 # @ingroup l2_modif_add
2695 def AddPolygonalFace(self, IdsOfNodes):
2696 return self.editor.AddPolygonalFace(IdsOfNodes)
2698 ## Creates both simple and quadratic volume (this is determined
2699 # by the number of given nodes).
2700 # @param IDsOfNodes the list of node IDs for creation of the element.
2701 # The order of nodes in this list should correspond to the description
2702 # of MED. \n This description is located by the following link:
2703 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2704 # @return the Id of the new volumic element
2705 # @ingroup l2_modif_add
2706 def AddVolume(self, IDsOfNodes):
2707 return self.editor.AddVolume(IDsOfNodes)
2709 ## Creates a volume of many faces, giving nodes for each face.
2710 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2711 # @param Quantities the list of integer values, Quantities[i]
2712 # gives the quantity of nodes in face number i.
2713 # @return the Id of the new volumic element
2714 # @ingroup l2_modif_add
2715 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2716 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2718 ## Creates a volume of many faces, giving the IDs of the existing faces.
2719 # @param IdsOfFaces the list of face IDs for volume creation.
2721 # Note: The created volume will refer only to the nodes
2722 # of the given faces, not to the faces themselves.
2723 # @return the Id of the new volumic element
2724 # @ingroup l2_modif_add
2725 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2726 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2729 ## @brief Binds a node to a vertex
2730 # @param NodeID a node ID
2731 # @param Vertex a vertex or vertex ID
2732 # @return True if succeed else raises an exception
2733 # @ingroup l2_modif_add
2734 def SetNodeOnVertex(self, NodeID, Vertex):
2735 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2736 VertexID = Vertex.GetSubShapeIndices()[0]
2740 self.editor.SetNodeOnVertex(NodeID, VertexID)
2741 except SALOME.SALOME_Exception, inst:
2742 raise ValueError, inst.details.text
2746 ## @brief Stores the node position on an edge
2747 # @param NodeID a node ID
2748 # @param Edge an edge or edge ID
2749 # @param paramOnEdge a parameter on the edge where the node is located
2750 # @return True if succeed else raises an exception
2751 # @ingroup l2_modif_add
2752 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2753 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2754 EdgeID = Edge.GetSubShapeIndices()[0]
2758 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2759 except SALOME.SALOME_Exception, inst:
2760 raise ValueError, inst.details.text
2763 ## @brief Stores node position on a face
2764 # @param NodeID a node ID
2765 # @param Face a face or face ID
2766 # @param u U parameter on the face where the node is located
2767 # @param v V parameter on the face where the node is located
2768 # @return True if succeed else raises an exception
2769 # @ingroup l2_modif_add
2770 def SetNodeOnFace(self, NodeID, Face, u, v):
2771 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2772 FaceID = Face.GetSubShapeIndices()[0]
2776 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2777 except SALOME.SALOME_Exception, inst:
2778 raise ValueError, inst.details.text
2781 ## @brief Binds a node to a solid
2782 # @param NodeID a node ID
2783 # @param Solid a solid or solid ID
2784 # @return True if succeed else raises an exception
2785 # @ingroup l2_modif_add
2786 def SetNodeInVolume(self, NodeID, Solid):
2787 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2788 SolidID = Solid.GetSubShapeIndices()[0]
2792 self.editor.SetNodeInVolume(NodeID, SolidID)
2793 except SALOME.SALOME_Exception, inst:
2794 raise ValueError, inst.details.text
2797 ## @brief Bind an element to a shape
2798 # @param ElementID an element ID
2799 # @param Shape a shape or shape ID
2800 # @return True if succeed else raises an exception
2801 # @ingroup l2_modif_add
2802 def SetMeshElementOnShape(self, ElementID, Shape):
2803 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2804 ShapeID = Shape.GetSubShapeIndices()[0]
2808 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2809 except SALOME.SALOME_Exception, inst:
2810 raise ValueError, inst.details.text
2814 ## Moves the node with the given id
2815 # @param NodeID the id of the node
2816 # @param x a new X coordinate
2817 # @param y a new Y coordinate
2818 # @param z a new Z coordinate
2819 # @return True if succeed else False
2820 # @ingroup l2_modif_movenode
2821 def MoveNode(self, NodeID, x, y, z):
2822 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2823 if hasVars: self.mesh.SetParameters(Parameters)
2824 return self.editor.MoveNode(NodeID, x, y, z)
2826 ## Finds the node closest to a point and moves it to a point location
2827 # @param x the X coordinate of a point
2828 # @param y the Y coordinate of a point
2829 # @param z the Z coordinate of a point
2830 # @param NodeID if specified (>0), the node with this ID is moved,
2831 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
2832 # @return the ID of a node
2833 # @ingroup l2_modif_throughp
2834 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2835 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2836 if hasVars: self.mesh.SetParameters(Parameters)
2837 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2839 ## Finds the node closest to a point
2840 # @param x the X coordinate of a point
2841 # @param y the Y coordinate of a point
2842 # @param z the Z coordinate of a point
2843 # @return the ID of a node
2844 # @ingroup l2_modif_throughp
2845 def FindNodeClosestTo(self, x, y, z):
2846 #preview = self.mesh.GetMeshEditPreviewer()
2847 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2848 return self.editor.FindNodeClosestTo(x, y, z)
2850 ## Finds the elements where a point lays IN or ON
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 elementType type of elements to find (SMESH.ALL type
2855 # means elements of any type excluding nodes, discrete and 0D elements)
2856 # @param meshPart a part of mesh (group, sub-mesh) to search within
2857 # @return list of IDs of found elements
2858 # @ingroup l2_modif_throughp
2859 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2861 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2863 return self.editor.FindElementsByPoint(x, y, z, elementType)
2865 # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2866 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2867 # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2869 def GetPointState(self, x, y, z):
2870 return self.editor.GetPointState(x, y, z)
2872 ## Finds the node closest to a point and moves it to a point location
2873 # @param x the X coordinate of a point
2874 # @param y the Y coordinate of a point
2875 # @param z the Z coordinate of a point
2876 # @return the ID of a moved node
2877 # @ingroup l2_modif_throughp
2878 def MeshToPassThroughAPoint(self, x, y, z):
2879 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2881 ## Replaces two neighbour triangles sharing Node1-Node2 link
2882 # with the triangles built on the same 4 nodes but having other common link.
2883 # @param NodeID1 the ID of the first node
2884 # @param NodeID2 the ID of the second node
2885 # @return false if proper faces were not found
2886 # @ingroup l2_modif_invdiag
2887 def InverseDiag(self, NodeID1, NodeID2):
2888 return self.editor.InverseDiag(NodeID1, NodeID2)
2890 ## Replaces two neighbour triangles sharing Node1-Node2 link
2891 # with a quadrangle built on the same 4 nodes.
2892 # @param NodeID1 the ID of the first node
2893 # @param NodeID2 the ID of the second node
2894 # @return false if proper faces were not found
2895 # @ingroup l2_modif_unitetri
2896 def DeleteDiag(self, NodeID1, NodeID2):
2897 return self.editor.DeleteDiag(NodeID1, NodeID2)
2899 ## Reorients elements by ids
2900 # @param IDsOfElements if undefined reorients all mesh elements
2901 # @return True if succeed else False
2902 # @ingroup l2_modif_changori
2903 def Reorient(self, IDsOfElements=None):
2904 if IDsOfElements == None:
2905 IDsOfElements = self.GetElementsId()
2906 return self.editor.Reorient(IDsOfElements)
2908 ## Reorients all elements of the object
2909 # @param theObject mesh, submesh or group
2910 # @return True if succeed else False
2911 # @ingroup l2_modif_changori
2912 def ReorientObject(self, theObject):
2913 if ( isinstance( theObject, Mesh )):
2914 theObject = theObject.GetMesh()
2915 return self.editor.ReorientObject(theObject)
2917 ## Reorient faces contained in \a the2DObject.
2918 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2919 # @param theDirection is a desired direction of normal of \a theFace.
2920 # It can be either a GEOM vector or a list of coordinates [x,y,z].
2921 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2922 # compared with theDirection. It can be either ID of face or a point
2923 # by which the face will be found. The point can be given as either
2924 # a GEOM vertex or a list of point coordinates.
2925 # @return number of reoriented faces
2926 # @ingroup l2_modif_changori
2927 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2928 unRegister = genObjUnRegister()
2930 if isinstance( the2DObject, Mesh ):
2931 the2DObject = the2DObject.GetMesh()
2932 if isinstance( the2DObject, list ):
2933 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2934 unRegister.set( the2DObject )
2935 # check theDirection
2936 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
2937 theDirection = self.smeshpyD.GetDirStruct( theDirection )
2938 if isinstance( theDirection, list ):
2939 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
2940 # prepare theFace and thePoint
2941 theFace = theFaceOrPoint
2942 thePoint = PointStruct(0,0,0)
2943 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
2944 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
2946 if isinstance( theFaceOrPoint, list ):
2947 thePoint = PointStruct( *theFaceOrPoint )
2949 if isinstance( theFaceOrPoint, PointStruct ):
2950 thePoint = theFaceOrPoint
2952 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
2954 ## Fuses the neighbouring triangles into quadrangles.
2955 # @param IDsOfElements The triangles to be fused,
2956 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2957 # choose a neighbour to fuse with.
2958 # @param MaxAngle is the maximum angle between element normals at which the fusion
2959 # is still performed; theMaxAngle is mesured in radians.
2960 # Also it could be a name of variable which defines angle in degrees.
2961 # @return TRUE in case of success, FALSE otherwise.
2962 # @ingroup l2_modif_unitetri
2963 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
2964 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2965 self.mesh.SetParameters(Parameters)
2966 if not IDsOfElements:
2967 IDsOfElements = self.GetElementsId()
2968 Functor = self.smeshpyD.GetFunctor(theCriterion)
2969 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
2971 ## Fuses the neighbouring triangles of the object into quadrangles
2972 # @param theObject is mesh, submesh or group
2973 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2974 # choose a neighbour to fuse with.
2975 # @param MaxAngle a max angle between element normals at which the fusion
2976 # is still performed; theMaxAngle is mesured in radians.
2977 # @return TRUE in case of success, FALSE otherwise.
2978 # @ingroup l2_modif_unitetri
2979 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
2980 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2981 self.mesh.SetParameters(Parameters)
2982 if isinstance( theObject, Mesh ):
2983 theObject = theObject.GetMesh()
2984 Functor = self.smeshpyD.GetFunctor(theCriterion)
2985 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
2987 ## Splits quadrangles into triangles.
2988 # @param IDsOfElements the faces to be splitted.
2989 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2990 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
2991 # value, then quadrangles will be split by the smallest diagonal.
2992 # @return TRUE in case of success, FALSE otherwise.
2993 # @ingroup l2_modif_cutquadr
2994 def QuadToTri (self, IDsOfElements, theCriterion = None):
2995 if IDsOfElements == []:
2996 IDsOfElements = self.GetElementsId()
2997 if theCriterion is None:
2998 theCriterion = FT_MaxElementLength2D
2999 Functor = self.smeshpyD.GetFunctor(theCriterion)
3000 return self.editor.QuadToTri(IDsOfElements, Functor)
3002 ## Splits quadrangles into triangles.
3003 # @param theObject the object from which the list of elements is taken,
3004 # this is mesh, submesh or group
3005 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3006 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3007 # value, then quadrangles will be split by the smallest diagonal.
3008 # @return TRUE in case of success, FALSE otherwise.
3009 # @ingroup l2_modif_cutquadr
3010 def QuadToTriObject (self, theObject, theCriterion = None):
3011 if ( isinstance( theObject, Mesh )):
3012 theObject = theObject.GetMesh()
3013 if theCriterion is None:
3014 theCriterion = FT_MaxElementLength2D
3015 Functor = self.smeshpyD.GetFunctor(theCriterion)
3016 return self.editor.QuadToTriObject(theObject, Functor)
3018 ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3020 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3021 # group or a list of face IDs. By default all quadrangles are split
3022 # @ingroup l2_modif_cutquadr
3023 def QuadTo4Tri (self, theElements=[]):
3024 unRegister = genObjUnRegister()
3025 if isinstance( theElements, Mesh ):
3026 theElements = theElements.mesh
3027 elif not theElements:
3028 theElements = self.mesh
3029 elif isinstance( theElements, list ):
3030 theElements = self.GetIDSource( theElements, SMESH.FACE )
3031 unRegister.set( theElements )
3032 return self.editor.QuadTo4Tri( theElements )
3034 ## Splits quadrangles into triangles.
3035 # @param IDsOfElements the faces to be splitted
3036 # @param Diag13 is used to choose a diagonal for splitting.
3037 # @return TRUE in case of success, FALSE otherwise.
3038 # @ingroup l2_modif_cutquadr
3039 def SplitQuad (self, IDsOfElements, Diag13):
3040 if IDsOfElements == []:
3041 IDsOfElements = self.GetElementsId()
3042 return self.editor.SplitQuad(IDsOfElements, Diag13)
3044 ## Splits quadrangles into triangles.
3045 # @param theObject the object from which the list of elements is taken,
3046 # this is mesh, submesh or group
3047 # @param Diag13 is used to choose a diagonal for splitting.
3048 # @return TRUE in case of success, FALSE otherwise.
3049 # @ingroup l2_modif_cutquadr
3050 def SplitQuadObject (self, theObject, Diag13):
3051 if ( isinstance( theObject, Mesh )):
3052 theObject = theObject.GetMesh()
3053 return self.editor.SplitQuadObject(theObject, Diag13)
3055 ## Finds a better splitting of the given quadrangle.
3056 # @param IDOfQuad the ID of the quadrangle to be splitted.
3057 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3058 # choose a diagonal for splitting.
3059 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3060 # diagonal is better, 0 if error occurs.
3061 # @ingroup l2_modif_cutquadr
3062 def BestSplit (self, IDOfQuad, theCriterion):
3063 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3065 ## Splits volumic elements into tetrahedrons
3066 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3067 # @param method flags passing splitting method:
3068 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3069 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3070 # @ingroup l2_modif_cutquadr
3071 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3072 unRegister = genObjUnRegister()
3073 if isinstance( elems, Mesh ):
3074 elems = elems.GetMesh()
3075 if ( isinstance( elems, list )):
3076 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3077 unRegister.set( elems )
3078 self.editor.SplitVolumesIntoTetra(elems, method)
3080 ## Splits hexahedra into prisms
3081 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3082 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3083 # gives a normal vector defining facets to split into triangles.
3084 # @a startHexPoint can be either a triple of coordinates or a vertex.
3085 # @param facetNormal a normal to a facet to split into triangles of a
3086 # hexahedron found by @a startHexPoint.
3087 # @a facetNormal can be either a triple of coordinates or an edge.
3088 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3089 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3090 # @param allDomains if @c False, only hexahedra adjacent to one closest
3091 # to @a startHexPoint are split, else @a startHexPoint
3092 # is used to find the facet to split in all domains present in @a elems.
3093 # @ingroup l2_modif_cutquadr
3094 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3095 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3097 unRegister = genObjUnRegister()
3098 if isinstance( elems, Mesh ):
3099 elems = elems.GetMesh()
3100 if ( isinstance( elems, list )):
3101 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3102 unRegister.set( elems )
3105 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3106 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3107 elif isinstance( startHexPoint, list ):
3108 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3111 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3112 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3113 elif isinstance( facetNormal, list ):
3114 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3117 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3119 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3121 ## Splits quadrangle faces near triangular facets of volumes
3123 # @ingroup l1_auxiliary
3124 def SplitQuadsNearTriangularFacets(self):
3125 faces_array = self.GetElementsByType(SMESH.FACE)
3126 for face_id in faces_array:
3127 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3128 quad_nodes = self.mesh.GetElemNodes(face_id)
3129 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3130 isVolumeFound = False
3131 for node1_elem in node1_elems:
3132 if not isVolumeFound:
3133 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3134 nb_nodes = self.GetElemNbNodes(node1_elem)
3135 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3136 volume_elem = node1_elem
3137 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3138 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3139 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3140 isVolumeFound = True
3141 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3142 self.SplitQuad([face_id], False) # diagonal 2-4
3143 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3144 isVolumeFound = True
3145 self.SplitQuad([face_id], True) # diagonal 1-3
3146 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3147 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3148 isVolumeFound = True
3149 self.SplitQuad([face_id], True) # diagonal 1-3
3151 ## @brief Splits hexahedrons into tetrahedrons.
3153 # This operation uses pattern mapping functionality for splitting.
3154 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3155 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3156 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3157 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3158 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3159 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3160 # @return TRUE in case of success, FALSE otherwise.
3161 # @ingroup l1_auxiliary
3162 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3163 # Pattern: 5.---------.6
3168 # (0,0,1) 4.---------.7 * |
3175 # (0,0,0) 0.---------.3
3176 pattern_tetra = "!!! Nb of points: \n 8 \n\
3186 !!! Indices of points of 6 tetras: \n\
3194 pattern = self.smeshpyD.GetPattern()
3195 isDone = pattern.LoadFromFile(pattern_tetra)
3197 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3200 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3201 isDone = pattern.MakeMesh(self.mesh, False, False)
3202 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3204 # split quafrangle faces near triangular facets of volumes
3205 self.SplitQuadsNearTriangularFacets()
3209 ## @brief Split hexahedrons into prisms.
3211 # Uses the pattern mapping functionality for splitting.
3212 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3213 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3214 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3215 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3216 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3217 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3218 # @return TRUE in case of success, FALSE otherwise.
3219 # @ingroup l1_auxiliary
3220 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3221 # Pattern: 5.---------.6
3226 # (0,0,1) 4.---------.7 |
3233 # (0,0,0) 0.---------.3
3234 pattern_prism = "!!! Nb of points: \n 8 \n\
3244 !!! Indices of points of 2 prisms: \n\
3248 pattern = self.smeshpyD.GetPattern()
3249 isDone = pattern.LoadFromFile(pattern_prism)
3251 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3254 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3255 isDone = pattern.MakeMesh(self.mesh, False, False)
3256 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3258 # Splits quafrangle faces near triangular facets of volumes
3259 self.SplitQuadsNearTriangularFacets()
3263 ## Smoothes elements
3264 # @param IDsOfElements the list if ids of elements to smooth
3265 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3266 # Note that nodes built on edges and boundary nodes are always fixed.
3267 # @param MaxNbOfIterations the maximum number of iterations
3268 # @param MaxAspectRatio varies in range [1.0, inf]
3269 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3270 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3271 # @return TRUE in case of success, FALSE otherwise.
3272 # @ingroup l2_modif_smooth
3273 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3274 MaxNbOfIterations, MaxAspectRatio, Method):
3275 if IDsOfElements == []:
3276 IDsOfElements = self.GetElementsId()
3277 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3278 self.mesh.SetParameters(Parameters)
3279 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3280 MaxNbOfIterations, MaxAspectRatio, Method)
3282 ## Smoothes elements which belong to the given object
3283 # @param theObject the object to smooth
3284 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3285 # Note that nodes built on edges and boundary nodes are always fixed.
3286 # @param MaxNbOfIterations the maximum number of iterations
3287 # @param MaxAspectRatio varies in range [1.0, inf]
3288 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3289 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3290 # @return TRUE in case of success, FALSE otherwise.
3291 # @ingroup l2_modif_smooth
3292 def SmoothObject(self, theObject, IDsOfFixedNodes,
3293 MaxNbOfIterations, MaxAspectRatio, Method):
3294 if ( isinstance( theObject, Mesh )):
3295 theObject = theObject.GetMesh()
3296 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3297 MaxNbOfIterations, MaxAspectRatio, Method)
3299 ## Parametrically smoothes the given elements
3300 # @param IDsOfElements the list if ids of elements to smooth
3301 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3302 # Note that nodes built on edges and boundary nodes are always fixed.
3303 # @param MaxNbOfIterations the maximum number of iterations
3304 # @param MaxAspectRatio varies in range [1.0, inf]
3305 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3306 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3307 # @return TRUE in case of success, FALSE otherwise.
3308 # @ingroup l2_modif_smooth
3309 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3310 MaxNbOfIterations, MaxAspectRatio, Method):
3311 if IDsOfElements == []:
3312 IDsOfElements = self.GetElementsId()
3313 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3314 self.mesh.SetParameters(Parameters)
3315 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3316 MaxNbOfIterations, MaxAspectRatio, Method)
3318 ## Parametrically smoothes the elements which belong to the given object
3319 # @param theObject the object 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 SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3329 MaxNbOfIterations, MaxAspectRatio, Method):
3330 if ( isinstance( theObject, Mesh )):
3331 theObject = theObject.GetMesh()
3332 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3333 MaxNbOfIterations, MaxAspectRatio, Method)
3335 ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3336 # them with quadratic with the same id.
3337 # @param theForce3d new node creation method:
3338 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3339 # 1 - the medium node lies at the middle of the line segments connecting start and end node of a mesh element
3340 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3341 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3342 # @ingroup l2_modif_tofromqu
3343 def ConvertToQuadratic(self, theForce3d, theSubMesh=None, theToBiQuad=False):
3344 if isinstance( theSubMesh, Mesh ):
3345 theSubMesh = theSubMesh.mesh
3347 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3350 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3352 self.editor.ConvertToQuadratic(theForce3d)
3353 error = self.editor.GetLastError()
3354 if error and error.comment:
3357 ## Converts the mesh from quadratic to ordinary,
3358 # deletes old quadratic elements, \n replacing
3359 # them with ordinary mesh elements with the same id.
3360 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3361 # @ingroup l2_modif_tofromqu
3362 def ConvertFromQuadratic(self, theSubMesh=None):
3364 self.editor.ConvertFromQuadraticObject(theSubMesh)
3366 return self.editor.ConvertFromQuadratic()
3368 ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3369 # @return TRUE if operation has been completed successfully, FALSE otherwise
3370 # @ingroup l2_modif_edit
3371 def Make2DMeshFrom3D(self):
3372 return self.editor. Make2DMeshFrom3D()
3374 ## Creates missing boundary elements
3375 # @param elements - elements whose boundary is to be checked:
3376 # mesh, group, sub-mesh or list of elements
3377 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3378 # @param dimension - defines type of boundary elements to create:
3379 # SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D
3380 # SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3381 # @param groupName - a name of group to store created boundary elements in,
3382 # "" means not to create the group
3383 # @param meshName - a name of new mesh to store created boundary elements in,
3384 # "" means not to create the new mesh
3385 # @param toCopyElements - if true, the checked elements will be copied into
3386 # the new mesh else only boundary elements will be copied into the new mesh
3387 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3388 # boundary elements will be copied into the new mesh
3389 # @return tuple (mesh, group) where boundary elements were added to
3390 # @ingroup l2_modif_edit
3391 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3392 toCopyElements=False, toCopyExistingBondary=False):
3393 unRegister = genObjUnRegister()
3394 if isinstance( elements, Mesh ):
3395 elements = elements.GetMesh()
3396 if ( isinstance( elements, list )):
3397 elemType = SMESH.ALL
3398 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3399 elements = self.editor.MakeIDSource(elements, elemType)
3400 unRegister.set( elements )
3401 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3402 toCopyElements,toCopyExistingBondary)
3403 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3407 # @brief Creates missing boundary elements around either the whole mesh or
3408 # groups of 2D elements
3409 # @param dimension - defines type of boundary elements to create
3410 # @param groupName - a name of group to store all boundary elements in,
3411 # "" means not to create the group
3412 # @param meshName - a name of a new mesh, which is a copy of the initial
3413 # mesh + created boundary elements; "" means not to create the new mesh
3414 # @param toCopyAll - if true, the whole initial mesh will be copied into
3415 # the new mesh else only boundary elements will be copied into the new mesh
3416 # @param groups - groups of 2D elements to make boundary around
3417 # @retval tuple( long, mesh, groups )
3418 # long - number of added boundary elements
3419 # mesh - the mesh where elements were added to
3420 # group - the group of boundary elements or None
3422 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3423 toCopyAll=False, groups=[]):
3424 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3426 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3427 return nb, mesh, group
3429 ## Renumber mesh nodes
3430 # @ingroup l2_modif_renumber
3431 def RenumberNodes(self):
3432 self.editor.RenumberNodes()
3434 ## Renumber mesh elements
3435 # @ingroup l2_modif_renumber
3436 def RenumberElements(self):
3437 self.editor.RenumberElements()
3439 ## Generates new elements by rotation of the elements around the axis
3440 # @param IDsOfElements the list of ids of elements to sweep
3441 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3442 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3443 # @param NbOfSteps the number of steps
3444 # @param Tolerance tolerance
3445 # @param MakeGroups forces the generation of new groups from existing ones
3446 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3447 # of all steps, else - size of each step
3448 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3449 # @ingroup l2_modif_extrurev
3450 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3451 MakeGroups=False, TotalAngle=False):
3452 if IDsOfElements == []:
3453 IDsOfElements = self.GetElementsId()
3454 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3455 Axis = self.smeshpyD.GetAxisStruct(Axis)
3456 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3457 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3458 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3459 self.mesh.SetParameters(Parameters)
3460 if TotalAngle and NbOfSteps:
3461 AngleInRadians /= NbOfSteps
3463 return self.editor.RotationSweepMakeGroups(IDsOfElements, Axis,
3464 AngleInRadians, NbOfSteps, Tolerance)
3465 self.editor.RotationSweep(IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance)
3468 ## Generates new elements by rotation of the elements of object around the axis
3469 # @param theObject object which elements should be sweeped.
3470 # It can be a mesh, a sub mesh or a group.
3471 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3472 # @param AngleInRadians the angle of Rotation
3473 # @param NbOfSteps number of steps
3474 # @param Tolerance tolerance
3475 # @param MakeGroups forces the generation of new groups from existing ones
3476 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3477 # of all steps, else - size of each step
3478 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3479 # @ingroup l2_modif_extrurev
3480 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3481 MakeGroups=False, TotalAngle=False):
3482 if ( isinstance( theObject, Mesh )):
3483 theObject = theObject.GetMesh()
3484 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3485 Axis = self.smeshpyD.GetAxisStruct(Axis)
3486 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3487 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3488 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3489 self.mesh.SetParameters(Parameters)
3490 if TotalAngle and NbOfSteps:
3491 AngleInRadians /= NbOfSteps
3493 return self.editor.RotationSweepObjectMakeGroups(theObject, Axis, AngleInRadians,
3494 NbOfSteps, Tolerance)
3495 self.editor.RotationSweepObject(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3498 ## Generates new elements by rotation of the elements of object around the axis
3499 # @param theObject object which elements should be sweeped.
3500 # It can be a mesh, a sub mesh or a group.
3501 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3502 # @param AngleInRadians the angle of Rotation
3503 # @param NbOfSteps number of steps
3504 # @param Tolerance tolerance
3505 # @param MakeGroups forces the generation of new groups from existing ones
3506 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3507 # of all steps, else - size of each step
3508 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3509 # @ingroup l2_modif_extrurev
3510 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3511 MakeGroups=False, TotalAngle=False):
3512 if ( isinstance( theObject, Mesh )):
3513 theObject = theObject.GetMesh()
3514 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3515 Axis = self.smeshpyD.GetAxisStruct(Axis)
3516 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3517 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3518 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3519 self.mesh.SetParameters(Parameters)
3520 if TotalAngle and NbOfSteps:
3521 AngleInRadians /= NbOfSteps
3523 return self.editor.RotationSweepObject1DMakeGroups(theObject, Axis, AngleInRadians,
3524 NbOfSteps, Tolerance)
3525 self.editor.RotationSweepObject1D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3528 ## Generates new elements by rotation of the elements of object around the axis
3529 # @param theObject object which elements should be sweeped.
3530 # It can be a mesh, a sub mesh or a group.
3531 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3532 # @param AngleInRadians the angle of Rotation
3533 # @param NbOfSteps number of steps
3534 # @param Tolerance tolerance
3535 # @param MakeGroups forces the generation of new groups from existing ones
3536 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3537 # of all steps, else - size of each step
3538 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3539 # @ingroup l2_modif_extrurev
3540 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3541 MakeGroups=False, TotalAngle=False):
3542 if ( isinstance( theObject, Mesh )):
3543 theObject = theObject.GetMesh()
3544 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3545 Axis = self.smeshpyD.GetAxisStruct(Axis)
3546 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3547 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3548 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3549 self.mesh.SetParameters(Parameters)
3550 if TotalAngle and NbOfSteps:
3551 AngleInRadians /= NbOfSteps
3553 return self.editor.RotationSweepObject2DMakeGroups(theObject, Axis, AngleInRadians,
3554 NbOfSteps, Tolerance)
3555 self.editor.RotationSweepObject2D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3558 ## Generates new elements by extrusion of the elements with given ids
3559 # @param IDsOfElements the list of elements ids for extrusion
3560 # @param StepVector vector or DirStruct or 3 vector components, defining
3561 # the direction and value of extrusion for one step (the total extrusion
3562 # length will be NbOfSteps * ||StepVector||)
3563 # @param NbOfSteps the number of steps
3564 # @param MakeGroups forces the generation of new groups from existing ones
3565 # @param IsNodes is True if elements with given ids are nodes
3566 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3567 # @ingroup l2_modif_extrurev
3568 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3569 if IDsOfElements == []:
3570 IDsOfElements = self.GetElementsId()
3571 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3572 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3573 if isinstance( StepVector, list ):
3574 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3575 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3576 Parameters = StepVector.PS.parameters + var_separator + Parameters
3577 self.mesh.SetParameters(Parameters)
3580 return self.editor.ExtrusionSweepMakeGroups0D(IDsOfElements, StepVector, NbOfSteps)
3582 return self.editor.ExtrusionSweepMakeGroups(IDsOfElements, StepVector, NbOfSteps)
3584 self.editor.ExtrusionSweep0D(IDsOfElements, StepVector, NbOfSteps)
3586 self.editor.ExtrusionSweep(IDsOfElements, StepVector, NbOfSteps)
3589 ## Generates new elements by extrusion of the elements with given ids
3590 # @param IDsOfElements is ids of elements
3591 # @param StepVector vector or DirStruct or 3 vector components, defining
3592 # the direction and value of extrusion for one step (the total extrusion
3593 # length will be NbOfSteps * ||StepVector||)
3594 # @param NbOfSteps the number of steps
3595 # @param ExtrFlags sets flags for extrusion
3596 # @param SewTolerance uses for comparing locations of nodes if flag
3597 # EXTRUSION_FLAG_SEW is set
3598 # @param MakeGroups forces the generation of new groups from existing ones
3599 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3600 # @ingroup l2_modif_extrurev
3601 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3602 ExtrFlags, SewTolerance, MakeGroups=False):
3603 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3604 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3605 if isinstance( StepVector, list ):
3606 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3608 return self.editor.AdvancedExtrusionMakeGroups(IDsOfElements, StepVector, NbOfSteps,
3609 ExtrFlags, SewTolerance)
3610 self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3611 ExtrFlags, SewTolerance)
3614 ## Generates new elements by extrusion of the elements which belong to the object
3615 # @param theObject the object which elements should be processed.
3616 # It can be a mesh, a sub mesh or a group.
3617 # @param StepVector vector or DirStruct or 3 vector components, defining
3618 # the direction and value of extrusion for one step (the total extrusion
3619 # length will be NbOfSteps * ||StepVector||)
3620 # @param NbOfSteps the number of steps
3621 # @param MakeGroups forces the generation of new groups from existing ones
3622 # @param IsNodes is True if elements which belong to the object are nodes
3623 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3624 # @ingroup l2_modif_extrurev
3625 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3626 if ( isinstance( theObject, Mesh )):
3627 theObject = theObject.GetMesh()
3628 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3629 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3630 if isinstance( StepVector, list ):
3631 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3632 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3633 Parameters = StepVector.PS.parameters + var_separator + Parameters
3634 self.mesh.SetParameters(Parameters)
3637 return self.editor.ExtrusionSweepObject0DMakeGroups(theObject, StepVector, NbOfSteps)
3639 return self.editor.ExtrusionSweepObjectMakeGroups(theObject, StepVector, NbOfSteps)
3641 self.editor.ExtrusionSweepObject0D(theObject, StepVector, NbOfSteps)
3643 self.editor.ExtrusionSweepObject(theObject, StepVector, NbOfSteps)
3646 ## Generates new elements by extrusion of the elements which belong to the object
3647 # @param theObject object which elements should be processed.
3648 # It can be a mesh, a sub mesh or a group.
3649 # @param StepVector vector or DirStruct or 3 vector components, defining
3650 # the direction and value of extrusion for one step (the total extrusion
3651 # length will be NbOfSteps * ||StepVector||)
3652 # @param NbOfSteps the number of steps
3653 # @param MakeGroups to generate 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 ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3657 if ( isinstance( theObject, Mesh )):
3658 theObject = theObject.GetMesh()
3659 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3660 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3661 if isinstance( StepVector, list ):
3662 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3663 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3664 Parameters = StepVector.PS.parameters + var_separator + Parameters
3665 self.mesh.SetParameters(Parameters)
3667 return self.editor.ExtrusionSweepObject1DMakeGroups(theObject, StepVector, NbOfSteps)
3668 self.editor.ExtrusionSweepObject1D(theObject, StepVector, NbOfSteps)
3671 ## Generates new elements by extrusion of the elements which belong to the object
3672 # @param theObject object which elements should be processed.
3673 # It can be a mesh, a sub mesh or a group.
3674 # @param StepVector vector or DirStruct or 3 vector components, defining
3675 # the direction and value of extrusion for one step (the total extrusion
3676 # length will be NbOfSteps * ||StepVector||)
3677 # @param NbOfSteps the number of steps
3678 # @param MakeGroups forces the generation of new groups from existing ones
3679 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3680 # @ingroup l2_modif_extrurev
3681 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3682 if ( isinstance( theObject, Mesh )):
3683 theObject = theObject.GetMesh()
3684 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3685 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3686 if isinstance( StepVector, list ):
3687 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3688 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3689 Parameters = StepVector.PS.parameters + var_separator + Parameters
3690 self.mesh.SetParameters(Parameters)
3692 return self.editor.ExtrusionSweepObject2DMakeGroups(theObject, StepVector, NbOfSteps)
3693 self.editor.ExtrusionSweepObject2D(theObject, StepVector, NbOfSteps)
3698 ## Generates new elements by extrusion of the given elements
3699 # The path of extrusion must be a meshed edge.
3700 # @param Base mesh or group, or submesh, or list of ids of elements for extrusion
3701 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3702 # @param NodeStart the start node from Path. Defines the direction of extrusion
3703 # @param HasAngles allows the shape to be rotated around the path
3704 # to get the resulting mesh in a helical fashion
3705 # @param Angles list of angles in radians
3706 # @param LinearVariation forces the computation of rotation angles as linear
3707 # variation of the given Angles along path steps
3708 # @param HasRefPoint allows using the reference point
3709 # @param RefPoint the point around which the elements are rotated (the mass
3710 # center of the elements by default).
3711 # The User can specify any point as the Reference Point.
3712 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
3713 # @param MakeGroups forces the generation of new groups from existing ones
3714 # @param ElemType type of elements for extrusion (if param Base is a mesh)
3715 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3716 # only SMESH::Extrusion_Error otherwise
3717 # @ingroup l2_modif_extrurev
3718 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
3719 HasAngles, Angles, LinearVariation,
3720 HasRefPoint, RefPoint, MakeGroups, ElemType):
3721 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3722 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3724 elif isinstance( RefPoint, list ):
3725 RefPoint = PointStruct(*RefPoint)
3727 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3728 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3729 self.mesh.SetParameters(Parameters)
3731 if (isinstance(Path, Mesh)): Path = Path.GetMesh()
3733 if isinstance(Base, list):
3735 if Base == []: IDsOfElements = self.GetElementsId()
3736 else: IDsOfElements = Base
3737 return self.editor.ExtrusionAlongPathX(IDsOfElements, Path, NodeStart,
3738 HasAngles, Angles, LinearVariation,
3739 HasRefPoint, RefPoint, MakeGroups, ElemType)
3741 if isinstance(Base, Mesh): Base = Base.GetMesh()
3742 if isinstance(Base, SMESH._objref_SMESH_Mesh) or isinstance(Base, SMESH._objref_SMESH_Group) or isinstance(Base, SMESH._objref_SMESH_subMesh):
3743 return self.editor.ExtrusionAlongPathObjX(Base, Path, NodeStart,
3744 HasAngles, Angles, LinearVariation,
3745 HasRefPoint, RefPoint, MakeGroups, ElemType)
3747 raise RuntimeError, "Invalid Base for ExtrusionAlongPathX"
3750 ## Generates new elements by extrusion of the given elements
3751 # The path of extrusion must be a meshed edge.
3752 # @param IDsOfElements ids of elements
3753 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
3754 # @param PathShape shape(edge) defines the sub-mesh for the path
3755 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3756 # @param HasAngles allows the shape to be rotated around the path
3757 # to get the resulting mesh in a helical fashion
3758 # @param Angles list of angles in radians
3759 # @param HasRefPoint allows using the reference point
3760 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3761 # The User can specify any point as the Reference Point.
3762 # @param MakeGroups forces the generation of new groups from existing ones
3763 # @param LinearVariation forces the computation of rotation angles as linear
3764 # variation of the given Angles along path steps
3765 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3766 # only SMESH::Extrusion_Error otherwise
3767 # @ingroup l2_modif_extrurev
3768 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
3769 HasAngles, Angles, HasRefPoint, RefPoint,
3770 MakeGroups=False, LinearVariation=False):
3771 if IDsOfElements == []:
3772 IDsOfElements = self.GetElementsId()
3773 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3774 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3776 if ( isinstance( PathMesh, Mesh )):
3777 PathMesh = PathMesh.GetMesh()
3778 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3779 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3780 self.mesh.SetParameters(Parameters)
3781 if HasAngles and Angles and LinearVariation:
3782 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3785 return self.editor.ExtrusionAlongPathMakeGroups(IDsOfElements, PathMesh,
3786 PathShape, NodeStart, HasAngles,
3787 Angles, HasRefPoint, RefPoint)
3788 return self.editor.ExtrusionAlongPath(IDsOfElements, PathMesh, PathShape,
3789 NodeStart, HasAngles, Angles, HasRefPoint, RefPoint)
3791 ## Generates new elements by extrusion of the elements which belong to the object
3792 # The path of extrusion must be a meshed edge.
3793 # @param theObject the object which elements should be processed.
3794 # It can be a mesh, a sub mesh or a group.
3795 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3796 # @param PathShape shape(edge) defines the sub-mesh for the path
3797 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3798 # @param HasAngles allows the shape to be rotated around the path
3799 # to get the resulting mesh in a helical fashion
3800 # @param Angles list of angles
3801 # @param HasRefPoint allows using the reference point
3802 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3803 # The User can specify any point as the Reference Point.
3804 # @param MakeGroups forces the generation of new groups from existing ones
3805 # @param LinearVariation forces the computation of rotation angles as linear
3806 # variation of the given Angles along path steps
3807 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3808 # only SMESH::Extrusion_Error otherwise
3809 # @ingroup l2_modif_extrurev
3810 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
3811 HasAngles, Angles, HasRefPoint, RefPoint,
3812 MakeGroups=False, LinearVariation=False):
3813 if ( isinstance( theObject, Mesh )):
3814 theObject = theObject.GetMesh()
3815 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3816 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3817 if ( isinstance( PathMesh, Mesh )):
3818 PathMesh = PathMesh.GetMesh()
3819 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3820 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3821 self.mesh.SetParameters(Parameters)
3822 if HasAngles and Angles and LinearVariation:
3823 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3826 return self.editor.ExtrusionAlongPathObjectMakeGroups(theObject, PathMesh,
3827 PathShape, NodeStart, HasAngles,
3828 Angles, HasRefPoint, RefPoint)
3829 return self.editor.ExtrusionAlongPathObject(theObject, PathMesh, PathShape,
3830 NodeStart, HasAngles, Angles, HasRefPoint,
3833 ## Generates new elements by extrusion of the elements which belong to the object
3834 # The path of extrusion must be a meshed edge.
3835 # @param theObject the object which elements should be processed.
3836 # It can be a mesh, a sub mesh or a group.
3837 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3838 # @param PathShape shape(edge) defines the sub-mesh for the path
3839 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3840 # @param HasAngles allows the shape to be rotated around the path
3841 # to get the resulting mesh in a helical fashion
3842 # @param Angles list of angles
3843 # @param HasRefPoint allows using the reference point
3844 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3845 # The User can specify any point as the Reference Point.
3846 # @param MakeGroups forces the generation of new groups from existing ones
3847 # @param LinearVariation forces the computation of rotation angles as linear
3848 # variation of the given Angles along path steps
3849 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3850 # only SMESH::Extrusion_Error otherwise
3851 # @ingroup l2_modif_extrurev
3852 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
3853 HasAngles, Angles, HasRefPoint, RefPoint,
3854 MakeGroups=False, LinearVariation=False):
3855 if ( isinstance( theObject, Mesh )):
3856 theObject = theObject.GetMesh()
3857 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3858 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3859 if ( isinstance( PathMesh, Mesh )):
3860 PathMesh = PathMesh.GetMesh()
3861 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3862 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3863 self.mesh.SetParameters(Parameters)
3864 if HasAngles and Angles and LinearVariation:
3865 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3868 return self.editor.ExtrusionAlongPathObject1DMakeGroups(theObject, PathMesh,
3869 PathShape, NodeStart, HasAngles,
3870 Angles, HasRefPoint, RefPoint)
3871 return self.editor.ExtrusionAlongPathObject1D(theObject, PathMesh, PathShape,
3872 NodeStart, HasAngles, Angles, HasRefPoint,
3875 ## Generates new elements by extrusion of the elements which belong to the object
3876 # The path of extrusion must be a meshed edge.
3877 # @param theObject the object which elements should be processed.
3878 # It can be a mesh, a sub mesh or a group.
3879 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3880 # @param PathShape shape(edge) defines the sub-mesh for the path
3881 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3882 # @param HasAngles allows the shape to be rotated around the path
3883 # to get the resulting mesh in a helical fashion
3884 # @param Angles list of angles
3885 # @param HasRefPoint allows using the reference point
3886 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3887 # The User can specify any point as the Reference Point.
3888 # @param MakeGroups forces the generation of new groups from existing ones
3889 # @param LinearVariation forces the computation of rotation angles as linear
3890 # variation of the given Angles along path steps
3891 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3892 # only SMESH::Extrusion_Error otherwise
3893 # @ingroup l2_modif_extrurev
3894 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
3895 HasAngles, Angles, HasRefPoint, RefPoint,
3896 MakeGroups=False, LinearVariation=False):
3897 if ( isinstance( theObject, Mesh )):
3898 theObject = theObject.GetMesh()
3899 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3900 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3901 if ( isinstance( PathMesh, Mesh )):
3902 PathMesh = PathMesh.GetMesh()
3903 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3904 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3905 self.mesh.SetParameters(Parameters)
3906 if HasAngles and Angles and LinearVariation:
3907 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3910 return self.editor.ExtrusionAlongPathObject2DMakeGroups(theObject, PathMesh,
3911 PathShape, NodeStart, HasAngles,
3912 Angles, HasRefPoint, RefPoint)
3913 return self.editor.ExtrusionAlongPathObject2D(theObject, PathMesh, PathShape,
3914 NodeStart, HasAngles, Angles, HasRefPoint,
3917 ## Creates a symmetrical copy of mesh elements
3918 # @param IDsOfElements list of elements ids
3919 # @param Mirror is AxisStruct or geom object(point, line, plane)
3920 # @param theMirrorType is POINT, AXIS or PLANE
3921 # If the Mirror is a geom object this parameter is unnecessary
3922 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
3923 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3924 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3925 # @ingroup l2_modif_trsf
3926 def Mirror(self, IDsOfElements, Mirror, theMirrorType, Copy=0, MakeGroups=False):
3927 if IDsOfElements == []:
3928 IDsOfElements = self.GetElementsId()
3929 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3930 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3931 self.mesh.SetParameters(Mirror.parameters)
3932 if Copy and MakeGroups:
3933 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
3934 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
3937 ## Creates a new mesh by a symmetrical copy of mesh elements
3938 # @param IDsOfElements the list of elements ids
3939 # @param Mirror is AxisStruct or geom object (point, line, plane)
3940 # @param theMirrorType is POINT, AXIS or PLANE
3941 # If the Mirror is a geom object this parameter is unnecessary
3942 # @param MakeGroups to generate new groups from existing ones
3943 # @param NewMeshName a name of the new mesh to create
3944 # @return instance of Mesh class
3945 # @ingroup l2_modif_trsf
3946 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType, MakeGroups=0, NewMeshName=""):
3947 if IDsOfElements == []:
3948 IDsOfElements = self.GetElementsId()
3949 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3950 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3951 self.mesh.SetParameters(Mirror.parameters)
3952 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
3953 MakeGroups, NewMeshName)
3954 return Mesh(self.smeshpyD,self.geompyD,mesh)
3956 ## Creates a symmetrical copy of the object
3957 # @param theObject mesh, submesh or group
3958 # @param Mirror AxisStruct or geom object (point, line, plane)
3959 # @param theMirrorType is POINT, AXIS or PLANE
3960 # If the Mirror is a geom object this parameter is unnecessary
3961 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
3962 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3963 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3964 # @ingroup l2_modif_trsf
3965 def MirrorObject (self, theObject, Mirror, theMirrorType, Copy=0, MakeGroups=False):
3966 if ( isinstance( theObject, Mesh )):
3967 theObject = theObject.GetMesh()
3968 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3969 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3970 self.mesh.SetParameters(Mirror.parameters)
3971 if Copy and MakeGroups:
3972 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
3973 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
3976 ## Creates a new mesh by a symmetrical copy of the object
3977 # @param theObject mesh, submesh or group
3978 # @param Mirror AxisStruct or geom object (point, line, plane)
3979 # @param theMirrorType POINT, AXIS or PLANE
3980 # If the Mirror is a geom object this parameter is unnecessary
3981 # @param MakeGroups forces the generation of new groups from existing ones
3982 # @param NewMeshName the name of the new mesh to create
3983 # @return instance of Mesh class
3984 # @ingroup l2_modif_trsf
3985 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType,MakeGroups=0, NewMeshName=""):
3986 if ( isinstance( theObject, Mesh )):
3987 theObject = theObject.GetMesh()
3988 if (isinstance(Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3989 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3990 self.mesh.SetParameters(Mirror.parameters)
3991 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
3992 MakeGroups, NewMeshName)
3993 return Mesh( self.smeshpyD,self.geompyD,mesh )
3995 ## Translates the elements
3996 # @param IDsOfElements list of elements ids
3997 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
3998 # @param Copy allows copying the translated elements
3999 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4000 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4001 # @ingroup l2_modif_trsf
4002 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4003 if IDsOfElements == []:
4004 IDsOfElements = self.GetElementsId()
4005 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4006 Vector = self.smeshpyD.GetDirStruct(Vector)
4007 if isinstance( Vector, list ):
4008 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4009 self.mesh.SetParameters(Vector.PS.parameters)
4010 if Copy and MakeGroups:
4011 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4012 self.editor.Translate(IDsOfElements, Vector, Copy)
4015 ## Creates a new mesh of translated elements
4016 # @param IDsOfElements list of elements ids
4017 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4018 # @param MakeGroups forces the generation of new groups from existing ones
4019 # @param NewMeshName the name of the newly created mesh
4020 # @return instance of Mesh class
4021 # @ingroup l2_modif_trsf
4022 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4023 if IDsOfElements == []:
4024 IDsOfElements = self.GetElementsId()
4025 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4026 Vector = self.smeshpyD.GetDirStruct(Vector)
4027 if isinstance( Vector, list ):
4028 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4029 self.mesh.SetParameters(Vector.PS.parameters)
4030 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4031 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4033 ## Translates the object
4034 # @param theObject the object to translate (mesh, submesh, or group)
4035 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4036 # @param Copy allows copying the translated elements
4037 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4038 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4039 # @ingroup l2_modif_trsf
4040 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4041 if ( isinstance( theObject, Mesh )):
4042 theObject = theObject.GetMesh()
4043 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4044 Vector = self.smeshpyD.GetDirStruct(Vector)
4045 if isinstance( Vector, list ):
4046 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4047 self.mesh.SetParameters(Vector.PS.parameters)
4048 if Copy and MakeGroups:
4049 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4050 self.editor.TranslateObject(theObject, Vector, Copy)
4053 ## Creates a new mesh from the translated object
4054 # @param theObject the object to translate (mesh, submesh, or group)
4055 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4056 # @param MakeGroups forces the generation of new groups from existing ones
4057 # @param NewMeshName the name of the newly created mesh
4058 # @return instance of Mesh class
4059 # @ingroup l2_modif_trsf
4060 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4061 if isinstance( theObject, Mesh ):
4062 theObject = theObject.GetMesh()
4063 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4064 Vector = self.smeshpyD.GetDirStruct(Vector)
4065 if isinstance( Vector, list ):
4066 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4067 self.mesh.SetParameters(Vector.PS.parameters)
4068 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4069 return Mesh( self.smeshpyD, self.geompyD, mesh )
4073 ## Scales the object
4074 # @param theObject - the object to translate (mesh, submesh, or group)
4075 # @param thePoint - base point for scale
4076 # @param theScaleFact - list of 1-3 scale factors for axises
4077 # @param Copy - allows copying the translated elements
4078 # @param MakeGroups - forces the generation of new groups from existing
4080 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4081 # empty list otherwise
4082 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4083 unRegister = genObjUnRegister()
4084 if ( isinstance( theObject, Mesh )):
4085 theObject = theObject.GetMesh()
4086 if ( isinstance( theObject, list )):
4087 theObject = self.GetIDSource(theObject, SMESH.ALL)
4088 unRegister.set( theObject )
4089 if ( isinstance( theScaleFact, float )):
4090 theScaleFact = [theScaleFact]
4091 if ( isinstance( theScaleFact, int )):
4092 theScaleFact = [ float(theScaleFact)]
4094 self.mesh.SetParameters(thePoint.parameters)
4096 if Copy and MakeGroups:
4097 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4098 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4101 ## Creates a new mesh from the translated object
4102 # @param theObject - the object to translate (mesh, submesh, or group)
4103 # @param thePoint - base point for scale
4104 # @param theScaleFact - list of 1-3 scale factors for axises
4105 # @param MakeGroups - forces the generation of new groups from existing ones
4106 # @param NewMeshName - the name of the newly created mesh
4107 # @return instance of Mesh class
4108 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4109 unRegister = genObjUnRegister()
4110 if (isinstance(theObject, Mesh)):
4111 theObject = theObject.GetMesh()
4112 if ( isinstance( theObject, list )):
4113 theObject = self.GetIDSource(theObject,SMESH.ALL)
4114 unRegister.set( theObject )
4115 if ( isinstance( theScaleFact, float )):
4116 theScaleFact = [theScaleFact]
4117 if ( isinstance( theScaleFact, int )):
4118 theScaleFact = [ float(theScaleFact)]
4120 self.mesh.SetParameters(thePoint.parameters)
4121 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4122 MakeGroups, NewMeshName)
4123 return Mesh( self.smeshpyD, self.geompyD, mesh )
4127 ## Rotates the elements
4128 # @param IDsOfElements list of elements ids
4129 # @param Axis the axis of rotation (AxisStruct or geom line)
4130 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4131 # @param Copy allows copying the rotated elements
4132 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4133 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4134 # @ingroup l2_modif_trsf
4135 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4136 if IDsOfElements == []:
4137 IDsOfElements = self.GetElementsId()
4138 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4139 Axis = self.smeshpyD.GetAxisStruct(Axis)
4140 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4141 Parameters = Axis.parameters + var_separator + Parameters
4142 self.mesh.SetParameters(Parameters)
4143 if Copy and MakeGroups:
4144 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4145 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4148 ## Creates a new mesh of rotated elements
4149 # @param IDsOfElements list of element ids
4150 # @param Axis the axis of rotation (AxisStruct or geom line)
4151 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4152 # @param MakeGroups forces the generation of new groups from existing ones
4153 # @param NewMeshName the name of the newly created mesh
4154 # @return instance of Mesh class
4155 # @ingroup l2_modif_trsf
4156 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4157 if IDsOfElements == []:
4158 IDsOfElements = self.GetElementsId()
4159 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4160 Axis = self.smeshpyD.GetAxisStruct(Axis)
4161 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4162 Parameters = Axis.parameters + var_separator + Parameters
4163 self.mesh.SetParameters(Parameters)
4164 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4165 MakeGroups, NewMeshName)
4166 return Mesh( self.smeshpyD, self.geompyD, mesh )
4168 ## Rotates the object
4169 # @param theObject the object to rotate( mesh, submesh, or group)
4170 # @param Axis the axis of rotation (AxisStruct or geom line)
4171 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4172 # @param Copy allows copying the rotated elements
4173 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4174 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4175 # @ingroup l2_modif_trsf
4176 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4177 if (isinstance(theObject, Mesh)):
4178 theObject = theObject.GetMesh()
4179 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4180 Axis = self.smeshpyD.GetAxisStruct(Axis)
4181 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4182 Parameters = Axis.parameters + ":" + Parameters
4183 self.mesh.SetParameters(Parameters)
4184 if Copy and MakeGroups:
4185 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4186 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4189 ## Creates a new mesh from the rotated object
4190 # @param theObject the object to rotate (mesh, submesh, or group)
4191 # @param Axis the axis of rotation (AxisStruct or geom line)
4192 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4193 # @param MakeGroups forces the generation of new groups from existing ones
4194 # @param NewMeshName the name of the newly created mesh
4195 # @return instance of Mesh class
4196 # @ingroup l2_modif_trsf
4197 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4198 if (isinstance( theObject, Mesh )):
4199 theObject = theObject.GetMesh()
4200 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4201 Axis = self.smeshpyD.GetAxisStruct(Axis)
4202 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4203 Parameters = Axis.parameters + ":" + Parameters
4204 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4205 MakeGroups, NewMeshName)
4206 self.mesh.SetParameters(Parameters)
4207 return Mesh( self.smeshpyD, self.geompyD, mesh )
4209 ## Finds groups of adjacent nodes within Tolerance.
4210 # @param Tolerance the value of tolerance
4211 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4212 # @ingroup l2_modif_trsf
4213 def FindCoincidentNodes (self, Tolerance):
4214 return self.editor.FindCoincidentNodes(Tolerance)
4216 ## Finds groups of ajacent nodes within Tolerance.
4217 # @param Tolerance the value of tolerance
4218 # @param SubMeshOrGroup SubMesh or Group
4219 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4220 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4221 # @ingroup l2_modif_trsf
4222 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance, exceptNodes=[]):
4223 unRegister = genObjUnRegister()
4224 if (isinstance( SubMeshOrGroup, Mesh )):
4225 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4226 if not isinstance( exceptNodes, list):
4227 exceptNodes = [ exceptNodes ]
4228 if exceptNodes and isinstance( exceptNodes[0], int):
4229 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE)]
4230 unRegister.set( exceptNodes )
4231 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,exceptNodes)
4234 # @param GroupsOfNodes a list of pairs of nodes IDs for merging (e.g. [[1,12],[25,4]])
4235 # @ingroup l2_modif_trsf
4236 def MergeNodes (self, GroupsOfNodes):
4237 self.editor.MergeNodes(GroupsOfNodes)
4239 ## Finds the elements built on the same nodes.
4240 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4241 # @return the list of pairs of equal elements IDs (e.g. [[1,12],[25,4]])
4242 # @ingroup l2_modif_trsf
4243 def FindEqualElements (self, MeshOrSubMeshOrGroup):
4244 if ( isinstance( MeshOrSubMeshOrGroup, Mesh )):
4245 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4246 return self.editor.FindEqualElements(MeshOrSubMeshOrGroup)
4248 ## Merges elements in each given group.
4249 # @param GroupsOfElementsID a list of pairs of elements IDs for merging (e.g. [[1,12],[25,4]])
4250 # @ingroup l2_modif_trsf
4251 def MergeElements(self, GroupsOfElementsID):
4252 self.editor.MergeElements(GroupsOfElementsID)
4254 ## Leaves one element and removes all other elements built on the same nodes.
4255 # @ingroup l2_modif_trsf
4256 def MergeEqualElements(self):
4257 self.editor.MergeEqualElements()
4259 ## Sews free borders
4260 # @return SMESH::Sew_Error
4261 # @ingroup l2_modif_trsf
4262 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4263 FirstNodeID2, SecondNodeID2, LastNodeID2,
4264 CreatePolygons, CreatePolyedrs):
4265 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4266 FirstNodeID2, SecondNodeID2, LastNodeID2,
4267 CreatePolygons, CreatePolyedrs)
4269 ## Sews conform free borders
4270 # @return SMESH::Sew_Error
4271 # @ingroup l2_modif_trsf
4272 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4273 FirstNodeID2, SecondNodeID2):
4274 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4275 FirstNodeID2, SecondNodeID2)
4277 ## Sews border to side
4278 # @return SMESH::Sew_Error
4279 # @ingroup l2_modif_trsf
4280 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4281 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4282 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4283 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4285 ## Sews two sides of a mesh. The nodes belonging to Side1 are
4286 # merged with the nodes of elements of Side2.
4287 # The number of elements in theSide1 and in theSide2 must be
4288 # equal and they should have similar nodal connectivity.
4289 # The nodes to merge should belong to side borders and
4290 # the first node should be linked to the second.
4291 # @return SMESH::Sew_Error
4292 # @ingroup l2_modif_trsf
4293 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4294 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4295 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4296 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4297 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4298 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4300 ## Sets new nodes for the given element.
4301 # @param ide the element id
4302 # @param newIDs nodes ids
4303 # @return If the number of nodes does not correspond to the type of element - returns false
4304 # @ingroup l2_modif_edit
4305 def ChangeElemNodes(self, ide, newIDs):
4306 return self.editor.ChangeElemNodes(ide, newIDs)
4308 ## If during the last operation of MeshEditor some nodes were
4309 # created, this method returns the list of their IDs, \n
4310 # if new nodes were not created - returns empty list
4311 # @return the list of integer values (can be empty)
4312 # @ingroup l1_auxiliary
4313 def GetLastCreatedNodes(self):
4314 return self.editor.GetLastCreatedNodes()
4316 ## If during the last operation of MeshEditor some elements were
4317 # created this method returns the list of their IDs, \n
4318 # if new elements were not created - returns empty list
4319 # @return the list of integer values (can be empty)
4320 # @ingroup l1_auxiliary
4321 def GetLastCreatedElems(self):
4322 return self.editor.GetLastCreatedElems()
4324 ## Clears sequences of nodes and elements created by mesh edition oparations
4325 # @ingroup l1_auxiliary
4326 def ClearLastCreated(self):
4327 self.editor.ClearLastCreated()
4329 ## Creates Duplicates given elements, i.e. creates new elements based on the
4330 # same nodes as the given ones.
4331 # @param theElements - container of elements to duplicate. It can be a Mesh,
4332 # sub-mesh, group, filter or a list of element IDs.
4333 # @param theGroupName - a name of group to contain the generated elements.
4334 # If a group with such a name already exists, the new elements
4335 # are added to the existng group, else a new group is created.
4336 # If \a theGroupName is empty, new elements are not added
4338 # @return a group where the new elements are added. None if theGroupName == "".
4339 # @ingroup l2_modif_edit
4340 def DoubleElements(self, theElements, theGroupName=""):
4341 unRegister = genObjUnRegister()
4342 if isinstance( theElements, Mesh ):
4343 theElements = theElements.mesh
4344 elif isinstance( theElements, list ):
4345 theElements = self.GetIDSource( theElements, SMESH.ALL )
4346 unRegister.set( theElements )
4347 return self.editor.DoubleElements(theElements, theGroupName)
4349 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4350 # @param theNodes identifiers of nodes to be doubled
4351 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4352 # nodes. If list of element identifiers is empty then nodes are doubled but
4353 # they not assigned to elements
4354 # @return TRUE if operation has been completed successfully, FALSE otherwise
4355 # @ingroup l2_modif_edit
4356 def DoubleNodes(self, theNodes, theModifiedElems):
4357 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4359 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4360 # This method provided for convenience works as DoubleNodes() described above.
4361 # @param theNodeId identifiers of node to be doubled
4362 # @param theModifiedElems identifiers of elements to be updated
4363 # @return TRUE if operation has been completed successfully, FALSE otherwise
4364 # @ingroup l2_modif_edit
4365 def DoubleNode(self, theNodeId, theModifiedElems):
4366 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4368 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4369 # This method provided for convenience works as DoubleNodes() described above.
4370 # @param theNodes group of nodes to be doubled
4371 # @param theModifiedElems group of elements to be updated.
4372 # @param theMakeGroup forces the generation of a group containing new nodes.
4373 # @return TRUE or a created group if operation has been completed successfully,
4374 # FALSE or None otherwise
4375 # @ingroup l2_modif_edit
4376 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4378 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4379 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4381 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4382 # This method provided for convenience works as DoubleNodes() described above.
4383 # @param theNodes list of groups of nodes to be doubled
4384 # @param theModifiedElems list of groups of elements to be updated.
4385 # @param theMakeGroup forces the generation of a group containing new nodes.
4386 # @return TRUE if operation has been completed successfully, FALSE otherwise
4387 # @ingroup l2_modif_edit
4388 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4390 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4391 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4393 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4394 # @param theElems - the list of elements (edges or faces) to be replicated
4395 # The nodes for duplication could be found from these elements
4396 # @param theNodesNot - list of nodes to NOT replicate
4397 # @param theAffectedElems - the list of elements (cells and edges) to which the
4398 # replicated nodes should be associated to.
4399 # @return TRUE if operation has been completed successfully, FALSE otherwise
4400 # @ingroup l2_modif_edit
4401 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4402 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4404 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4405 # @param theElems - the list of elements (edges or faces) to be replicated
4406 # The nodes for duplication could be found from these elements
4407 # @param theNodesNot - list of nodes to NOT replicate
4408 # @param theShape - shape to detect affected elements (element which geometric center
4409 # located on or inside shape).
4410 # The replicated nodes should be associated to affected elements.
4411 # @return TRUE if operation has been completed successfully, FALSE otherwise
4412 # @ingroup l2_modif_edit
4413 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4414 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4416 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4417 # This method provided for convenience works as DoubleNodes() described above.
4418 # @param theElems - group of of elements (edges or faces) to be replicated
4419 # @param theNodesNot - group of nodes not to replicated
4420 # @param theAffectedElems - group of elements to which the replicated nodes
4421 # should be associated to.
4422 # @param theMakeGroup forces the generation of a group containing new elements.
4423 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4424 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4425 # FALSE or None otherwise
4426 # @ingroup l2_modif_edit
4427 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4428 theMakeGroup=False, theMakeNodeGroup=False):
4429 if theMakeGroup or theMakeNodeGroup:
4430 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4432 theMakeGroup, theMakeNodeGroup)
4433 if theMakeGroup and theMakeNodeGroup:
4436 return twoGroups[ int(theMakeNodeGroup) ]
4437 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4439 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4440 # This method provided for convenience works as DoubleNodes() described above.
4441 # @param theElems - group of of elements (edges or faces) to be replicated
4442 # @param theNodesNot - group of nodes not to replicated
4443 # @param theShape - shape to detect affected elements (element which geometric center
4444 # located on or inside shape).
4445 # The replicated nodes should be associated to affected elements.
4446 # @ingroup l2_modif_edit
4447 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4448 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4450 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4451 # This method provided for convenience works as DoubleNodes() described above.
4452 # @param theElems - list of groups of elements (edges or faces) to be replicated
4453 # @param theNodesNot - list of groups of nodes not to replicated
4454 # @param theAffectedElems - group of elements to which the replicated nodes
4455 # should be associated to.
4456 # @param theMakeGroup forces the generation of a group containing new elements.
4457 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4458 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4459 # FALSE or None otherwise
4460 # @ingroup l2_modif_edit
4461 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4462 theMakeGroup=False, theMakeNodeGroup=False):
4463 if theMakeGroup or theMakeNodeGroup:
4464 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4466 theMakeGroup, theMakeNodeGroup)
4467 if theMakeGroup and theMakeNodeGroup:
4470 return twoGroups[ int(theMakeNodeGroup) ]
4471 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4473 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4474 # This method provided for convenience works as DoubleNodes() described above.
4475 # @param theElems - list of groups of elements (edges or faces) to be replicated
4476 # @param theNodesNot - list of groups of nodes not to replicated
4477 # @param theShape - shape to detect affected elements (element which geometric center
4478 # located on or inside shape).
4479 # The replicated nodes should be associated to affected elements.
4480 # @return TRUE if operation has been completed successfully, FALSE otherwise
4481 # @ingroup l2_modif_edit
4482 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4483 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4485 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4486 # This method is the first step of DoubleNodeElemGroupsInRegion.
4487 # @param theElems - list of groups of elements (edges or faces) to be replicated
4488 # @param theNodesNot - list of groups of nodes not to replicated
4489 # @param theShape - shape to detect affected elements (element which geometric center
4490 # located on or inside shape).
4491 # The replicated nodes should be associated to affected elements.
4492 # @return groups of affected elements
4493 # @ingroup l2_modif_edit
4494 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4495 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4497 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4498 # The list of groups must describe a partition of the mesh volumes.
4499 # The nodes of the internal faces at the boundaries of the groups are doubled.
4500 # In option, the internal faces are replaced by flat elements.
4501 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4502 # @param theDomains - list of groups of volumes
4503 # @param createJointElems - if TRUE, create the elements
4504 # @return TRUE if operation has been completed successfully, FALSE otherwise
4505 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems ):
4506 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems )
4508 ## Double nodes on some external faces and create flat elements.
4509 # Flat elements are mainly used by some types of mechanic calculations.
4511 # Each group of the list must be constituted of faces.
4512 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4513 # @param theGroupsOfFaces - list of groups of faces
4514 # @return TRUE if operation has been completed successfully, FALSE otherwise
4515 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4516 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4518 ## identify all the elements around a geom shape, get the faces delimiting the hole
4520 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4521 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4523 def _getFunctor(self, funcType ):
4524 fn = self.functors[ funcType._v ]
4526 fn = self.smeshpyD.GetFunctor(funcType)
4527 fn.SetMesh(self.mesh)
4528 self.functors[ funcType._v ] = fn
4531 def _valueFromFunctor(self, funcType, elemId):
4532 fn = self._getFunctor( funcType )
4533 if fn.GetElementType() == self.GetElementType(elemId, True):
4534 val = fn.GetValue(elemId)
4539 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4540 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4541 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4542 # @ingroup l1_measurements
4543 def GetLength(self, elemId=None):
4546 length = self.smeshpyD.GetLength(self)
4548 length = self._valueFromFunctor(SMESH.FT_Length, elemId)
4551 ## Get area of 2D element or sum of areas of all 2D mesh elements
4552 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4553 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4554 # @ingroup l1_measurements
4555 def GetArea(self, elemId=None):
4558 area = self.smeshpyD.GetArea(self)
4560 area = self._valueFromFunctor(SMESH.FT_Area, elemId)
4563 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4564 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4565 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4566 # @ingroup l1_measurements
4567 def GetVolume(self, elemId=None):
4570 volume = self.smeshpyD.GetVolume(self)
4572 volume = self._valueFromFunctor(SMESH.FT_Volume3D, elemId)
4575 ## Get maximum element length.
4576 # @param elemId mesh element ID
4577 # @return element's maximum length value
4578 # @ingroup l1_measurements
4579 def GetMaxElementLength(self, elemId):
4580 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4581 ftype = SMESH.FT_MaxElementLength3D
4583 ftype = SMESH.FT_MaxElementLength2D
4584 return self._valueFromFunctor(ftype, elemId)
4586 ## Get aspect ratio of 2D or 3D element.
4587 # @param elemId mesh element ID
4588 # @return element's aspect ratio value
4589 # @ingroup l1_measurements
4590 def GetAspectRatio(self, elemId):
4591 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4592 ftype = SMESH.FT_AspectRatio3D
4594 ftype = SMESH.FT_AspectRatio
4595 return self._valueFromFunctor(ftype, elemId)
4597 ## Get warping angle of 2D element.
4598 # @param elemId mesh element ID
4599 # @return element's warping angle value
4600 # @ingroup l1_measurements
4601 def GetWarping(self, elemId):
4602 return self._valueFromFunctor(SMESH.FT_Warping, elemId)
4604 ## Get minimum angle of 2D element.
4605 # @param elemId mesh element ID
4606 # @return element's minimum angle value
4607 # @ingroup l1_measurements
4608 def GetMinimumAngle(self, elemId):
4609 return self._valueFromFunctor(SMESH.FT_MinimumAngle, elemId)
4611 ## Get taper of 2D element.
4612 # @param elemId mesh element ID
4613 # @return element's taper value
4614 # @ingroup l1_measurements
4615 def GetTaper(self, elemId):
4616 return self._valueFromFunctor(SMESH.FT_Taper, elemId)
4618 ## Get skew of 2D element.
4619 # @param elemId mesh element ID
4620 # @return element's skew value
4621 # @ingroup l1_measurements
4622 def GetSkew(self, elemId):
4623 return self._valueFromFunctor(SMESH.FT_Skew, elemId)
4625 pass # end of Mesh class
4627 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
4629 class Pattern(SMESH._objref_SMESH_Pattern):
4631 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4632 decrFun = lambda i: i-1
4633 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4634 theMesh.SetParameters(Parameters)
4635 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4637 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4638 decrFun = lambda i: i-1
4639 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4640 theMesh.SetParameters(Parameters)
4641 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4643 # Registering the new proxy for Pattern
4644 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4646 ## Private class used to bind methods creating algorithms to the class Mesh
4651 self.defaultAlgoType = ""
4652 self.algoTypeToClass = {}
4654 # Stores a python class of algorithm
4655 def add(self, algoClass):
4656 if type( algoClass ).__name__ == 'classobj' and \
4657 hasattr( algoClass, "algoType"):
4658 self.algoTypeToClass[ algoClass.algoType ] = algoClass
4659 if not self.defaultAlgoType and \
4660 hasattr( algoClass, "isDefault") and algoClass.isDefault:
4661 self.defaultAlgoType = algoClass.algoType
4662 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
4664 # creates a copy of self and assign mesh to the copy
4665 def copy(self, mesh):
4666 other = algoCreator()
4667 other.defaultAlgoType = self.defaultAlgoType
4668 other.algoTypeToClass = self.algoTypeToClass
4672 # creates an instance of algorithm
4673 def __call__(self,algo="",geom=0,*args):
4674 algoType = self.defaultAlgoType
4675 for arg in args + (algo,geom):
4676 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
4678 if isinstance( arg, str ) and arg:
4680 if not algoType and self.algoTypeToClass:
4681 algoType = self.algoTypeToClass.keys()[0]
4682 if self.algoTypeToClass.has_key( algoType ):
4683 #print "Create algo",algoType
4684 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
4685 raise RuntimeError, "No class found for algo type %s" % algoType
4688 # Private class used to substitute and store variable parameters of hypotheses.
4690 class hypMethodWrapper:
4691 def __init__(self, hyp, method):
4693 self.method = method
4694 #print "REBIND:", method.__name__
4697 # call a method of hypothesis with calling SetVarParameter() before
4698 def __call__(self,*args):
4700 return self.method( self.hyp, *args ) # hypothesis method with no args
4702 #print "MethWrapper.__call__",self.method.__name__, args
4704 parsed = ParseParameters(*args) # replace variables with their values
4705 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
4706 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
4707 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
4708 # maybe there is a replaced string arg which is not variable
4709 result = self.method( self.hyp, *args )
4710 except ValueError, detail: # raised by ParseParameters()
4712 result = self.method( self.hyp, *args )
4713 except omniORB.CORBA.BAD_PARAM:
4714 raise ValueError, detail # wrong variable name
4719 # A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
4720 class genObjUnRegister:
4722 def __init__(self, genObj=None):
4723 self.genObjList = []
4727 def set(self, genObj):
4728 "Store one or a list of of SALOME.GenericObj'es"
4729 if isinstance( genObj, list ):
4730 self.genObjList.extend( genObj )
4732 self.genObjList.append( genObj )
4736 for genObj in self.genObjList:
4737 if genObj and hasattr( genObj, "UnRegister" ):
4740 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
4742 #print "pluginName: ", pluginName
4743 pluginBuilderName = pluginName + "Builder"
4745 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
4746 except Exception, e:
4747 from salome_utils import verbose
4748 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
4750 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
4751 plugin = eval( pluginBuilderName )
4752 #print " plugin:" , str(plugin)
4754 # add methods creating algorithms to Mesh
4755 for k in dir( plugin ):
4756 if k[0] == '_': continue
4757 algo = getattr( plugin, k )
4758 #print " algo:", str(algo)
4759 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
4760 #print " meshMethod:" , str(algo.meshMethod)
4761 if not hasattr( Mesh, algo.meshMethod ):
4762 setattr( Mesh, algo.meshMethod, algoCreator() )
4764 getattr( Mesh, algo.meshMethod ).add( algo )