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()
1566 hyp_name = GetName( hyp )
1569 geom_name = geom.GetName()
1571 if self.mesh.HasShapeToMesh():
1572 hyp_type = hyp.GetName()
1573 lib_name = hyp.GetLibName()
1574 isSubMesh = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1575 isApplicable = self.smeshpyD.IsApplicable(hyp_name, lib_name, geom, isSubMesh)
1577 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1578 status = self.mesh.AddHypothesis(geom, hyp)
1579 isAlgo = hyp._narrow( SMESH_Algo )
1580 TreatHypoStatus( status, hyp_name, geom_name, isAlgo )
1583 TreatHypoStatus( HYP_BAD_GEOMETRY, hyp_name, geom_name, isAlgo )
1584 return HYP_BAD_GEOMETRY
1586 ## Return True if an algorithm of hypothesis is assigned to a given shape
1587 # @param hyp a hypothesis to check
1588 # @param geom a subhape of mesh geometry
1589 # @return True of False
1590 # @ingroup l2_hypotheses
1591 def IsUsedHypothesis(self, hyp, geom):
1592 if not hyp: # or not geom
1594 if isinstance( hyp, Mesh_Algorithm ):
1595 hyp = hyp.GetAlgorithm()
1597 hyps = self.GetHypothesisList(geom)
1599 if h.GetId() == hyp.GetId():
1603 ## Unassigns a hypothesis
1604 # @param hyp a hypothesis to unassign
1605 # @param geom a sub-shape of mesh geometry
1606 # @return SMESH.Hypothesis_Status
1607 # @ingroup l2_hypotheses
1608 def RemoveHypothesis(self, hyp, geom=0):
1611 if isinstance( hyp, Mesh_Algorithm ):
1612 hyp = hyp.GetAlgorithm()
1618 if self.IsUsedHypothesis( hyp, shape ):
1619 return self.mesh.RemoveHypothesis( shape, hyp )
1620 hypName = GetName( hyp )
1621 geoName = GetName( shape )
1622 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1625 ## Gets the list of hypotheses added on a geometry
1626 # @param geom a sub-shape of mesh geometry
1627 # @return the sequence of SMESH_Hypothesis
1628 # @ingroup l2_hypotheses
1629 def GetHypothesisList(self, geom):
1630 return self.mesh.GetHypothesisList( geom )
1632 ## Removes all global hypotheses
1633 # @ingroup l2_hypotheses
1634 def RemoveGlobalHypotheses(self):
1635 current_hyps = self.mesh.GetHypothesisList( self.geom )
1636 for hyp in current_hyps:
1637 self.mesh.RemoveHypothesis( self.geom, hyp )
1641 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1642 ## allowing to overwrite the file if it exists or add the exported data to its contents
1643 # @param f is the file name
1644 # @param auto_groups boolean parameter for creating/not creating
1645 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1646 # the typical use is auto_groups=false.
1647 # @param version MED format version(MED_V2_1 or MED_V2_2)
1648 # @param overwrite boolean parameter for overwriting/not overwriting the file
1649 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1650 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1651 # - 1D if all mesh nodes lie on OX coordinate axis, or
1652 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1653 # - 3D in the rest cases.
1654 # If @a autoDimension is @c False, the space dimension is always 3.
1655 # @param fields : list of GEOM fields defined on the shape to mesh.
1656 # @param geomAssocFields : each character of this string means a need to export a
1657 # corresponding field; correspondence between fields and characters is following:
1658 # - 'v' stands for _vertices_ field;
1659 # - 'e' stands for _edges_ field;
1660 # - 'f' stands for _faces_ field;
1661 # - 's' stands for _solids_ field.
1662 # @ingroup l2_impexp
1663 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1664 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1665 if meshPart or fields or geomAssocFields:
1666 unRegister = genObjUnRegister()
1667 if isinstance( meshPart, list ):
1668 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1669 unRegister.set( meshPart )
1670 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1671 fields, geomAssocFields)
1673 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1675 ## Exports the mesh in a file in SAUV format
1676 # @param f is the file name
1677 # @param auto_groups boolean parameter for creating/not creating
1678 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1679 # the typical use is auto_groups=false.
1680 # @ingroup l2_impexp
1681 def ExportSAUV(self, f, auto_groups=0):
1682 self.mesh.ExportSAUV(f, auto_groups)
1684 ## Exports the mesh in a file in DAT format
1685 # @param f the file name
1686 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1687 # @ingroup l2_impexp
1688 def ExportDAT(self, f, meshPart=None):
1690 unRegister = genObjUnRegister()
1691 if isinstance( meshPart, list ):
1692 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1693 unRegister.set( meshPart )
1694 self.mesh.ExportPartToDAT( meshPart, f )
1696 self.mesh.ExportDAT(f)
1698 ## Exports the mesh in a file in UNV format
1699 # @param f the file name
1700 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1701 # @ingroup l2_impexp
1702 def ExportUNV(self, f, meshPart=None):
1704 unRegister = genObjUnRegister()
1705 if isinstance( meshPart, list ):
1706 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1707 unRegister.set( meshPart )
1708 self.mesh.ExportPartToUNV( meshPart, f )
1710 self.mesh.ExportUNV(f)
1712 ## Export the mesh in a file in STL format
1713 # @param f the file name
1714 # @param ascii defines the file encoding
1715 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1716 # @ingroup l2_impexp
1717 def ExportSTL(self, f, ascii=1, meshPart=None):
1719 unRegister = genObjUnRegister()
1720 if isinstance( meshPart, list ):
1721 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1722 unRegister.set( meshPart )
1723 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1725 self.mesh.ExportSTL(f, ascii)
1727 ## Exports the mesh in a file in CGNS format
1728 # @param f is the file name
1729 # @param overwrite boolean parameter for overwriting/not overwriting the file
1730 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1731 # @ingroup l2_impexp
1732 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1733 unRegister = genObjUnRegister()
1734 if isinstance( meshPart, list ):
1735 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1736 unRegister.set( meshPart )
1737 if isinstance( meshPart, Mesh ):
1738 meshPart = meshPart.mesh
1740 meshPart = self.mesh
1741 self.mesh.ExportCGNS(meshPart, f, overwrite)
1743 ## Exports the mesh in a file in GMF format.
1744 # GMF files must have .mesh extension for the ASCII format and .meshb for
1745 # the bynary format. Other extensions are not allowed.
1746 # @param f is the file name
1747 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1748 # @ingroup l2_impexp
1749 def ExportGMF(self, f, meshPart=None):
1750 unRegister = genObjUnRegister()
1751 if isinstance( meshPart, list ):
1752 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1753 unRegister.set( meshPart )
1754 if isinstance( meshPart, Mesh ):
1755 meshPart = meshPart.mesh
1757 meshPart = self.mesh
1758 self.mesh.ExportGMF(meshPart, f, True)
1760 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1761 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1762 ## allowing to overwrite the file if it exists or add the exported data to its contents
1763 # @param f the file name
1764 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1765 # @param opt boolean parameter for creating/not creating
1766 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1767 # @param overwrite boolean parameter for overwriting/not overwriting the file
1768 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1769 # - 1D if all mesh nodes lie on OX coordinate axis, or
1770 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1771 # - 3D in the rest cases.
1773 # If @a autoDimension is @c False, the space dimension is always 3.
1774 # @ingroup l2_impexp
1775 def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1776 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1778 # Operations with groups:
1779 # ----------------------
1781 ## Creates an empty mesh group
1782 # @param elementType the type of elements in the group
1783 # @param name the name of the mesh group
1784 # @return SMESH_Group
1785 # @ingroup l2_grps_create
1786 def CreateEmptyGroup(self, elementType, name):
1787 return self.mesh.CreateGroup(elementType, name)
1789 ## Creates a mesh group based on the geometric object \a grp
1790 # and gives a \a name, \n if this parameter is not defined
1791 # the name is the same as the geometric group name \n
1792 # Note: Works like GroupOnGeom().
1793 # @param grp a geometric group, a vertex, an edge, a face or a solid
1794 # @param name the name of the mesh group
1795 # @return SMESH_GroupOnGeom
1796 # @ingroup l2_grps_create
1797 def Group(self, grp, name=""):
1798 return self.GroupOnGeom(grp, name)
1800 ## Creates a mesh group based on the geometrical object \a grp
1801 # and gives a \a name, \n if this parameter is not defined
1802 # the name is the same as the geometrical group name
1803 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1804 # @param name the name of the mesh group
1805 # @param typ the type of elements in the group. If not set, it is
1806 # automatically detected by the type of the geometry
1807 # @return SMESH_GroupOnGeom
1808 # @ingroup l2_grps_create
1809 def GroupOnGeom(self, grp, name="", typ=None):
1810 AssureGeomPublished( self, grp, name )
1812 name = grp.GetName()
1814 typ = self._groupTypeFromShape( grp )
1815 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1817 ## Pivate method to get a type of group on geometry
1818 def _groupTypeFromShape( self, shape ):
1819 tgeo = str(shape.GetShapeType())
1820 if tgeo == "VERTEX":
1822 elif tgeo == "EDGE":
1824 elif tgeo == "FACE" or tgeo == "SHELL":
1826 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1828 elif tgeo == "COMPOUND":
1829 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1831 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1832 return self._groupTypeFromShape( sub[0] )
1835 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1838 ## Creates a mesh group with given \a name based on the \a filter which
1839 ## is a special type of group dynamically updating it's contents during
1840 ## mesh modification
1841 # @param typ the type of elements in the group
1842 # @param name the name of the mesh group
1843 # @param filter the filter defining group contents
1844 # @return SMESH_GroupOnFilter
1845 # @ingroup l2_grps_create
1846 def GroupOnFilter(self, typ, name, filter):
1847 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1849 ## Creates a mesh group by the given ids of elements
1850 # @param groupName the name of the mesh group
1851 # @param elementType the type of elements in the group
1852 # @param elemIDs the list of ids
1853 # @return SMESH_Group
1854 # @ingroup l2_grps_create
1855 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1856 group = self.mesh.CreateGroup(elementType, groupName)
1860 ## Creates a mesh group by the given conditions
1861 # @param groupName the name of the mesh group
1862 # @param elementType the type of elements in the group
1863 # @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1864 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1865 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
1866 # @param UnaryOp FT_LogicalNOT or FT_Undefined
1867 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1868 # FT_LyingOnGeom, FT_CoplanarFaces criteria
1869 # @return SMESH_Group
1870 # @ingroup l2_grps_create
1874 CritType=FT_Undefined,
1877 UnaryOp=FT_Undefined,
1879 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1880 group = self.MakeGroupByCriterion(groupName, aCriterion)
1883 ## Creates a mesh group by the given criterion
1884 # @param groupName the name of the mesh group
1885 # @param Criterion the instance of Criterion class
1886 # @return SMESH_Group
1887 # @ingroup l2_grps_create
1888 def MakeGroupByCriterion(self, groupName, Criterion):
1889 aFilterMgr = self.smeshpyD.CreateFilterManager()
1890 aFilter = aFilterMgr.CreateFilter()
1892 aCriteria.append(Criterion)
1893 aFilter.SetCriteria(aCriteria)
1894 group = self.MakeGroupByFilter(groupName, aFilter)
1895 aFilterMgr.UnRegister()
1898 ## Creates a mesh group by the given criteria (list of criteria)
1899 # @param groupName the name of the mesh group
1900 # @param theCriteria the list of criteria
1901 # @return SMESH_Group
1902 # @ingroup l2_grps_create
1903 def MakeGroupByCriteria(self, groupName, theCriteria):
1904 aFilterMgr = self.smeshpyD.CreateFilterManager()
1905 aFilter = aFilterMgr.CreateFilter()
1906 aFilter.SetCriteria(theCriteria)
1907 group = self.MakeGroupByFilter(groupName, aFilter)
1908 aFilterMgr.UnRegister()
1911 ## Creates a mesh group by the given filter
1912 # @param groupName the name of the mesh group
1913 # @param theFilter the instance of Filter class
1914 # @return SMESH_Group
1915 # @ingroup l2_grps_create
1916 def MakeGroupByFilter(self, groupName, theFilter):
1917 group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1918 theFilter.SetMesh( self.mesh )
1919 group.AddFrom( theFilter )
1923 # @ingroup l2_grps_delete
1924 def RemoveGroup(self, group):
1925 self.mesh.RemoveGroup(group)
1927 ## Removes a group with its contents
1928 # @ingroup l2_grps_delete
1929 def RemoveGroupWithContents(self, group):
1930 self.mesh.RemoveGroupWithContents(group)
1932 ## Gets the list of groups existing in the mesh in the order of creation (starting from the oldest one)
1933 # @return a sequence of SMESH_GroupBase
1934 # @ingroup l2_grps_create
1935 def GetGroups(self):
1936 return self.mesh.GetGroups()
1938 ## Gets the number of groups existing in the mesh
1939 # @return the quantity of groups as an integer value
1940 # @ingroup l2_grps_create
1942 return self.mesh.NbGroups()
1944 ## Gets the list of names of groups existing in the mesh
1945 # @return list of strings
1946 # @ingroup l2_grps_create
1947 def GetGroupNames(self):
1948 groups = self.GetGroups()
1950 for group in groups:
1951 names.append(group.GetName())
1954 ## Produces a union of two groups
1955 # A new group is created. All mesh elements that are
1956 # present in the initial groups are added to the new one
1957 # @return an instance of SMESH_Group
1958 # @ingroup l2_grps_operon
1959 def UnionGroups(self, group1, group2, name):
1960 return self.mesh.UnionGroups(group1, group2, name)
1962 ## Produces a union list of groups
1963 # New group is created. All mesh elements that are present in
1964 # initial groups are added to the new one
1965 # @return an instance of SMESH_Group
1966 # @ingroup l2_grps_operon
1967 def UnionListOfGroups(self, groups, name):
1968 return self.mesh.UnionListOfGroups(groups, name)
1970 ## Prodices an intersection of two groups
1971 # A new group is created. All mesh elements that are common
1972 # for the two initial groups are added to the new one.
1973 # @return an instance of SMESH_Group
1974 # @ingroup l2_grps_operon
1975 def IntersectGroups(self, group1, group2, name):
1976 return self.mesh.IntersectGroups(group1, group2, name)
1978 ## Produces an intersection of groups
1979 # New group is created. All mesh elements that are present in all
1980 # initial groups simultaneously are added to the new one
1981 # @return an instance of SMESH_Group
1982 # @ingroup l2_grps_operon
1983 def IntersectListOfGroups(self, groups, name):
1984 return self.mesh.IntersectListOfGroups(groups, name)
1986 ## Produces a cut of two groups
1987 # A new group is created. All mesh elements that are present in
1988 # the main group but are not present in the tool group are added to the new one
1989 # @return an instance of SMESH_Group
1990 # @ingroup l2_grps_operon
1991 def CutGroups(self, main_group, tool_group, name):
1992 return self.mesh.CutGroups(main_group, tool_group, name)
1994 ## Produces a cut of groups
1995 # A new group is created. All mesh elements that are present in main groups
1996 # but do not present in tool groups are added to the new one
1997 # @return an instance of SMESH_Group
1998 # @ingroup l2_grps_operon
1999 def CutListOfGroups(self, main_groups, tool_groups, name):
2000 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2002 ## Produces a group of elements of specified type using list of existing groups
2003 # A new group is created. System
2004 # 1) extracts all nodes on which groups elements are built
2005 # 2) combines all elements of specified dimension laying on these nodes
2006 # @return an instance of SMESH_Group
2007 # @ingroup l2_grps_operon
2008 def CreateDimGroup(self, groups, elem_type, name):
2009 return self.mesh.CreateDimGroup(groups, elem_type, name)
2012 ## Convert group on geom into standalone group
2013 # @ingroup l2_grps_delete
2014 def ConvertToStandalone(self, group):
2015 return self.mesh.ConvertToStandalone(group)
2017 # Get some info about mesh:
2018 # ------------------------
2020 ## Returns the log of nodes and elements added or removed
2021 # since the previous clear of the log.
2022 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2023 # @return list of log_block structures:
2028 # @ingroup l1_auxiliary
2029 def GetLog(self, clearAfterGet):
2030 return self.mesh.GetLog(clearAfterGet)
2032 ## Clears the log of nodes and elements added or removed since the previous
2033 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2034 # @ingroup l1_auxiliary
2036 self.mesh.ClearLog()
2038 ## Toggles auto color mode on the object.
2039 # @param theAutoColor the flag which toggles auto color mode.
2040 # @ingroup l1_auxiliary
2041 def SetAutoColor(self, theAutoColor):
2042 self.mesh.SetAutoColor(theAutoColor)
2044 ## Gets flag of object auto color mode.
2045 # @return True or False
2046 # @ingroup l1_auxiliary
2047 def GetAutoColor(self):
2048 return self.mesh.GetAutoColor()
2050 ## Gets the internal ID
2051 # @return integer value, which is the internal Id of the mesh
2052 # @ingroup l1_auxiliary
2054 return self.mesh.GetId()
2057 # @return integer value, which is the study Id of the mesh
2058 # @ingroup l1_auxiliary
2059 def GetStudyId(self):
2060 return self.mesh.GetStudyId()
2062 ## Checks the group names for duplications.
2063 # Consider the maximum group name length stored in MED file.
2064 # @return True or False
2065 # @ingroup l1_auxiliary
2066 def HasDuplicatedGroupNamesMED(self):
2067 return self.mesh.HasDuplicatedGroupNamesMED()
2069 ## Obtains the mesh editor tool
2070 # @return an instance of SMESH_MeshEditor
2071 # @ingroup l1_modifying
2072 def GetMeshEditor(self):
2075 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2076 # can be passed as argument to a method accepting mesh, group or sub-mesh
2077 # @return an instance of SMESH_IDSource
2078 # @ingroup l1_auxiliary
2079 def GetIDSource(self, ids, elemType):
2080 return self.editor.MakeIDSource(ids, elemType)
2083 # Get informations about mesh contents:
2084 # ------------------------------------
2086 ## Gets the mesh stattistic
2087 # @return dictionary type element - count of elements
2088 # @ingroup l1_meshinfo
2089 def GetMeshInfo(self, obj = None):
2090 if not obj: obj = self.mesh
2091 return self.smeshpyD.GetMeshInfo(obj)
2093 ## Returns the number of nodes in the mesh
2094 # @return an integer value
2095 # @ingroup l1_meshinfo
2097 return self.mesh.NbNodes()
2099 ## Returns the number of elements in the mesh
2100 # @return an integer value
2101 # @ingroup l1_meshinfo
2102 def NbElements(self):
2103 return self.mesh.NbElements()
2105 ## Returns the number of 0d elements in the mesh
2106 # @return an integer value
2107 # @ingroup l1_meshinfo
2108 def Nb0DElements(self):
2109 return self.mesh.Nb0DElements()
2111 ## Returns the number of ball discrete elements in the mesh
2112 # @return an integer value
2113 # @ingroup l1_meshinfo
2115 return self.mesh.NbBalls()
2117 ## Returns the number of edges in the mesh
2118 # @return an integer value
2119 # @ingroup l1_meshinfo
2121 return self.mesh.NbEdges()
2123 ## Returns the number of edges with the given order in the mesh
2124 # @param elementOrder the order of elements:
2125 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2126 # @return an integer value
2127 # @ingroup l1_meshinfo
2128 def NbEdgesOfOrder(self, elementOrder):
2129 return self.mesh.NbEdgesOfOrder(elementOrder)
2131 ## Returns the number of faces in the mesh
2132 # @return an integer value
2133 # @ingroup l1_meshinfo
2135 return self.mesh.NbFaces()
2137 ## Returns the number of faces with the given order in the mesh
2138 # @param elementOrder the order of elements:
2139 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2140 # @return an integer value
2141 # @ingroup l1_meshinfo
2142 def NbFacesOfOrder(self, elementOrder):
2143 return self.mesh.NbFacesOfOrder(elementOrder)
2145 ## Returns the number of triangles in the mesh
2146 # @return an integer value
2147 # @ingroup l1_meshinfo
2148 def NbTriangles(self):
2149 return self.mesh.NbTriangles()
2151 ## Returns the number of triangles with the given order in the mesh
2152 # @param elementOrder is the order of elements:
2153 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2154 # @return an integer value
2155 # @ingroup l1_meshinfo
2156 def NbTrianglesOfOrder(self, elementOrder):
2157 return self.mesh.NbTrianglesOfOrder(elementOrder)
2159 ## Returns the number of biquadratic triangles in the mesh
2160 # @return an integer value
2161 # @ingroup l1_meshinfo
2162 def NbBiQuadTriangles(self):
2163 return self.mesh.NbBiQuadTriangles()
2165 ## Returns the number of quadrangles in the mesh
2166 # @return an integer value
2167 # @ingroup l1_meshinfo
2168 def NbQuadrangles(self):
2169 return self.mesh.NbQuadrangles()
2171 ## Returns the number of quadrangles with the given order in the mesh
2172 # @param elementOrder the order of elements:
2173 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2174 # @return an integer value
2175 # @ingroup l1_meshinfo
2176 def NbQuadranglesOfOrder(self, elementOrder):
2177 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2179 ## Returns the number of biquadratic quadrangles in the mesh
2180 # @return an integer value
2181 # @ingroup l1_meshinfo
2182 def NbBiQuadQuadrangles(self):
2183 return self.mesh.NbBiQuadQuadrangles()
2185 ## Returns the number of polygons in the mesh
2186 # @return an integer value
2187 # @ingroup l1_meshinfo
2188 def NbPolygons(self):
2189 return self.mesh.NbPolygons()
2191 ## Returns the number of volumes in the mesh
2192 # @return an integer value
2193 # @ingroup l1_meshinfo
2194 def NbVolumes(self):
2195 return self.mesh.NbVolumes()
2197 ## Returns the number of volumes with the given order in the mesh
2198 # @param elementOrder the order of elements:
2199 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2200 # @return an integer value
2201 # @ingroup l1_meshinfo
2202 def NbVolumesOfOrder(self, elementOrder):
2203 return self.mesh.NbVolumesOfOrder(elementOrder)
2205 ## Returns the number of tetrahedrons in the mesh
2206 # @return an integer value
2207 # @ingroup l1_meshinfo
2209 return self.mesh.NbTetras()
2211 ## Returns the number of tetrahedrons with the given order in the mesh
2212 # @param elementOrder the order of elements:
2213 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2214 # @return an integer value
2215 # @ingroup l1_meshinfo
2216 def NbTetrasOfOrder(self, elementOrder):
2217 return self.mesh.NbTetrasOfOrder(elementOrder)
2219 ## Returns the number of hexahedrons in the mesh
2220 # @return an integer value
2221 # @ingroup l1_meshinfo
2223 return self.mesh.NbHexas()
2225 ## Returns the number of hexahedrons with the given order in the mesh
2226 # @param elementOrder the order of elements:
2227 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2228 # @return an integer value
2229 # @ingroup l1_meshinfo
2230 def NbHexasOfOrder(self, elementOrder):
2231 return self.mesh.NbHexasOfOrder(elementOrder)
2233 ## Returns the number of triquadratic hexahedrons in the mesh
2234 # @return an integer value
2235 # @ingroup l1_meshinfo
2236 def NbTriQuadraticHexas(self):
2237 return self.mesh.NbTriQuadraticHexas()
2239 ## Returns the number of pyramids in the mesh
2240 # @return an integer value
2241 # @ingroup l1_meshinfo
2242 def NbPyramids(self):
2243 return self.mesh.NbPyramids()
2245 ## Returns the number of pyramids with the given order in the mesh
2246 # @param elementOrder the order of elements:
2247 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2248 # @return an integer value
2249 # @ingroup l1_meshinfo
2250 def NbPyramidsOfOrder(self, elementOrder):
2251 return self.mesh.NbPyramidsOfOrder(elementOrder)
2253 ## Returns the number of prisms in the mesh
2254 # @return an integer value
2255 # @ingroup l1_meshinfo
2257 return self.mesh.NbPrisms()
2259 ## Returns the number of prisms with the given order in the mesh
2260 # @param elementOrder the order of elements:
2261 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2262 # @return an integer value
2263 # @ingroup l1_meshinfo
2264 def NbPrismsOfOrder(self, elementOrder):
2265 return self.mesh.NbPrismsOfOrder(elementOrder)
2267 ## Returns the number of hexagonal prisms in the mesh
2268 # @return an integer value
2269 # @ingroup l1_meshinfo
2270 def NbHexagonalPrisms(self):
2271 return self.mesh.NbHexagonalPrisms()
2273 ## Returns the number of polyhedrons in the mesh
2274 # @return an integer value
2275 # @ingroup l1_meshinfo
2276 def NbPolyhedrons(self):
2277 return self.mesh.NbPolyhedrons()
2279 ## Returns the number of submeshes in the mesh
2280 # @return an integer value
2281 # @ingroup l1_meshinfo
2282 def NbSubMesh(self):
2283 return self.mesh.NbSubMesh()
2285 ## Returns the list of mesh elements IDs
2286 # @return the list of integer values
2287 # @ingroup l1_meshinfo
2288 def GetElementsId(self):
2289 return self.mesh.GetElementsId()
2291 ## Returns the list of IDs of mesh elements with the given type
2292 # @param elementType the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2293 # @return list of integer values
2294 # @ingroup l1_meshinfo
2295 def GetElementsByType(self, elementType):
2296 return self.mesh.GetElementsByType(elementType)
2298 ## Returns the list of mesh nodes IDs
2299 # @return the list of integer values
2300 # @ingroup l1_meshinfo
2301 def GetNodesId(self):
2302 return self.mesh.GetNodesId()
2304 # Get the information about mesh elements:
2305 # ------------------------------------
2307 ## Returns the type of mesh element
2308 # @return the value from SMESH::ElementType enumeration
2309 # @ingroup l1_meshinfo
2310 def GetElementType(self, id, iselem):
2311 return self.mesh.GetElementType(id, iselem)
2313 ## Returns the geometric type of mesh element
2314 # @return the value from SMESH::EntityType enumeration
2315 # @ingroup l1_meshinfo
2316 def GetElementGeomType(self, id):
2317 return self.mesh.GetElementGeomType(id)
2319 ## Returns the shape type of mesh element
2320 # @return the value from SMESH::GeometryType enumeration
2321 # @ingroup l1_meshinfo
2322 def GetElementShape(self, id):
2323 return self.mesh.GetElementShape(id)
2325 ## Returns the list of submesh elements IDs
2326 # @param Shape a geom object(sub-shape) IOR
2327 # Shape must be the sub-shape of a ShapeToMesh()
2328 # @return the list of integer values
2329 # @ingroup l1_meshinfo
2330 def GetSubMeshElementsId(self, Shape):
2331 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2332 ShapeID = Shape.GetSubShapeIndices()[0]
2335 return self.mesh.GetSubMeshElementsId(ShapeID)
2337 ## Returns the list of submesh nodes IDs
2338 # @param Shape a geom object(sub-shape) IOR
2339 # Shape must be the sub-shape of a ShapeToMesh()
2340 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2341 # @return the list of integer values
2342 # @ingroup l1_meshinfo
2343 def GetSubMeshNodesId(self, Shape, all):
2344 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2345 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2348 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2350 ## Returns type of elements on given shape
2351 # @param Shape a geom object(sub-shape) IOR
2352 # Shape must be a sub-shape of a ShapeToMesh()
2353 # @return element type
2354 # @ingroup l1_meshinfo
2355 def GetSubMeshElementType(self, Shape):
2356 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2357 ShapeID = Shape.GetSubShapeIndices()[0]
2360 return self.mesh.GetSubMeshElementType(ShapeID)
2362 ## Gets the mesh description
2363 # @return string value
2364 # @ingroup l1_meshinfo
2366 return self.mesh.Dump()
2369 # Get the information about nodes and elements of a mesh by its IDs:
2370 # -----------------------------------------------------------
2372 ## Gets XYZ coordinates of a node
2373 # \n If there is no nodes for the given ID - returns an empty list
2374 # @return a list of double precision values
2375 # @ingroup l1_meshinfo
2376 def GetNodeXYZ(self, id):
2377 return self.mesh.GetNodeXYZ(id)
2379 ## Returns list of IDs of inverse elements for the given node
2380 # \n If there is no node for the given ID - returns an empty list
2381 # @return a list of integer values
2382 # @ingroup l1_meshinfo
2383 def GetNodeInverseElements(self, id):
2384 return self.mesh.GetNodeInverseElements(id)
2386 ## @brief Returns the position of a node on the shape
2387 # @return SMESH::NodePosition
2388 # @ingroup l1_meshinfo
2389 def GetNodePosition(self,NodeID):
2390 return self.mesh.GetNodePosition(NodeID)
2392 ## @brief Returns the position of an element on the shape
2393 # @return SMESH::ElementPosition
2394 # @ingroup l1_meshinfo
2395 def GetElementPosition(self,ElemID):
2396 return self.mesh.GetElementPosition(ElemID)
2398 ## If the given element is a node, returns the ID of shape
2399 # \n If there is no node for the given ID - returns -1
2400 # @return an integer value
2401 # @ingroup l1_meshinfo
2402 def GetShapeID(self, id):
2403 return self.mesh.GetShapeID(id)
2405 ## Returns the ID of the result shape after
2406 # FindShape() from SMESH_MeshEditor for the given element
2407 # \n If there is no element for the given ID - returns -1
2408 # @return an integer value
2409 # @ingroup l1_meshinfo
2410 def GetShapeIDForElem(self,id):
2411 return self.mesh.GetShapeIDForElem(id)
2413 ## Returns the number of nodes for the given element
2414 # \n If there is no element for the given ID - returns -1
2415 # @return an integer value
2416 # @ingroup l1_meshinfo
2417 def GetElemNbNodes(self, id):
2418 return self.mesh.GetElemNbNodes(id)
2420 ## Returns the node ID the given (zero based) index for the given element
2421 # \n If there is no element for the given ID - returns -1
2422 # \n If there is no node for the given index - returns -2
2423 # @return an integer value
2424 # @ingroup l1_meshinfo
2425 def GetElemNode(self, id, index):
2426 return self.mesh.GetElemNode(id, index)
2428 ## Returns the IDs of nodes of the given element
2429 # @return a list of integer values
2430 # @ingroup l1_meshinfo
2431 def GetElemNodes(self, id):
2432 return self.mesh.GetElemNodes(id)
2434 ## Returns true if the given node is the medium node in the given quadratic element
2435 # @ingroup l1_meshinfo
2436 def IsMediumNode(self, elementID, nodeID):
2437 return self.mesh.IsMediumNode(elementID, nodeID)
2439 ## Returns true if the given node is the medium node in one of quadratic elements
2440 # @ingroup l1_meshinfo
2441 def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2442 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2444 ## Returns the number of edges for the given element
2445 # @ingroup l1_meshinfo
2446 def ElemNbEdges(self, id):
2447 return self.mesh.ElemNbEdges(id)
2449 ## Returns the number of faces for the given element
2450 # @ingroup l1_meshinfo
2451 def ElemNbFaces(self, id):
2452 return self.mesh.ElemNbFaces(id)
2454 ## Returns nodes of given face (counted from zero) for given volumic element.
2455 # @ingroup l1_meshinfo
2456 def GetElemFaceNodes(self,elemId, faceIndex):
2457 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2459 ## Returns three components of normal of given mesh face
2460 # (or an empty array in KO case)
2461 # @ingroup l1_meshinfo
2462 def GetFaceNormal(self, faceId, normalized=False):
2463 return self.mesh.GetFaceNormal(faceId,normalized)
2465 ## Returns an element based on all given nodes.
2466 # @ingroup l1_meshinfo
2467 def FindElementByNodes(self,nodes):
2468 return self.mesh.FindElementByNodes(nodes)
2470 ## Returns true if the given element is a polygon
2471 # @ingroup l1_meshinfo
2472 def IsPoly(self, id):
2473 return self.mesh.IsPoly(id)
2475 ## Returns true if the given element is quadratic
2476 # @ingroup l1_meshinfo
2477 def IsQuadratic(self, id):
2478 return self.mesh.IsQuadratic(id)
2480 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2481 # @ingroup l1_meshinfo
2482 def GetBallDiameter(self, id):
2483 return self.mesh.GetBallDiameter(id)
2485 ## Returns XYZ coordinates of the barycenter of the given element
2486 # \n If there is no element for the given ID - returns an empty list
2487 # @return a list of three double values
2488 # @ingroup l1_meshinfo
2489 def BaryCenter(self, id):
2490 return self.mesh.BaryCenter(id)
2492 ## Passes mesh elements through the given filter and return IDs of fitting elements
2493 # @param theFilter SMESH_Filter
2494 # @return a list of ids
2495 # @ingroup l1_controls
2496 def GetIdsFromFilter(self, theFilter):
2497 theFilter.SetMesh( self.mesh )
2498 return theFilter.GetIDs()
2500 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2501 # Returns a list of special structures (borders).
2502 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2503 # @ingroup l1_controls
2504 def GetFreeBorders(self):
2505 aFilterMgr = self.smeshpyD.CreateFilterManager()
2506 aPredicate = aFilterMgr.CreateFreeEdges()
2507 aPredicate.SetMesh(self.mesh)
2508 aBorders = aPredicate.GetBorders()
2509 aFilterMgr.UnRegister()
2513 # Get mesh measurements information:
2514 # ------------------------------------
2516 ## Get minimum distance between two nodes, elements or distance to the origin
2517 # @param id1 first node/element id
2518 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2519 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2520 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2521 # @return minimum distance value
2522 # @sa GetMinDistance()
2523 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2524 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2525 return aMeasure.value
2527 ## Get measure structure specifying minimum distance data between two objects
2528 # @param id1 first node/element id
2529 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2530 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2531 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2532 # @return Measure structure
2534 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2536 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2538 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2541 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2543 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2548 aMeasurements = self.smeshpyD.CreateMeasurements()
2549 aMeasure = aMeasurements.MinDistance(id1, id2)
2550 genObjUnRegister([aMeasurements,id1, id2])
2553 ## Get bounding box of the specified object(s)
2554 # @param objects single source object or list of source objects or list of nodes/elements IDs
2555 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2556 # @c False specifies that @a objects are nodes
2557 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2558 # @sa GetBoundingBox()
2559 def BoundingBox(self, objects=None, isElem=False):
2560 result = self.GetBoundingBox(objects, isElem)
2564 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2567 ## Get measure structure specifying bounding box data of the specified object(s)
2568 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2569 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2570 # @c False specifies that @a objects are nodes
2571 # @return Measure structure
2573 def GetBoundingBox(self, IDs=None, isElem=False):
2576 elif isinstance(IDs, tuple):
2578 if not isinstance(IDs, list):
2580 if len(IDs) > 0 and isinstance(IDs[0], int):
2583 unRegister = genObjUnRegister()
2585 if isinstance(o, Mesh):
2586 srclist.append(o.mesh)
2587 elif hasattr(o, "_narrow"):
2588 src = o._narrow(SMESH.SMESH_IDSource)
2589 if src: srclist.append(src)
2591 elif isinstance(o, list):
2593 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2595 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2596 unRegister.set( srclist[-1] )
2599 aMeasurements = self.smeshpyD.CreateMeasurements()
2600 unRegister.set( aMeasurements )
2601 aMeasure = aMeasurements.BoundingBox(srclist)
2604 # Mesh edition (SMESH_MeshEditor functionality):
2605 # ---------------------------------------------
2607 ## Removes the elements from the mesh by ids
2608 # @param IDsOfElements is a list of ids of elements to remove
2609 # @return True or False
2610 # @ingroup l2_modif_del
2611 def RemoveElements(self, IDsOfElements):
2612 return self.editor.RemoveElements(IDsOfElements)
2614 ## Removes nodes from mesh by ids
2615 # @param IDsOfNodes is a list of ids of nodes to remove
2616 # @return True or False
2617 # @ingroup l2_modif_del
2618 def RemoveNodes(self, IDsOfNodes):
2619 return self.editor.RemoveNodes(IDsOfNodes)
2621 ## Removes all orphan (free) nodes from mesh
2622 # @return number of the removed nodes
2623 # @ingroup l2_modif_del
2624 def RemoveOrphanNodes(self):
2625 return self.editor.RemoveOrphanNodes()
2627 ## Add a node to the mesh by coordinates
2628 # @return Id of the new node
2629 # @ingroup l2_modif_add
2630 def AddNode(self, x, y, z):
2631 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2632 if hasVars: self.mesh.SetParameters(Parameters)
2633 return self.editor.AddNode( x, y, z)
2635 ## Creates a 0D element on a node with given number.
2636 # @param IDOfNode the ID of node for creation of the element.
2637 # @return the Id of the new 0D element
2638 # @ingroup l2_modif_add
2639 def Add0DElement(self, IDOfNode):
2640 return self.editor.Add0DElement(IDOfNode)
2642 ## Create 0D elements on all nodes of the given elements except those
2643 # nodes on which a 0D element already exists.
2644 # @param theObject an object on whose nodes 0D elements will be created.
2645 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2646 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2647 # @param theGroupName optional name of a group to add 0D elements created
2648 # and/or found on nodes of \a theObject.
2649 # @return an object (a new group or a temporary SMESH_IDSource) holding
2650 # IDs of new and/or found 0D elements. IDs of 0D elements
2651 # can be retrieved from the returned object by calling GetIDs()
2652 # @ingroup l2_modif_add
2653 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2654 unRegister = genObjUnRegister()
2655 if isinstance( theObject, Mesh ):
2656 theObject = theObject.GetMesh()
2657 if isinstance( theObject, list ):
2658 theObject = self.GetIDSource( theObject, SMESH.ALL )
2659 unRegister.set( theObject )
2660 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2662 ## Creates a ball element on a node with given ID.
2663 # @param IDOfNode the ID of node for creation of the element.
2664 # @param diameter the bal diameter.
2665 # @return the Id of the new ball element
2666 # @ingroup l2_modif_add
2667 def AddBall(self, IDOfNode, diameter):
2668 return self.editor.AddBall( IDOfNode, diameter )
2670 ## Creates a linear or quadratic edge (this is determined
2671 # by the number of given nodes).
2672 # @param IDsOfNodes the list of node IDs for creation of the element.
2673 # The order of nodes in this list should correspond to the description
2674 # of MED. \n This description is located by the following link:
2675 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2676 # @return the Id of the new edge
2677 # @ingroup l2_modif_add
2678 def AddEdge(self, IDsOfNodes):
2679 return self.editor.AddEdge(IDsOfNodes)
2681 ## Creates a linear or quadratic face (this is determined
2682 # by the number of given nodes).
2683 # @param IDsOfNodes the list of node IDs for creation of the element.
2684 # The order of nodes in this list should correspond to the description
2685 # of MED. \n This description is located by the following link:
2686 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2687 # @return the Id of the new face
2688 # @ingroup l2_modif_add
2689 def AddFace(self, IDsOfNodes):
2690 return self.editor.AddFace(IDsOfNodes)
2692 ## Adds a polygonal face to the mesh by the list of node IDs
2693 # @param IdsOfNodes the list of node IDs for creation of the element.
2694 # @return the Id of the new face
2695 # @ingroup l2_modif_add
2696 def AddPolygonalFace(self, IdsOfNodes):
2697 return self.editor.AddPolygonalFace(IdsOfNodes)
2699 ## Creates both simple and quadratic volume (this is determined
2700 # by the number of given nodes).
2701 # @param IDsOfNodes the list of node IDs for creation of the element.
2702 # The order of nodes in this list should correspond to the description
2703 # of MED. \n This description is located by the following link:
2704 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2705 # @return the Id of the new volumic element
2706 # @ingroup l2_modif_add
2707 def AddVolume(self, IDsOfNodes):
2708 return self.editor.AddVolume(IDsOfNodes)
2710 ## Creates a volume of many faces, giving nodes for each face.
2711 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2712 # @param Quantities the list of integer values, Quantities[i]
2713 # gives the quantity of nodes in face number i.
2714 # @return the Id of the new volumic element
2715 # @ingroup l2_modif_add
2716 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2717 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2719 ## Creates a volume of many faces, giving the IDs of the existing faces.
2720 # @param IdsOfFaces the list of face IDs for volume creation.
2722 # Note: The created volume will refer only to the nodes
2723 # of the given faces, not to the faces themselves.
2724 # @return the Id of the new volumic element
2725 # @ingroup l2_modif_add
2726 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2727 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2730 ## @brief Binds a node to a vertex
2731 # @param NodeID a node ID
2732 # @param Vertex a vertex or vertex ID
2733 # @return True if succeed else raises an exception
2734 # @ingroup l2_modif_add
2735 def SetNodeOnVertex(self, NodeID, Vertex):
2736 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2737 VertexID = Vertex.GetSubShapeIndices()[0]
2741 self.editor.SetNodeOnVertex(NodeID, VertexID)
2742 except SALOME.SALOME_Exception, inst:
2743 raise ValueError, inst.details.text
2747 ## @brief Stores the node position on an edge
2748 # @param NodeID a node ID
2749 # @param Edge an edge or edge ID
2750 # @param paramOnEdge a parameter on the edge where the node is located
2751 # @return True if succeed else raises an exception
2752 # @ingroup l2_modif_add
2753 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2754 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2755 EdgeID = Edge.GetSubShapeIndices()[0]
2759 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2760 except SALOME.SALOME_Exception, inst:
2761 raise ValueError, inst.details.text
2764 ## @brief Stores node position on a face
2765 # @param NodeID a node ID
2766 # @param Face a face or face ID
2767 # @param u U parameter on the face where the node is located
2768 # @param v V parameter on the face where the node is located
2769 # @return True if succeed else raises an exception
2770 # @ingroup l2_modif_add
2771 def SetNodeOnFace(self, NodeID, Face, u, v):
2772 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2773 FaceID = Face.GetSubShapeIndices()[0]
2777 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2778 except SALOME.SALOME_Exception, inst:
2779 raise ValueError, inst.details.text
2782 ## @brief Binds a node to a solid
2783 # @param NodeID a node ID
2784 # @param Solid a solid or solid ID
2785 # @return True if succeed else raises an exception
2786 # @ingroup l2_modif_add
2787 def SetNodeInVolume(self, NodeID, Solid):
2788 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2789 SolidID = Solid.GetSubShapeIndices()[0]
2793 self.editor.SetNodeInVolume(NodeID, SolidID)
2794 except SALOME.SALOME_Exception, inst:
2795 raise ValueError, inst.details.text
2798 ## @brief Bind an element to a shape
2799 # @param ElementID an element ID
2800 # @param Shape a shape or shape ID
2801 # @return True if succeed else raises an exception
2802 # @ingroup l2_modif_add
2803 def SetMeshElementOnShape(self, ElementID, Shape):
2804 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2805 ShapeID = Shape.GetSubShapeIndices()[0]
2809 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2810 except SALOME.SALOME_Exception, inst:
2811 raise ValueError, inst.details.text
2815 ## Moves the node with the given id
2816 # @param NodeID the id of the node
2817 # @param x a new X coordinate
2818 # @param y a new Y coordinate
2819 # @param z a new Z coordinate
2820 # @return True if succeed else False
2821 # @ingroup l2_modif_movenode
2822 def MoveNode(self, NodeID, x, y, z):
2823 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2824 if hasVars: self.mesh.SetParameters(Parameters)
2825 return self.editor.MoveNode(NodeID, x, y, z)
2827 ## Finds the node closest to a point and moves it to a point location
2828 # @param x the X coordinate of a point
2829 # @param y the Y coordinate of a point
2830 # @param z the Z coordinate of a point
2831 # @param NodeID if specified (>0), the node with this ID is moved,
2832 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
2833 # @return the ID of a node
2834 # @ingroup l2_modif_throughp
2835 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2836 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2837 if hasVars: self.mesh.SetParameters(Parameters)
2838 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2840 ## Finds the node closest to a point
2841 # @param x the X coordinate of a point
2842 # @param y the Y coordinate of a point
2843 # @param z the Z coordinate of a point
2844 # @return the ID of a node
2845 # @ingroup l2_modif_throughp
2846 def FindNodeClosestTo(self, x, y, z):
2847 #preview = self.mesh.GetMeshEditPreviewer()
2848 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2849 return self.editor.FindNodeClosestTo(x, y, z)
2851 ## Finds the elements where a point lays IN or ON
2852 # @param x the X coordinate of a point
2853 # @param y the Y coordinate of a point
2854 # @param z the Z coordinate of a point
2855 # @param elementType type of elements to find (SMESH.ALL type
2856 # means elements of any type excluding nodes, discrete and 0D elements)
2857 # @param meshPart a part of mesh (group, sub-mesh) to search within
2858 # @return list of IDs of found elements
2859 # @ingroup l2_modif_throughp
2860 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2862 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2864 return self.editor.FindElementsByPoint(x, y, z, elementType)
2866 # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2867 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2868 # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2870 def GetPointState(self, x, y, z):
2871 return self.editor.GetPointState(x, y, z)
2873 ## Finds the node closest to a point and moves it to a point location
2874 # @param x the X coordinate of a point
2875 # @param y the Y coordinate of a point
2876 # @param z the Z coordinate of a point
2877 # @return the ID of a moved node
2878 # @ingroup l2_modif_throughp
2879 def MeshToPassThroughAPoint(self, x, y, z):
2880 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2882 ## Replaces two neighbour triangles sharing Node1-Node2 link
2883 # with the triangles built on the same 4 nodes but having other common link.
2884 # @param NodeID1 the ID of the first node
2885 # @param NodeID2 the ID of the second node
2886 # @return false if proper faces were not found
2887 # @ingroup l2_modif_invdiag
2888 def InverseDiag(self, NodeID1, NodeID2):
2889 return self.editor.InverseDiag(NodeID1, NodeID2)
2891 ## Replaces two neighbour triangles sharing Node1-Node2 link
2892 # with a quadrangle built on the same 4 nodes.
2893 # @param NodeID1 the ID of the first node
2894 # @param NodeID2 the ID of the second node
2895 # @return false if proper faces were not found
2896 # @ingroup l2_modif_unitetri
2897 def DeleteDiag(self, NodeID1, NodeID2):
2898 return self.editor.DeleteDiag(NodeID1, NodeID2)
2900 ## Reorients elements by ids
2901 # @param IDsOfElements if undefined reorients all mesh elements
2902 # @return True if succeed else False
2903 # @ingroup l2_modif_changori
2904 def Reorient(self, IDsOfElements=None):
2905 if IDsOfElements == None:
2906 IDsOfElements = self.GetElementsId()
2907 return self.editor.Reorient(IDsOfElements)
2909 ## Reorients all elements of the object
2910 # @param theObject mesh, submesh or group
2911 # @return True if succeed else False
2912 # @ingroup l2_modif_changori
2913 def ReorientObject(self, theObject):
2914 if ( isinstance( theObject, Mesh )):
2915 theObject = theObject.GetMesh()
2916 return self.editor.ReorientObject(theObject)
2918 ## Reorient faces contained in \a the2DObject.
2919 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2920 # @param theDirection is a desired direction of normal of \a theFace.
2921 # It can be either a GEOM vector or a list of coordinates [x,y,z].
2922 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2923 # compared with theDirection. It can be either ID of face or a point
2924 # by which the face will be found. The point can be given as either
2925 # a GEOM vertex or a list of point coordinates.
2926 # @return number of reoriented faces
2927 # @ingroup l2_modif_changori
2928 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2929 unRegister = genObjUnRegister()
2931 if isinstance( the2DObject, Mesh ):
2932 the2DObject = the2DObject.GetMesh()
2933 if isinstance( the2DObject, list ):
2934 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2935 unRegister.set( the2DObject )
2936 # check theDirection
2937 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
2938 theDirection = self.smeshpyD.GetDirStruct( theDirection )
2939 if isinstance( theDirection, list ):
2940 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
2941 # prepare theFace and thePoint
2942 theFace = theFaceOrPoint
2943 thePoint = PointStruct(0,0,0)
2944 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
2945 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
2947 if isinstance( theFaceOrPoint, list ):
2948 thePoint = PointStruct( *theFaceOrPoint )
2950 if isinstance( theFaceOrPoint, PointStruct ):
2951 thePoint = theFaceOrPoint
2953 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
2955 ## Fuses the neighbouring triangles into quadrangles.
2956 # @param IDsOfElements The triangles to be fused,
2957 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2958 # choose a neighbour to fuse with.
2959 # @param MaxAngle is the maximum angle between element normals at which the fusion
2960 # is still performed; theMaxAngle is mesured in radians.
2961 # Also it could be a name of variable which defines angle in degrees.
2962 # @return TRUE in case of success, FALSE otherwise.
2963 # @ingroup l2_modif_unitetri
2964 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
2965 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2966 self.mesh.SetParameters(Parameters)
2967 if not IDsOfElements:
2968 IDsOfElements = self.GetElementsId()
2969 Functor = self.smeshpyD.GetFunctor(theCriterion)
2970 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
2972 ## Fuses the neighbouring triangles of the object into quadrangles
2973 # @param theObject is mesh, submesh or group
2974 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2975 # choose a neighbour to fuse with.
2976 # @param MaxAngle a max angle between element normals at which the fusion
2977 # is still performed; theMaxAngle is mesured in radians.
2978 # @return TRUE in case of success, FALSE otherwise.
2979 # @ingroup l2_modif_unitetri
2980 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
2981 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2982 self.mesh.SetParameters(Parameters)
2983 if isinstance( theObject, Mesh ):
2984 theObject = theObject.GetMesh()
2985 Functor = self.smeshpyD.GetFunctor(theCriterion)
2986 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
2988 ## Splits quadrangles into triangles.
2989 # @param IDsOfElements the faces to be splitted.
2990 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2991 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
2992 # value, then quadrangles will be split by the smallest diagonal.
2993 # @return TRUE in case of success, FALSE otherwise.
2994 # @ingroup l2_modif_cutquadr
2995 def QuadToTri (self, IDsOfElements, theCriterion = None):
2996 if IDsOfElements == []:
2997 IDsOfElements = self.GetElementsId()
2998 if theCriterion is None:
2999 theCriterion = FT_MaxElementLength2D
3000 Functor = self.smeshpyD.GetFunctor(theCriterion)
3001 return self.editor.QuadToTri(IDsOfElements, Functor)
3003 ## Splits quadrangles into triangles.
3004 # @param theObject the object from which the list of elements is taken,
3005 # this is mesh, submesh or group
3006 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3007 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3008 # value, then quadrangles will be split by the smallest diagonal.
3009 # @return TRUE in case of success, FALSE otherwise.
3010 # @ingroup l2_modif_cutquadr
3011 def QuadToTriObject (self, theObject, theCriterion = None):
3012 if ( isinstance( theObject, Mesh )):
3013 theObject = theObject.GetMesh()
3014 if theCriterion is None:
3015 theCriterion = FT_MaxElementLength2D
3016 Functor = self.smeshpyD.GetFunctor(theCriterion)
3017 return self.editor.QuadToTriObject(theObject, Functor)
3019 ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3021 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3022 # group or a list of face IDs. By default all quadrangles are split
3023 # @ingroup l2_modif_cutquadr
3024 def QuadTo4Tri (self, theElements=[]):
3025 unRegister = genObjUnRegister()
3026 if isinstance( theElements, Mesh ):
3027 theElements = theElements.mesh
3028 elif not theElements:
3029 theElements = self.mesh
3030 elif isinstance( theElements, list ):
3031 theElements = self.GetIDSource( theElements, SMESH.FACE )
3032 unRegister.set( theElements )
3033 return self.editor.QuadTo4Tri( theElements )
3035 ## Splits quadrangles into triangles.
3036 # @param IDsOfElements the faces to be splitted
3037 # @param Diag13 is used to choose a diagonal for splitting.
3038 # @return TRUE in case of success, FALSE otherwise.
3039 # @ingroup l2_modif_cutquadr
3040 def SplitQuad (self, IDsOfElements, Diag13):
3041 if IDsOfElements == []:
3042 IDsOfElements = self.GetElementsId()
3043 return self.editor.SplitQuad(IDsOfElements, Diag13)
3045 ## Splits quadrangles into triangles.
3046 # @param theObject the object from which the list of elements is taken,
3047 # this is mesh, submesh or group
3048 # @param Diag13 is used to choose a diagonal for splitting.
3049 # @return TRUE in case of success, FALSE otherwise.
3050 # @ingroup l2_modif_cutquadr
3051 def SplitQuadObject (self, theObject, Diag13):
3052 if ( isinstance( theObject, Mesh )):
3053 theObject = theObject.GetMesh()
3054 return self.editor.SplitQuadObject(theObject, Diag13)
3056 ## Finds a better splitting of the given quadrangle.
3057 # @param IDOfQuad the ID of the quadrangle to be splitted.
3058 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3059 # choose a diagonal for splitting.
3060 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3061 # diagonal is better, 0 if error occurs.
3062 # @ingroup l2_modif_cutquadr
3063 def BestSplit (self, IDOfQuad, theCriterion):
3064 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3066 ## Splits volumic elements into tetrahedrons
3067 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3068 # @param method flags passing splitting method:
3069 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3070 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3071 # @ingroup l2_modif_cutquadr
3072 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3073 unRegister = genObjUnRegister()
3074 if isinstance( elems, Mesh ):
3075 elems = elems.GetMesh()
3076 if ( isinstance( elems, list )):
3077 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3078 unRegister.set( elems )
3079 self.editor.SplitVolumesIntoTetra(elems, method)
3081 ## Splits hexahedra into prisms
3082 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3083 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3084 # gives a normal vector defining facets to split into triangles.
3085 # @a startHexPoint can be either a triple of coordinates or a vertex.
3086 # @param facetNormal a normal to a facet to split into triangles of a
3087 # hexahedron found by @a startHexPoint.
3088 # @a facetNormal can be either a triple of coordinates or an edge.
3089 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3090 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3091 # @param allDomains if @c False, only hexahedra adjacent to one closest
3092 # to @a startHexPoint are split, else @a startHexPoint
3093 # is used to find the facet to split in all domains present in @a elems.
3094 # @ingroup l2_modif_cutquadr
3095 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3096 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3098 unRegister = genObjUnRegister()
3099 if isinstance( elems, Mesh ):
3100 elems = elems.GetMesh()
3101 if ( isinstance( elems, list )):
3102 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3103 unRegister.set( elems )
3106 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3107 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3108 elif isinstance( startHexPoint, list ):
3109 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3112 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3113 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3114 elif isinstance( facetNormal, list ):
3115 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3118 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3120 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3122 ## Splits quadrangle faces near triangular facets of volumes
3124 # @ingroup l1_auxiliary
3125 def SplitQuadsNearTriangularFacets(self):
3126 faces_array = self.GetElementsByType(SMESH.FACE)
3127 for face_id in faces_array:
3128 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3129 quad_nodes = self.mesh.GetElemNodes(face_id)
3130 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3131 isVolumeFound = False
3132 for node1_elem in node1_elems:
3133 if not isVolumeFound:
3134 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3135 nb_nodes = self.GetElemNbNodes(node1_elem)
3136 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3137 volume_elem = node1_elem
3138 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3139 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3140 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3141 isVolumeFound = True
3142 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3143 self.SplitQuad([face_id], False) # diagonal 2-4
3144 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3145 isVolumeFound = True
3146 self.SplitQuad([face_id], True) # diagonal 1-3
3147 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3148 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3149 isVolumeFound = True
3150 self.SplitQuad([face_id], True) # diagonal 1-3
3152 ## @brief Splits hexahedrons into tetrahedrons.
3154 # This operation uses pattern mapping functionality for splitting.
3155 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3156 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3157 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3158 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3159 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3160 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3161 # @return TRUE in case of success, FALSE otherwise.
3162 # @ingroup l1_auxiliary
3163 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3164 # Pattern: 5.---------.6
3169 # (0,0,1) 4.---------.7 * |
3176 # (0,0,0) 0.---------.3
3177 pattern_tetra = "!!! Nb of points: \n 8 \n\
3187 !!! Indices of points of 6 tetras: \n\
3195 pattern = self.smeshpyD.GetPattern()
3196 isDone = pattern.LoadFromFile(pattern_tetra)
3198 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3201 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3202 isDone = pattern.MakeMesh(self.mesh, False, False)
3203 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3205 # split quafrangle faces near triangular facets of volumes
3206 self.SplitQuadsNearTriangularFacets()
3210 ## @brief Split hexahedrons into prisms.
3212 # Uses the pattern mapping functionality for splitting.
3213 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3214 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3215 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3216 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3217 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3218 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3219 # @return TRUE in case of success, FALSE otherwise.
3220 # @ingroup l1_auxiliary
3221 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3222 # Pattern: 5.---------.6
3227 # (0,0,1) 4.---------.7 |
3234 # (0,0,0) 0.---------.3
3235 pattern_prism = "!!! Nb of points: \n 8 \n\
3245 !!! Indices of points of 2 prisms: \n\
3249 pattern = self.smeshpyD.GetPattern()
3250 isDone = pattern.LoadFromFile(pattern_prism)
3252 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3255 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3256 isDone = pattern.MakeMesh(self.mesh, False, False)
3257 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3259 # Splits quafrangle faces near triangular facets of volumes
3260 self.SplitQuadsNearTriangularFacets()
3264 ## Smoothes elements
3265 # @param IDsOfElements the list if ids of elements to smooth
3266 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3267 # Note that nodes built on edges and boundary nodes are always fixed.
3268 # @param MaxNbOfIterations the maximum number of iterations
3269 # @param MaxAspectRatio varies in range [1.0, inf]
3270 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3271 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3272 # @return TRUE in case of success, FALSE otherwise.
3273 # @ingroup l2_modif_smooth
3274 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3275 MaxNbOfIterations, MaxAspectRatio, Method):
3276 if IDsOfElements == []:
3277 IDsOfElements = self.GetElementsId()
3278 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3279 self.mesh.SetParameters(Parameters)
3280 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3281 MaxNbOfIterations, MaxAspectRatio, Method)
3283 ## Smoothes elements which belong to the given object
3284 # @param theObject the object to smooth
3285 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3286 # Note that nodes built on edges and boundary nodes are always fixed.
3287 # @param MaxNbOfIterations the maximum number of iterations
3288 # @param MaxAspectRatio varies in range [1.0, inf]
3289 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3290 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3291 # @return TRUE in case of success, FALSE otherwise.
3292 # @ingroup l2_modif_smooth
3293 def SmoothObject(self, theObject, IDsOfFixedNodes,
3294 MaxNbOfIterations, MaxAspectRatio, Method):
3295 if ( isinstance( theObject, Mesh )):
3296 theObject = theObject.GetMesh()
3297 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3298 MaxNbOfIterations, MaxAspectRatio, Method)
3300 ## Parametrically smoothes the given elements
3301 # @param IDsOfElements the list if ids of elements to smooth
3302 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3303 # Note that nodes built on edges and boundary nodes are always fixed.
3304 # @param MaxNbOfIterations the maximum number of iterations
3305 # @param MaxAspectRatio varies in range [1.0, inf]
3306 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3307 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3308 # @return TRUE in case of success, FALSE otherwise.
3309 # @ingroup l2_modif_smooth
3310 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3311 MaxNbOfIterations, MaxAspectRatio, Method):
3312 if IDsOfElements == []:
3313 IDsOfElements = self.GetElementsId()
3314 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3315 self.mesh.SetParameters(Parameters)
3316 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3317 MaxNbOfIterations, MaxAspectRatio, Method)
3319 ## Parametrically smoothes the elements which belong to the given object
3320 # @param theObject the object to smooth
3321 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3322 # Note that nodes built on edges and boundary nodes are always fixed.
3323 # @param MaxNbOfIterations the maximum number of iterations
3324 # @param MaxAspectRatio varies in range [1.0, inf]
3325 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3326 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3327 # @return TRUE in case of success, FALSE otherwise.
3328 # @ingroup l2_modif_smooth
3329 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3330 MaxNbOfIterations, MaxAspectRatio, Method):
3331 if ( isinstance( theObject, Mesh )):
3332 theObject = theObject.GetMesh()
3333 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3334 MaxNbOfIterations, MaxAspectRatio, Method)
3336 ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3337 # them with quadratic with the same id.
3338 # @param theForce3d new node creation method:
3339 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3340 # 1 - the medium node lies at the middle of the line segments connecting start and end node of a mesh element
3341 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3342 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3343 # @ingroup l2_modif_tofromqu
3344 def ConvertToQuadratic(self, theForce3d, theSubMesh=None, theToBiQuad=False):
3345 if isinstance( theSubMesh, Mesh ):
3346 theSubMesh = theSubMesh.mesh
3348 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3351 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3353 self.editor.ConvertToQuadratic(theForce3d)
3354 error = self.editor.GetLastError()
3355 if error and error.comment:
3358 ## Converts the mesh from quadratic to ordinary,
3359 # deletes old quadratic elements, \n replacing
3360 # them with ordinary mesh elements with the same id.
3361 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3362 # @ingroup l2_modif_tofromqu
3363 def ConvertFromQuadratic(self, theSubMesh=None):
3365 self.editor.ConvertFromQuadraticObject(theSubMesh)
3367 return self.editor.ConvertFromQuadratic()
3369 ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3370 # @return TRUE if operation has been completed successfully, FALSE otherwise
3371 # @ingroup l2_modif_edit
3372 def Make2DMeshFrom3D(self):
3373 return self.editor. Make2DMeshFrom3D()
3375 ## Creates missing boundary elements
3376 # @param elements - elements whose boundary is to be checked:
3377 # mesh, group, sub-mesh or list of elements
3378 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3379 # @param dimension - defines type of boundary elements to create:
3380 # SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D
3381 # SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3382 # @param groupName - a name of group to store created boundary elements in,
3383 # "" means not to create the group
3384 # @param meshName - a name of new mesh to store created boundary elements in,
3385 # "" means not to create the new mesh
3386 # @param toCopyElements - if true, the checked elements will be copied into
3387 # the new mesh else only boundary elements will be copied into the new mesh
3388 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3389 # boundary elements will be copied into the new mesh
3390 # @return tuple (mesh, group) where boundary elements were added to
3391 # @ingroup l2_modif_edit
3392 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3393 toCopyElements=False, toCopyExistingBondary=False):
3394 unRegister = genObjUnRegister()
3395 if isinstance( elements, Mesh ):
3396 elements = elements.GetMesh()
3397 if ( isinstance( elements, list )):
3398 elemType = SMESH.ALL
3399 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3400 elements = self.editor.MakeIDSource(elements, elemType)
3401 unRegister.set( elements )
3402 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3403 toCopyElements,toCopyExistingBondary)
3404 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3408 # @brief Creates missing boundary elements around either the whole mesh or
3409 # groups of 2D elements
3410 # @param dimension - defines type of boundary elements to create
3411 # @param groupName - a name of group to store all boundary elements in,
3412 # "" means not to create the group
3413 # @param meshName - a name of a new mesh, which is a copy of the initial
3414 # mesh + created boundary elements; "" means not to create the new mesh
3415 # @param toCopyAll - if true, the whole initial mesh will be copied into
3416 # the new mesh else only boundary elements will be copied into the new mesh
3417 # @param groups - groups of 2D elements to make boundary around
3418 # @retval tuple( long, mesh, groups )
3419 # long - number of added boundary elements
3420 # mesh - the mesh where elements were added to
3421 # group - the group of boundary elements or None
3423 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3424 toCopyAll=False, groups=[]):
3425 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3427 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3428 return nb, mesh, group
3430 ## Renumber mesh nodes
3431 # @ingroup l2_modif_renumber
3432 def RenumberNodes(self):
3433 self.editor.RenumberNodes()
3435 ## Renumber mesh elements
3436 # @ingroup l2_modif_renumber
3437 def RenumberElements(self):
3438 self.editor.RenumberElements()
3440 ## Generates new elements by rotation of the elements around the axis
3441 # @param IDsOfElements the list of ids of elements to sweep
3442 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3443 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3444 # @param NbOfSteps the number of steps
3445 # @param Tolerance tolerance
3446 # @param MakeGroups forces the generation of new groups from existing ones
3447 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3448 # of all steps, else - size of each step
3449 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3450 # @ingroup l2_modif_extrurev
3451 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3452 MakeGroups=False, TotalAngle=False):
3453 if IDsOfElements == []:
3454 IDsOfElements = self.GetElementsId()
3455 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3456 Axis = self.smeshpyD.GetAxisStruct(Axis)
3457 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3458 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3459 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3460 self.mesh.SetParameters(Parameters)
3461 if TotalAngle and NbOfSteps:
3462 AngleInRadians /= NbOfSteps
3464 return self.editor.RotationSweepMakeGroups(IDsOfElements, Axis,
3465 AngleInRadians, NbOfSteps, Tolerance)
3466 self.editor.RotationSweep(IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance)
3469 ## Generates new elements by rotation of the elements of object around the axis
3470 # @param theObject object which elements should be sweeped.
3471 # It can be a mesh, a sub mesh or a group.
3472 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3473 # @param AngleInRadians the angle of Rotation
3474 # @param NbOfSteps number of steps
3475 # @param Tolerance tolerance
3476 # @param MakeGroups forces the generation of new groups from existing ones
3477 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3478 # of all steps, else - size of each step
3479 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3480 # @ingroup l2_modif_extrurev
3481 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3482 MakeGroups=False, TotalAngle=False):
3483 if ( isinstance( theObject, Mesh )):
3484 theObject = theObject.GetMesh()
3485 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3486 Axis = self.smeshpyD.GetAxisStruct(Axis)
3487 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3488 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3489 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3490 self.mesh.SetParameters(Parameters)
3491 if TotalAngle and NbOfSteps:
3492 AngleInRadians /= NbOfSteps
3494 return self.editor.RotationSweepObjectMakeGroups(theObject, Axis, AngleInRadians,
3495 NbOfSteps, Tolerance)
3496 self.editor.RotationSweepObject(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3499 ## Generates new elements by rotation of the elements of object around the axis
3500 # @param theObject object which elements should be sweeped.
3501 # It can be a mesh, a sub mesh or a group.
3502 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3503 # @param AngleInRadians the angle of Rotation
3504 # @param NbOfSteps number of steps
3505 # @param Tolerance tolerance
3506 # @param MakeGroups forces the generation of new groups from existing ones
3507 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3508 # of all steps, else - size of each step
3509 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3510 # @ingroup l2_modif_extrurev
3511 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3512 MakeGroups=False, TotalAngle=False):
3513 if ( isinstance( theObject, Mesh )):
3514 theObject = theObject.GetMesh()
3515 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3516 Axis = self.smeshpyD.GetAxisStruct(Axis)
3517 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3518 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3519 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3520 self.mesh.SetParameters(Parameters)
3521 if TotalAngle and NbOfSteps:
3522 AngleInRadians /= NbOfSteps
3524 return self.editor.RotationSweepObject1DMakeGroups(theObject, Axis, AngleInRadians,
3525 NbOfSteps, Tolerance)
3526 self.editor.RotationSweepObject1D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3529 ## Generates new elements by rotation of the elements of object around the axis
3530 # @param theObject object which elements should be sweeped.
3531 # It can be a mesh, a sub mesh or a group.
3532 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3533 # @param AngleInRadians the angle of Rotation
3534 # @param NbOfSteps number of steps
3535 # @param Tolerance tolerance
3536 # @param MakeGroups forces the generation of new groups from existing ones
3537 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3538 # of all steps, else - size of each step
3539 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3540 # @ingroup l2_modif_extrurev
3541 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3542 MakeGroups=False, TotalAngle=False):
3543 if ( isinstance( theObject, Mesh )):
3544 theObject = theObject.GetMesh()
3545 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3546 Axis = self.smeshpyD.GetAxisStruct(Axis)
3547 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3548 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3549 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3550 self.mesh.SetParameters(Parameters)
3551 if TotalAngle and NbOfSteps:
3552 AngleInRadians /= NbOfSteps
3554 return self.editor.RotationSweepObject2DMakeGroups(theObject, Axis, AngleInRadians,
3555 NbOfSteps, Tolerance)
3556 self.editor.RotationSweepObject2D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3559 ## Generates new elements by extrusion of the elements with given ids
3560 # @param IDsOfElements the list of elements ids for extrusion
3561 # @param StepVector vector or DirStruct or 3 vector components, defining
3562 # the direction and value of extrusion for one step (the total extrusion
3563 # length will be NbOfSteps * ||StepVector||)
3564 # @param NbOfSteps the number of steps
3565 # @param MakeGroups forces the generation of new groups from existing ones
3566 # @param IsNodes is True if elements with given ids are nodes
3567 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3568 # @ingroup l2_modif_extrurev
3569 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3570 if IDsOfElements == []:
3571 IDsOfElements = self.GetElementsId()
3572 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3573 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3574 if isinstance( StepVector, list ):
3575 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3576 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3577 Parameters = StepVector.PS.parameters + var_separator + Parameters
3578 self.mesh.SetParameters(Parameters)
3581 return self.editor.ExtrusionSweepMakeGroups0D(IDsOfElements, StepVector, NbOfSteps)
3583 return self.editor.ExtrusionSweepMakeGroups(IDsOfElements, StepVector, NbOfSteps)
3585 self.editor.ExtrusionSweep0D(IDsOfElements, StepVector, NbOfSteps)
3587 self.editor.ExtrusionSweep(IDsOfElements, StepVector, NbOfSteps)
3590 ## Generates new elements by extrusion of the elements with given ids
3591 # @param IDsOfElements is ids of elements
3592 # @param StepVector vector or DirStruct or 3 vector components, defining
3593 # the direction and value of extrusion for one step (the total extrusion
3594 # length will be NbOfSteps * ||StepVector||)
3595 # @param NbOfSteps the number of steps
3596 # @param ExtrFlags sets flags for extrusion
3597 # @param SewTolerance uses for comparing locations of nodes if flag
3598 # EXTRUSION_FLAG_SEW is set
3599 # @param MakeGroups forces the generation of new groups from existing ones
3600 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3601 # @ingroup l2_modif_extrurev
3602 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3603 ExtrFlags, SewTolerance, MakeGroups=False):
3604 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3605 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3606 if isinstance( StepVector, list ):
3607 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3609 return self.editor.AdvancedExtrusionMakeGroups(IDsOfElements, StepVector, NbOfSteps,
3610 ExtrFlags, SewTolerance)
3611 self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3612 ExtrFlags, SewTolerance)
3615 ## Generates new elements by extrusion of the elements which belong to the object
3616 # @param theObject the object which elements should be processed.
3617 # It can be a mesh, a sub mesh or a group.
3618 # @param StepVector vector or DirStruct or 3 vector components, defining
3619 # the direction and value of extrusion for one step (the total extrusion
3620 # length will be NbOfSteps * ||StepVector||)
3621 # @param NbOfSteps the number of steps
3622 # @param MakeGroups forces the generation of new groups from existing ones
3623 # @param IsNodes is True if elements which belong to the object are nodes
3624 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3625 # @ingroup l2_modif_extrurev
3626 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3627 if ( isinstance( theObject, Mesh )):
3628 theObject = theObject.GetMesh()
3629 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3630 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3631 if isinstance( StepVector, list ):
3632 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3633 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3634 Parameters = StepVector.PS.parameters + var_separator + Parameters
3635 self.mesh.SetParameters(Parameters)
3638 return self.editor.ExtrusionSweepObject0DMakeGroups(theObject, StepVector, NbOfSteps)
3640 return self.editor.ExtrusionSweepObjectMakeGroups(theObject, StepVector, NbOfSteps)
3642 self.editor.ExtrusionSweepObject0D(theObject, StepVector, NbOfSteps)
3644 self.editor.ExtrusionSweepObject(theObject, StepVector, NbOfSteps)
3647 ## Generates new elements by extrusion of the elements which belong to the object
3648 # @param theObject object which elements should be processed.
3649 # It can be a mesh, a sub mesh or a group.
3650 # @param StepVector vector or DirStruct or 3 vector components, defining
3651 # the direction and value of extrusion for one step (the total extrusion
3652 # length will be NbOfSteps * ||StepVector||)
3653 # @param NbOfSteps the number of steps
3654 # @param MakeGroups to generate new groups from existing ones
3655 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3656 # @ingroup l2_modif_extrurev
3657 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3658 if ( isinstance( theObject, Mesh )):
3659 theObject = theObject.GetMesh()
3660 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3661 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3662 if isinstance( StepVector, list ):
3663 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3664 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3665 Parameters = StepVector.PS.parameters + var_separator + Parameters
3666 self.mesh.SetParameters(Parameters)
3668 return self.editor.ExtrusionSweepObject1DMakeGroups(theObject, StepVector, NbOfSteps)
3669 self.editor.ExtrusionSweepObject1D(theObject, StepVector, NbOfSteps)
3672 ## Generates new elements by extrusion of the elements which belong to the object
3673 # @param theObject object which elements should be processed.
3674 # It can be a mesh, a sub mesh or a group.
3675 # @param StepVector vector or DirStruct or 3 vector components, defining
3676 # the direction and value of extrusion for one step (the total extrusion
3677 # length will be NbOfSteps * ||StepVector||)
3678 # @param NbOfSteps the number of steps
3679 # @param MakeGroups forces the generation of new groups from existing ones
3680 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3681 # @ingroup l2_modif_extrurev
3682 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3683 if ( isinstance( theObject, Mesh )):
3684 theObject = theObject.GetMesh()
3685 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3686 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3687 if isinstance( StepVector, list ):
3688 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3689 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3690 Parameters = StepVector.PS.parameters + var_separator + Parameters
3691 self.mesh.SetParameters(Parameters)
3693 return self.editor.ExtrusionSweepObject2DMakeGroups(theObject, StepVector, NbOfSteps)
3694 self.editor.ExtrusionSweepObject2D(theObject, StepVector, NbOfSteps)
3699 ## Generates new elements by extrusion of the given elements
3700 # The path of extrusion must be a meshed edge.
3701 # @param Base mesh or group, or submesh, or list of ids of elements for extrusion
3702 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3703 # @param NodeStart the start node from Path. Defines the direction of extrusion
3704 # @param HasAngles allows the shape to be rotated around the path
3705 # to get the resulting mesh in a helical fashion
3706 # @param Angles list of angles in radians
3707 # @param LinearVariation forces the computation of rotation angles as linear
3708 # variation of the given Angles along path steps
3709 # @param HasRefPoint allows using the reference point
3710 # @param RefPoint the point around which the elements are rotated (the mass
3711 # center of the elements by default).
3712 # The User can specify any point as the Reference Point.
3713 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
3714 # @param MakeGroups forces the generation of new groups from existing ones
3715 # @param ElemType type of elements for extrusion (if param Base is a mesh)
3716 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3717 # only SMESH::Extrusion_Error otherwise
3718 # @ingroup l2_modif_extrurev
3719 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
3720 HasAngles, Angles, LinearVariation,
3721 HasRefPoint, RefPoint, MakeGroups, ElemType):
3722 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3723 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3725 elif isinstance( RefPoint, list ):
3726 RefPoint = PointStruct(*RefPoint)
3728 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3729 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3730 self.mesh.SetParameters(Parameters)
3732 if (isinstance(Path, Mesh)): Path = Path.GetMesh()
3734 if isinstance(Base, list):
3736 if Base == []: IDsOfElements = self.GetElementsId()
3737 else: IDsOfElements = Base
3738 return self.editor.ExtrusionAlongPathX(IDsOfElements, Path, NodeStart,
3739 HasAngles, Angles, LinearVariation,
3740 HasRefPoint, RefPoint, MakeGroups, ElemType)
3742 if isinstance(Base, Mesh): Base = Base.GetMesh()
3743 if isinstance(Base, SMESH._objref_SMESH_Mesh) or isinstance(Base, SMESH._objref_SMESH_Group) or isinstance(Base, SMESH._objref_SMESH_subMesh):
3744 return self.editor.ExtrusionAlongPathObjX(Base, Path, NodeStart,
3745 HasAngles, Angles, LinearVariation,
3746 HasRefPoint, RefPoint, MakeGroups, ElemType)
3748 raise RuntimeError, "Invalid Base for ExtrusionAlongPathX"
3751 ## Generates new elements by extrusion of the given elements
3752 # The path of extrusion must be a meshed edge.
3753 # @param IDsOfElements ids of elements
3754 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
3755 # @param PathShape shape(edge) defines the sub-mesh for the path
3756 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3757 # @param HasAngles allows the shape to be rotated around the path
3758 # to get the resulting mesh in a helical fashion
3759 # @param Angles list of angles in radians
3760 # @param HasRefPoint allows using the reference point
3761 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3762 # The User can specify any point as the Reference Point.
3763 # @param MakeGroups forces the generation of new groups from existing ones
3764 # @param LinearVariation forces the computation of rotation angles as linear
3765 # variation of the given Angles along path steps
3766 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3767 # only SMESH::Extrusion_Error otherwise
3768 # @ingroup l2_modif_extrurev
3769 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
3770 HasAngles, Angles, HasRefPoint, RefPoint,
3771 MakeGroups=False, LinearVariation=False):
3772 if IDsOfElements == []:
3773 IDsOfElements = self.GetElementsId()
3774 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3775 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3777 if ( isinstance( PathMesh, Mesh )):
3778 PathMesh = PathMesh.GetMesh()
3779 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3780 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3781 self.mesh.SetParameters(Parameters)
3782 if HasAngles and Angles and LinearVariation:
3783 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3786 return self.editor.ExtrusionAlongPathMakeGroups(IDsOfElements, PathMesh,
3787 PathShape, NodeStart, HasAngles,
3788 Angles, HasRefPoint, RefPoint)
3789 return self.editor.ExtrusionAlongPath(IDsOfElements, PathMesh, PathShape,
3790 NodeStart, HasAngles, Angles, HasRefPoint, RefPoint)
3792 ## Generates new elements by extrusion of the elements which belong to the object
3793 # The path of extrusion must be a meshed edge.
3794 # @param theObject the object which elements should be processed.
3795 # It can be a mesh, a sub mesh or a group.
3796 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3797 # @param PathShape shape(edge) defines the sub-mesh for the path
3798 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3799 # @param HasAngles allows the shape to be rotated around the path
3800 # to get the resulting mesh in a helical fashion
3801 # @param Angles list of angles
3802 # @param HasRefPoint allows using the reference point
3803 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3804 # The User can specify any point as the Reference Point.
3805 # @param MakeGroups forces the generation of new groups from existing ones
3806 # @param LinearVariation forces the computation of rotation angles as linear
3807 # variation of the given Angles along path steps
3808 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3809 # only SMESH::Extrusion_Error otherwise
3810 # @ingroup l2_modif_extrurev
3811 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
3812 HasAngles, Angles, HasRefPoint, RefPoint,
3813 MakeGroups=False, LinearVariation=False):
3814 if ( isinstance( theObject, Mesh )):
3815 theObject = theObject.GetMesh()
3816 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3817 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3818 if ( isinstance( PathMesh, Mesh )):
3819 PathMesh = PathMesh.GetMesh()
3820 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3821 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3822 self.mesh.SetParameters(Parameters)
3823 if HasAngles and Angles and LinearVariation:
3824 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3827 return self.editor.ExtrusionAlongPathObjectMakeGroups(theObject, PathMesh,
3828 PathShape, NodeStart, HasAngles,
3829 Angles, HasRefPoint, RefPoint)
3830 return self.editor.ExtrusionAlongPathObject(theObject, PathMesh, PathShape,
3831 NodeStart, HasAngles, Angles, HasRefPoint,
3834 ## Generates new elements by extrusion of the elements which belong to the object
3835 # The path of extrusion must be a meshed edge.
3836 # @param theObject the object which elements should be processed.
3837 # It can be a mesh, a sub mesh or a group.
3838 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3839 # @param PathShape shape(edge) defines the sub-mesh for the path
3840 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3841 # @param HasAngles allows the shape to be rotated around the path
3842 # to get the resulting mesh in a helical fashion
3843 # @param Angles list of angles
3844 # @param HasRefPoint allows using the reference point
3845 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3846 # The User can specify any point as the Reference Point.
3847 # @param MakeGroups forces the generation of new groups from existing ones
3848 # @param LinearVariation forces the computation of rotation angles as linear
3849 # variation of the given Angles along path steps
3850 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3851 # only SMESH::Extrusion_Error otherwise
3852 # @ingroup l2_modif_extrurev
3853 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
3854 HasAngles, Angles, HasRefPoint, RefPoint,
3855 MakeGroups=False, LinearVariation=False):
3856 if ( isinstance( theObject, Mesh )):
3857 theObject = theObject.GetMesh()
3858 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3859 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3860 if ( isinstance( PathMesh, Mesh )):
3861 PathMesh = PathMesh.GetMesh()
3862 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3863 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3864 self.mesh.SetParameters(Parameters)
3865 if HasAngles and Angles and LinearVariation:
3866 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3869 return self.editor.ExtrusionAlongPathObject1DMakeGroups(theObject, PathMesh,
3870 PathShape, NodeStart, HasAngles,
3871 Angles, HasRefPoint, RefPoint)
3872 return self.editor.ExtrusionAlongPathObject1D(theObject, PathMesh, PathShape,
3873 NodeStart, HasAngles, Angles, HasRefPoint,
3876 ## Generates new elements by extrusion of the elements which belong to the object
3877 # The path of extrusion must be a meshed edge.
3878 # @param theObject the object which elements should be processed.
3879 # It can be a mesh, a sub mesh or a group.
3880 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3881 # @param PathShape shape(edge) defines the sub-mesh for the path
3882 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3883 # @param HasAngles allows the shape to be rotated around the path
3884 # to get the resulting mesh in a helical fashion
3885 # @param Angles list of angles
3886 # @param HasRefPoint allows using the reference point
3887 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3888 # The User can specify any point as the Reference Point.
3889 # @param MakeGroups forces the generation of new groups from existing ones
3890 # @param LinearVariation forces the computation of rotation angles as linear
3891 # variation of the given Angles along path steps
3892 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3893 # only SMESH::Extrusion_Error otherwise
3894 # @ingroup l2_modif_extrurev
3895 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
3896 HasAngles, Angles, HasRefPoint, RefPoint,
3897 MakeGroups=False, LinearVariation=False):
3898 if ( isinstance( theObject, Mesh )):
3899 theObject = theObject.GetMesh()
3900 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3901 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3902 if ( isinstance( PathMesh, Mesh )):
3903 PathMesh = PathMesh.GetMesh()
3904 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3905 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3906 self.mesh.SetParameters(Parameters)
3907 if HasAngles and Angles and LinearVariation:
3908 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3911 return self.editor.ExtrusionAlongPathObject2DMakeGroups(theObject, PathMesh,
3912 PathShape, NodeStart, HasAngles,
3913 Angles, HasRefPoint, RefPoint)
3914 return self.editor.ExtrusionAlongPathObject2D(theObject, PathMesh, PathShape,
3915 NodeStart, HasAngles, Angles, HasRefPoint,
3918 ## Creates a symmetrical copy of mesh elements
3919 # @param IDsOfElements list of elements ids
3920 # @param Mirror is AxisStruct or geom object(point, line, plane)
3921 # @param theMirrorType is POINT, AXIS or PLANE
3922 # If the Mirror is a geom object this parameter is unnecessary
3923 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
3924 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3925 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3926 # @ingroup l2_modif_trsf
3927 def Mirror(self, IDsOfElements, Mirror, theMirrorType, Copy=0, MakeGroups=False):
3928 if IDsOfElements == []:
3929 IDsOfElements = self.GetElementsId()
3930 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3931 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3932 self.mesh.SetParameters(Mirror.parameters)
3933 if Copy and MakeGroups:
3934 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
3935 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
3938 ## Creates a new mesh by a symmetrical copy of mesh elements
3939 # @param IDsOfElements the list of elements ids
3940 # @param Mirror is AxisStruct or geom object (point, line, plane)
3941 # @param theMirrorType is POINT, AXIS or PLANE
3942 # If the Mirror is a geom object this parameter is unnecessary
3943 # @param MakeGroups to generate new groups from existing ones
3944 # @param NewMeshName a name of the new mesh to create
3945 # @return instance of Mesh class
3946 # @ingroup l2_modif_trsf
3947 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType, MakeGroups=0, NewMeshName=""):
3948 if IDsOfElements == []:
3949 IDsOfElements = self.GetElementsId()
3950 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3951 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3952 self.mesh.SetParameters(Mirror.parameters)
3953 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
3954 MakeGroups, NewMeshName)
3955 return Mesh(self.smeshpyD,self.geompyD,mesh)
3957 ## Creates a symmetrical copy of the object
3958 # @param theObject mesh, submesh or group
3959 # @param Mirror AxisStruct or geom object (point, line, plane)
3960 # @param theMirrorType is POINT, AXIS or PLANE
3961 # If the Mirror is a geom object this parameter is unnecessary
3962 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
3963 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3964 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3965 # @ingroup l2_modif_trsf
3966 def MirrorObject (self, theObject, Mirror, theMirrorType, Copy=0, MakeGroups=False):
3967 if ( isinstance( theObject, Mesh )):
3968 theObject = theObject.GetMesh()
3969 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3970 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3971 self.mesh.SetParameters(Mirror.parameters)
3972 if Copy and MakeGroups:
3973 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
3974 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
3977 ## Creates a new mesh by a symmetrical copy of the object
3978 # @param theObject mesh, submesh or group
3979 # @param Mirror AxisStruct or geom object (point, line, plane)
3980 # @param theMirrorType POINT, AXIS or PLANE
3981 # If the Mirror is a geom object this parameter is unnecessary
3982 # @param MakeGroups forces the generation of new groups from existing ones
3983 # @param NewMeshName the name of the new mesh to create
3984 # @return instance of Mesh class
3985 # @ingroup l2_modif_trsf
3986 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType,MakeGroups=0, NewMeshName=""):
3987 if ( isinstance( theObject, Mesh )):
3988 theObject = theObject.GetMesh()
3989 if (isinstance(Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3990 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3991 self.mesh.SetParameters(Mirror.parameters)
3992 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
3993 MakeGroups, NewMeshName)
3994 return Mesh( self.smeshpyD,self.geompyD,mesh )
3996 ## Translates the elements
3997 # @param IDsOfElements list of elements ids
3998 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
3999 # @param Copy allows copying the translated elements
4000 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4001 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4002 # @ingroup l2_modif_trsf
4003 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4004 if IDsOfElements == []:
4005 IDsOfElements = self.GetElementsId()
4006 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4007 Vector = self.smeshpyD.GetDirStruct(Vector)
4008 if isinstance( Vector, list ):
4009 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4010 self.mesh.SetParameters(Vector.PS.parameters)
4011 if Copy and MakeGroups:
4012 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4013 self.editor.Translate(IDsOfElements, Vector, Copy)
4016 ## Creates a new mesh of translated elements
4017 # @param IDsOfElements list of elements ids
4018 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4019 # @param MakeGroups forces the generation of new groups from existing ones
4020 # @param NewMeshName the name of the newly created mesh
4021 # @return instance of Mesh class
4022 # @ingroup l2_modif_trsf
4023 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4024 if IDsOfElements == []:
4025 IDsOfElements = self.GetElementsId()
4026 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4027 Vector = self.smeshpyD.GetDirStruct(Vector)
4028 if isinstance( Vector, list ):
4029 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4030 self.mesh.SetParameters(Vector.PS.parameters)
4031 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4032 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4034 ## Translates the object
4035 # @param theObject the object to translate (mesh, submesh, or group)
4036 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4037 # @param Copy allows copying the translated elements
4038 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4039 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4040 # @ingroup l2_modif_trsf
4041 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4042 if ( isinstance( theObject, Mesh )):
4043 theObject = theObject.GetMesh()
4044 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4045 Vector = self.smeshpyD.GetDirStruct(Vector)
4046 if isinstance( Vector, list ):
4047 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4048 self.mesh.SetParameters(Vector.PS.parameters)
4049 if Copy and MakeGroups:
4050 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4051 self.editor.TranslateObject(theObject, Vector, Copy)
4054 ## Creates a new mesh from the translated object
4055 # @param theObject the object to translate (mesh, submesh, or group)
4056 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4057 # @param MakeGroups forces the generation of new groups from existing ones
4058 # @param NewMeshName the name of the newly created mesh
4059 # @return instance of Mesh class
4060 # @ingroup l2_modif_trsf
4061 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4062 if isinstance( theObject, Mesh ):
4063 theObject = theObject.GetMesh()
4064 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4065 Vector = self.smeshpyD.GetDirStruct(Vector)
4066 if isinstance( Vector, list ):
4067 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4068 self.mesh.SetParameters(Vector.PS.parameters)
4069 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4070 return Mesh( self.smeshpyD, self.geompyD, mesh )
4074 ## Scales the object
4075 # @param theObject - the object to translate (mesh, submesh, or group)
4076 # @param thePoint - base point for scale
4077 # @param theScaleFact - list of 1-3 scale factors for axises
4078 # @param Copy - allows copying the translated elements
4079 # @param MakeGroups - forces the generation of new groups from existing
4081 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4082 # empty list otherwise
4083 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4084 unRegister = genObjUnRegister()
4085 if ( isinstance( theObject, Mesh )):
4086 theObject = theObject.GetMesh()
4087 if ( isinstance( theObject, list )):
4088 theObject = self.GetIDSource(theObject, SMESH.ALL)
4089 unRegister.set( theObject )
4090 if ( isinstance( theScaleFact, float )):
4091 theScaleFact = [theScaleFact]
4092 if ( isinstance( theScaleFact, int )):
4093 theScaleFact = [ float(theScaleFact)]
4095 self.mesh.SetParameters(thePoint.parameters)
4097 if Copy and MakeGroups:
4098 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4099 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4102 ## Creates a new mesh from the translated object
4103 # @param theObject - the object to translate (mesh, submesh, or group)
4104 # @param thePoint - base point for scale
4105 # @param theScaleFact - list of 1-3 scale factors for axises
4106 # @param MakeGroups - forces the generation of new groups from existing ones
4107 # @param NewMeshName - the name of the newly created mesh
4108 # @return instance of Mesh class
4109 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4110 unRegister = genObjUnRegister()
4111 if (isinstance(theObject, Mesh)):
4112 theObject = theObject.GetMesh()
4113 if ( isinstance( theObject, list )):
4114 theObject = self.GetIDSource(theObject,SMESH.ALL)
4115 unRegister.set( theObject )
4116 if ( isinstance( theScaleFact, float )):
4117 theScaleFact = [theScaleFact]
4118 if ( isinstance( theScaleFact, int )):
4119 theScaleFact = [ float(theScaleFact)]
4121 self.mesh.SetParameters(thePoint.parameters)
4122 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4123 MakeGroups, NewMeshName)
4124 return Mesh( self.smeshpyD, self.geompyD, mesh )
4128 ## Rotates the elements
4129 # @param IDsOfElements list of elements ids
4130 # @param Axis the axis of rotation (AxisStruct or geom line)
4131 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4132 # @param Copy allows copying the rotated elements
4133 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4134 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4135 # @ingroup l2_modif_trsf
4136 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4137 if IDsOfElements == []:
4138 IDsOfElements = self.GetElementsId()
4139 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4140 Axis = self.smeshpyD.GetAxisStruct(Axis)
4141 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4142 Parameters = Axis.parameters + var_separator + Parameters
4143 self.mesh.SetParameters(Parameters)
4144 if Copy and MakeGroups:
4145 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4146 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4149 ## Creates a new mesh of rotated elements
4150 # @param IDsOfElements list of element ids
4151 # @param Axis the axis of rotation (AxisStruct or geom line)
4152 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4153 # @param MakeGroups forces the generation of new groups from existing ones
4154 # @param NewMeshName the name of the newly created mesh
4155 # @return instance of Mesh class
4156 # @ingroup l2_modif_trsf
4157 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4158 if IDsOfElements == []:
4159 IDsOfElements = self.GetElementsId()
4160 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4161 Axis = self.smeshpyD.GetAxisStruct(Axis)
4162 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4163 Parameters = Axis.parameters + var_separator + Parameters
4164 self.mesh.SetParameters(Parameters)
4165 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4166 MakeGroups, NewMeshName)
4167 return Mesh( self.smeshpyD, self.geompyD, mesh )
4169 ## Rotates the object
4170 # @param theObject the object to rotate( mesh, submesh, or group)
4171 # @param Axis the axis of rotation (AxisStruct or geom line)
4172 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4173 # @param Copy allows copying the rotated elements
4174 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4175 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4176 # @ingroup l2_modif_trsf
4177 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4178 if (isinstance(theObject, Mesh)):
4179 theObject = theObject.GetMesh()
4180 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4181 Axis = self.smeshpyD.GetAxisStruct(Axis)
4182 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4183 Parameters = Axis.parameters + ":" + Parameters
4184 self.mesh.SetParameters(Parameters)
4185 if Copy and MakeGroups:
4186 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4187 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4190 ## Creates a new mesh from the rotated object
4191 # @param theObject the object to rotate (mesh, submesh, or group)
4192 # @param Axis the axis of rotation (AxisStruct or geom line)
4193 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4194 # @param MakeGroups forces the generation of new groups from existing ones
4195 # @param NewMeshName the name of the newly created mesh
4196 # @return instance of Mesh class
4197 # @ingroup l2_modif_trsf
4198 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4199 if (isinstance( theObject, Mesh )):
4200 theObject = theObject.GetMesh()
4201 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4202 Axis = self.smeshpyD.GetAxisStruct(Axis)
4203 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4204 Parameters = Axis.parameters + ":" + Parameters
4205 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4206 MakeGroups, NewMeshName)
4207 self.mesh.SetParameters(Parameters)
4208 return Mesh( self.smeshpyD, self.geompyD, mesh )
4210 ## Finds groups of adjacent nodes within Tolerance.
4211 # @param Tolerance the value of tolerance
4212 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4213 # @ingroup l2_modif_trsf
4214 def FindCoincidentNodes (self, Tolerance):
4215 return self.editor.FindCoincidentNodes(Tolerance)
4217 ## Finds groups of ajacent nodes within Tolerance.
4218 # @param Tolerance the value of tolerance
4219 # @param SubMeshOrGroup SubMesh or Group
4220 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4221 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4222 # @ingroup l2_modif_trsf
4223 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance, exceptNodes=[]):
4224 unRegister = genObjUnRegister()
4225 if (isinstance( SubMeshOrGroup, Mesh )):
4226 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4227 if not isinstance( exceptNodes, list):
4228 exceptNodes = [ exceptNodes ]
4229 if exceptNodes and isinstance( exceptNodes[0], int):
4230 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE)]
4231 unRegister.set( exceptNodes )
4232 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,exceptNodes)
4235 # @param GroupsOfNodes a list of pairs of nodes IDs for merging (e.g. [[1,12],[25,4]])
4236 # @ingroup l2_modif_trsf
4237 def MergeNodes (self, GroupsOfNodes):
4238 self.editor.MergeNodes(GroupsOfNodes)
4240 ## Finds the elements built on the same nodes.
4241 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4242 # @return the list of pairs of equal elements IDs (e.g. [[1,12],[25,4]])
4243 # @ingroup l2_modif_trsf
4244 def FindEqualElements (self, MeshOrSubMeshOrGroup):
4245 if ( isinstance( MeshOrSubMeshOrGroup, Mesh )):
4246 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4247 return self.editor.FindEqualElements(MeshOrSubMeshOrGroup)
4249 ## Merges elements in each given group.
4250 # @param GroupsOfElementsID a list of pairs of elements IDs for merging (e.g. [[1,12],[25,4]])
4251 # @ingroup l2_modif_trsf
4252 def MergeElements(self, GroupsOfElementsID):
4253 self.editor.MergeElements(GroupsOfElementsID)
4255 ## Leaves one element and removes all other elements built on the same nodes.
4256 # @ingroup l2_modif_trsf
4257 def MergeEqualElements(self):
4258 self.editor.MergeEqualElements()
4260 ## Sews free borders
4261 # @return SMESH::Sew_Error
4262 # @ingroup l2_modif_trsf
4263 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4264 FirstNodeID2, SecondNodeID2, LastNodeID2,
4265 CreatePolygons, CreatePolyedrs):
4266 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4267 FirstNodeID2, SecondNodeID2, LastNodeID2,
4268 CreatePolygons, CreatePolyedrs)
4270 ## Sews conform free borders
4271 # @return SMESH::Sew_Error
4272 # @ingroup l2_modif_trsf
4273 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4274 FirstNodeID2, SecondNodeID2):
4275 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4276 FirstNodeID2, SecondNodeID2)
4278 ## Sews border to side
4279 # @return SMESH::Sew_Error
4280 # @ingroup l2_modif_trsf
4281 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4282 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4283 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4284 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4286 ## Sews two sides of a mesh. The nodes belonging to Side1 are
4287 # merged with the nodes of elements of Side2.
4288 # The number of elements in theSide1 and in theSide2 must be
4289 # equal and they should have similar nodal connectivity.
4290 # The nodes to merge should belong to side borders and
4291 # the first node should be linked to the second.
4292 # @return SMESH::Sew_Error
4293 # @ingroup l2_modif_trsf
4294 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4295 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4296 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4297 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4298 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4299 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4301 ## Sets new nodes for the given element.
4302 # @param ide the element id
4303 # @param newIDs nodes ids
4304 # @return If the number of nodes does not correspond to the type of element - returns false
4305 # @ingroup l2_modif_edit
4306 def ChangeElemNodes(self, ide, newIDs):
4307 return self.editor.ChangeElemNodes(ide, newIDs)
4309 ## If during the last operation of MeshEditor some nodes were
4310 # created, this method returns the list of their IDs, \n
4311 # if new nodes were not created - returns empty list
4312 # @return the list of integer values (can be empty)
4313 # @ingroup l1_auxiliary
4314 def GetLastCreatedNodes(self):
4315 return self.editor.GetLastCreatedNodes()
4317 ## If during the last operation of MeshEditor some elements were
4318 # created this method returns the list of their IDs, \n
4319 # if new elements were not created - returns empty list
4320 # @return the list of integer values (can be empty)
4321 # @ingroup l1_auxiliary
4322 def GetLastCreatedElems(self):
4323 return self.editor.GetLastCreatedElems()
4325 ## Clears sequences of nodes and elements created by mesh edition oparations
4326 # @ingroup l1_auxiliary
4327 def ClearLastCreated(self):
4328 self.editor.ClearLastCreated()
4330 ## Creates Duplicates given elements, i.e. creates new elements based on the
4331 # same nodes as the given ones.
4332 # @param theElements - container of elements to duplicate. It can be a Mesh,
4333 # sub-mesh, group, filter or a list of element IDs.
4334 # @param theGroupName - a name of group to contain the generated elements.
4335 # If a group with such a name already exists, the new elements
4336 # are added to the existng group, else a new group is created.
4337 # If \a theGroupName is empty, new elements are not added
4339 # @return a group where the new elements are added. None if theGroupName == "".
4340 # @ingroup l2_modif_edit
4341 def DoubleElements(self, theElements, theGroupName=""):
4342 unRegister = genObjUnRegister()
4343 if isinstance( theElements, Mesh ):
4344 theElements = theElements.mesh
4345 elif isinstance( theElements, list ):
4346 theElements = self.GetIDSource( theElements, SMESH.ALL )
4347 unRegister.set( theElements )
4348 return self.editor.DoubleElements(theElements, theGroupName)
4350 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4351 # @param theNodes identifiers of nodes to be doubled
4352 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4353 # nodes. If list of element identifiers is empty then nodes are doubled but
4354 # they not assigned to elements
4355 # @return TRUE if operation has been completed successfully, FALSE otherwise
4356 # @ingroup l2_modif_edit
4357 def DoubleNodes(self, theNodes, theModifiedElems):
4358 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4360 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4361 # This method provided for convenience works as DoubleNodes() described above.
4362 # @param theNodeId identifiers of node to be doubled
4363 # @param theModifiedElems identifiers of elements to be updated
4364 # @return TRUE if operation has been completed successfully, FALSE otherwise
4365 # @ingroup l2_modif_edit
4366 def DoubleNode(self, theNodeId, theModifiedElems):
4367 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4369 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4370 # This method provided for convenience works as DoubleNodes() described above.
4371 # @param theNodes group of nodes to be doubled
4372 # @param theModifiedElems group of elements to be updated.
4373 # @param theMakeGroup forces the generation of a group containing new nodes.
4374 # @return TRUE or a created group if operation has been completed successfully,
4375 # FALSE or None otherwise
4376 # @ingroup l2_modif_edit
4377 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4379 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4380 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4382 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4383 # This method provided for convenience works as DoubleNodes() described above.
4384 # @param theNodes list of groups of nodes to be doubled
4385 # @param theModifiedElems list of groups of elements to be updated.
4386 # @param theMakeGroup forces the generation of a group containing new nodes.
4387 # @return TRUE if operation has been completed successfully, FALSE otherwise
4388 # @ingroup l2_modif_edit
4389 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4391 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4392 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4394 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4395 # @param theElems - the list of elements (edges or faces) to be replicated
4396 # The nodes for duplication could be found from these elements
4397 # @param theNodesNot - list of nodes to NOT replicate
4398 # @param theAffectedElems - the list of elements (cells and edges) to which the
4399 # replicated nodes should be associated to.
4400 # @return TRUE if operation has been completed successfully, FALSE otherwise
4401 # @ingroup l2_modif_edit
4402 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4403 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4405 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4406 # @param theElems - the list of elements (edges or faces) to be replicated
4407 # The nodes for duplication could be found from these elements
4408 # @param theNodesNot - list of nodes to NOT replicate
4409 # @param theShape - shape to detect affected elements (element which geometric center
4410 # located on or inside shape).
4411 # The replicated nodes should be associated to affected elements.
4412 # @return TRUE if operation has been completed successfully, FALSE otherwise
4413 # @ingroup l2_modif_edit
4414 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4415 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4417 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4418 # This method provided for convenience works as DoubleNodes() described above.
4419 # @param theElems - group of of elements (edges or faces) to be replicated
4420 # @param theNodesNot - group of nodes not to replicated
4421 # @param theAffectedElems - group of elements to which the replicated nodes
4422 # should be associated to.
4423 # @param theMakeGroup forces the generation of a group containing new elements.
4424 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4425 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4426 # FALSE or None otherwise
4427 # @ingroup l2_modif_edit
4428 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4429 theMakeGroup=False, theMakeNodeGroup=False):
4430 if theMakeGroup or theMakeNodeGroup:
4431 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4433 theMakeGroup, theMakeNodeGroup)
4434 if theMakeGroup and theMakeNodeGroup:
4437 return twoGroups[ int(theMakeNodeGroup) ]
4438 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4440 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4441 # This method provided for convenience works as DoubleNodes() described above.
4442 # @param theElems - group of of elements (edges or faces) to be replicated
4443 # @param theNodesNot - group of nodes not to replicated
4444 # @param theShape - shape to detect affected elements (element which geometric center
4445 # located on or inside shape).
4446 # The replicated nodes should be associated to affected elements.
4447 # @ingroup l2_modif_edit
4448 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4449 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4451 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4452 # This method provided for convenience works as DoubleNodes() described above.
4453 # @param theElems - list of groups of elements (edges or faces) to be replicated
4454 # @param theNodesNot - list of groups of nodes not to replicated
4455 # @param theAffectedElems - group of elements to which the replicated nodes
4456 # should be associated to.
4457 # @param theMakeGroup forces the generation of a group containing new elements.
4458 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4459 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4460 # FALSE or None otherwise
4461 # @ingroup l2_modif_edit
4462 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4463 theMakeGroup=False, theMakeNodeGroup=False):
4464 if theMakeGroup or theMakeNodeGroup:
4465 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4467 theMakeGroup, theMakeNodeGroup)
4468 if theMakeGroup and theMakeNodeGroup:
4471 return twoGroups[ int(theMakeNodeGroup) ]
4472 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4474 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4475 # This method provided for convenience works as DoubleNodes() described above.
4476 # @param theElems - list of groups of elements (edges or faces) to be replicated
4477 # @param theNodesNot - list of groups of nodes not to replicated
4478 # @param theShape - shape to detect affected elements (element which geometric center
4479 # located on or inside shape).
4480 # The replicated nodes should be associated to affected elements.
4481 # @return TRUE if operation has been completed successfully, FALSE otherwise
4482 # @ingroup l2_modif_edit
4483 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4484 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4486 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4487 # This method is the first step of DoubleNodeElemGroupsInRegion.
4488 # @param theElems - list of groups of elements (edges or faces) to be replicated
4489 # @param theNodesNot - list of groups of nodes not to replicated
4490 # @param theShape - shape to detect affected elements (element which geometric center
4491 # located on or inside shape).
4492 # The replicated nodes should be associated to affected elements.
4493 # @return groups of affected elements
4494 # @ingroup l2_modif_edit
4495 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4496 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4498 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4499 # The list of groups must describe a partition of the mesh volumes.
4500 # The nodes of the internal faces at the boundaries of the groups are doubled.
4501 # In option, the internal faces are replaced by flat elements.
4502 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4503 # @param theDomains - list of groups of volumes
4504 # @param createJointElems - if TRUE, create the elements
4505 # @return TRUE if operation has been completed successfully, FALSE otherwise
4506 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems ):
4507 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems )
4509 ## Double nodes on some external faces and create flat elements.
4510 # Flat elements are mainly used by some types of mechanic calculations.
4512 # Each group of the list must be constituted of faces.
4513 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4514 # @param theGroupsOfFaces - list of groups of faces
4515 # @return TRUE if operation has been completed successfully, FALSE otherwise
4516 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4517 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4519 ## identify all the elements around a geom shape, get the faces delimiting the hole
4521 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4522 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4524 def _getFunctor(self, funcType ):
4525 fn = self.functors[ funcType._v ]
4527 fn = self.smeshpyD.GetFunctor(funcType)
4528 fn.SetMesh(self.mesh)
4529 self.functors[ funcType._v ] = fn
4532 def _valueFromFunctor(self, funcType, elemId):
4533 fn = self._getFunctor( funcType )
4534 if fn.GetElementType() == self.GetElementType(elemId, True):
4535 val = fn.GetValue(elemId)
4540 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4541 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4542 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4543 # @ingroup l1_measurements
4544 def GetLength(self, elemId=None):
4547 length = self.smeshpyD.GetLength(self)
4549 length = self._valueFromFunctor(SMESH.FT_Length, elemId)
4552 ## Get area of 2D element or sum of areas of all 2D mesh elements
4553 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4554 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4555 # @ingroup l1_measurements
4556 def GetArea(self, elemId=None):
4559 area = self.smeshpyD.GetArea(self)
4561 area = self._valueFromFunctor(SMESH.FT_Area, elemId)
4564 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4565 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4566 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4567 # @ingroup l1_measurements
4568 def GetVolume(self, elemId=None):
4571 volume = self.smeshpyD.GetVolume(self)
4573 volume = self._valueFromFunctor(SMESH.FT_Volume3D, elemId)
4576 ## Get maximum element length.
4577 # @param elemId mesh element ID
4578 # @return element's maximum length value
4579 # @ingroup l1_measurements
4580 def GetMaxElementLength(self, elemId):
4581 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4582 ftype = SMESH.FT_MaxElementLength3D
4584 ftype = SMESH.FT_MaxElementLength2D
4585 return self._valueFromFunctor(ftype, elemId)
4587 ## Get aspect ratio of 2D or 3D element.
4588 # @param elemId mesh element ID
4589 # @return element's aspect ratio value
4590 # @ingroup l1_measurements
4591 def GetAspectRatio(self, elemId):
4592 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4593 ftype = SMESH.FT_AspectRatio3D
4595 ftype = SMESH.FT_AspectRatio
4596 return self._valueFromFunctor(ftype, elemId)
4598 ## Get warping angle of 2D element.
4599 # @param elemId mesh element ID
4600 # @return element's warping angle value
4601 # @ingroup l1_measurements
4602 def GetWarping(self, elemId):
4603 return self._valueFromFunctor(SMESH.FT_Warping, elemId)
4605 ## Get minimum angle of 2D element.
4606 # @param elemId mesh element ID
4607 # @return element's minimum angle value
4608 # @ingroup l1_measurements
4609 def GetMinimumAngle(self, elemId):
4610 return self._valueFromFunctor(SMESH.FT_MinimumAngle, elemId)
4612 ## Get taper of 2D element.
4613 # @param elemId mesh element ID
4614 # @return element's taper value
4615 # @ingroup l1_measurements
4616 def GetTaper(self, elemId):
4617 return self._valueFromFunctor(SMESH.FT_Taper, elemId)
4619 ## Get skew of 2D element.
4620 # @param elemId mesh element ID
4621 # @return element's skew value
4622 # @ingroup l1_measurements
4623 def GetSkew(self, elemId):
4624 return self._valueFromFunctor(SMESH.FT_Skew, elemId)
4626 pass # end of Mesh class
4628 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
4630 class Pattern(SMESH._objref_SMESH_Pattern):
4632 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4633 decrFun = lambda i: i-1
4634 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4635 theMesh.SetParameters(Parameters)
4636 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4638 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4639 decrFun = lambda i: i-1
4640 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4641 theMesh.SetParameters(Parameters)
4642 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4644 # Registering the new proxy for Pattern
4645 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4647 ## Private class used to bind methods creating algorithms to the class Mesh
4652 self.defaultAlgoType = ""
4653 self.algoTypeToClass = {}
4655 # Stores a python class of algorithm
4656 def add(self, algoClass):
4657 if type( algoClass ).__name__ == 'classobj' and \
4658 hasattr( algoClass, "algoType"):
4659 self.algoTypeToClass[ algoClass.algoType ] = algoClass
4660 if not self.defaultAlgoType and \
4661 hasattr( algoClass, "isDefault") and algoClass.isDefault:
4662 self.defaultAlgoType = algoClass.algoType
4663 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
4665 # creates a copy of self and assign mesh to the copy
4666 def copy(self, mesh):
4667 other = algoCreator()
4668 other.defaultAlgoType = self.defaultAlgoType
4669 other.algoTypeToClass = self.algoTypeToClass
4673 # creates an instance of algorithm
4674 def __call__(self,algo="",geom=0,*args):
4675 algoType = self.defaultAlgoType
4676 for arg in args + (algo,geom):
4677 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
4679 if isinstance( arg, str ) and arg:
4681 if not algoType and self.algoTypeToClass:
4682 algoType = self.algoTypeToClass.keys()[0]
4683 if self.algoTypeToClass.has_key( algoType ):
4684 #print "Create algo",algoType
4685 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
4686 raise RuntimeError, "No class found for algo type %s" % algoType
4689 # Private class used to substitute and store variable parameters of hypotheses.
4691 class hypMethodWrapper:
4692 def __init__(self, hyp, method):
4694 self.method = method
4695 #print "REBIND:", method.__name__
4698 # call a method of hypothesis with calling SetVarParameter() before
4699 def __call__(self,*args):
4701 return self.method( self.hyp, *args ) # hypothesis method with no args
4703 #print "MethWrapper.__call__",self.method.__name__, args
4705 parsed = ParseParameters(*args) # replace variables with their values
4706 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
4707 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
4708 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
4709 # maybe there is a replaced string arg which is not variable
4710 result = self.method( self.hyp, *args )
4711 except ValueError, detail: # raised by ParseParameters()
4713 result = self.method( self.hyp, *args )
4714 except omniORB.CORBA.BAD_PARAM:
4715 raise ValueError, detail # wrong variable name
4720 # A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
4721 class genObjUnRegister:
4723 def __init__(self, genObj=None):
4724 self.genObjList = []
4728 def set(self, genObj):
4729 "Store one or a list of of SALOME.GenericObj'es"
4730 if isinstance( genObj, list ):
4731 self.genObjList.extend( genObj )
4733 self.genObjList.append( genObj )
4737 for genObj in self.genObjList:
4738 if genObj and hasattr( genObj, "UnRegister" ):
4741 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
4743 #print "pluginName: ", pluginName
4744 pluginBuilderName = pluginName + "Builder"
4746 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
4747 except Exception, e:
4748 from salome_utils import verbose
4749 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
4751 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
4752 plugin = eval( pluginBuilderName )
4753 #print " plugin:" , str(plugin)
4755 # add methods creating algorithms to Mesh
4756 for k in dir( plugin ):
4757 if k[0] == '_': continue
4758 algo = getattr( plugin, k )
4759 #print " algo:", str(algo)
4760 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
4761 #print " meshMethod:" , str(algo.meshMethod)
4762 if not hasattr( Mesh, algo.meshMethod ):
4763 setattr( Mesh, algo.meshMethod, algoCreator() )
4765 getattr( Mesh, algo.meshMethod ).add( algo )