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 = hyp.GetName()
1567 lib_name = hyp.GetLibName()
1570 geom_name = geom.GetName()
1572 isAlgo = hyp._narrow( SMESH_Algo )
1573 if self.mesh.HasShapeToMesh():
1574 isApplicable = self.smeshpyD.IsApplicable(hyp_name, lib_name, geom, not geom.IsSame( self.mesh.GetShapeToMesh() ) )
1576 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1577 status = self.mesh.AddHypothesis(geom, hyp)
1578 TreatHypoStatus( status, hyp_name, geom_name, isAlgo )
1581 TreatHypoStatus( HYP_BAD_GEOMETRY, hyp_name, geom_name, isAlgo )
1582 return HYP_BAD_GEOMETRY
1584 ## Return True if an algorithm of hypothesis is assigned to a given shape
1585 # @param hyp a hypothesis to check
1586 # @param geom a subhape of mesh geometry
1587 # @return True of False
1588 # @ingroup l2_hypotheses
1589 def IsUsedHypothesis(self, hyp, geom):
1590 if not hyp: # or not geom
1592 if isinstance( hyp, Mesh_Algorithm ):
1593 hyp = hyp.GetAlgorithm()
1595 hyps = self.GetHypothesisList(geom)
1597 if h.GetId() == hyp.GetId():
1601 ## Unassigns a hypothesis
1602 # @param hyp a hypothesis to unassign
1603 # @param geom a sub-shape of mesh geometry
1604 # @return SMESH.Hypothesis_Status
1605 # @ingroup l2_hypotheses
1606 def RemoveHypothesis(self, hyp, geom=0):
1609 if isinstance( hyp, Mesh_Algorithm ):
1610 hyp = hyp.GetAlgorithm()
1616 if self.IsUsedHypothesis( hyp, shape ):
1617 return self.mesh.RemoveHypothesis( shape, hyp )
1618 hypName = GetName( hyp )
1619 geoName = GetName( shape )
1620 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1623 ## Gets the list of hypotheses added on a geometry
1624 # @param geom a sub-shape of mesh geometry
1625 # @return the sequence of SMESH_Hypothesis
1626 # @ingroup l2_hypotheses
1627 def GetHypothesisList(self, geom):
1628 return self.mesh.GetHypothesisList( geom )
1630 ## Removes all global hypotheses
1631 # @ingroup l2_hypotheses
1632 def RemoveGlobalHypotheses(self):
1633 current_hyps = self.mesh.GetHypothesisList( self.geom )
1634 for hyp in current_hyps:
1635 self.mesh.RemoveHypothesis( self.geom, hyp )
1639 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1640 ## allowing to overwrite the file if it exists or add the exported data to its contents
1641 # @param f is the file name
1642 # @param auto_groups boolean parameter for creating/not creating
1643 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1644 # the typical use is auto_groups=false.
1645 # @param version MED format version(MED_V2_1 or MED_V2_2)
1646 # @param overwrite boolean parameter for overwriting/not overwriting the file
1647 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1648 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1649 # - 1D if all mesh nodes lie on OX coordinate axis, or
1650 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1651 # - 3D in the rest cases.
1653 # If @a autoDimension is @c False, the space dimension is always 3.
1654 # @ingroup l2_impexp
1655 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1656 overwrite=1, meshPart=None, autoDimension=True):
1658 unRegister = genObjUnRegister()
1659 if isinstance( meshPart, list ):
1660 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1661 unRegister.set( meshPart )
1662 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension)
1664 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1666 ## Exports the mesh in a file in SAUV format
1667 # @param f is the file name
1668 # @param auto_groups boolean parameter for creating/not creating
1669 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1670 # the typical use is auto_groups=false.
1671 # @ingroup l2_impexp
1672 def ExportSAUV(self, f, auto_groups=0):
1673 self.mesh.ExportSAUV(f, auto_groups)
1675 ## Exports the mesh in a file in DAT format
1676 # @param f the file name
1677 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1678 # @ingroup l2_impexp
1679 def ExportDAT(self, f, meshPart=None):
1681 unRegister = genObjUnRegister()
1682 if isinstance( meshPart, list ):
1683 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1684 unRegister.set( meshPart )
1685 self.mesh.ExportPartToDAT( meshPart, f )
1687 self.mesh.ExportDAT(f)
1689 ## Exports the mesh in a file in UNV format
1690 # @param f the file name
1691 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1692 # @ingroup l2_impexp
1693 def ExportUNV(self, f, meshPart=None):
1695 unRegister = genObjUnRegister()
1696 if isinstance( meshPart, list ):
1697 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1698 unRegister.set( meshPart )
1699 self.mesh.ExportPartToUNV( meshPart, f )
1701 self.mesh.ExportUNV(f)
1703 ## Export the mesh in a file in STL format
1704 # @param f the file name
1705 # @param ascii defines the file encoding
1706 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1707 # @ingroup l2_impexp
1708 def ExportSTL(self, f, ascii=1, meshPart=None):
1710 unRegister = genObjUnRegister()
1711 if isinstance( meshPart, list ):
1712 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1713 unRegister.set( meshPart )
1714 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1716 self.mesh.ExportSTL(f, ascii)
1718 ## Exports the mesh in a file in CGNS format
1719 # @param f is the file name
1720 # @param overwrite boolean parameter for overwriting/not overwriting the file
1721 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1722 # @ingroup l2_impexp
1723 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1724 unRegister = genObjUnRegister()
1725 if isinstance( meshPart, list ):
1726 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1727 unRegister.set( meshPart )
1728 if isinstance( meshPart, Mesh ):
1729 meshPart = meshPart.mesh
1731 meshPart = self.mesh
1732 self.mesh.ExportCGNS(meshPart, f, overwrite)
1734 ## Exports the mesh in a file in GMF format.
1735 # GMF files must have .mesh extension for the ASCII format and .meshb for
1736 # the bynary format. Other extensions are not allowed.
1737 # @param f is the file name
1738 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1739 # @ingroup l2_impexp
1740 def ExportGMF(self, f, meshPart=None):
1741 unRegister = genObjUnRegister()
1742 if isinstance( meshPart, list ):
1743 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1744 unRegister.set( meshPart )
1745 if isinstance( meshPart, Mesh ):
1746 meshPart = meshPart.mesh
1748 meshPart = self.mesh
1749 self.mesh.ExportGMF(meshPart, f, True)
1751 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1752 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1753 ## allowing to overwrite the file if it exists or add the exported data to its contents
1754 # @param f the file name
1755 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1756 # @param opt boolean parameter for creating/not creating
1757 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1758 # @param overwrite boolean parameter for overwriting/not overwriting the file
1759 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1760 # - 1D if all mesh nodes lie on OX coordinate axis, or
1761 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1762 # - 3D in the rest cases.
1764 # If @a autoDimension is @c False, the space dimension is always 3.
1765 # @ingroup l2_impexp
1766 def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1767 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1769 # Operations with groups:
1770 # ----------------------
1772 ## Creates an empty mesh group
1773 # @param elementType the type of elements in the group
1774 # @param name the name of the mesh group
1775 # @return SMESH_Group
1776 # @ingroup l2_grps_create
1777 def CreateEmptyGroup(self, elementType, name):
1778 return self.mesh.CreateGroup(elementType, name)
1780 ## Creates a mesh group based on the geometric object \a grp
1781 # and gives a \a name, \n if this parameter is not defined
1782 # the name is the same as the geometric group name \n
1783 # Note: Works like GroupOnGeom().
1784 # @param grp a geometric group, a vertex, an edge, a face or a solid
1785 # @param name the name of the mesh group
1786 # @return SMESH_GroupOnGeom
1787 # @ingroup l2_grps_create
1788 def Group(self, grp, name=""):
1789 return self.GroupOnGeom(grp, name)
1791 ## Creates a mesh group based on the geometrical object \a grp
1792 # and gives a \a name, \n if this parameter is not defined
1793 # the name is the same as the geometrical group name
1794 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1795 # @param name the name of the mesh group
1796 # @param typ the type of elements in the group. If not set, it is
1797 # automatically detected by the type of the geometry
1798 # @return SMESH_GroupOnGeom
1799 # @ingroup l2_grps_create
1800 def GroupOnGeom(self, grp, name="", typ=None):
1801 AssureGeomPublished( self, grp, name )
1803 name = grp.GetName()
1805 typ = self._groupTypeFromShape( grp )
1806 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1808 ## Pivate method to get a type of group on geometry
1809 def _groupTypeFromShape( self, shape ):
1810 tgeo = str(shape.GetShapeType())
1811 if tgeo == "VERTEX":
1813 elif tgeo == "EDGE":
1815 elif tgeo == "FACE" or tgeo == "SHELL":
1817 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1819 elif tgeo == "COMPOUND":
1820 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1822 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1823 return self._groupTypeFromShape( sub[0] )
1826 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1829 ## Creates a mesh group with given \a name based on the \a filter which
1830 ## is a special type of group dynamically updating it's contents during
1831 ## mesh modification
1832 # @param typ the type of elements in the group
1833 # @param name the name of the mesh group
1834 # @param filter the filter defining group contents
1835 # @return SMESH_GroupOnFilter
1836 # @ingroup l2_grps_create
1837 def GroupOnFilter(self, typ, name, filter):
1838 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1840 ## Creates a mesh group by the given ids of elements
1841 # @param groupName the name of the mesh group
1842 # @param elementType the type of elements in the group
1843 # @param elemIDs the list of ids
1844 # @return SMESH_Group
1845 # @ingroup l2_grps_create
1846 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1847 group = self.mesh.CreateGroup(elementType, groupName)
1851 ## Creates a mesh group by the given conditions
1852 # @param groupName the name of the mesh group
1853 # @param elementType the type of elements in the group
1854 # @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1855 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1856 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
1857 # @param UnaryOp FT_LogicalNOT or FT_Undefined
1858 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1859 # FT_LyingOnGeom, FT_CoplanarFaces criteria
1860 # @return SMESH_Group
1861 # @ingroup l2_grps_create
1865 CritType=FT_Undefined,
1868 UnaryOp=FT_Undefined,
1870 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1871 group = self.MakeGroupByCriterion(groupName, aCriterion)
1874 ## Creates a mesh group by the given criterion
1875 # @param groupName the name of the mesh group
1876 # @param Criterion the instance of Criterion class
1877 # @return SMESH_Group
1878 # @ingroup l2_grps_create
1879 def MakeGroupByCriterion(self, groupName, Criterion):
1880 aFilterMgr = self.smeshpyD.CreateFilterManager()
1881 aFilter = aFilterMgr.CreateFilter()
1883 aCriteria.append(Criterion)
1884 aFilter.SetCriteria(aCriteria)
1885 group = self.MakeGroupByFilter(groupName, aFilter)
1886 aFilterMgr.UnRegister()
1889 ## Creates a mesh group by the given criteria (list of criteria)
1890 # @param groupName the name of the mesh group
1891 # @param theCriteria the list of criteria
1892 # @return SMESH_Group
1893 # @ingroup l2_grps_create
1894 def MakeGroupByCriteria(self, groupName, theCriteria):
1895 aFilterMgr = self.smeshpyD.CreateFilterManager()
1896 aFilter = aFilterMgr.CreateFilter()
1897 aFilter.SetCriteria(theCriteria)
1898 group = self.MakeGroupByFilter(groupName, aFilter)
1899 aFilterMgr.UnRegister()
1902 ## Creates a mesh group by the given filter
1903 # @param groupName the name of the mesh group
1904 # @param theFilter the instance of Filter class
1905 # @return SMESH_Group
1906 # @ingroup l2_grps_create
1907 def MakeGroupByFilter(self, groupName, theFilter):
1908 group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1909 theFilter.SetMesh( self.mesh )
1910 group.AddFrom( theFilter )
1914 # @ingroup l2_grps_delete
1915 def RemoveGroup(self, group):
1916 self.mesh.RemoveGroup(group)
1918 ## Removes a group with its contents
1919 # @ingroup l2_grps_delete
1920 def RemoveGroupWithContents(self, group):
1921 self.mesh.RemoveGroupWithContents(group)
1923 ## Gets the list of groups existing in the mesh in the order of creation (starting from the oldest one)
1924 # @return a sequence of SMESH_GroupBase
1925 # @ingroup l2_grps_create
1926 def GetGroups(self):
1927 return self.mesh.GetGroups()
1929 ## Gets the number of groups existing in the mesh
1930 # @return the quantity of groups as an integer value
1931 # @ingroup l2_grps_create
1933 return self.mesh.NbGroups()
1935 ## Gets the list of names of groups existing in the mesh
1936 # @return list of strings
1937 # @ingroup l2_grps_create
1938 def GetGroupNames(self):
1939 groups = self.GetGroups()
1941 for group in groups:
1942 names.append(group.GetName())
1945 ## Produces a union of two groups
1946 # A new group is created. All mesh elements that are
1947 # present in the initial groups are added to the new one
1948 # @return an instance of SMESH_Group
1949 # @ingroup l2_grps_operon
1950 def UnionGroups(self, group1, group2, name):
1951 return self.mesh.UnionGroups(group1, group2, name)
1953 ## Produces a union list of groups
1954 # New group is created. All mesh elements that are present in
1955 # initial groups are added to the new one
1956 # @return an instance of SMESH_Group
1957 # @ingroup l2_grps_operon
1958 def UnionListOfGroups(self, groups, name):
1959 return self.mesh.UnionListOfGroups(groups, name)
1961 ## Prodices an intersection of two groups
1962 # A new group is created. All mesh elements that are common
1963 # for the two initial groups are added to the new one.
1964 # @return an instance of SMESH_Group
1965 # @ingroup l2_grps_operon
1966 def IntersectGroups(self, group1, group2, name):
1967 return self.mesh.IntersectGroups(group1, group2, name)
1969 ## Produces an intersection of groups
1970 # New group is created. All mesh elements that are present in all
1971 # initial groups simultaneously are added to the new one
1972 # @return an instance of SMESH_Group
1973 # @ingroup l2_grps_operon
1974 def IntersectListOfGroups(self, groups, name):
1975 return self.mesh.IntersectListOfGroups(groups, name)
1977 ## Produces a cut of two groups
1978 # A new group is created. All mesh elements that are present in
1979 # the main group but are not present in the tool group are added to the new one
1980 # @return an instance of SMESH_Group
1981 # @ingroup l2_grps_operon
1982 def CutGroups(self, main_group, tool_group, name):
1983 return self.mesh.CutGroups(main_group, tool_group, name)
1985 ## Produces a cut of groups
1986 # A new group is created. All mesh elements that are present in main groups
1987 # but do not present in tool groups are added to the new one
1988 # @return an instance of SMESH_Group
1989 # @ingroup l2_grps_operon
1990 def CutListOfGroups(self, main_groups, tool_groups, name):
1991 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
1993 ## Produces a group of elements of specified type using list of existing groups
1994 # A new group is created. System
1995 # 1) extracts all nodes on which groups elements are built
1996 # 2) combines all elements of specified dimension laying on these nodes
1997 # @return an instance of SMESH_Group
1998 # @ingroup l2_grps_operon
1999 def CreateDimGroup(self, groups, elem_type, name):
2000 return self.mesh.CreateDimGroup(groups, elem_type, name)
2003 ## Convert group on geom into standalone group
2004 # @ingroup l2_grps_delete
2005 def ConvertToStandalone(self, group):
2006 return self.mesh.ConvertToStandalone(group)
2008 # Get some info about mesh:
2009 # ------------------------
2011 ## Returns the log of nodes and elements added or removed
2012 # since the previous clear of the log.
2013 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2014 # @return list of log_block structures:
2019 # @ingroup l1_auxiliary
2020 def GetLog(self, clearAfterGet):
2021 return self.mesh.GetLog(clearAfterGet)
2023 ## Clears the log of nodes and elements added or removed since the previous
2024 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2025 # @ingroup l1_auxiliary
2027 self.mesh.ClearLog()
2029 ## Toggles auto color mode on the object.
2030 # @param theAutoColor the flag which toggles auto color mode.
2031 # @ingroup l1_auxiliary
2032 def SetAutoColor(self, theAutoColor):
2033 self.mesh.SetAutoColor(theAutoColor)
2035 ## Gets flag of object auto color mode.
2036 # @return True or False
2037 # @ingroup l1_auxiliary
2038 def GetAutoColor(self):
2039 return self.mesh.GetAutoColor()
2041 ## Gets the internal ID
2042 # @return integer value, which is the internal Id of the mesh
2043 # @ingroup l1_auxiliary
2045 return self.mesh.GetId()
2048 # @return integer value, which is the study Id of the mesh
2049 # @ingroup l1_auxiliary
2050 def GetStudyId(self):
2051 return self.mesh.GetStudyId()
2053 ## Checks the group names for duplications.
2054 # Consider the maximum group name length stored in MED file.
2055 # @return True or False
2056 # @ingroup l1_auxiliary
2057 def HasDuplicatedGroupNamesMED(self):
2058 return self.mesh.HasDuplicatedGroupNamesMED()
2060 ## Obtains the mesh editor tool
2061 # @return an instance of SMESH_MeshEditor
2062 # @ingroup l1_modifying
2063 def GetMeshEditor(self):
2066 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2067 # can be passed as argument to a method accepting mesh, group or sub-mesh
2068 # @return an instance of SMESH_IDSource
2069 # @ingroup l1_auxiliary
2070 def GetIDSource(self, ids, elemType):
2071 return self.editor.MakeIDSource(ids, elemType)
2074 # Get informations about mesh contents:
2075 # ------------------------------------
2077 ## Gets the mesh stattistic
2078 # @return dictionary type element - count of elements
2079 # @ingroup l1_meshinfo
2080 def GetMeshInfo(self, obj = None):
2081 if not obj: obj = self.mesh
2082 return self.smeshpyD.GetMeshInfo(obj)
2084 ## Returns the number of nodes in the mesh
2085 # @return an integer value
2086 # @ingroup l1_meshinfo
2088 return self.mesh.NbNodes()
2090 ## Returns the number of elements in the mesh
2091 # @return an integer value
2092 # @ingroup l1_meshinfo
2093 def NbElements(self):
2094 return self.mesh.NbElements()
2096 ## Returns the number of 0d elements in the mesh
2097 # @return an integer value
2098 # @ingroup l1_meshinfo
2099 def Nb0DElements(self):
2100 return self.mesh.Nb0DElements()
2102 ## Returns the number of ball discrete elements in the mesh
2103 # @return an integer value
2104 # @ingroup l1_meshinfo
2106 return self.mesh.NbBalls()
2108 ## Returns the number of edges in the mesh
2109 # @return an integer value
2110 # @ingroup l1_meshinfo
2112 return self.mesh.NbEdges()
2114 ## Returns the number of edges with the given order in the mesh
2115 # @param elementOrder the order of elements:
2116 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2117 # @return an integer value
2118 # @ingroup l1_meshinfo
2119 def NbEdgesOfOrder(self, elementOrder):
2120 return self.mesh.NbEdgesOfOrder(elementOrder)
2122 ## Returns the number of faces in the mesh
2123 # @return an integer value
2124 # @ingroup l1_meshinfo
2126 return self.mesh.NbFaces()
2128 ## Returns the number of faces with the given order in the mesh
2129 # @param elementOrder the order of elements:
2130 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2131 # @return an integer value
2132 # @ingroup l1_meshinfo
2133 def NbFacesOfOrder(self, elementOrder):
2134 return self.mesh.NbFacesOfOrder(elementOrder)
2136 ## Returns the number of triangles in the mesh
2137 # @return an integer value
2138 # @ingroup l1_meshinfo
2139 def NbTriangles(self):
2140 return self.mesh.NbTriangles()
2142 ## Returns the number of triangles with the given order in the mesh
2143 # @param elementOrder is the order of elements:
2144 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2145 # @return an integer value
2146 # @ingroup l1_meshinfo
2147 def NbTrianglesOfOrder(self, elementOrder):
2148 return self.mesh.NbTrianglesOfOrder(elementOrder)
2150 ## Returns the number of biquadratic triangles in the mesh
2151 # @return an integer value
2152 # @ingroup l1_meshinfo
2153 def NbBiQuadTriangles(self):
2154 return self.mesh.NbBiQuadTriangles()
2156 ## Returns the number of quadrangles in the mesh
2157 # @return an integer value
2158 # @ingroup l1_meshinfo
2159 def NbQuadrangles(self):
2160 return self.mesh.NbQuadrangles()
2162 ## Returns the number of quadrangles with the given order in the mesh
2163 # @param elementOrder the order of elements:
2164 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2165 # @return an integer value
2166 # @ingroup l1_meshinfo
2167 def NbQuadranglesOfOrder(self, elementOrder):
2168 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2170 ## Returns the number of biquadratic quadrangles in the mesh
2171 # @return an integer value
2172 # @ingroup l1_meshinfo
2173 def NbBiQuadQuadrangles(self):
2174 return self.mesh.NbBiQuadQuadrangles()
2176 ## Returns the number of polygons in the mesh
2177 # @return an integer value
2178 # @ingroup l1_meshinfo
2179 def NbPolygons(self):
2180 return self.mesh.NbPolygons()
2182 ## Returns the number of volumes in the mesh
2183 # @return an integer value
2184 # @ingroup l1_meshinfo
2185 def NbVolumes(self):
2186 return self.mesh.NbVolumes()
2188 ## Returns the number of volumes with the given order in the mesh
2189 # @param elementOrder the order of elements:
2190 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2191 # @return an integer value
2192 # @ingroup l1_meshinfo
2193 def NbVolumesOfOrder(self, elementOrder):
2194 return self.mesh.NbVolumesOfOrder(elementOrder)
2196 ## Returns the number of tetrahedrons in the mesh
2197 # @return an integer value
2198 # @ingroup l1_meshinfo
2200 return self.mesh.NbTetras()
2202 ## Returns the number of tetrahedrons with the given order in the mesh
2203 # @param elementOrder the order of elements:
2204 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2205 # @return an integer value
2206 # @ingroup l1_meshinfo
2207 def NbTetrasOfOrder(self, elementOrder):
2208 return self.mesh.NbTetrasOfOrder(elementOrder)
2210 ## Returns the number of hexahedrons in the mesh
2211 # @return an integer value
2212 # @ingroup l1_meshinfo
2214 return self.mesh.NbHexas()
2216 ## Returns the number of hexahedrons with the given order in the mesh
2217 # @param elementOrder the order of elements:
2218 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2219 # @return an integer value
2220 # @ingroup l1_meshinfo
2221 def NbHexasOfOrder(self, elementOrder):
2222 return self.mesh.NbHexasOfOrder(elementOrder)
2224 ## Returns the number of triquadratic hexahedrons in the mesh
2225 # @return an integer value
2226 # @ingroup l1_meshinfo
2227 def NbTriQuadraticHexas(self):
2228 return self.mesh.NbTriQuadraticHexas()
2230 ## Returns the number of pyramids in the mesh
2231 # @return an integer value
2232 # @ingroup l1_meshinfo
2233 def NbPyramids(self):
2234 return self.mesh.NbPyramids()
2236 ## Returns the number of pyramids with the given order in the mesh
2237 # @param elementOrder the order of elements:
2238 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2239 # @return an integer value
2240 # @ingroup l1_meshinfo
2241 def NbPyramidsOfOrder(self, elementOrder):
2242 return self.mesh.NbPyramidsOfOrder(elementOrder)
2244 ## Returns the number of prisms in the mesh
2245 # @return an integer value
2246 # @ingroup l1_meshinfo
2248 return self.mesh.NbPrisms()
2250 ## Returns the number of prisms with the given order in the mesh
2251 # @param elementOrder the order of elements:
2252 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2253 # @return an integer value
2254 # @ingroup l1_meshinfo
2255 def NbPrismsOfOrder(self, elementOrder):
2256 return self.mesh.NbPrismsOfOrder(elementOrder)
2258 ## Returns the number of hexagonal prisms in the mesh
2259 # @return an integer value
2260 # @ingroup l1_meshinfo
2261 def NbHexagonalPrisms(self):
2262 return self.mesh.NbHexagonalPrisms()
2264 ## Returns the number of polyhedrons in the mesh
2265 # @return an integer value
2266 # @ingroup l1_meshinfo
2267 def NbPolyhedrons(self):
2268 return self.mesh.NbPolyhedrons()
2270 ## Returns the number of submeshes in the mesh
2271 # @return an integer value
2272 # @ingroup l1_meshinfo
2273 def NbSubMesh(self):
2274 return self.mesh.NbSubMesh()
2276 ## Returns the list of mesh elements IDs
2277 # @return the list of integer values
2278 # @ingroup l1_meshinfo
2279 def GetElementsId(self):
2280 return self.mesh.GetElementsId()
2282 ## Returns the list of IDs of mesh elements with the given type
2283 # @param elementType the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2284 # @return list of integer values
2285 # @ingroup l1_meshinfo
2286 def GetElementsByType(self, elementType):
2287 return self.mesh.GetElementsByType(elementType)
2289 ## Returns the list of mesh nodes IDs
2290 # @return the list of integer values
2291 # @ingroup l1_meshinfo
2292 def GetNodesId(self):
2293 return self.mesh.GetNodesId()
2295 # Get the information about mesh elements:
2296 # ------------------------------------
2298 ## Returns the type of mesh element
2299 # @return the value from SMESH::ElementType enumeration
2300 # @ingroup l1_meshinfo
2301 def GetElementType(self, id, iselem):
2302 return self.mesh.GetElementType(id, iselem)
2304 ## Returns the geometric type of mesh element
2305 # @return the value from SMESH::EntityType enumeration
2306 # @ingroup l1_meshinfo
2307 def GetElementGeomType(self, id):
2308 return self.mesh.GetElementGeomType(id)
2310 ## Returns the shape type of mesh element
2311 # @return the value from SMESH::GeometryType enumeration
2312 # @ingroup l1_meshinfo
2313 def GetElementShape(self, id):
2314 return self.mesh.GetElementShape(id)
2316 ## Returns the list of submesh elements IDs
2317 # @param Shape a geom object(sub-shape) IOR
2318 # Shape must be the sub-shape of a ShapeToMesh()
2319 # @return the list of integer values
2320 # @ingroup l1_meshinfo
2321 def GetSubMeshElementsId(self, Shape):
2322 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2323 ShapeID = Shape.GetSubShapeIndices()[0]
2326 return self.mesh.GetSubMeshElementsId(ShapeID)
2328 ## Returns the list of submesh nodes IDs
2329 # @param Shape a geom object(sub-shape) IOR
2330 # Shape must be the sub-shape of a ShapeToMesh()
2331 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2332 # @return the list of integer values
2333 # @ingroup l1_meshinfo
2334 def GetSubMeshNodesId(self, Shape, all):
2335 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2336 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2339 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2341 ## Returns type of elements on given shape
2342 # @param Shape a geom object(sub-shape) IOR
2343 # Shape must be a sub-shape of a ShapeToMesh()
2344 # @return element type
2345 # @ingroup l1_meshinfo
2346 def GetSubMeshElementType(self, Shape):
2347 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2348 ShapeID = Shape.GetSubShapeIndices()[0]
2351 return self.mesh.GetSubMeshElementType(ShapeID)
2353 ## Gets the mesh description
2354 # @return string value
2355 # @ingroup l1_meshinfo
2357 return self.mesh.Dump()
2360 # Get the information about nodes and elements of a mesh by its IDs:
2361 # -----------------------------------------------------------
2363 ## Gets XYZ coordinates of a node
2364 # \n If there is no nodes for the given ID - returns an empty list
2365 # @return a list of double precision values
2366 # @ingroup l1_meshinfo
2367 def GetNodeXYZ(self, id):
2368 return self.mesh.GetNodeXYZ(id)
2370 ## Returns list of IDs of inverse elements for the given node
2371 # \n If there is no node for the given ID - returns an empty list
2372 # @return a list of integer values
2373 # @ingroup l1_meshinfo
2374 def GetNodeInverseElements(self, id):
2375 return self.mesh.GetNodeInverseElements(id)
2377 ## @brief Returns the position of a node on the shape
2378 # @return SMESH::NodePosition
2379 # @ingroup l1_meshinfo
2380 def GetNodePosition(self,NodeID):
2381 return self.mesh.GetNodePosition(NodeID)
2383 ## @brief Returns the position of an element on the shape
2384 # @return SMESH::ElementPosition
2385 # @ingroup l1_meshinfo
2386 def GetElementPosition(self,ElemID):
2387 return self.mesh.GetElementPosition(ElemID)
2389 ## If the given element is a node, returns the ID of shape
2390 # \n If there is no node for the given ID - returns -1
2391 # @return an integer value
2392 # @ingroup l1_meshinfo
2393 def GetShapeID(self, id):
2394 return self.mesh.GetShapeID(id)
2396 ## Returns the ID of the result shape after
2397 # FindShape() from SMESH_MeshEditor for the given element
2398 # \n If there is no element for the given ID - returns -1
2399 # @return an integer value
2400 # @ingroup l1_meshinfo
2401 def GetShapeIDForElem(self,id):
2402 return self.mesh.GetShapeIDForElem(id)
2404 ## Returns the number of nodes for the given element
2405 # \n If there is no element for the given ID - returns -1
2406 # @return an integer value
2407 # @ingroup l1_meshinfo
2408 def GetElemNbNodes(self, id):
2409 return self.mesh.GetElemNbNodes(id)
2411 ## Returns the node ID the given (zero based) index for the given element
2412 # \n If there is no element for the given ID - returns -1
2413 # \n If there is no node for the given index - returns -2
2414 # @return an integer value
2415 # @ingroup l1_meshinfo
2416 def GetElemNode(self, id, index):
2417 return self.mesh.GetElemNode(id, index)
2419 ## Returns the IDs of nodes of the given element
2420 # @return a list of integer values
2421 # @ingroup l1_meshinfo
2422 def GetElemNodes(self, id):
2423 return self.mesh.GetElemNodes(id)
2425 ## Returns true if the given node is the medium node in the given quadratic element
2426 # @ingroup l1_meshinfo
2427 def IsMediumNode(self, elementID, nodeID):
2428 return self.mesh.IsMediumNode(elementID, nodeID)
2430 ## Returns true if the given node is the medium node in one of quadratic elements
2431 # @ingroup l1_meshinfo
2432 def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2433 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2435 ## Returns the number of edges for the given element
2436 # @ingroup l1_meshinfo
2437 def ElemNbEdges(self, id):
2438 return self.mesh.ElemNbEdges(id)
2440 ## Returns the number of faces for the given element
2441 # @ingroup l1_meshinfo
2442 def ElemNbFaces(self, id):
2443 return self.mesh.ElemNbFaces(id)
2445 ## Returns nodes of given face (counted from zero) for given volumic element.
2446 # @ingroup l1_meshinfo
2447 def GetElemFaceNodes(self,elemId, faceIndex):
2448 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2450 ## Returns three components of normal of given mesh face
2451 # (or an empty array in KO case)
2452 # @ingroup l1_meshinfo
2453 def GetFaceNormal(self, faceId, normalized=False):
2454 return self.mesh.GetFaceNormal(faceId,normalized)
2456 ## Returns an element based on all given nodes.
2457 # @ingroup l1_meshinfo
2458 def FindElementByNodes(self,nodes):
2459 return self.mesh.FindElementByNodes(nodes)
2461 ## Returns true if the given element is a polygon
2462 # @ingroup l1_meshinfo
2463 def IsPoly(self, id):
2464 return self.mesh.IsPoly(id)
2466 ## Returns true if the given element is quadratic
2467 # @ingroup l1_meshinfo
2468 def IsQuadratic(self, id):
2469 return self.mesh.IsQuadratic(id)
2471 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2472 # @ingroup l1_meshinfo
2473 def GetBallDiameter(self, id):
2474 return self.mesh.GetBallDiameter(id)
2476 ## Returns XYZ coordinates of the barycenter of the given element
2477 # \n If there is no element for the given ID - returns an empty list
2478 # @return a list of three double values
2479 # @ingroup l1_meshinfo
2480 def BaryCenter(self, id):
2481 return self.mesh.BaryCenter(id)
2483 ## Passes mesh elements through the given filter and return IDs of fitting elements
2484 # @param theFilter SMESH_Filter
2485 # @return a list of ids
2486 # @ingroup l1_controls
2487 def GetIdsFromFilter(self, theFilter):
2488 theFilter.SetMesh( self.mesh )
2489 return theFilter.GetIDs()
2491 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2492 # Returns a list of special structures (borders).
2493 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2494 # @ingroup l1_controls
2495 def GetFreeBorders(self):
2496 aFilterMgr = self.smeshpyD.CreateFilterManager()
2497 aPredicate = aFilterMgr.CreateFreeEdges()
2498 aPredicate.SetMesh(self.mesh)
2499 aBorders = aPredicate.GetBorders()
2500 aFilterMgr.UnRegister()
2504 # Get mesh measurements information:
2505 # ------------------------------------
2507 ## Get minimum distance between two nodes, elements or distance to the origin
2508 # @param id1 first node/element id
2509 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2510 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2511 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2512 # @return minimum distance value
2513 # @sa GetMinDistance()
2514 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2515 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2516 return aMeasure.value
2518 ## Get measure structure specifying minimum distance data between two objects
2519 # @param id1 first node/element id
2520 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2521 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2522 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2523 # @return Measure structure
2525 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2527 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2529 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2532 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2534 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2539 aMeasurements = self.smeshpyD.CreateMeasurements()
2540 aMeasure = aMeasurements.MinDistance(id1, id2)
2541 genObjUnRegister([aMeasurements,id1, id2])
2544 ## Get bounding box of the specified object(s)
2545 # @param objects single source object or list of source objects or list of nodes/elements IDs
2546 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2547 # @c False specifies that @a objects are nodes
2548 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2549 # @sa GetBoundingBox()
2550 def BoundingBox(self, objects=None, isElem=False):
2551 result = self.GetBoundingBox(objects, isElem)
2555 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2558 ## Get measure structure specifying bounding box data of the specified object(s)
2559 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2560 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2561 # @c False specifies that @a objects are nodes
2562 # @return Measure structure
2564 def GetBoundingBox(self, IDs=None, isElem=False):
2567 elif isinstance(IDs, tuple):
2569 if not isinstance(IDs, list):
2571 if len(IDs) > 0 and isinstance(IDs[0], int):
2574 unRegister = genObjUnRegister()
2576 if isinstance(o, Mesh):
2577 srclist.append(o.mesh)
2578 elif hasattr(o, "_narrow"):
2579 src = o._narrow(SMESH.SMESH_IDSource)
2580 if src: srclist.append(src)
2582 elif isinstance(o, list):
2584 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2586 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2587 unRegister.set( srclist[-1] )
2590 aMeasurements = self.smeshpyD.CreateMeasurements()
2591 unRegister.set( aMeasurements )
2592 aMeasure = aMeasurements.BoundingBox(srclist)
2595 # Mesh edition (SMESH_MeshEditor functionality):
2596 # ---------------------------------------------
2598 ## Removes the elements from the mesh by ids
2599 # @param IDsOfElements is a list of ids of elements to remove
2600 # @return True or False
2601 # @ingroup l2_modif_del
2602 def RemoveElements(self, IDsOfElements):
2603 return self.editor.RemoveElements(IDsOfElements)
2605 ## Removes nodes from mesh by ids
2606 # @param IDsOfNodes is a list of ids of nodes to remove
2607 # @return True or False
2608 # @ingroup l2_modif_del
2609 def RemoveNodes(self, IDsOfNodes):
2610 return self.editor.RemoveNodes(IDsOfNodes)
2612 ## Removes all orphan (free) nodes from mesh
2613 # @return number of the removed nodes
2614 # @ingroup l2_modif_del
2615 def RemoveOrphanNodes(self):
2616 return self.editor.RemoveOrphanNodes()
2618 ## Add a node to the mesh by coordinates
2619 # @return Id of the new node
2620 # @ingroup l2_modif_add
2621 def AddNode(self, x, y, z):
2622 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2623 if hasVars: self.mesh.SetParameters(Parameters)
2624 return self.editor.AddNode( x, y, z)
2626 ## Creates a 0D element on a node with given number.
2627 # @param IDOfNode the ID of node for creation of the element.
2628 # @return the Id of the new 0D element
2629 # @ingroup l2_modif_add
2630 def Add0DElement(self, IDOfNode):
2631 return self.editor.Add0DElement(IDOfNode)
2633 ## Create 0D elements on all nodes of the given elements except those
2634 # nodes on which a 0D element already exists.
2635 # @param theObject an object on whose nodes 0D elements will be created.
2636 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2637 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2638 # @param theGroupName optional name of a group to add 0D elements created
2639 # and/or found on nodes of \a theObject.
2640 # @return an object (a new group or a temporary SMESH_IDSource) holding
2641 # IDs of new and/or found 0D elements. IDs of 0D elements
2642 # can be retrieved from the returned object by calling GetIDs()
2643 # @ingroup l2_modif_add
2644 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2645 unRegister = genObjUnRegister()
2646 if isinstance( theObject, Mesh ):
2647 theObject = theObject.GetMesh()
2648 if isinstance( theObject, list ):
2649 theObject = self.GetIDSource( theObject, SMESH.ALL )
2650 unRegister.set( theObject )
2651 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2653 ## Creates a ball element on a node with given ID.
2654 # @param IDOfNode the ID of node for creation of the element.
2655 # @param diameter the bal diameter.
2656 # @return the Id of the new ball element
2657 # @ingroup l2_modif_add
2658 def AddBall(self, IDOfNode, diameter):
2659 return self.editor.AddBall( IDOfNode, diameter )
2661 ## Creates a linear or quadratic edge (this is determined
2662 # by the number of given nodes).
2663 # @param IDsOfNodes the list of node IDs for creation of the element.
2664 # The order of nodes in this list should correspond to the description
2665 # of MED. \n This description is located by the following link:
2666 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2667 # @return the Id of the new edge
2668 # @ingroup l2_modif_add
2669 def AddEdge(self, IDsOfNodes):
2670 return self.editor.AddEdge(IDsOfNodes)
2672 ## Creates a linear or quadratic face (this is determined
2673 # by the number of given nodes).
2674 # @param IDsOfNodes the list of node IDs for creation of the element.
2675 # The order of nodes in this list should correspond to the description
2676 # of MED. \n This description is located by the following link:
2677 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2678 # @return the Id of the new face
2679 # @ingroup l2_modif_add
2680 def AddFace(self, IDsOfNodes):
2681 return self.editor.AddFace(IDsOfNodes)
2683 ## Adds a polygonal face to the mesh by the list of node IDs
2684 # @param IdsOfNodes the list of node IDs for creation of the element.
2685 # @return the Id of the new face
2686 # @ingroup l2_modif_add
2687 def AddPolygonalFace(self, IdsOfNodes):
2688 return self.editor.AddPolygonalFace(IdsOfNodes)
2690 ## Creates both simple and quadratic volume (this is determined
2691 # by the number of given nodes).
2692 # @param IDsOfNodes the list of node IDs for creation of the element.
2693 # The order of nodes in this list should correspond to the description
2694 # of MED. \n This description is located by the following link:
2695 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2696 # @return the Id of the new volumic element
2697 # @ingroup l2_modif_add
2698 def AddVolume(self, IDsOfNodes):
2699 return self.editor.AddVolume(IDsOfNodes)
2701 ## Creates a volume of many faces, giving nodes for each face.
2702 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2703 # @param Quantities the list of integer values, Quantities[i]
2704 # gives the quantity of nodes in face number i.
2705 # @return the Id of the new volumic element
2706 # @ingroup l2_modif_add
2707 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2708 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2710 ## Creates a volume of many faces, giving the IDs of the existing faces.
2711 # @param IdsOfFaces the list of face IDs for volume creation.
2713 # Note: The created volume will refer only to the nodes
2714 # of the given faces, not to the faces themselves.
2715 # @return the Id of the new volumic element
2716 # @ingroup l2_modif_add
2717 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2718 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2721 ## @brief Binds a node to a vertex
2722 # @param NodeID a node ID
2723 # @param Vertex a vertex or vertex ID
2724 # @return True if succeed else raises an exception
2725 # @ingroup l2_modif_add
2726 def SetNodeOnVertex(self, NodeID, Vertex):
2727 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2728 VertexID = Vertex.GetSubShapeIndices()[0]
2732 self.editor.SetNodeOnVertex(NodeID, VertexID)
2733 except SALOME.SALOME_Exception, inst:
2734 raise ValueError, inst.details.text
2738 ## @brief Stores the node position on an edge
2739 # @param NodeID a node ID
2740 # @param Edge an edge or edge ID
2741 # @param paramOnEdge a parameter on the edge where the node is located
2742 # @return True if succeed else raises an exception
2743 # @ingroup l2_modif_add
2744 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2745 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2746 EdgeID = Edge.GetSubShapeIndices()[0]
2750 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2751 except SALOME.SALOME_Exception, inst:
2752 raise ValueError, inst.details.text
2755 ## @brief Stores node position on a face
2756 # @param NodeID a node ID
2757 # @param Face a face or face ID
2758 # @param u U parameter on the face where the node is located
2759 # @param v V parameter on the face where the node is located
2760 # @return True if succeed else raises an exception
2761 # @ingroup l2_modif_add
2762 def SetNodeOnFace(self, NodeID, Face, u, v):
2763 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2764 FaceID = Face.GetSubShapeIndices()[0]
2768 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2769 except SALOME.SALOME_Exception, inst:
2770 raise ValueError, inst.details.text
2773 ## @brief Binds a node to a solid
2774 # @param NodeID a node ID
2775 # @param Solid a solid or solid ID
2776 # @return True if succeed else raises an exception
2777 # @ingroup l2_modif_add
2778 def SetNodeInVolume(self, NodeID, Solid):
2779 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2780 SolidID = Solid.GetSubShapeIndices()[0]
2784 self.editor.SetNodeInVolume(NodeID, SolidID)
2785 except SALOME.SALOME_Exception, inst:
2786 raise ValueError, inst.details.text
2789 ## @brief Bind an element to a shape
2790 # @param ElementID an element ID
2791 # @param Shape a shape or shape ID
2792 # @return True if succeed else raises an exception
2793 # @ingroup l2_modif_add
2794 def SetMeshElementOnShape(self, ElementID, Shape):
2795 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2796 ShapeID = Shape.GetSubShapeIndices()[0]
2800 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2801 except SALOME.SALOME_Exception, inst:
2802 raise ValueError, inst.details.text
2806 ## Moves the node with the given id
2807 # @param NodeID the id of the node
2808 # @param x a new X coordinate
2809 # @param y a new Y coordinate
2810 # @param z a new Z coordinate
2811 # @return True if succeed else False
2812 # @ingroup l2_modif_movenode
2813 def MoveNode(self, NodeID, x, y, z):
2814 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2815 if hasVars: self.mesh.SetParameters(Parameters)
2816 return self.editor.MoveNode(NodeID, x, y, z)
2818 ## Finds the node closest to a point and moves it to a point location
2819 # @param x the X coordinate of a point
2820 # @param y the Y coordinate of a point
2821 # @param z the Z coordinate of a point
2822 # @param NodeID if specified (>0), the node with this ID is moved,
2823 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
2824 # @return the ID of a node
2825 # @ingroup l2_modif_throughp
2826 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2827 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2828 if hasVars: self.mesh.SetParameters(Parameters)
2829 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2831 ## Finds the node closest to a point
2832 # @param x the X coordinate of a point
2833 # @param y the Y coordinate of a point
2834 # @param z the Z coordinate of a point
2835 # @return the ID of a node
2836 # @ingroup l2_modif_throughp
2837 def FindNodeClosestTo(self, x, y, z):
2838 #preview = self.mesh.GetMeshEditPreviewer()
2839 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2840 return self.editor.FindNodeClosestTo(x, y, z)
2842 ## Finds the elements where a point lays IN or ON
2843 # @param x the X coordinate of a point
2844 # @param y the Y coordinate of a point
2845 # @param z the Z coordinate of a point
2846 # @param elementType type of elements to find (SMESH.ALL type
2847 # means elements of any type excluding nodes, discrete and 0D elements)
2848 # @param meshPart a part of mesh (group, sub-mesh) to search within
2849 # @return list of IDs of found elements
2850 # @ingroup l2_modif_throughp
2851 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2853 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2855 return self.editor.FindElementsByPoint(x, y, z, elementType)
2857 # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2858 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2859 # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2861 def GetPointState(self, x, y, z):
2862 return self.editor.GetPointState(x, y, z)
2864 ## Finds the node closest to a point and moves it to a point location
2865 # @param x the X coordinate of a point
2866 # @param y the Y coordinate of a point
2867 # @param z the Z coordinate of a point
2868 # @return the ID of a moved node
2869 # @ingroup l2_modif_throughp
2870 def MeshToPassThroughAPoint(self, x, y, z):
2871 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2873 ## Replaces two neighbour triangles sharing Node1-Node2 link
2874 # with the triangles built on the same 4 nodes but having other common link.
2875 # @param NodeID1 the ID of the first node
2876 # @param NodeID2 the ID of the second node
2877 # @return false if proper faces were not found
2878 # @ingroup l2_modif_invdiag
2879 def InverseDiag(self, NodeID1, NodeID2):
2880 return self.editor.InverseDiag(NodeID1, NodeID2)
2882 ## Replaces two neighbour triangles sharing Node1-Node2 link
2883 # with a quadrangle built on the same 4 nodes.
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_unitetri
2888 def DeleteDiag(self, NodeID1, NodeID2):
2889 return self.editor.DeleteDiag(NodeID1, NodeID2)
2891 ## Reorients elements by ids
2892 # @param IDsOfElements if undefined reorients all mesh elements
2893 # @return True if succeed else False
2894 # @ingroup l2_modif_changori
2895 def Reorient(self, IDsOfElements=None):
2896 if IDsOfElements == None:
2897 IDsOfElements = self.GetElementsId()
2898 return self.editor.Reorient(IDsOfElements)
2900 ## Reorients all elements of the object
2901 # @param theObject mesh, submesh or group
2902 # @return True if succeed else False
2903 # @ingroup l2_modif_changori
2904 def ReorientObject(self, theObject):
2905 if ( isinstance( theObject, Mesh )):
2906 theObject = theObject.GetMesh()
2907 return self.editor.ReorientObject(theObject)
2909 ## Reorient faces contained in \a the2DObject.
2910 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2911 # @param theDirection is a desired direction of normal of \a theFace.
2912 # It can be either a GEOM vector or a list of coordinates [x,y,z].
2913 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2914 # compared with theDirection. It can be either ID of face or a point
2915 # by which the face will be found. The point can be given as either
2916 # a GEOM vertex or a list of point coordinates.
2917 # @return number of reoriented faces
2918 # @ingroup l2_modif_changori
2919 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2920 unRegister = genObjUnRegister()
2922 if isinstance( the2DObject, Mesh ):
2923 the2DObject = the2DObject.GetMesh()
2924 if isinstance( the2DObject, list ):
2925 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2926 unRegister.set( the2DObject )
2927 # check theDirection
2928 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
2929 theDirection = self.smeshpyD.GetDirStruct( theDirection )
2930 if isinstance( theDirection, list ):
2931 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
2932 # prepare theFace and thePoint
2933 theFace = theFaceOrPoint
2934 thePoint = PointStruct(0,0,0)
2935 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
2936 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
2938 if isinstance( theFaceOrPoint, list ):
2939 thePoint = PointStruct( *theFaceOrPoint )
2941 if isinstance( theFaceOrPoint, PointStruct ):
2942 thePoint = theFaceOrPoint
2944 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
2946 ## Fuses the neighbouring triangles into quadrangles.
2947 # @param IDsOfElements The triangles to be fused,
2948 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2949 # choose a neighbour to fuse with.
2950 # @param MaxAngle is the maximum angle between element normals at which the fusion
2951 # is still performed; theMaxAngle is mesured in radians.
2952 # Also it could be a name of variable which defines angle in degrees.
2953 # @return TRUE in case of success, FALSE otherwise.
2954 # @ingroup l2_modif_unitetri
2955 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
2956 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2957 self.mesh.SetParameters(Parameters)
2958 if not IDsOfElements:
2959 IDsOfElements = self.GetElementsId()
2960 Functor = self.smeshpyD.GetFunctor(theCriterion)
2961 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
2963 ## Fuses the neighbouring triangles of the object into quadrangles
2964 # @param theObject is mesh, submesh or group
2965 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2966 # choose a neighbour to fuse with.
2967 # @param MaxAngle a max angle between element normals at which the fusion
2968 # is still performed; theMaxAngle is mesured in radians.
2969 # @return TRUE in case of success, FALSE otherwise.
2970 # @ingroup l2_modif_unitetri
2971 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
2972 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2973 self.mesh.SetParameters(Parameters)
2974 if isinstance( theObject, Mesh ):
2975 theObject = theObject.GetMesh()
2976 Functor = self.smeshpyD.GetFunctor(theCriterion)
2977 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
2979 ## Splits quadrangles into triangles.
2980 # @param IDsOfElements the faces to be splitted.
2981 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2982 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
2983 # value, then quadrangles will be split by the smallest diagonal.
2984 # @return TRUE in case of success, FALSE otherwise.
2985 # @ingroup l2_modif_cutquadr
2986 def QuadToTri (self, IDsOfElements, theCriterion = None):
2987 if IDsOfElements == []:
2988 IDsOfElements = self.GetElementsId()
2989 if theCriterion is None:
2990 theCriterion = FT_MaxElementLength2D
2991 Functor = self.smeshpyD.GetFunctor(theCriterion)
2992 return self.editor.QuadToTri(IDsOfElements, Functor)
2994 ## Splits quadrangles into triangles.
2995 # @param theObject the object from which the list of elements is taken,
2996 # this is mesh, submesh or group
2997 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2998 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
2999 # value, then quadrangles will be split by the smallest diagonal.
3000 # @return TRUE in case of success, FALSE otherwise.
3001 # @ingroup l2_modif_cutquadr
3002 def QuadToTriObject (self, theObject, theCriterion = None):
3003 if ( isinstance( theObject, Mesh )):
3004 theObject = theObject.GetMesh()
3005 if theCriterion is None:
3006 theCriterion = FT_MaxElementLength2D
3007 Functor = self.smeshpyD.GetFunctor(theCriterion)
3008 return self.editor.QuadToTriObject(theObject, Functor)
3010 ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3012 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3013 # group or a list of face IDs. By default all quadrangles are split
3014 # @ingroup l2_modif_cutquadr
3015 def QuadTo4Tri (self, theElements=[]):
3016 unRegister = genObjUnRegister()
3017 if isinstance( theElements, Mesh ):
3018 theElements = theElements.mesh
3019 elif not theElements:
3020 theElements = self.mesh
3021 elif isinstance( theElements, list ):
3022 theElements = self.GetIDSource( theElements, SMESH.FACE )
3023 unRegister.set( theElements )
3024 return self.editor.QuadTo4Tri( theElements )
3026 ## Splits quadrangles into triangles.
3027 # @param IDsOfElements the faces to be splitted
3028 # @param Diag13 is used to choose a diagonal for splitting.
3029 # @return TRUE in case of success, FALSE otherwise.
3030 # @ingroup l2_modif_cutquadr
3031 def SplitQuad (self, IDsOfElements, Diag13):
3032 if IDsOfElements == []:
3033 IDsOfElements = self.GetElementsId()
3034 return self.editor.SplitQuad(IDsOfElements, Diag13)
3036 ## Splits quadrangles into triangles.
3037 # @param theObject the object from which the list of elements is taken,
3038 # this is mesh, submesh or group
3039 # @param Diag13 is used to choose a diagonal for splitting.
3040 # @return TRUE in case of success, FALSE otherwise.
3041 # @ingroup l2_modif_cutquadr
3042 def SplitQuadObject (self, theObject, Diag13):
3043 if ( isinstance( theObject, Mesh )):
3044 theObject = theObject.GetMesh()
3045 return self.editor.SplitQuadObject(theObject, Diag13)
3047 ## Finds a better splitting of the given quadrangle.
3048 # @param IDOfQuad the ID of the quadrangle to be splitted.
3049 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3050 # choose a diagonal for splitting.
3051 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3052 # diagonal is better, 0 if error occurs.
3053 # @ingroup l2_modif_cutquadr
3054 def BestSplit (self, IDOfQuad, theCriterion):
3055 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3057 ## Splits volumic elements into tetrahedrons
3058 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3059 # @param method flags passing splitting method:
3060 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3061 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3062 # @ingroup l2_modif_cutquadr
3063 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3064 unRegister = genObjUnRegister()
3065 if isinstance( elems, Mesh ):
3066 elems = elems.GetMesh()
3067 if ( isinstance( elems, list )):
3068 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3069 unRegister.set( elems )
3070 self.editor.SplitVolumesIntoTetra(elems, method)
3072 ## Splits hexahedra into prisms
3073 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3074 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3075 # gives a normal vector defining facets to split into triangles.
3076 # @a startHexPoint can be either a triple of coordinates or a vertex.
3077 # @param facetNormal a normal to a facet to split into triangles of a
3078 # hexahedron found by @a startHexPoint.
3079 # @a facetNormal can be either a triple of coordinates or an edge.
3080 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3081 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3082 # @param allDomains if @c False, only hexahedra adjacent to one closest
3083 # to @a startHexPoint are split, else @a startHexPoint
3084 # is used to find the facet to split in all domains present in @a elems.
3085 # @ingroup l2_modif_cutquadr
3086 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3087 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3089 unRegister = genObjUnRegister()
3090 if isinstance( elems, Mesh ):
3091 elems = elems.GetMesh()
3092 if ( isinstance( elems, list )):
3093 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3094 unRegister.set( elems )
3097 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3098 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3099 elif isinstance( startHexPoint, list ):
3100 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3103 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3104 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3105 elif isinstance( facetNormal, list ):
3106 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3109 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3111 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3113 ## Splits quadrangle faces near triangular facets of volumes
3115 # @ingroup l1_auxiliary
3116 def SplitQuadsNearTriangularFacets(self):
3117 faces_array = self.GetElementsByType(SMESH.FACE)
3118 for face_id in faces_array:
3119 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3120 quad_nodes = self.mesh.GetElemNodes(face_id)
3121 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3122 isVolumeFound = False
3123 for node1_elem in node1_elems:
3124 if not isVolumeFound:
3125 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3126 nb_nodes = self.GetElemNbNodes(node1_elem)
3127 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3128 volume_elem = node1_elem
3129 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3130 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3131 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3132 isVolumeFound = True
3133 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3134 self.SplitQuad([face_id], False) # diagonal 2-4
3135 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3136 isVolumeFound = True
3137 self.SplitQuad([face_id], True) # diagonal 1-3
3138 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3139 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3140 isVolumeFound = True
3141 self.SplitQuad([face_id], True) # diagonal 1-3
3143 ## @brief Splits hexahedrons into tetrahedrons.
3145 # This operation uses pattern mapping functionality for splitting.
3146 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3147 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3148 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3149 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3150 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3151 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3152 # @return TRUE in case of success, FALSE otherwise.
3153 # @ingroup l1_auxiliary
3154 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3155 # Pattern: 5.---------.6
3160 # (0,0,1) 4.---------.7 * |
3167 # (0,0,0) 0.---------.3
3168 pattern_tetra = "!!! Nb of points: \n 8 \n\
3178 !!! Indices of points of 6 tetras: \n\
3186 pattern = self.smeshpyD.GetPattern()
3187 isDone = pattern.LoadFromFile(pattern_tetra)
3189 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3192 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3193 isDone = pattern.MakeMesh(self.mesh, False, False)
3194 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3196 # split quafrangle faces near triangular facets of volumes
3197 self.SplitQuadsNearTriangularFacets()
3201 ## @brief Split hexahedrons into prisms.
3203 # Uses the pattern mapping functionality for splitting.
3204 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3205 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3206 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3207 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3208 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3209 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3210 # @return TRUE in case of success, FALSE otherwise.
3211 # @ingroup l1_auxiliary
3212 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3213 # Pattern: 5.---------.6
3218 # (0,0,1) 4.---------.7 |
3225 # (0,0,0) 0.---------.3
3226 pattern_prism = "!!! Nb of points: \n 8 \n\
3236 !!! Indices of points of 2 prisms: \n\
3240 pattern = self.smeshpyD.GetPattern()
3241 isDone = pattern.LoadFromFile(pattern_prism)
3243 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3246 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3247 isDone = pattern.MakeMesh(self.mesh, False, False)
3248 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3250 # Splits quafrangle faces near triangular facets of volumes
3251 self.SplitQuadsNearTriangularFacets()
3255 ## Smoothes elements
3256 # @param IDsOfElements the list if ids of elements to smooth
3257 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3258 # Note that nodes built on edges and boundary nodes are always fixed.
3259 # @param MaxNbOfIterations the maximum number of iterations
3260 # @param MaxAspectRatio varies in range [1.0, inf]
3261 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3262 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3263 # @return TRUE in case of success, FALSE otherwise.
3264 # @ingroup l2_modif_smooth
3265 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3266 MaxNbOfIterations, MaxAspectRatio, Method):
3267 if IDsOfElements == []:
3268 IDsOfElements = self.GetElementsId()
3269 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3270 self.mesh.SetParameters(Parameters)
3271 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3272 MaxNbOfIterations, MaxAspectRatio, Method)
3274 ## Smoothes elements which belong to the given object
3275 # @param theObject the object to smooth
3276 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3277 # Note that nodes built on edges and boundary nodes are always fixed.
3278 # @param MaxNbOfIterations the maximum number of iterations
3279 # @param MaxAspectRatio varies in range [1.0, inf]
3280 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3281 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3282 # @return TRUE in case of success, FALSE otherwise.
3283 # @ingroup l2_modif_smooth
3284 def SmoothObject(self, theObject, IDsOfFixedNodes,
3285 MaxNbOfIterations, MaxAspectRatio, Method):
3286 if ( isinstance( theObject, Mesh )):
3287 theObject = theObject.GetMesh()
3288 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3289 MaxNbOfIterations, MaxAspectRatio, Method)
3291 ## Parametrically smoothes the given elements
3292 # @param IDsOfElements the list if ids of elements to smooth
3293 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3294 # Note that nodes built on edges and boundary nodes are always fixed.
3295 # @param MaxNbOfIterations the maximum number of iterations
3296 # @param MaxAspectRatio varies in range [1.0, inf]
3297 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3298 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3299 # @return TRUE in case of success, FALSE otherwise.
3300 # @ingroup l2_modif_smooth
3301 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3302 MaxNbOfIterations, MaxAspectRatio, Method):
3303 if IDsOfElements == []:
3304 IDsOfElements = self.GetElementsId()
3305 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3306 self.mesh.SetParameters(Parameters)
3307 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3308 MaxNbOfIterations, MaxAspectRatio, Method)
3310 ## Parametrically smoothes the elements which belong to the given object
3311 # @param theObject the object to smooth
3312 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3313 # Note that nodes built on edges and boundary nodes are always fixed.
3314 # @param MaxNbOfIterations the maximum number of iterations
3315 # @param MaxAspectRatio varies in range [1.0, inf]
3316 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3317 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3318 # @return TRUE in case of success, FALSE otherwise.
3319 # @ingroup l2_modif_smooth
3320 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3321 MaxNbOfIterations, MaxAspectRatio, Method):
3322 if ( isinstance( theObject, Mesh )):
3323 theObject = theObject.GetMesh()
3324 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3325 MaxNbOfIterations, MaxAspectRatio, Method)
3327 ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3328 # them with quadratic with the same id.
3329 # @param theForce3d new node creation method:
3330 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3331 # 1 - the medium node lies at the middle of the line segments connecting start and end node of a mesh element
3332 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3333 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3334 # @ingroup l2_modif_tofromqu
3335 def ConvertToQuadratic(self, theForce3d, theSubMesh=None, theToBiQuad=False):
3336 if isinstance( theSubMesh, Mesh ):
3337 theSubMesh = theSubMesh.mesh
3339 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3342 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3344 self.editor.ConvertToQuadratic(theForce3d)
3345 error = self.editor.GetLastError()
3346 if error and error.comment:
3349 ## Converts the mesh from quadratic to ordinary,
3350 # deletes old quadratic elements, \n replacing
3351 # them with ordinary mesh elements with the same id.
3352 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3353 # @ingroup l2_modif_tofromqu
3354 def ConvertFromQuadratic(self, theSubMesh=None):
3356 self.editor.ConvertFromQuadraticObject(theSubMesh)
3358 return self.editor.ConvertFromQuadratic()
3360 ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3361 # @return TRUE if operation has been completed successfully, FALSE otherwise
3362 # @ingroup l2_modif_edit
3363 def Make2DMeshFrom3D(self):
3364 return self.editor. Make2DMeshFrom3D()
3366 ## Creates missing boundary elements
3367 # @param elements - elements whose boundary is to be checked:
3368 # mesh, group, sub-mesh or list of elements
3369 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3370 # @param dimension - defines type of boundary elements to create:
3371 # SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D
3372 # SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3373 # @param groupName - a name of group to store created boundary elements in,
3374 # "" means not to create the group
3375 # @param meshName - a name of new mesh to store created boundary elements in,
3376 # "" means not to create the new mesh
3377 # @param toCopyElements - if true, the checked elements will be copied into
3378 # the new mesh else only boundary elements will be copied into the new mesh
3379 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3380 # boundary elements will be copied into the new mesh
3381 # @return tuple (mesh, group) where boundary elements were added to
3382 # @ingroup l2_modif_edit
3383 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3384 toCopyElements=False, toCopyExistingBondary=False):
3385 unRegister = genObjUnRegister()
3386 if isinstance( elements, Mesh ):
3387 elements = elements.GetMesh()
3388 if ( isinstance( elements, list )):
3389 elemType = SMESH.ALL
3390 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3391 elements = self.editor.MakeIDSource(elements, elemType)
3392 unRegister.set( elements )
3393 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3394 toCopyElements,toCopyExistingBondary)
3395 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3399 # @brief Creates missing boundary elements around either the whole mesh or
3400 # groups of 2D elements
3401 # @param dimension - defines type of boundary elements to create
3402 # @param groupName - a name of group to store all boundary elements in,
3403 # "" means not to create the group
3404 # @param meshName - a name of a new mesh, which is a copy of the initial
3405 # mesh + created boundary elements; "" means not to create the new mesh
3406 # @param toCopyAll - if true, the whole initial mesh will be copied into
3407 # the new mesh else only boundary elements will be copied into the new mesh
3408 # @param groups - groups of 2D elements to make boundary around
3409 # @retval tuple( long, mesh, groups )
3410 # long - number of added boundary elements
3411 # mesh - the mesh where elements were added to
3412 # group - the group of boundary elements or None
3414 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3415 toCopyAll=False, groups=[]):
3416 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3418 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3419 return nb, mesh, group
3421 ## Renumber mesh nodes
3422 # @ingroup l2_modif_renumber
3423 def RenumberNodes(self):
3424 self.editor.RenumberNodes()
3426 ## Renumber mesh elements
3427 # @ingroup l2_modif_renumber
3428 def RenumberElements(self):
3429 self.editor.RenumberElements()
3431 ## Generates new elements by rotation of the elements around the axis
3432 # @param IDsOfElements the list of ids of elements to sweep
3433 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3434 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3435 # @param NbOfSteps the number of steps
3436 # @param Tolerance tolerance
3437 # @param MakeGroups forces the generation of new groups from existing ones
3438 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3439 # of all steps, else - size of each step
3440 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3441 # @ingroup l2_modif_extrurev
3442 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3443 MakeGroups=False, TotalAngle=False):
3444 if IDsOfElements == []:
3445 IDsOfElements = self.GetElementsId()
3446 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3447 Axis = self.smeshpyD.GetAxisStruct(Axis)
3448 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3449 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3450 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3451 self.mesh.SetParameters(Parameters)
3452 if TotalAngle and NbOfSteps:
3453 AngleInRadians /= NbOfSteps
3455 return self.editor.RotationSweepMakeGroups(IDsOfElements, Axis,
3456 AngleInRadians, NbOfSteps, Tolerance)
3457 self.editor.RotationSweep(IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance)
3460 ## Generates new elements by rotation of the elements of object around the axis
3461 # @param theObject object which elements should be sweeped.
3462 # It can be a mesh, a sub mesh or a group.
3463 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3464 # @param AngleInRadians the angle of Rotation
3465 # @param NbOfSteps number of steps
3466 # @param Tolerance tolerance
3467 # @param MakeGroups forces the generation of new groups from existing ones
3468 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3469 # of all steps, else - size of each step
3470 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3471 # @ingroup l2_modif_extrurev
3472 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3473 MakeGroups=False, TotalAngle=False):
3474 if ( isinstance( theObject, Mesh )):
3475 theObject = theObject.GetMesh()
3476 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3477 Axis = self.smeshpyD.GetAxisStruct(Axis)
3478 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3479 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3480 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3481 self.mesh.SetParameters(Parameters)
3482 if TotalAngle and NbOfSteps:
3483 AngleInRadians /= NbOfSteps
3485 return self.editor.RotationSweepObjectMakeGroups(theObject, Axis, AngleInRadians,
3486 NbOfSteps, Tolerance)
3487 self.editor.RotationSweepObject(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3490 ## Generates new elements by rotation of the elements of object around the axis
3491 # @param theObject object which elements should be sweeped.
3492 # It can be a mesh, a sub mesh or a group.
3493 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3494 # @param AngleInRadians the angle of Rotation
3495 # @param NbOfSteps number of steps
3496 # @param Tolerance tolerance
3497 # @param MakeGroups forces the generation of new groups from existing ones
3498 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3499 # of all steps, else - size of each step
3500 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3501 # @ingroup l2_modif_extrurev
3502 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3503 MakeGroups=False, TotalAngle=False):
3504 if ( isinstance( theObject, Mesh )):
3505 theObject = theObject.GetMesh()
3506 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3507 Axis = self.smeshpyD.GetAxisStruct(Axis)
3508 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3509 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3510 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3511 self.mesh.SetParameters(Parameters)
3512 if TotalAngle and NbOfSteps:
3513 AngleInRadians /= NbOfSteps
3515 return self.editor.RotationSweepObject1DMakeGroups(theObject, Axis, AngleInRadians,
3516 NbOfSteps, Tolerance)
3517 self.editor.RotationSweepObject1D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3520 ## Generates new elements by rotation of the elements of object around the axis
3521 # @param theObject object which elements should be sweeped.
3522 # It can be a mesh, a sub mesh or a group.
3523 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3524 # @param AngleInRadians the angle of Rotation
3525 # @param NbOfSteps number of steps
3526 # @param Tolerance tolerance
3527 # @param MakeGroups forces the generation of new groups from existing ones
3528 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3529 # of all steps, else - size of each step
3530 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3531 # @ingroup l2_modif_extrurev
3532 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3533 MakeGroups=False, TotalAngle=False):
3534 if ( isinstance( theObject, Mesh )):
3535 theObject = theObject.GetMesh()
3536 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3537 Axis = self.smeshpyD.GetAxisStruct(Axis)
3538 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3539 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3540 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3541 self.mesh.SetParameters(Parameters)
3542 if TotalAngle and NbOfSteps:
3543 AngleInRadians /= NbOfSteps
3545 return self.editor.RotationSweepObject2DMakeGroups(theObject, Axis, AngleInRadians,
3546 NbOfSteps, Tolerance)
3547 self.editor.RotationSweepObject2D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3550 ## Generates new elements by extrusion of the elements with given ids
3551 # @param IDsOfElements the list of elements ids for extrusion
3552 # @param StepVector vector or DirStruct or 3 vector components, defining
3553 # the direction and value of extrusion for one step (the total extrusion
3554 # length will be NbOfSteps * ||StepVector||)
3555 # @param NbOfSteps the number of steps
3556 # @param MakeGroups forces the generation of new groups from existing ones
3557 # @param IsNodes is True if elements with given ids are nodes
3558 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3559 # @ingroup l2_modif_extrurev
3560 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3561 if IDsOfElements == []:
3562 IDsOfElements = self.GetElementsId()
3563 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3564 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3565 if isinstance( StepVector, list ):
3566 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3567 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3568 Parameters = StepVector.PS.parameters + var_separator + Parameters
3569 self.mesh.SetParameters(Parameters)
3572 return self.editor.ExtrusionSweepMakeGroups0D(IDsOfElements, StepVector, NbOfSteps)
3574 return self.editor.ExtrusionSweepMakeGroups(IDsOfElements, StepVector, NbOfSteps)
3576 self.editor.ExtrusionSweep0D(IDsOfElements, StepVector, NbOfSteps)
3578 self.editor.ExtrusionSweep(IDsOfElements, StepVector, NbOfSteps)
3581 ## Generates new elements by extrusion of the elements with given ids
3582 # @param IDsOfElements is ids of elements
3583 # @param StepVector vector or DirStruct or 3 vector components, defining
3584 # the direction and value of extrusion for one step (the total extrusion
3585 # length will be NbOfSteps * ||StepVector||)
3586 # @param NbOfSteps the number of steps
3587 # @param ExtrFlags sets flags for extrusion
3588 # @param SewTolerance uses for comparing locations of nodes if flag
3589 # EXTRUSION_FLAG_SEW is set
3590 # @param MakeGroups forces the generation of new groups from existing ones
3591 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3592 # @ingroup l2_modif_extrurev
3593 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3594 ExtrFlags, SewTolerance, MakeGroups=False):
3595 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3596 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3597 if isinstance( StepVector, list ):
3598 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3600 return self.editor.AdvancedExtrusionMakeGroups(IDsOfElements, StepVector, NbOfSteps,
3601 ExtrFlags, SewTolerance)
3602 self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3603 ExtrFlags, SewTolerance)
3606 ## Generates new elements by extrusion of the elements which belong to the object
3607 # @param theObject the object which elements should be processed.
3608 # It can be a mesh, a sub mesh or a group.
3609 # @param StepVector vector or DirStruct or 3 vector components, defining
3610 # the direction and value of extrusion for one step (the total extrusion
3611 # length will be NbOfSteps * ||StepVector||)
3612 # @param NbOfSteps the number of steps
3613 # @param MakeGroups forces the generation of new groups from existing ones
3614 # @param IsNodes is True if elements which belong to the object are nodes
3615 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3616 # @ingroup l2_modif_extrurev
3617 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3618 if ( isinstance( theObject, Mesh )):
3619 theObject = theObject.GetMesh()
3620 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3621 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3622 if isinstance( StepVector, list ):
3623 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3624 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3625 Parameters = StepVector.PS.parameters + var_separator + Parameters
3626 self.mesh.SetParameters(Parameters)
3629 return self.editor.ExtrusionSweepObject0DMakeGroups(theObject, StepVector, NbOfSteps)
3631 return self.editor.ExtrusionSweepObjectMakeGroups(theObject, StepVector, NbOfSteps)
3633 self.editor.ExtrusionSweepObject0D(theObject, StepVector, NbOfSteps)
3635 self.editor.ExtrusionSweepObject(theObject, StepVector, NbOfSteps)
3638 ## Generates new elements by extrusion of the elements which belong to the object
3639 # @param theObject object which elements should be processed.
3640 # It can be a mesh, a sub mesh or a group.
3641 # @param StepVector vector or DirStruct or 3 vector components, defining
3642 # the direction and value of extrusion for one step (the total extrusion
3643 # length will be NbOfSteps * ||StepVector||)
3644 # @param NbOfSteps the number of steps
3645 # @param MakeGroups to generate new groups from existing ones
3646 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3647 # @ingroup l2_modif_extrurev
3648 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3649 if ( isinstance( theObject, Mesh )):
3650 theObject = theObject.GetMesh()
3651 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3652 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3653 if isinstance( StepVector, list ):
3654 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3655 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3656 Parameters = StepVector.PS.parameters + var_separator + Parameters
3657 self.mesh.SetParameters(Parameters)
3659 return self.editor.ExtrusionSweepObject1DMakeGroups(theObject, StepVector, NbOfSteps)
3660 self.editor.ExtrusionSweepObject1D(theObject, StepVector, NbOfSteps)
3663 ## Generates new elements by extrusion of the elements which belong to the object
3664 # @param theObject object which elements should be processed.
3665 # It can be a mesh, a sub mesh or a group.
3666 # @param StepVector vector or DirStruct or 3 vector components, defining
3667 # the direction and value of extrusion for one step (the total extrusion
3668 # length will be NbOfSteps * ||StepVector||)
3669 # @param NbOfSteps the number of steps
3670 # @param MakeGroups forces the generation of new groups from existing ones
3671 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3672 # @ingroup l2_modif_extrurev
3673 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3674 if ( isinstance( theObject, Mesh )):
3675 theObject = theObject.GetMesh()
3676 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3677 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3678 if isinstance( StepVector, list ):
3679 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3680 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3681 Parameters = StepVector.PS.parameters + var_separator + Parameters
3682 self.mesh.SetParameters(Parameters)
3684 return self.editor.ExtrusionSweepObject2DMakeGroups(theObject, StepVector, NbOfSteps)
3685 self.editor.ExtrusionSweepObject2D(theObject, StepVector, NbOfSteps)
3690 ## Generates new elements by extrusion of the given elements
3691 # The path of extrusion must be a meshed edge.
3692 # @param Base mesh or group, or submesh, or list of ids of elements for extrusion
3693 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3694 # @param NodeStart the start node from Path. Defines the direction of extrusion
3695 # @param HasAngles allows the shape to be rotated around the path
3696 # to get the resulting mesh in a helical fashion
3697 # @param Angles list of angles in radians
3698 # @param LinearVariation forces the computation of rotation angles as linear
3699 # variation of the given Angles along path steps
3700 # @param HasRefPoint allows using the reference point
3701 # @param RefPoint the point around which the elements are rotated (the mass
3702 # center of the elements by default).
3703 # The User can specify any point as the Reference Point.
3704 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
3705 # @param MakeGroups forces the generation of new groups from existing ones
3706 # @param ElemType type of elements for extrusion (if param Base is a mesh)
3707 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3708 # only SMESH::Extrusion_Error otherwise
3709 # @ingroup l2_modif_extrurev
3710 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
3711 HasAngles, Angles, LinearVariation,
3712 HasRefPoint, RefPoint, MakeGroups, ElemType):
3713 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3714 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3716 elif isinstance( RefPoint, list ):
3717 RefPoint = PointStruct(*RefPoint)
3719 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3720 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3721 self.mesh.SetParameters(Parameters)
3723 if (isinstance(Path, Mesh)): Path = Path.GetMesh()
3725 if isinstance(Base, list):
3727 if Base == []: IDsOfElements = self.GetElementsId()
3728 else: IDsOfElements = Base
3729 return self.editor.ExtrusionAlongPathX(IDsOfElements, Path, NodeStart,
3730 HasAngles, Angles, LinearVariation,
3731 HasRefPoint, RefPoint, MakeGroups, ElemType)
3733 if isinstance(Base, Mesh): Base = Base.GetMesh()
3734 if isinstance(Base, SMESH._objref_SMESH_Mesh) or isinstance(Base, SMESH._objref_SMESH_Group) or isinstance(Base, SMESH._objref_SMESH_subMesh):
3735 return self.editor.ExtrusionAlongPathObjX(Base, Path, NodeStart,
3736 HasAngles, Angles, LinearVariation,
3737 HasRefPoint, RefPoint, MakeGroups, ElemType)
3739 raise RuntimeError, "Invalid Base for ExtrusionAlongPathX"
3742 ## Generates new elements by extrusion of the given elements
3743 # The path of extrusion must be a meshed edge.
3744 # @param IDsOfElements ids of elements
3745 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
3746 # @param PathShape shape(edge) defines the sub-mesh for the path
3747 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3748 # @param HasAngles allows the shape to be rotated around the path
3749 # to get the resulting mesh in a helical fashion
3750 # @param Angles list of angles in radians
3751 # @param HasRefPoint allows using the reference point
3752 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3753 # The User can specify any point as the Reference Point.
3754 # @param MakeGroups forces the generation of new groups from existing ones
3755 # @param LinearVariation forces the computation of rotation angles as linear
3756 # variation of the given Angles along path steps
3757 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3758 # only SMESH::Extrusion_Error otherwise
3759 # @ingroup l2_modif_extrurev
3760 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
3761 HasAngles, Angles, HasRefPoint, RefPoint,
3762 MakeGroups=False, LinearVariation=False):
3763 if IDsOfElements == []:
3764 IDsOfElements = self.GetElementsId()
3765 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3766 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3768 if ( isinstance( PathMesh, Mesh )):
3769 PathMesh = PathMesh.GetMesh()
3770 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3771 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3772 self.mesh.SetParameters(Parameters)
3773 if HasAngles and Angles and LinearVariation:
3774 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3777 return self.editor.ExtrusionAlongPathMakeGroups(IDsOfElements, PathMesh,
3778 PathShape, NodeStart, HasAngles,
3779 Angles, HasRefPoint, RefPoint)
3780 return self.editor.ExtrusionAlongPath(IDsOfElements, PathMesh, PathShape,
3781 NodeStart, HasAngles, Angles, HasRefPoint, RefPoint)
3783 ## Generates new elements by extrusion of the elements which belong to the object
3784 # The path of extrusion must be a meshed edge.
3785 # @param theObject the object which elements should be processed.
3786 # It can be a mesh, a sub mesh or a group.
3787 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3788 # @param PathShape shape(edge) defines the sub-mesh for the path
3789 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3790 # @param HasAngles allows the shape to be rotated around the path
3791 # to get the resulting mesh in a helical fashion
3792 # @param Angles list of angles
3793 # @param HasRefPoint allows using the reference point
3794 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3795 # The User can specify any point as the Reference Point.
3796 # @param MakeGroups forces the generation of new groups from existing ones
3797 # @param LinearVariation forces the computation of rotation angles as linear
3798 # variation of the given Angles along path steps
3799 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3800 # only SMESH::Extrusion_Error otherwise
3801 # @ingroup l2_modif_extrurev
3802 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
3803 HasAngles, Angles, HasRefPoint, RefPoint,
3804 MakeGroups=False, LinearVariation=False):
3805 if ( isinstance( theObject, Mesh )):
3806 theObject = theObject.GetMesh()
3807 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3808 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3809 if ( isinstance( PathMesh, Mesh )):
3810 PathMesh = PathMesh.GetMesh()
3811 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3812 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3813 self.mesh.SetParameters(Parameters)
3814 if HasAngles and Angles and LinearVariation:
3815 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3818 return self.editor.ExtrusionAlongPathObjectMakeGroups(theObject, PathMesh,
3819 PathShape, NodeStart, HasAngles,
3820 Angles, HasRefPoint, RefPoint)
3821 return self.editor.ExtrusionAlongPathObject(theObject, PathMesh, PathShape,
3822 NodeStart, HasAngles, Angles, HasRefPoint,
3825 ## Generates new elements by extrusion of the elements which belong to the object
3826 # The path of extrusion must be a meshed edge.
3827 # @param theObject the object which elements should be processed.
3828 # It can be a mesh, a sub mesh or a group.
3829 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3830 # @param PathShape shape(edge) defines the sub-mesh for the path
3831 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3832 # @param HasAngles allows the shape to be rotated around the path
3833 # to get the resulting mesh in a helical fashion
3834 # @param Angles list of angles
3835 # @param HasRefPoint allows using the reference point
3836 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3837 # The User can specify any point as the Reference Point.
3838 # @param MakeGroups forces the generation of new groups from existing ones
3839 # @param LinearVariation forces the computation of rotation angles as linear
3840 # variation of the given Angles along path steps
3841 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3842 # only SMESH::Extrusion_Error otherwise
3843 # @ingroup l2_modif_extrurev
3844 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
3845 HasAngles, Angles, HasRefPoint, RefPoint,
3846 MakeGroups=False, LinearVariation=False):
3847 if ( isinstance( theObject, Mesh )):
3848 theObject = theObject.GetMesh()
3849 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3850 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3851 if ( isinstance( PathMesh, Mesh )):
3852 PathMesh = PathMesh.GetMesh()
3853 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3854 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3855 self.mesh.SetParameters(Parameters)
3856 if HasAngles and Angles and LinearVariation:
3857 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3860 return self.editor.ExtrusionAlongPathObject1DMakeGroups(theObject, PathMesh,
3861 PathShape, NodeStart, HasAngles,
3862 Angles, HasRefPoint, RefPoint)
3863 return self.editor.ExtrusionAlongPathObject1D(theObject, PathMesh, PathShape,
3864 NodeStart, HasAngles, Angles, HasRefPoint,
3867 ## Generates new elements by extrusion of the elements which belong to the object
3868 # The path of extrusion must be a meshed edge.
3869 # @param theObject the object which elements should be processed.
3870 # It can be a mesh, a sub mesh or a group.
3871 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3872 # @param PathShape shape(edge) defines the sub-mesh for the path
3873 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3874 # @param HasAngles allows the shape to be rotated around the path
3875 # to get the resulting mesh in a helical fashion
3876 # @param Angles list of angles
3877 # @param HasRefPoint allows using the reference point
3878 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3879 # The User can specify any point as the Reference Point.
3880 # @param MakeGroups forces the generation of new groups from existing ones
3881 # @param LinearVariation forces the computation of rotation angles as linear
3882 # variation of the given Angles along path steps
3883 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3884 # only SMESH::Extrusion_Error otherwise
3885 # @ingroup l2_modif_extrurev
3886 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
3887 HasAngles, Angles, HasRefPoint, RefPoint,
3888 MakeGroups=False, LinearVariation=False):
3889 if ( isinstance( theObject, Mesh )):
3890 theObject = theObject.GetMesh()
3891 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3892 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3893 if ( isinstance( PathMesh, Mesh )):
3894 PathMesh = PathMesh.GetMesh()
3895 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3896 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3897 self.mesh.SetParameters(Parameters)
3898 if HasAngles and Angles and LinearVariation:
3899 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3902 return self.editor.ExtrusionAlongPathObject2DMakeGroups(theObject, PathMesh,
3903 PathShape, NodeStart, HasAngles,
3904 Angles, HasRefPoint, RefPoint)
3905 return self.editor.ExtrusionAlongPathObject2D(theObject, PathMesh, PathShape,
3906 NodeStart, HasAngles, Angles, HasRefPoint,
3909 ## Creates a symmetrical copy of mesh elements
3910 # @param IDsOfElements list of elements ids
3911 # @param Mirror is AxisStruct or geom object(point, line, plane)
3912 # @param theMirrorType is POINT, AXIS or PLANE
3913 # If the Mirror is a geom object this parameter is unnecessary
3914 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
3915 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3916 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3917 # @ingroup l2_modif_trsf
3918 def Mirror(self, IDsOfElements, Mirror, theMirrorType, Copy=0, MakeGroups=False):
3919 if IDsOfElements == []:
3920 IDsOfElements = self.GetElementsId()
3921 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3922 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3923 self.mesh.SetParameters(Mirror.parameters)
3924 if Copy and MakeGroups:
3925 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
3926 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
3929 ## Creates a new mesh by a symmetrical copy of mesh elements
3930 # @param IDsOfElements the list of elements ids
3931 # @param Mirror is AxisStruct or geom object (point, line, plane)
3932 # @param theMirrorType is POINT, AXIS or PLANE
3933 # If the Mirror is a geom object this parameter is unnecessary
3934 # @param MakeGroups to generate new groups from existing ones
3935 # @param NewMeshName a name of the new mesh to create
3936 # @return instance of Mesh class
3937 # @ingroup l2_modif_trsf
3938 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType, MakeGroups=0, NewMeshName=""):
3939 if IDsOfElements == []:
3940 IDsOfElements = self.GetElementsId()
3941 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3942 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3943 self.mesh.SetParameters(Mirror.parameters)
3944 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
3945 MakeGroups, NewMeshName)
3946 return Mesh(self.smeshpyD,self.geompyD,mesh)
3948 ## Creates a symmetrical copy of the object
3949 # @param theObject mesh, submesh or group
3950 # @param Mirror AxisStruct or geom object (point, line, plane)
3951 # @param theMirrorType is POINT, AXIS or PLANE
3952 # If the Mirror is a geom object this parameter is unnecessary
3953 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
3954 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3955 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3956 # @ingroup l2_modif_trsf
3957 def MirrorObject (self, theObject, Mirror, theMirrorType, Copy=0, MakeGroups=False):
3958 if ( isinstance( theObject, Mesh )):
3959 theObject = theObject.GetMesh()
3960 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3961 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3962 self.mesh.SetParameters(Mirror.parameters)
3963 if Copy and MakeGroups:
3964 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
3965 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
3968 ## Creates a new mesh by a symmetrical copy of the object
3969 # @param theObject mesh, submesh or group
3970 # @param Mirror AxisStruct or geom object (point, line, plane)
3971 # @param theMirrorType POINT, AXIS or PLANE
3972 # If the Mirror is a geom object this parameter is unnecessary
3973 # @param MakeGroups forces the generation of new groups from existing ones
3974 # @param NewMeshName the name of the new mesh to create
3975 # @return instance of Mesh class
3976 # @ingroup l2_modif_trsf
3977 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType,MakeGroups=0, NewMeshName=""):
3978 if ( isinstance( theObject, Mesh )):
3979 theObject = theObject.GetMesh()
3980 if (isinstance(Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3981 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3982 self.mesh.SetParameters(Mirror.parameters)
3983 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
3984 MakeGroups, NewMeshName)
3985 return Mesh( self.smeshpyD,self.geompyD,mesh )
3987 ## Translates the elements
3988 # @param IDsOfElements list of elements ids
3989 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
3990 # @param Copy allows copying the translated elements
3991 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3992 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3993 # @ingroup l2_modif_trsf
3994 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
3995 if IDsOfElements == []:
3996 IDsOfElements = self.GetElementsId()
3997 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
3998 Vector = self.smeshpyD.GetDirStruct(Vector)
3999 if isinstance( Vector, list ):
4000 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4001 self.mesh.SetParameters(Vector.PS.parameters)
4002 if Copy and MakeGroups:
4003 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4004 self.editor.Translate(IDsOfElements, Vector, Copy)
4007 ## Creates a new mesh of translated elements
4008 # @param IDsOfElements list of elements ids
4009 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4010 # @param MakeGroups forces the generation of new groups from existing ones
4011 # @param NewMeshName the name of the newly created mesh
4012 # @return instance of Mesh class
4013 # @ingroup l2_modif_trsf
4014 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4015 if IDsOfElements == []:
4016 IDsOfElements = self.GetElementsId()
4017 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4018 Vector = self.smeshpyD.GetDirStruct(Vector)
4019 if isinstance( Vector, list ):
4020 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4021 self.mesh.SetParameters(Vector.PS.parameters)
4022 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4023 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4025 ## Translates the object
4026 # @param theObject the object to translate (mesh, submesh, or group)
4027 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4028 # @param Copy allows copying the translated elements
4029 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4030 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4031 # @ingroup l2_modif_trsf
4032 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4033 if ( isinstance( theObject, Mesh )):
4034 theObject = theObject.GetMesh()
4035 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4036 Vector = self.smeshpyD.GetDirStruct(Vector)
4037 if isinstance( Vector, list ):
4038 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4039 self.mesh.SetParameters(Vector.PS.parameters)
4040 if Copy and MakeGroups:
4041 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4042 self.editor.TranslateObject(theObject, Vector, Copy)
4045 ## Creates a new mesh from the translated object
4046 # @param theObject the object to translate (mesh, submesh, or group)
4047 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4048 # @param MakeGroups forces the generation of new groups from existing ones
4049 # @param NewMeshName the name of the newly created mesh
4050 # @return instance of Mesh class
4051 # @ingroup l2_modif_trsf
4052 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4053 if isinstance( theObject, Mesh ):
4054 theObject = theObject.GetMesh()
4055 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4056 Vector = self.smeshpyD.GetDirStruct(Vector)
4057 if isinstance( Vector, list ):
4058 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4059 self.mesh.SetParameters(Vector.PS.parameters)
4060 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4061 return Mesh( self.smeshpyD, self.geompyD, mesh )
4065 ## Scales the object
4066 # @param theObject - the object to translate (mesh, submesh, or group)
4067 # @param thePoint - base point for scale
4068 # @param theScaleFact - list of 1-3 scale factors for axises
4069 # @param Copy - allows copying the translated elements
4070 # @param MakeGroups - forces the generation of new groups from existing
4072 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4073 # empty list otherwise
4074 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4075 unRegister = genObjUnRegister()
4076 if ( isinstance( theObject, Mesh )):
4077 theObject = theObject.GetMesh()
4078 if ( isinstance( theObject, list )):
4079 theObject = self.GetIDSource(theObject, SMESH.ALL)
4080 unRegister.set( theObject )
4081 if ( isinstance( theScaleFact, float )):
4082 theScaleFact = [theScaleFact]
4083 if ( isinstance( theScaleFact, int )):
4084 theScaleFact = [ float(theScaleFact)]
4086 self.mesh.SetParameters(thePoint.parameters)
4088 if Copy and MakeGroups:
4089 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4090 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4093 ## Creates a new mesh from the translated object
4094 # @param theObject - the object to translate (mesh, submesh, or group)
4095 # @param thePoint - base point for scale
4096 # @param theScaleFact - list of 1-3 scale factors for axises
4097 # @param MakeGroups - forces the generation of new groups from existing ones
4098 # @param NewMeshName - the name of the newly created mesh
4099 # @return instance of Mesh class
4100 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4101 unRegister = genObjUnRegister()
4102 if (isinstance(theObject, Mesh)):
4103 theObject = theObject.GetMesh()
4104 if ( isinstance( theObject, list )):
4105 theObject = self.GetIDSource(theObject,SMESH.ALL)
4106 unRegister.set( theObject )
4107 if ( isinstance( theScaleFact, float )):
4108 theScaleFact = [theScaleFact]
4109 if ( isinstance( theScaleFact, int )):
4110 theScaleFact = [ float(theScaleFact)]
4112 self.mesh.SetParameters(thePoint.parameters)
4113 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4114 MakeGroups, NewMeshName)
4115 return Mesh( self.smeshpyD, self.geompyD, mesh )
4119 ## Rotates the elements
4120 # @param IDsOfElements list of elements ids
4121 # @param Axis the axis of rotation (AxisStruct or geom line)
4122 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4123 # @param Copy allows copying the rotated elements
4124 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4125 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4126 # @ingroup l2_modif_trsf
4127 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4128 if IDsOfElements == []:
4129 IDsOfElements = self.GetElementsId()
4130 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4131 Axis = self.smeshpyD.GetAxisStruct(Axis)
4132 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4133 Parameters = Axis.parameters + var_separator + Parameters
4134 self.mesh.SetParameters(Parameters)
4135 if Copy and MakeGroups:
4136 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4137 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4140 ## Creates a new mesh of rotated elements
4141 # @param IDsOfElements list of element ids
4142 # @param Axis the axis of rotation (AxisStruct or geom line)
4143 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4144 # @param MakeGroups forces the generation of new groups from existing ones
4145 # @param NewMeshName the name of the newly created mesh
4146 # @return instance of Mesh class
4147 # @ingroup l2_modif_trsf
4148 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4149 if IDsOfElements == []:
4150 IDsOfElements = self.GetElementsId()
4151 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4152 Axis = self.smeshpyD.GetAxisStruct(Axis)
4153 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4154 Parameters = Axis.parameters + var_separator + Parameters
4155 self.mesh.SetParameters(Parameters)
4156 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4157 MakeGroups, NewMeshName)
4158 return Mesh( self.smeshpyD, self.geompyD, mesh )
4160 ## Rotates the object
4161 # @param theObject the object to rotate( mesh, submesh, or group)
4162 # @param Axis the axis of rotation (AxisStruct or geom line)
4163 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4164 # @param Copy allows copying the rotated elements
4165 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4166 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4167 # @ingroup l2_modif_trsf
4168 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4169 if (isinstance(theObject, Mesh)):
4170 theObject = theObject.GetMesh()
4171 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4172 Axis = self.smeshpyD.GetAxisStruct(Axis)
4173 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4174 Parameters = Axis.parameters + ":" + Parameters
4175 self.mesh.SetParameters(Parameters)
4176 if Copy and MakeGroups:
4177 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4178 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4181 ## Creates a new mesh from the rotated object
4182 # @param theObject the object to rotate (mesh, submesh, or group)
4183 # @param Axis the axis of rotation (AxisStruct or geom line)
4184 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4185 # @param MakeGroups forces the generation of new groups from existing ones
4186 # @param NewMeshName the name of the newly created mesh
4187 # @return instance of Mesh class
4188 # @ingroup l2_modif_trsf
4189 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4190 if (isinstance( theObject, Mesh )):
4191 theObject = theObject.GetMesh()
4192 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4193 Axis = self.smeshpyD.GetAxisStruct(Axis)
4194 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4195 Parameters = Axis.parameters + ":" + Parameters
4196 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4197 MakeGroups, NewMeshName)
4198 self.mesh.SetParameters(Parameters)
4199 return Mesh( self.smeshpyD, self.geompyD, mesh )
4201 ## Finds groups of adjacent nodes within Tolerance.
4202 # @param Tolerance the value of tolerance
4203 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4204 # @ingroup l2_modif_trsf
4205 def FindCoincidentNodes (self, Tolerance):
4206 return self.editor.FindCoincidentNodes(Tolerance)
4208 ## Finds groups of ajacent nodes within Tolerance.
4209 # @param Tolerance the value of tolerance
4210 # @param SubMeshOrGroup SubMesh or Group
4211 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4212 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4213 # @ingroup l2_modif_trsf
4214 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance, exceptNodes=[]):
4215 unRegister = genObjUnRegister()
4216 if (isinstance( SubMeshOrGroup, Mesh )):
4217 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4218 if not isinstance( exceptNodes, list):
4219 exceptNodes = [ exceptNodes ]
4220 if exceptNodes and isinstance( exceptNodes[0], int):
4221 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE)]
4222 unRegister.set( exceptNodes )
4223 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,exceptNodes)
4226 # @param GroupsOfNodes a list of pairs of nodes IDs for merging (e.g. [[1,12],[25,4]])
4227 # @ingroup l2_modif_trsf
4228 def MergeNodes (self, GroupsOfNodes):
4229 self.editor.MergeNodes(GroupsOfNodes)
4231 ## Finds the elements built on the same nodes.
4232 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4233 # @return the list of pairs of equal elements IDs (e.g. [[1,12],[25,4]])
4234 # @ingroup l2_modif_trsf
4235 def FindEqualElements (self, MeshOrSubMeshOrGroup):
4236 if ( isinstance( MeshOrSubMeshOrGroup, Mesh )):
4237 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4238 return self.editor.FindEqualElements(MeshOrSubMeshOrGroup)
4240 ## Merges elements in each given group.
4241 # @param GroupsOfElementsID a list of pairs of elements IDs for merging (e.g. [[1,12],[25,4]])
4242 # @ingroup l2_modif_trsf
4243 def MergeElements(self, GroupsOfElementsID):
4244 self.editor.MergeElements(GroupsOfElementsID)
4246 ## Leaves one element and removes all other elements built on the same nodes.
4247 # @ingroup l2_modif_trsf
4248 def MergeEqualElements(self):
4249 self.editor.MergeEqualElements()
4251 ## Sews free borders
4252 # @return SMESH::Sew_Error
4253 # @ingroup l2_modif_trsf
4254 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4255 FirstNodeID2, SecondNodeID2, LastNodeID2,
4256 CreatePolygons, CreatePolyedrs):
4257 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4258 FirstNodeID2, SecondNodeID2, LastNodeID2,
4259 CreatePolygons, CreatePolyedrs)
4261 ## Sews conform free borders
4262 # @return SMESH::Sew_Error
4263 # @ingroup l2_modif_trsf
4264 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4265 FirstNodeID2, SecondNodeID2):
4266 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4267 FirstNodeID2, SecondNodeID2)
4269 ## Sews border to side
4270 # @return SMESH::Sew_Error
4271 # @ingroup l2_modif_trsf
4272 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4273 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4274 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4275 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4277 ## Sews two sides of a mesh. The nodes belonging to Side1 are
4278 # merged with the nodes of elements of Side2.
4279 # The number of elements in theSide1 and in theSide2 must be
4280 # equal and they should have similar nodal connectivity.
4281 # The nodes to merge should belong to side borders and
4282 # the first node should be linked to the second.
4283 # @return SMESH::Sew_Error
4284 # @ingroup l2_modif_trsf
4285 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4286 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4287 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4288 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4289 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4290 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4292 ## Sets new nodes for the given element.
4293 # @param ide the element id
4294 # @param newIDs nodes ids
4295 # @return If the number of nodes does not correspond to the type of element - returns false
4296 # @ingroup l2_modif_edit
4297 def ChangeElemNodes(self, ide, newIDs):
4298 return self.editor.ChangeElemNodes(ide, newIDs)
4300 ## If during the last operation of MeshEditor some nodes were
4301 # created, this method returns the list of their IDs, \n
4302 # if new nodes were not created - returns empty list
4303 # @return the list of integer values (can be empty)
4304 # @ingroup l1_auxiliary
4305 def GetLastCreatedNodes(self):
4306 return self.editor.GetLastCreatedNodes()
4308 ## If during the last operation of MeshEditor some elements were
4309 # created this method returns the list of their IDs, \n
4310 # if new elements were not created - returns empty list
4311 # @return the list of integer values (can be empty)
4312 # @ingroup l1_auxiliary
4313 def GetLastCreatedElems(self):
4314 return self.editor.GetLastCreatedElems()
4316 ## Clears sequences of nodes and elements created by mesh edition oparations
4317 # @ingroup l1_auxiliary
4318 def ClearLastCreated(self):
4319 self.editor.ClearLastCreated()
4321 ## Creates Duplicates given elements, i.e. creates new elements based on the
4322 # same nodes as the given ones.
4323 # @param theElements - container of elements to duplicate. It can be a Mesh,
4324 # sub-mesh, group, filter or a list of element IDs.
4325 # @param theGroupName - a name of group to contain the generated elements.
4326 # If a group with such a name already exists, the new elements
4327 # are added to the existng group, else a new group is created.
4328 # If \a theGroupName is empty, new elements are not added
4330 # @return a group where the new elements are added. None if theGroupName == "".
4331 # @ingroup l2_modif_edit
4332 def DoubleElements(self, theElements, theGroupName=""):
4333 unRegister = genObjUnRegister()
4334 if isinstance( theElements, Mesh ):
4335 theElements = theElements.mesh
4336 elif isinstance( theElements, list ):
4337 theElements = self.GetIDSource( theElements, SMESH.ALL )
4338 unRegister.set( theElements )
4339 return self.editor.DoubleElements(theElements, theGroupName)
4341 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4342 # @param theNodes identifiers of nodes to be doubled
4343 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4344 # nodes. If list of element identifiers is empty then nodes are doubled but
4345 # they not assigned to elements
4346 # @return TRUE if operation has been completed successfully, FALSE otherwise
4347 # @ingroup l2_modif_edit
4348 def DoubleNodes(self, theNodes, theModifiedElems):
4349 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4351 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4352 # This method provided for convenience works as DoubleNodes() described above.
4353 # @param theNodeId identifiers of node to be doubled
4354 # @param theModifiedElems identifiers of elements to be updated
4355 # @return TRUE if operation has been completed successfully, FALSE otherwise
4356 # @ingroup l2_modif_edit
4357 def DoubleNode(self, theNodeId, theModifiedElems):
4358 return self.editor.DoubleNode(theNodeId, 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 theNodes group of nodes to be doubled
4363 # @param theModifiedElems group of elements to be updated.
4364 # @param theMakeGroup forces the generation of a group containing new nodes.
4365 # @return TRUE or a created group if operation has been completed successfully,
4366 # FALSE or None otherwise
4367 # @ingroup l2_modif_edit
4368 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4370 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4371 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4373 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4374 # This method provided for convenience works as DoubleNodes() described above.
4375 # @param theNodes list of groups of nodes to be doubled
4376 # @param theModifiedElems list of groups of elements to be updated.
4377 # @param theMakeGroup forces the generation of a group containing new nodes.
4378 # @return TRUE if operation has been completed successfully, FALSE otherwise
4379 # @ingroup l2_modif_edit
4380 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4382 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4383 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4385 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4386 # @param theElems - the list of elements (edges or faces) to be replicated
4387 # The nodes for duplication could be found from these elements
4388 # @param theNodesNot - list of nodes to NOT replicate
4389 # @param theAffectedElems - the list of elements (cells and edges) to which the
4390 # replicated nodes should be associated to.
4391 # @return TRUE if operation has been completed successfully, FALSE otherwise
4392 # @ingroup l2_modif_edit
4393 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4394 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4396 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4397 # @param theElems - the list of elements (edges or faces) to be replicated
4398 # The nodes for duplication could be found from these elements
4399 # @param theNodesNot - list of nodes to NOT replicate
4400 # @param theShape - shape to detect affected elements (element which geometric center
4401 # located on or inside shape).
4402 # The replicated nodes should be associated to affected elements.
4403 # @return TRUE if operation has been completed successfully, FALSE otherwise
4404 # @ingroup l2_modif_edit
4405 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4406 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4408 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4409 # This method provided for convenience works as DoubleNodes() described above.
4410 # @param theElems - group of of elements (edges or faces) to be replicated
4411 # @param theNodesNot - group of nodes not to replicated
4412 # @param theAffectedElems - group of elements to which the replicated nodes
4413 # should be associated to.
4414 # @param theMakeGroup forces the generation of a group containing new elements.
4415 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4416 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4417 # FALSE or None otherwise
4418 # @ingroup l2_modif_edit
4419 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4420 theMakeGroup=False, theMakeNodeGroup=False):
4421 if theMakeGroup or theMakeNodeGroup:
4422 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4424 theMakeGroup, theMakeNodeGroup)
4425 if theMakeGroup and theMakeNodeGroup:
4428 return twoGroups[ int(theMakeNodeGroup) ]
4429 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4431 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4432 # This method provided for convenience works as DoubleNodes() described above.
4433 # @param theElems - group of of elements (edges or faces) to be replicated
4434 # @param theNodesNot - group of nodes not to replicated
4435 # @param theShape - shape to detect affected elements (element which geometric center
4436 # located on or inside shape).
4437 # The replicated nodes should be associated to affected elements.
4438 # @ingroup l2_modif_edit
4439 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4440 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4442 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4443 # This method provided for convenience works as DoubleNodes() described above.
4444 # @param theElems - list of groups of elements (edges or faces) to be replicated
4445 # @param theNodesNot - list of groups of nodes not to replicated
4446 # @param theAffectedElems - group of elements to which the replicated nodes
4447 # should be associated to.
4448 # @param theMakeGroup forces the generation of a group containing new elements.
4449 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4450 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4451 # FALSE or None otherwise
4452 # @ingroup l2_modif_edit
4453 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4454 theMakeGroup=False, theMakeNodeGroup=False):
4455 if theMakeGroup or theMakeNodeGroup:
4456 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4458 theMakeGroup, theMakeNodeGroup)
4459 if theMakeGroup and theMakeNodeGroup:
4462 return twoGroups[ int(theMakeNodeGroup) ]
4463 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4465 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4466 # This method provided for convenience works as DoubleNodes() described above.
4467 # @param theElems - list of groups of elements (edges or faces) to be replicated
4468 # @param theNodesNot - list of groups of nodes not to replicated
4469 # @param theShape - shape to detect affected elements (element which geometric center
4470 # located on or inside shape).
4471 # The replicated nodes should be associated to affected elements.
4472 # @return TRUE if operation has been completed successfully, FALSE otherwise
4473 # @ingroup l2_modif_edit
4474 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4475 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4477 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4478 # This method is the first step of DoubleNodeElemGroupsInRegion.
4479 # @param theElems - list of groups of elements (edges or faces) to be replicated
4480 # @param theNodesNot - list of groups of nodes not to replicated
4481 # @param theShape - shape to detect affected elements (element which geometric center
4482 # located on or inside shape).
4483 # The replicated nodes should be associated to affected elements.
4484 # @return groups of affected elements
4485 # @ingroup l2_modif_edit
4486 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4487 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4489 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4490 # The list of groups must describe a partition of the mesh volumes.
4491 # The nodes of the internal faces at the boundaries of the groups are doubled.
4492 # In option, the internal faces are replaced by flat elements.
4493 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4494 # @param theDomains - list of groups of volumes
4495 # @param createJointElems - if TRUE, create the elements
4496 # @return TRUE if operation has been completed successfully, FALSE otherwise
4497 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems ):
4498 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems )
4500 ## Double nodes on some external faces and create flat elements.
4501 # Flat elements are mainly used by some types of mechanic calculations.
4503 # Each group of the list must be constituted of faces.
4504 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4505 # @param theGroupsOfFaces - list of groups of faces
4506 # @return TRUE if operation has been completed successfully, FALSE otherwise
4507 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4508 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4510 ## identify all the elements around a geom shape, get the faces delimiting the hole
4512 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4513 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4515 def _getFunctor(self, funcType ):
4516 fn = self.functors[ funcType._v ]
4518 fn = self.smeshpyD.GetFunctor(funcType)
4519 fn.SetMesh(self.mesh)
4520 self.functors[ funcType._v ] = fn
4523 def _valueFromFunctor(self, funcType, elemId):
4524 fn = self._getFunctor( funcType )
4525 if fn.GetElementType() == self.GetElementType(elemId, True):
4526 val = fn.GetValue(elemId)
4531 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4532 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4533 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4534 # @ingroup l1_measurements
4535 def GetLength(self, elemId=None):
4538 length = self.smeshpyD.GetLength(self)
4540 length = self._valueFromFunctor(SMESH.FT_Length, elemId)
4543 ## Get area of 2D element or sum of areas of all 2D mesh elements
4544 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4545 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4546 # @ingroup l1_measurements
4547 def GetArea(self, elemId=None):
4550 area = self.smeshpyD.GetArea(self)
4552 area = self._valueFromFunctor(SMESH.FT_Area, elemId)
4555 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4556 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4557 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4558 # @ingroup l1_measurements
4559 def GetVolume(self, elemId=None):
4562 volume = self.smeshpyD.GetVolume(self)
4564 volume = self._valueFromFunctor(SMESH.FT_Volume3D, elemId)
4567 ## Get maximum element length.
4568 # @param elemId mesh element ID
4569 # @return element's maximum length value
4570 # @ingroup l1_measurements
4571 def GetMaxElementLength(self, elemId):
4572 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4573 ftype = SMESH.FT_MaxElementLength3D
4575 ftype = SMESH.FT_MaxElementLength2D
4576 return self._valueFromFunctor(ftype, elemId)
4578 ## Get aspect ratio of 2D or 3D element.
4579 # @param elemId mesh element ID
4580 # @return element's aspect ratio value
4581 # @ingroup l1_measurements
4582 def GetAspectRatio(self, elemId):
4583 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4584 ftype = SMESH.FT_AspectRatio3D
4586 ftype = SMESH.FT_AspectRatio
4587 return self._valueFromFunctor(ftype, elemId)
4589 ## Get warping angle of 2D element.
4590 # @param elemId mesh element ID
4591 # @return element's warping angle value
4592 # @ingroup l1_measurements
4593 def GetWarping(self, elemId):
4594 return self._valueFromFunctor(SMESH.FT_Warping, elemId)
4596 ## Get minimum angle of 2D element.
4597 # @param elemId mesh element ID
4598 # @return element's minimum angle value
4599 # @ingroup l1_measurements
4600 def GetMinimumAngle(self, elemId):
4601 return self._valueFromFunctor(SMESH.FT_MinimumAngle, elemId)
4603 ## Get taper of 2D element.
4604 # @param elemId mesh element ID
4605 # @return element's taper value
4606 # @ingroup l1_measurements
4607 def GetTaper(self, elemId):
4608 return self._valueFromFunctor(SMESH.FT_Taper, elemId)
4610 ## Get skew of 2D element.
4611 # @param elemId mesh element ID
4612 # @return element's skew value
4613 # @ingroup l1_measurements
4614 def GetSkew(self, elemId):
4615 return self._valueFromFunctor(SMESH.FT_Skew, elemId)
4617 pass # end of Mesh class
4619 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
4621 class Pattern(SMESH._objref_SMESH_Pattern):
4623 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4624 decrFun = lambda i: i-1
4625 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4626 theMesh.SetParameters(Parameters)
4627 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4629 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4630 decrFun = lambda i: i-1
4631 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4632 theMesh.SetParameters(Parameters)
4633 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4635 # Registering the new proxy for Pattern
4636 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4638 ## Private class used to bind methods creating algorithms to the class Mesh
4643 self.defaultAlgoType = ""
4644 self.algoTypeToClass = {}
4646 # Stores a python class of algorithm
4647 def add(self, algoClass):
4648 if type( algoClass ).__name__ == 'classobj' and \
4649 hasattr( algoClass, "algoType"):
4650 self.algoTypeToClass[ algoClass.algoType ] = algoClass
4651 if not self.defaultAlgoType and \
4652 hasattr( algoClass, "isDefault") and algoClass.isDefault:
4653 self.defaultAlgoType = algoClass.algoType
4654 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
4656 # creates a copy of self and assign mesh to the copy
4657 def copy(self, mesh):
4658 other = algoCreator()
4659 other.defaultAlgoType = self.defaultAlgoType
4660 other.algoTypeToClass = self.algoTypeToClass
4664 # creates an instance of algorithm
4665 def __call__(self,algo="",geom=0,*args):
4666 algoType = self.defaultAlgoType
4667 for arg in args + (algo,geom):
4668 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
4670 if isinstance( arg, str ) and arg:
4672 if not algoType and self.algoTypeToClass:
4673 algoType = self.algoTypeToClass.keys()[0]
4674 if self.algoTypeToClass.has_key( algoType ):
4675 #print "Create algo",algoType
4676 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
4677 raise RuntimeError, "No class found for algo type %s" % algoType
4680 # Private class used to substitute and store variable parameters of hypotheses.
4682 class hypMethodWrapper:
4683 def __init__(self, hyp, method):
4685 self.method = method
4686 #print "REBIND:", method.__name__
4689 # call a method of hypothesis with calling SetVarParameter() before
4690 def __call__(self,*args):
4692 return self.method( self.hyp, *args ) # hypothesis method with no args
4694 #print "MethWrapper.__call__",self.method.__name__, args
4696 parsed = ParseParameters(*args) # replace variables with their values
4697 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
4698 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
4699 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
4700 # maybe there is a replaced string arg which is not variable
4701 result = self.method( self.hyp, *args )
4702 except ValueError, detail: # raised by ParseParameters()
4704 result = self.method( self.hyp, *args )
4705 except omniORB.CORBA.BAD_PARAM:
4706 raise ValueError, detail # wrong variable name
4711 # A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
4712 class genObjUnRegister:
4714 def __init__(self, genObj=None):
4715 self.genObjList = []
4719 def set(self, genObj):
4720 "Store one or a list of of SALOME.GenericObj'es"
4721 if isinstance( genObj, list ):
4722 self.genObjList.extend( genObj )
4724 self.genObjList.append( genObj )
4728 for genObj in self.genObjList:
4729 if genObj and hasattr( genObj, "UnRegister" ):
4732 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
4734 #print "pluginName: ", pluginName
4735 pluginBuilderName = pluginName + "Builder"
4737 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
4738 except Exception, e:
4739 from salome_utils import verbose
4740 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
4742 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
4743 plugin = eval( pluginBuilderName )
4744 #print " plugin:" , str(plugin)
4746 # add methods creating algorithms to Mesh
4747 for k in dir( plugin ):
4748 if k[0] == '_': continue
4749 algo = getattr( plugin, k )
4750 #print " algo:", str(algo)
4751 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
4752 #print " meshMethod:" , str(algo.meshMethod)
4753 if not hasattr( Mesh, algo.meshMethod ):
4754 setattr( Mesh, algo.meshMethod, algoCreator() )
4756 getattr( Mesh, algo.meshMethod ).add( algo )