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