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)
388 notebook.myStudy = theStudy
390 ## Creates a mesh. This can be either an empty mesh, possibly having an underlying geometry,
391 # or a mesh wrapping a CORBA mesh given as a parameter.
392 # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
393 # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
394 # (2) a Geometrical object for meshing or
396 # @param name the name for the new mesh.
397 # @return an instance of Mesh class.
398 # @ingroup l2_construct
399 def Mesh(self, obj=0, name=0):
400 if isinstance(obj,str):
402 return Mesh(self,self.geompyD,obj,name)
404 ## Returns a long value from enumeration
405 # @ingroup l1_controls
406 def EnumToLong(self,theItem):
409 ## Returns a string representation of the color.
410 # To be used with filters.
411 # @param c color value (SALOMEDS.Color)
412 # @ingroup l1_controls
413 def ColorToString(self,c):
415 if isinstance(c, SALOMEDS.Color):
416 val = "%s;%s;%s" % (c.R, c.G, c.B)
417 elif isinstance(c, str):
420 raise ValueError, "Color value should be of string or SALOMEDS.Color type"
423 ## Gets PointStruct from vertex
424 # @param theVertex a GEOM object(vertex)
425 # @return SMESH.PointStruct
426 # @ingroup l1_auxiliary
427 def GetPointStruct(self,theVertex):
428 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
429 return PointStruct(x,y,z)
431 ## Gets DirStruct from vector
432 # @param theVector a GEOM object(vector)
433 # @return SMESH.DirStruct
434 # @ingroup l1_auxiliary
435 def GetDirStruct(self,theVector):
436 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
437 if(len(vertices) != 2):
438 print "Error: vector object is incorrect."
440 p1 = self.geompyD.PointCoordinates(vertices[0])
441 p2 = self.geompyD.PointCoordinates(vertices[1])
442 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
443 dirst = DirStruct(pnt)
446 ## Makes DirStruct from a triplet
447 # @param x,y,z vector components
448 # @return SMESH.DirStruct
449 # @ingroup l1_auxiliary
450 def MakeDirStruct(self,x,y,z):
451 pnt = PointStruct(x,y,z)
452 return DirStruct(pnt)
454 ## Get AxisStruct from object
455 # @param theObj a GEOM object (line or plane)
456 # @return SMESH.AxisStruct
457 # @ingroup l1_auxiliary
458 def GetAxisStruct(self,theObj):
459 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
461 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
462 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
463 vertex1 = self.geompyD.PointCoordinates(vertex1)
464 vertex2 = self.geompyD.PointCoordinates(vertex2)
465 vertex3 = self.geompyD.PointCoordinates(vertex3)
466 vertex4 = self.geompyD.PointCoordinates(vertex4)
467 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
468 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
469 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] ]
470 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
472 elif len(edges) == 1:
473 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
474 p1 = self.geompyD.PointCoordinates( vertex1 )
475 p2 = self.geompyD.PointCoordinates( vertex2 )
476 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
480 # From SMESH_Gen interface:
481 # ------------------------
483 ## Sets the given name to the object
484 # @param obj the object to rename
485 # @param name a new object name
486 # @ingroup l1_auxiliary
487 def SetName(self, obj, name):
488 if isinstance( obj, Mesh ):
490 elif isinstance( obj, Mesh_Algorithm ):
491 obj = obj.GetAlgorithm()
492 ior = salome.orb.object_to_string(obj)
493 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
495 ## Sets the current mode
496 # @ingroup l1_auxiliary
497 def SetEmbeddedMode( self,theMode ):
498 #self.SetEmbeddedMode(theMode)
499 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
501 ## Gets the current mode
502 # @ingroup l1_auxiliary
503 def IsEmbeddedMode(self):
504 #return self.IsEmbeddedMode()
505 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
507 ## Sets the current study
508 # @ingroup l1_auxiliary
509 def SetCurrentStudy( self, theStudy, geompyD = None ):
510 #self.SetCurrentStudy(theStudy)
512 from salome.geom import geomBuilder
513 geompyD = geomBuilder.geom
516 self.SetGeomEngine(geompyD)
517 SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
520 notebook = salome_notebook.NoteBook( theStudy )
522 notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
524 ## Gets the current study
525 # @ingroup l1_auxiliary
526 def GetCurrentStudy(self):
527 #return self.GetCurrentStudy()
528 return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
530 ## Creates a Mesh object importing data from the given UNV file
531 # @return an instance of Mesh class
533 def CreateMeshesFromUNV( self,theFileName ):
534 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
535 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
538 ## Creates a Mesh object(s) importing data from the given MED file
539 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
541 def CreateMeshesFromMED( self,theFileName ):
542 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
543 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
544 return aMeshes, aStatus
546 ## Creates a Mesh object(s) importing data from the given SAUV file
547 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
549 def CreateMeshesFromSAUV( self,theFileName ):
550 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
551 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
552 return aMeshes, aStatus
554 ## Creates a Mesh object importing data from the given STL file
555 # @return an instance of Mesh class
557 def CreateMeshesFromSTL( self, theFileName ):
558 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
559 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
562 ## Creates Mesh objects importing data from the given CGNS file
563 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
565 def CreateMeshesFromCGNS( self, theFileName ):
566 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
567 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
568 return aMeshes, aStatus
570 ## Creates a Mesh object importing data from the given GMF file.
571 # GMF files must have .mesh extension for the ASCII format and .meshb for
573 # @return [ an instance of Mesh class, SMESH.ComputeError ]
575 def CreateMeshesFromGMF( self, theFileName ):
576 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
579 if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
580 return Mesh(self, self.geompyD, aSmeshMesh), error
582 ## Concatenate the given meshes into one mesh.
583 # @return an instance of Mesh class
584 # @param meshes the meshes to combine into one mesh
585 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
586 # @param mergeNodesAndElements if true, equal nodes and elements aremerged
587 # @param mergeTolerance tolerance for merging nodes
588 # @param allGroups forces creation of groups of all elements
589 # @param name name of a new mesh
590 def Concatenate( self, meshes, uniteIdenticalGroups,
591 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
593 if not meshes: return None
594 for i,m in enumerate(meshes):
595 if isinstance(m, Mesh):
596 meshes[i] = m.GetMesh()
597 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
598 meshes[0].SetParameters(Parameters)
600 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
601 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
603 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
604 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
605 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
608 ## Create a mesh by copying a part of another mesh.
609 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
610 # to copy nodes or elements not contained in any mesh object,
611 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
612 # @param meshName a name of the new mesh
613 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
614 # @param toKeepIDs to preserve IDs of the copied elements or not
615 # @return an instance of Mesh class
616 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
617 if (isinstance( meshPart, Mesh )):
618 meshPart = meshPart.GetMesh()
619 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
620 return Mesh(self, self.geompyD, mesh)
622 ## From SMESH_Gen interface
623 # @return the list of integer values
624 # @ingroup l1_auxiliary
625 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
626 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
628 ## From SMESH_Gen interface. Creates a pattern
629 # @return an instance of SMESH_Pattern
631 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
632 # @ingroup l2_modif_patterns
633 def GetPattern(self):
634 return SMESH._objref_SMESH_Gen.GetPattern(self)
636 ## Sets number of segments per diagonal of boundary box of geometry by which
637 # default segment length of appropriate 1D hypotheses is defined.
638 # Default value is 10
639 # @ingroup l1_auxiliary
640 def SetBoundaryBoxSegmentation(self, nbSegments):
641 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
643 # Filtering. Auxiliary functions:
644 # ------------------------------
646 ## Creates an empty criterion
647 # @return SMESH.Filter.Criterion
648 # @ingroup l1_controls
649 def GetEmptyCriterion(self):
650 Type = self.EnumToLong(FT_Undefined)
651 Compare = self.EnumToLong(FT_Undefined)
655 UnaryOp = self.EnumToLong(FT_Undefined)
656 BinaryOp = self.EnumToLong(FT_Undefined)
659 Precision = -1 ##@1e-07
660 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
661 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
663 ## Creates a criterion by the given parameters
664 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
665 # @param elementType the type of elements(NODE, EDGE, FACE, VOLUME)
666 # @param CritType the type of criterion (FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc.)
667 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
668 # @param Threshold the threshold value (range of ids as string, shape, numeric)
669 # @param UnaryOp FT_LogicalNOT or FT_Undefined
670 # @param BinaryOp a binary logical operation FT_LogicalAND, FT_LogicalOR or
671 # FT_Undefined (must be for the last criterion of all criteria)
672 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
673 # FT_LyingOnGeom, FT_CoplanarFaces criteria
674 # @return SMESH.Filter.Criterion
676 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
677 # @ingroup l1_controls
678 def GetCriterion(self,elementType,
680 Compare = FT_EqualTo,
682 UnaryOp=FT_Undefined,
683 BinaryOp=FT_Undefined,
685 if not CritType in SMESH.FunctorType._items:
686 raise TypeError, "CritType should be of SMESH.FunctorType"
687 aCriterion = self.GetEmptyCriterion()
688 aCriterion.TypeOfElement = elementType
689 aCriterion.Type = self.EnumToLong(CritType)
690 aCriterion.Tolerance = Tolerance
692 aThreshold = Threshold
694 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
695 aCriterion.Compare = self.EnumToLong(Compare)
696 elif Compare == "=" or Compare == "==":
697 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
699 aCriterion.Compare = self.EnumToLong(FT_LessThan)
701 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
702 elif Compare != FT_Undefined:
703 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
706 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
707 FT_BelongToCylinder, FT_LyingOnGeom]:
708 # Checks that Threshold is GEOM object
709 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
710 aCriterion.ThresholdStr = GetName(aThreshold)
711 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
712 if not aCriterion.ThresholdID:
713 name = aCriterion.ThresholdStr
715 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
716 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
717 #raise RuntimeError, "Threshold shape must be published"
719 print "Error: The Threshold should be a shape."
721 if isinstance(UnaryOp,float):
722 aCriterion.Tolerance = UnaryOp
723 UnaryOp = FT_Undefined
725 elif CritType == FT_RangeOfIds:
726 # Checks that Threshold is string
727 if isinstance(aThreshold, str):
728 aCriterion.ThresholdStr = aThreshold
730 print "Error: The Threshold should be a string."
732 elif CritType == FT_CoplanarFaces:
733 # Checks the Threshold
734 if isinstance(aThreshold, int):
735 aCriterion.ThresholdID = str(aThreshold)
736 elif isinstance(aThreshold, str):
739 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
740 aCriterion.ThresholdID = aThreshold
743 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
744 elif CritType == FT_ConnectedElements:
745 # Checks the Threshold
746 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
747 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
748 if not aCriterion.ThresholdID:
749 name = aThreshold.GetName()
751 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
752 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
753 elif isinstance(aThreshold, int): # node id
754 aCriterion.Threshold = aThreshold
755 elif isinstance(aThreshold, list): # 3 point coordinates
756 if len( aThreshold ) < 3:
757 raise ValueError, "too few point coordinates, must be 3"
758 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
759 elif isinstance(aThreshold, str):
760 if aThreshold.isdigit():
761 aCriterion.Threshold = aThreshold # node id
763 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
766 "The Threshold should either a VERTEX, or a node ID, "\
767 "or a list of point coordinates and not '%s'"%aThreshold
768 elif CritType == FT_ElemGeomType:
769 # Checks the Threshold
771 aCriterion.Threshold = self.EnumToLong(aThreshold)
772 assert( aThreshold in SMESH.GeometryType._items )
774 if isinstance(aThreshold, int):
775 aCriterion.Threshold = aThreshold
777 print "Error: The Threshold should be an integer or SMESH.GeometryType."
781 elif CritType == FT_EntityType:
782 # Checks the Threshold
784 aCriterion.Threshold = self.EnumToLong(aThreshold)
785 assert( aThreshold in SMESH.EntityType._items )
787 if isinstance(aThreshold, int):
788 aCriterion.Threshold = aThreshold
790 print "Error: The Threshold should be an integer or SMESH.EntityType."
795 elif CritType == FT_GroupColor:
796 # Checks the Threshold
798 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
800 print "Error: The threshold value should be of SALOMEDS.Color type"
803 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
804 FT_LinearOrQuadratic, FT_BadOrientedVolume,
805 FT_BareBorderFace, FT_BareBorderVolume,
806 FT_OverConstrainedFace, FT_OverConstrainedVolume,
807 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
808 # At this point the Threshold is unnecessary
809 if aThreshold == FT_LogicalNOT:
810 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
811 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
812 aCriterion.BinaryOp = aThreshold
816 aThreshold = float(aThreshold)
817 aCriterion.Threshold = aThreshold
819 print "Error: The Threshold should be a number."
822 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
823 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
825 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
826 aCriterion.BinaryOp = self.EnumToLong(Threshold)
828 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
829 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
831 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
832 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
836 ## Creates a filter with the given parameters
837 # @param elementType the type of elements in the group
838 # @param CritType the type of criterion ( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
839 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
840 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
841 # @param UnaryOp FT_LogicalNOT or FT_Undefined
842 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
843 # FT_LyingOnGeom, FT_CoplanarFaces and FT_EqualNodes criteria
844 # @param mesh the mesh to initialize the filter with
845 # @return SMESH_Filter
847 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
848 # @ingroup l1_controls
849 def GetFilter(self,elementType,
850 CritType=FT_Undefined,
853 UnaryOp=FT_Undefined,
856 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
857 aFilterMgr = self.CreateFilterManager()
858 aFilter = aFilterMgr.CreateFilter()
860 aCriteria.append(aCriterion)
861 aFilter.SetCriteria(aCriteria)
863 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
864 else : aFilter.SetMesh( mesh )
865 aFilterMgr.UnRegister()
868 ## Creates a filter from criteria
869 # @param criteria a list of criteria
870 # @param binOp binary operator used when binary operator of criteria is undefined
871 # @return SMESH_Filter
873 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
874 # @ingroup l1_controls
875 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
876 for i in range( len( criteria ) - 1 ):
877 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
878 criteria[i].BinaryOp = self.EnumToLong( binOp )
879 aFilterMgr = self.CreateFilterManager()
880 aFilter = aFilterMgr.CreateFilter()
881 aFilter.SetCriteria(criteria)
882 aFilterMgr.UnRegister()
885 ## Creates a numerical functor by its type
886 # @param theCriterion FT_...; functor type
887 # @return SMESH_NumericalFunctor
888 # @ingroup l1_controls
889 def GetFunctor(self,theCriterion):
890 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
892 aFilterMgr = self.CreateFilterManager()
894 if theCriterion == FT_AspectRatio:
895 functor = aFilterMgr.CreateAspectRatio()
896 elif theCriterion == FT_AspectRatio3D:
897 functor = aFilterMgr.CreateAspectRatio3D()
898 elif theCriterion == FT_Warping:
899 functor = aFilterMgr.CreateWarping()
900 elif theCriterion == FT_MinimumAngle:
901 functor = aFilterMgr.CreateMinimumAngle()
902 elif theCriterion == FT_Taper:
903 functor = aFilterMgr.CreateTaper()
904 elif theCriterion == FT_Skew:
905 functor = aFilterMgr.CreateSkew()
906 elif theCriterion == FT_Area:
907 functor = aFilterMgr.CreateArea()
908 elif theCriterion == FT_Volume3D:
909 functor = aFilterMgr.CreateVolume3D()
910 elif theCriterion == FT_MaxElementLength2D:
911 functor = aFilterMgr.CreateMaxElementLength2D()
912 elif theCriterion == FT_MaxElementLength3D:
913 functor = aFilterMgr.CreateMaxElementLength3D()
914 elif theCriterion == FT_MultiConnection:
915 functor = aFilterMgr.CreateMultiConnection()
916 elif theCriterion == FT_MultiConnection2D:
917 functor = aFilterMgr.CreateMultiConnection2D()
918 elif theCriterion == FT_Length:
919 functor = aFilterMgr.CreateLength()
920 elif theCriterion == FT_Length2D:
921 functor = aFilterMgr.CreateLength2D()
923 print "Error: given parameter is not numerical functor type."
924 aFilterMgr.UnRegister()
927 ## Creates hypothesis
928 # @param theHType mesh hypothesis type (string)
929 # @param theLibName mesh plug-in library name
930 # @return created hypothesis instance
931 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
932 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
934 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
937 # wrap hypothesis methods
938 #print "HYPOTHESIS", theHType
939 for meth_name in dir( hyp.__class__ ):
940 if not meth_name.startswith("Get") and \
941 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
942 method = getattr ( hyp.__class__, meth_name )
944 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
948 ## Gets the mesh statistic
949 # @return dictionary "element type" - "count of elements"
950 # @ingroup l1_meshinfo
951 def GetMeshInfo(self, obj):
952 if isinstance( obj, Mesh ):
955 if hasattr(obj, "GetMeshInfo"):
956 values = obj.GetMeshInfo()
957 for i in range(SMESH.Entity_Last._v):
958 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
962 ## Get minimum distance between two objects
964 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
965 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
967 # @param src1 first source object
968 # @param src2 second source object
969 # @param id1 node/element id from the first source
970 # @param id2 node/element id from the second (or first) source
971 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
972 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
973 # @return minimum distance value
974 # @sa GetMinDistance()
975 # @ingroup l1_measurements
976 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
977 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
981 result = result.value
984 ## Get measure structure specifying minimum distance data between two objects
986 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
987 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
989 # @param src1 first source object
990 # @param src2 second source object
991 # @param id1 node/element id from the first source
992 # @param id2 node/element id from the second (or first) source
993 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
994 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
995 # @return Measure structure or None if input data is invalid
997 # @ingroup l1_measurements
998 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
999 if isinstance(src1, Mesh): src1 = src1.mesh
1000 if isinstance(src2, Mesh): src2 = src2.mesh
1001 if src2 is None and id2 != 0: src2 = src1
1002 if not hasattr(src1, "_narrow"): return None
1003 src1 = src1._narrow(SMESH.SMESH_IDSource)
1004 if not src1: return None
1005 unRegister = genObjUnRegister()
1008 e = m.GetMeshEditor()
1010 src1 = e.MakeIDSource([id1], SMESH.FACE)
1012 src1 = e.MakeIDSource([id1], SMESH.NODE)
1013 unRegister.set( src1 )
1015 if hasattr(src2, "_narrow"):
1016 src2 = src2._narrow(SMESH.SMESH_IDSource)
1017 if src2 and id2 != 0:
1019 e = m.GetMeshEditor()
1021 src2 = e.MakeIDSource([id2], SMESH.FACE)
1023 src2 = e.MakeIDSource([id2], SMESH.NODE)
1024 unRegister.set( src2 )
1027 aMeasurements = self.CreateMeasurements()
1028 unRegister.set( aMeasurements )
1029 result = aMeasurements.MinDistance(src1, src2)
1032 ## Get bounding box of the specified object(s)
1033 # @param objects single source object or list of source objects
1034 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1035 # @sa GetBoundingBox()
1036 # @ingroup l1_measurements
1037 def BoundingBox(self, objects):
1038 result = self.GetBoundingBox(objects)
1042 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1045 ## Get measure structure specifying bounding box data of the specified object(s)
1046 # @param objects single source object or list of source objects
1047 # @return Measure structure
1049 # @ingroup l1_measurements
1050 def GetBoundingBox(self, objects):
1051 if isinstance(objects, tuple):
1052 objects = list(objects)
1053 if not isinstance(objects, list):
1057 if isinstance(o, Mesh):
1058 srclist.append(o.mesh)
1059 elif hasattr(o, "_narrow"):
1060 src = o._narrow(SMESH.SMESH_IDSource)
1061 if src: srclist.append(src)
1064 aMeasurements = self.CreateMeasurements()
1065 result = aMeasurements.BoundingBox(srclist)
1066 aMeasurements.UnRegister()
1069 ## Get sum of lengths of all 1D elements in the mesh object.
1070 # @param obj mesh, submesh or group
1071 # @return sum of lengths of all 1D elements
1072 # @ingroup l1_measurements
1073 def GetLength(self, obj):
1074 if isinstance(obj, Mesh): obj = obj.mesh
1075 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1076 aMeasurements = self.CreateMeasurements()
1077 value = aMeasurements.Length(obj)
1078 aMeasurements.UnRegister()
1081 ## Get sum of areas of all 2D elements in the mesh object.
1082 # @param obj mesh, submesh or group
1083 # @return sum of areas of all 2D elements
1084 # @ingroup l1_measurements
1085 def GetArea(self, obj):
1086 if isinstance(obj, Mesh): obj = obj.mesh
1087 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1088 aMeasurements = self.CreateMeasurements()
1089 value = aMeasurements.Area(obj)
1090 aMeasurements.UnRegister()
1093 ## Get sum of volumes of all 3D elements in the mesh object.
1094 # @param obj mesh, submesh or group
1095 # @return sum of volumes of all 3D elements
1096 # @ingroup l1_measurements
1097 def GetVolume(self, obj):
1098 if isinstance(obj, Mesh): obj = obj.mesh
1099 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1100 aMeasurements = self.CreateMeasurements()
1101 value = aMeasurements.Volume(obj)
1102 aMeasurements.UnRegister()
1105 pass # end of class smeshBuilder
1108 #Registering the new proxy for SMESH_Gen
1109 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1111 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1112 # interface to create or load meshes.
1117 # salome.salome_init()
1118 # from salome.smesh import smeshBuilder
1119 # smesh = smeshBuilder.New(theStudy)
1121 # @param study SALOME study, generally obtained by salome.myStudy.
1122 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1123 # @return smeshBuilder instance
1125 def New( study, instance=None):
1127 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1128 interface to create or load meshes.
1132 salome.salome_init()
1133 from salome.smesh import smeshBuilder
1134 smesh = smeshBuilder.New(theStudy)
1137 study SALOME study, generally obtained by salome.myStudy.
1138 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1140 smeshBuilder instance
1148 smeshInst = smeshBuilder()
1149 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1150 smeshInst.init_smesh(study)
1154 # Public class: Mesh
1155 # ==================
1157 ## This class allows defining and managing a mesh.
1158 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1159 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1160 # new nodes and elements and by changing the existing entities), to get information
1161 # about a mesh and to export a mesh into different formats.
1163 __metaclass__ = MeshMeta
1171 # Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1172 # sets the GUI name of this mesh to \a name.
1173 # @param smeshpyD an instance of smeshBuilder class
1174 # @param geompyD an instance of geomBuilder class
1175 # @param obj Shape to be meshed or SMESH_Mesh object
1176 # @param name Study name of the mesh
1177 # @ingroup l2_construct
1178 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1179 self.smeshpyD=smeshpyD
1180 self.geompyD=geompyD
1185 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1188 # publish geom of mesh (issue 0021122)
1189 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1191 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1192 if studyID != geompyD.myStudyId:
1193 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1196 geo_name = name + " shape"
1198 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1199 geompyD.addToStudy( self.geom, geo_name )
1200 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1202 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1205 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1207 self.smeshpyD.SetName(self.mesh, name)
1209 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1212 self.geom = self.mesh.GetShapeToMesh()
1214 self.editor = self.mesh.GetMeshEditor()
1215 self.functors = [None] * SMESH.FT_Undefined._v
1217 # set self to algoCreator's
1218 for attrName in dir(self):
1219 attr = getattr( self, attrName )
1220 if isinstance( attr, algoCreator ):
1221 #print "algoCreator ", attrName
1222 setattr( self, attrName, attr.copy( self ))
1227 ## Destructor. Clean-up resources
1230 #self.mesh.UnRegister()
1234 ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1235 # @param theMesh a SMESH_Mesh object
1236 # @ingroup l2_construct
1237 def SetMesh(self, theMesh):
1238 # do not call Register() as this prevents mesh servant deletion at closing study
1239 #if self.mesh: self.mesh.UnRegister()
1242 #self.mesh.Register()
1243 self.geom = self.mesh.GetShapeToMesh()
1246 ## Returns the mesh, that is an instance of SMESH_Mesh interface
1247 # @return a SMESH_Mesh object
1248 # @ingroup l2_construct
1252 ## Gets the name of the mesh
1253 # @return the name of the mesh as a string
1254 # @ingroup l2_construct
1256 name = GetName(self.GetMesh())
1259 ## Sets a name to the mesh
1260 # @param name a new name of the mesh
1261 # @ingroup l2_construct
1262 def SetName(self, name):
1263 self.smeshpyD.SetName(self.GetMesh(), name)
1265 ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1266 # The subMesh object gives access to the IDs of nodes and elements.
1267 # @param geom a geometrical object (shape)
1268 # @param name a name for the submesh
1269 # @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1270 # @ingroup l2_submeshes
1271 def GetSubMesh(self, geom, name):
1272 AssureGeomPublished( self, geom, name )
1273 submesh = self.mesh.GetSubMesh( geom, name )
1276 ## Returns the shape associated to the mesh
1277 # @return a GEOM_Object
1278 # @ingroup l2_construct
1282 ## Associates the given shape to the mesh (entails the recreation of the mesh)
1283 # @param geom the shape to be meshed (GEOM_Object)
1284 # @ingroup l2_construct
1285 def SetShape(self, geom):
1286 self.mesh = self.smeshpyD.CreateMesh(geom)
1288 ## Loads mesh from the study after opening the study
1292 ## Returns true if the hypotheses are defined well
1293 # @param theSubObject a sub-shape of a mesh shape
1294 # @return True or False
1295 # @ingroup l2_construct
1296 def IsReadyToCompute(self, theSubObject):
1297 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1299 ## Returns errors of hypotheses definition.
1300 # The list of errors is empty if everything is OK.
1301 # @param theSubObject a sub-shape of a mesh shape
1302 # @return a list of errors
1303 # @ingroup l2_construct
1304 def GetAlgoState(self, theSubObject):
1305 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1307 ## Returns a geometrical object on which the given element was built.
1308 # The returned geometrical object, if not nil, is either found in the
1309 # study or published by this method with the given name
1310 # @param theElementID the id of the mesh element
1311 # @param theGeomName the user-defined name of the geometrical object
1312 # @return GEOM::GEOM_Object instance
1313 # @ingroup l2_construct
1314 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1315 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1317 ## Returns the mesh dimension depending on the dimension of the underlying shape
1318 # or, if the mesh is not based on any shape, basing on deimension of elements
1319 # @return mesh dimension as an integer value [0,3]
1320 # @ingroup l1_auxiliary
1321 def MeshDimension(self):
1322 if self.mesh.HasShapeToMesh():
1323 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1324 if len( shells ) > 0 :
1326 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1328 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1333 if self.NbVolumes() > 0: return 3
1334 if self.NbFaces() > 0: return 2
1335 if self.NbEdges() > 0: return 1
1338 ## Evaluates size of prospective mesh on a shape
1339 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1340 # To know predicted number of e.g. edges, inquire it this way
1341 # Evaluate()[ EnumToLong( Entity_Edge )]
1342 def Evaluate(self, geom=0):
1343 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1345 geom = self.mesh.GetShapeToMesh()
1348 return self.smeshpyD.Evaluate(self.mesh, geom)
1351 ## Computes the mesh and returns the status of the computation
1352 # @param geom geomtrical shape on which mesh data should be computed
1353 # @param discardModifs if True and the mesh has been edited since
1354 # a last total re-compute and that may prevent successful partial re-compute,
1355 # then the mesh is cleaned before Compute()
1356 # @return True or False
1357 # @ingroup l2_construct
1358 def Compute(self, geom=0, discardModifs=False):
1359 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1361 geom = self.mesh.GetShapeToMesh()
1366 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1368 ok = self.smeshpyD.Compute(self.mesh, geom)
1369 except SALOME.SALOME_Exception, ex:
1370 print "Mesh computation failed, exception caught:"
1371 print " ", ex.details.text
1374 print "Mesh computation failed, exception caught:"
1375 traceback.print_exc()
1379 # Treat compute errors
1380 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1381 for err in computeErrors:
1383 if self.mesh.HasShapeToMesh():
1385 mainIOR = salome.orb.object_to_string(geom)
1386 for sname in salome.myStudyManager.GetOpenStudies():
1387 s = salome.myStudyManager.GetStudyByName(sname)
1389 mainSO = s.FindObjectIOR(mainIOR)
1390 if not mainSO: continue
1391 if err.subShapeID == 1:
1392 shapeText = ' on "%s"' % mainSO.GetName()
1393 subIt = s.NewChildIterator(mainSO)
1395 subSO = subIt.Value()
1397 obj = subSO.GetObject()
1398 if not obj: continue
1399 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1401 ids = go.GetSubShapeIndices()
1402 if len(ids) == 1 and ids[0] == err.subShapeID:
1403 shapeText = ' on "%s"' % subSO.GetName()
1406 shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1408 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1410 shapeText = " on subshape #%s" % (err.subShapeID)
1412 shapeText = " on subshape #%s" % (err.subShapeID)
1414 stdErrors = ["OK", #COMPERR_OK
1415 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1416 "std::exception", #COMPERR_STD_EXCEPTION
1417 "OCC exception", #COMPERR_OCC_EXCEPTION
1418 "..", #COMPERR_SLM_EXCEPTION
1419 "Unknown exception", #COMPERR_EXCEPTION
1420 "Memory allocation problem", #COMPERR_MEMORY_PB
1421 "Algorithm failed", #COMPERR_ALGO_FAILED
1422 "Unexpected geometry", #COMPERR_BAD_SHAPE
1423 "Warning", #COMPERR_WARNING
1424 "Computation cancelled",#COMPERR_CANCELED
1425 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1427 if err.code < len(stdErrors): errText = stdErrors[err.code]
1429 errText = "code %s" % -err.code
1430 if errText: errText += ". "
1431 errText += err.comment
1432 if allReasons != "":allReasons += "\n"
1434 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1436 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1440 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1442 if err.isGlobalAlgo:
1450 reason = '%s %sD algorithm is missing' % (glob, dim)
1451 elif err.state == HYP_MISSING:
1452 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1453 % (glob, dim, name, dim))
1454 elif err.state == HYP_NOTCONFORM:
1455 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1456 elif err.state == HYP_BAD_PARAMETER:
1457 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1458 % ( glob, dim, name ))
1459 elif err.state == HYP_BAD_GEOMETRY:
1460 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1461 'geometry' % ( glob, dim, name ))
1462 elif err.state == HYP_HIDDEN_ALGO:
1463 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1464 'algorithm of upper dimension generating %sD mesh'
1465 % ( glob, dim, name, glob, dim ))
1467 reason = ("For unknown reason. "
1468 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1470 if allReasons != "":allReasons += "\n"
1471 allReasons += "- " + reason
1473 if not ok or allReasons != "":
1474 msg = '"' + GetName(self.mesh) + '"'
1475 if ok: msg += " has been computed with warnings"
1476 else: msg += " has not been computed"
1477 if allReasons != "": msg += ":"
1482 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1483 smeshgui = salome.ImportComponentGUI("SMESH")
1484 smeshgui.Init(self.mesh.GetStudyId())
1485 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1486 salome.sg.updateObjBrowser(1)
1490 ## Return submesh objects list in meshing order
1491 # @return list of list of submesh objects
1492 # @ingroup l2_construct
1493 def GetMeshOrder(self):
1494 return self.mesh.GetMeshOrder()
1496 ## Return submesh objects list in meshing order
1497 # @return list of list of submesh objects
1498 # @ingroup l2_construct
1499 def SetMeshOrder(self, submeshes):
1500 return self.mesh.SetMeshOrder(submeshes)
1502 ## Removes all nodes and elements
1503 # @ingroup l2_construct
1506 if ( salome.sg.hasDesktop() and
1507 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() )):
1508 smeshgui = salome.ImportComponentGUI("SMESH")
1509 smeshgui.Init(self.mesh.GetStudyId())
1510 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1511 salome.sg.updateObjBrowser(1)
1513 ## Removes all nodes and elements of indicated shape
1514 # @ingroup l2_construct
1515 def ClearSubMesh(self, geomId):
1516 self.mesh.ClearSubMesh(geomId)
1517 if salome.sg.hasDesktop():
1518 smeshgui = salome.ImportComponentGUI("SMESH")
1519 smeshgui.Init(self.mesh.GetStudyId())
1520 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1521 salome.sg.updateObjBrowser(1)
1523 ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1524 # @param fineness [0.0,1.0] defines mesh fineness
1525 # @return True or False
1526 # @ingroup l3_algos_basic
1527 def AutomaticTetrahedralization(self, fineness=0):
1528 dim = self.MeshDimension()
1530 self.RemoveGlobalHypotheses()
1531 self.Segment().AutomaticLength(fineness)
1533 self.Triangle().LengthFromEdges()
1538 return self.Compute()
1540 ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1541 # @param fineness [0.0, 1.0] defines mesh fineness
1542 # @return True or False
1543 # @ingroup l3_algos_basic
1544 def AutomaticHexahedralization(self, fineness=0):
1545 dim = self.MeshDimension()
1546 # assign the hypotheses
1547 self.RemoveGlobalHypotheses()
1548 self.Segment().AutomaticLength(fineness)
1555 return self.Compute()
1557 ## Assigns a hypothesis
1558 # @param hyp a hypothesis to assign
1559 # @param geom a subhape of mesh geometry
1560 # @return SMESH.Hypothesis_Status
1561 # @ingroup l2_hypotheses
1562 def AddHypothesis(self, hyp, geom=0):
1563 if isinstance( hyp, Mesh_Algorithm ):
1564 hyp = hyp.GetAlgorithm()
1569 geom = self.mesh.GetShapeToMesh()
1572 if self.mesh.HasShapeToMesh():
1573 hyp_type = hyp.GetName()
1574 lib_name = hyp.GetLibName()
1575 checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1576 if checkAll and geom:
1577 checkAll = geom.GetType() == 37
1578 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1580 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1581 status = self.mesh.AddHypothesis(geom, hyp)
1583 status = HYP_BAD_GEOMETRY
1584 hyp_name = GetName( hyp )
1587 geom_name = geom.GetName()
1588 isAlgo = hyp._narrow( SMESH_Algo )
1589 TreatHypoStatus( status, hyp_name, geom_name, isAlgo )
1592 ## Return True if an algorithm of hypothesis is assigned to a given shape
1593 # @param hyp a hypothesis to check
1594 # @param geom a subhape of mesh geometry
1595 # @return True of False
1596 # @ingroup l2_hypotheses
1597 def IsUsedHypothesis(self, hyp, geom):
1598 if not hyp: # or not geom
1600 if isinstance( hyp, Mesh_Algorithm ):
1601 hyp = hyp.GetAlgorithm()
1603 hyps = self.GetHypothesisList(geom)
1605 if h.GetId() == hyp.GetId():
1609 ## Unassigns a hypothesis
1610 # @param hyp a hypothesis to unassign
1611 # @param geom a sub-shape of mesh geometry
1612 # @return SMESH.Hypothesis_Status
1613 # @ingroup l2_hypotheses
1614 def RemoveHypothesis(self, hyp, geom=0):
1617 if isinstance( hyp, Mesh_Algorithm ):
1618 hyp = hyp.GetAlgorithm()
1624 if self.IsUsedHypothesis( hyp, shape ):
1625 return self.mesh.RemoveHypothesis( shape, hyp )
1626 hypName = GetName( hyp )
1627 geoName = GetName( shape )
1628 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1631 ## Gets the list of hypotheses added on a geometry
1632 # @param geom a sub-shape of mesh geometry
1633 # @return the sequence of SMESH_Hypothesis
1634 # @ingroup l2_hypotheses
1635 def GetHypothesisList(self, geom):
1636 return self.mesh.GetHypothesisList( geom )
1638 ## Removes all global hypotheses
1639 # @ingroup l2_hypotheses
1640 def RemoveGlobalHypotheses(self):
1641 current_hyps = self.mesh.GetHypothesisList( self.geom )
1642 for hyp in current_hyps:
1643 self.mesh.RemoveHypothesis( self.geom, hyp )
1647 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1648 ## allowing to overwrite the file if it exists or add the exported data to its contents
1649 # @param f is the file name
1650 # @param auto_groups boolean parameter for creating/not creating
1651 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1652 # the typical use is auto_groups=false.
1653 # @param version MED format version(MED_V2_1 or MED_V2_2)
1654 # @param overwrite boolean parameter for overwriting/not overwriting the file
1655 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1656 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1657 # - 1D if all mesh nodes lie on OX coordinate axis, or
1658 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1659 # - 3D in the rest cases.
1660 # If @a autoDimension is @c False, the space dimension is always 3.
1661 # @param fields : list of GEOM fields defined on the shape to mesh.
1662 # @param geomAssocFields : each character of this string means a need to export a
1663 # corresponding field; correspondence between fields and characters is following:
1664 # - 'v' stands for _vertices_ field;
1665 # - 'e' stands for _edges_ field;
1666 # - 'f' stands for _faces_ field;
1667 # - 's' stands for _solids_ field.
1668 # @ingroup l2_impexp
1669 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1670 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1671 if meshPart or fields or geomAssocFields:
1672 unRegister = genObjUnRegister()
1673 if isinstance( meshPart, list ):
1674 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1675 unRegister.set( meshPart )
1676 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1677 fields, geomAssocFields)
1679 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1681 ## Exports the mesh in a file in SAUV format
1682 # @param f is the file name
1683 # @param auto_groups boolean parameter for creating/not creating
1684 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1685 # the typical use is auto_groups=false.
1686 # @ingroup l2_impexp
1687 def ExportSAUV(self, f, auto_groups=0):
1688 self.mesh.ExportSAUV(f, auto_groups)
1690 ## Exports the mesh in a file in DAT format
1691 # @param f the file name
1692 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1693 # @ingroup l2_impexp
1694 def ExportDAT(self, f, meshPart=None):
1696 unRegister = genObjUnRegister()
1697 if isinstance( meshPart, list ):
1698 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1699 unRegister.set( meshPart )
1700 self.mesh.ExportPartToDAT( meshPart, f )
1702 self.mesh.ExportDAT(f)
1704 ## Exports the mesh in a file in UNV format
1705 # @param f the file name
1706 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1707 # @ingroup l2_impexp
1708 def ExportUNV(self, f, meshPart=None):
1710 unRegister = genObjUnRegister()
1711 if isinstance( meshPart, list ):
1712 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1713 unRegister.set( meshPart )
1714 self.mesh.ExportPartToUNV( meshPart, f )
1716 self.mesh.ExportUNV(f)
1718 ## Export the mesh in a file in STL format
1719 # @param f the file name
1720 # @param ascii defines the file encoding
1721 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1722 # @ingroup l2_impexp
1723 def ExportSTL(self, f, ascii=1, meshPart=None):
1725 unRegister = genObjUnRegister()
1726 if isinstance( meshPart, list ):
1727 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1728 unRegister.set( meshPart )
1729 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1731 self.mesh.ExportSTL(f, ascii)
1733 ## Exports the mesh in a file in CGNS format
1734 # @param f is the file name
1735 # @param overwrite boolean parameter for overwriting/not overwriting the file
1736 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1737 # @ingroup l2_impexp
1738 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1739 unRegister = genObjUnRegister()
1740 if isinstance( meshPart, list ):
1741 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1742 unRegister.set( meshPart )
1743 if isinstance( meshPart, Mesh ):
1744 meshPart = meshPart.mesh
1746 meshPart = self.mesh
1747 self.mesh.ExportCGNS(meshPart, f, overwrite)
1749 ## Exports the mesh in a file in GMF format.
1750 # GMF files must have .mesh extension for the ASCII format and .meshb for
1751 # the bynary format. Other extensions are not allowed.
1752 # @param f is the file name
1753 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1754 # @ingroup l2_impexp
1755 def ExportGMF(self, f, meshPart=None):
1756 unRegister = genObjUnRegister()
1757 if isinstance( meshPart, list ):
1758 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1759 unRegister.set( meshPart )
1760 if isinstance( meshPart, Mesh ):
1761 meshPart = meshPart.mesh
1763 meshPart = self.mesh
1764 self.mesh.ExportGMF(meshPart, f, True)
1766 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1767 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1768 ## allowing to overwrite the file if it exists or add the exported data to its contents
1769 # @param f the file name
1770 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1771 # @param opt boolean parameter for creating/not creating
1772 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1773 # @param overwrite boolean parameter for overwriting/not overwriting the file
1774 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1775 # - 1D if all mesh nodes lie on OX coordinate axis, or
1776 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1777 # - 3D in the rest cases.
1779 # If @a autoDimension is @c False, the space dimension is always 3.
1780 # @ingroup l2_impexp
1781 def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1782 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1784 # Operations with groups:
1785 # ----------------------
1787 ## Creates an empty mesh group
1788 # @param elementType the type of elements in the group
1789 # @param name the name of the mesh group
1790 # @return SMESH_Group
1791 # @ingroup l2_grps_create
1792 def CreateEmptyGroup(self, elementType, name):
1793 return self.mesh.CreateGroup(elementType, name)
1795 ## Creates a mesh group based on the geometric object \a grp
1796 # and gives a \a name, \n if this parameter is not defined
1797 # the name is the same as the geometric group name \n
1798 # Note: Works like GroupOnGeom().
1799 # @param grp a geometric group, a vertex, an edge, a face or a solid
1800 # @param name the name of the mesh group
1801 # @return SMESH_GroupOnGeom
1802 # @ingroup l2_grps_create
1803 def Group(self, grp, name=""):
1804 return self.GroupOnGeom(grp, name)
1806 ## Creates a mesh group based on the geometrical object \a grp
1807 # and gives a \a name, \n if this parameter is not defined
1808 # the name is the same as the geometrical group name
1809 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1810 # @param name the name of the mesh group
1811 # @param typ the type of elements in the group. If not set, it is
1812 # automatically detected by the type of the geometry
1813 # @return SMESH_GroupOnGeom
1814 # @ingroup l2_grps_create
1815 def GroupOnGeom(self, grp, name="", typ=None):
1816 AssureGeomPublished( self, grp, name )
1818 name = grp.GetName()
1820 typ = self._groupTypeFromShape( grp )
1821 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1823 ## Pivate method to get a type of group on geometry
1824 def _groupTypeFromShape( self, shape ):
1825 tgeo = str(shape.GetShapeType())
1826 if tgeo == "VERTEX":
1828 elif tgeo == "EDGE":
1830 elif tgeo == "FACE" or tgeo == "SHELL":
1832 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1834 elif tgeo == "COMPOUND":
1835 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1837 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1838 return self._groupTypeFromShape( sub[0] )
1841 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1844 ## Creates a mesh group with given \a name based on the \a filter which
1845 ## is a special type of group dynamically updating it's contents during
1846 ## mesh modification
1847 # @param typ the type of elements in the group
1848 # @param name the name of the mesh group
1849 # @param filter the filter defining group contents
1850 # @return SMESH_GroupOnFilter
1851 # @ingroup l2_grps_create
1852 def GroupOnFilter(self, typ, name, filter):
1853 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1855 ## Creates a mesh group by the given ids of elements
1856 # @param groupName the name of the mesh group
1857 # @param elementType the type of elements in the group
1858 # @param elemIDs the list of ids
1859 # @return SMESH_Group
1860 # @ingroup l2_grps_create
1861 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1862 group = self.mesh.CreateGroup(elementType, groupName)
1866 ## Creates a mesh group by the given conditions
1867 # @param groupName the name of the mesh group
1868 # @param elementType the type of elements in the group
1869 # @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1870 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1871 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
1872 # @param UnaryOp FT_LogicalNOT or FT_Undefined
1873 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1874 # FT_LyingOnGeom, FT_CoplanarFaces criteria
1875 # @return SMESH_Group
1876 # @ingroup l2_grps_create
1880 CritType=FT_Undefined,
1883 UnaryOp=FT_Undefined,
1885 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1886 group = self.MakeGroupByCriterion(groupName, aCriterion)
1889 ## Creates a mesh group by the given criterion
1890 # @param groupName the name of the mesh group
1891 # @param Criterion the instance of Criterion class
1892 # @return SMESH_Group
1893 # @ingroup l2_grps_create
1894 def MakeGroupByCriterion(self, groupName, Criterion):
1895 aFilterMgr = self.smeshpyD.CreateFilterManager()
1896 aFilter = aFilterMgr.CreateFilter()
1898 aCriteria.append(Criterion)
1899 aFilter.SetCriteria(aCriteria)
1900 group = self.MakeGroupByFilter(groupName, aFilter)
1901 aFilterMgr.UnRegister()
1904 ## Creates a mesh group by the given criteria (list of criteria)
1905 # @param groupName the name of the mesh group
1906 # @param theCriteria the list of criteria
1907 # @return SMESH_Group
1908 # @ingroup l2_grps_create
1909 def MakeGroupByCriteria(self, groupName, theCriteria):
1910 aFilterMgr = self.smeshpyD.CreateFilterManager()
1911 aFilter = aFilterMgr.CreateFilter()
1912 aFilter.SetCriteria(theCriteria)
1913 group = self.MakeGroupByFilter(groupName, aFilter)
1914 aFilterMgr.UnRegister()
1917 ## Creates a mesh group by the given filter
1918 # @param groupName the name of the mesh group
1919 # @param theFilter the instance of Filter class
1920 # @return SMESH_Group
1921 # @ingroup l2_grps_create
1922 def MakeGroupByFilter(self, groupName, theFilter):
1923 group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1924 theFilter.SetMesh( self.mesh )
1925 group.AddFrom( theFilter )
1929 # @ingroup l2_grps_delete
1930 def RemoveGroup(self, group):
1931 self.mesh.RemoveGroup(group)
1933 ## Removes a group with its contents
1934 # @ingroup l2_grps_delete
1935 def RemoveGroupWithContents(self, group):
1936 self.mesh.RemoveGroupWithContents(group)
1938 ## Gets the list of groups existing in the mesh in the order of creation (starting from the oldest one)
1939 # @return a sequence of SMESH_GroupBase
1940 # @ingroup l2_grps_create
1941 def GetGroups(self):
1942 return self.mesh.GetGroups()
1944 ## Gets the number of groups existing in the mesh
1945 # @return the quantity of groups as an integer value
1946 # @ingroup l2_grps_create
1948 return self.mesh.NbGroups()
1950 ## Gets the list of names of groups existing in the mesh
1951 # @return list of strings
1952 # @ingroup l2_grps_create
1953 def GetGroupNames(self):
1954 groups = self.GetGroups()
1956 for group in groups:
1957 names.append(group.GetName())
1960 ## Produces a union of two groups
1961 # A new group is created. All mesh elements that are
1962 # present in the initial groups are added to the new one
1963 # @return an instance of SMESH_Group
1964 # @ingroup l2_grps_operon
1965 def UnionGroups(self, group1, group2, name):
1966 return self.mesh.UnionGroups(group1, group2, name)
1968 ## Produces a union list of groups
1969 # New group is created. All mesh elements that are present in
1970 # initial groups are added to the new one
1971 # @return an instance of SMESH_Group
1972 # @ingroup l2_grps_operon
1973 def UnionListOfGroups(self, groups, name):
1974 return self.mesh.UnionListOfGroups(groups, name)
1976 ## Prodices an intersection of two groups
1977 # A new group is created. All mesh elements that are common
1978 # for the two initial groups are added to the new one.
1979 # @return an instance of SMESH_Group
1980 # @ingroup l2_grps_operon
1981 def IntersectGroups(self, group1, group2, name):
1982 return self.mesh.IntersectGroups(group1, group2, name)
1984 ## Produces an intersection of groups
1985 # New group is created. All mesh elements that are present in all
1986 # initial groups simultaneously are added to the new one
1987 # @return an instance of SMESH_Group
1988 # @ingroup l2_grps_operon
1989 def IntersectListOfGroups(self, groups, name):
1990 return self.mesh.IntersectListOfGroups(groups, name)
1992 ## Produces a cut of two groups
1993 # A new group is created. All mesh elements that are present in
1994 # the main group but are not present in the tool group are added to the new one
1995 # @return an instance of SMESH_Group
1996 # @ingroup l2_grps_operon
1997 def CutGroups(self, main_group, tool_group, name):
1998 return self.mesh.CutGroups(main_group, tool_group, name)
2000 ## Produces a cut of groups
2001 # A new group is created. All mesh elements that are present in main groups
2002 # but do not present in tool groups are added to the new one
2003 # @return an instance of SMESH_Group
2004 # @ingroup l2_grps_operon
2005 def CutListOfGroups(self, main_groups, tool_groups, name):
2006 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2008 ## Produces a group of elements of specified type using list of existing groups
2009 # A new group is created. System
2010 # 1) extracts all nodes on which groups elements are built
2011 # 2) combines all elements of specified dimension laying on these nodes
2012 # @return an instance of SMESH_Group
2013 # @ingroup l2_grps_operon
2014 def CreateDimGroup(self, groups, elem_type, name):
2015 return self.mesh.CreateDimGroup(groups, elem_type, name)
2018 ## Convert group on geom into standalone group
2019 # @ingroup l2_grps_delete
2020 def ConvertToStandalone(self, group):
2021 return self.mesh.ConvertToStandalone(group)
2023 # Get some info about mesh:
2024 # ------------------------
2026 ## Returns the log of nodes and elements added or removed
2027 # since the previous clear of the log.
2028 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2029 # @return list of log_block structures:
2034 # @ingroup l1_auxiliary
2035 def GetLog(self, clearAfterGet):
2036 return self.mesh.GetLog(clearAfterGet)
2038 ## Clears the log of nodes and elements added or removed since the previous
2039 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2040 # @ingroup l1_auxiliary
2042 self.mesh.ClearLog()
2044 ## Toggles auto color mode on the object.
2045 # @param theAutoColor the flag which toggles auto color mode.
2046 # @ingroup l1_auxiliary
2047 def SetAutoColor(self, theAutoColor):
2048 self.mesh.SetAutoColor(theAutoColor)
2050 ## Gets flag of object auto color mode.
2051 # @return True or False
2052 # @ingroup l1_auxiliary
2053 def GetAutoColor(self):
2054 return self.mesh.GetAutoColor()
2056 ## Gets the internal ID
2057 # @return integer value, which is the internal Id of the mesh
2058 # @ingroup l1_auxiliary
2060 return self.mesh.GetId()
2063 # @return integer value, which is the study Id of the mesh
2064 # @ingroup l1_auxiliary
2065 def GetStudyId(self):
2066 return self.mesh.GetStudyId()
2068 ## Checks the group names for duplications.
2069 # Consider the maximum group name length stored in MED file.
2070 # @return True or False
2071 # @ingroup l1_auxiliary
2072 def HasDuplicatedGroupNamesMED(self):
2073 return self.mesh.HasDuplicatedGroupNamesMED()
2075 ## Obtains the mesh editor tool
2076 # @return an instance of SMESH_MeshEditor
2077 # @ingroup l1_modifying
2078 def GetMeshEditor(self):
2081 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2082 # can be passed as argument to a method accepting mesh, group or sub-mesh
2083 # @return an instance of SMESH_IDSource
2084 # @ingroup l1_auxiliary
2085 def GetIDSource(self, ids, elemType):
2086 return self.editor.MakeIDSource(ids, elemType)
2089 # Get informations about mesh contents:
2090 # ------------------------------------
2092 ## Gets the mesh stattistic
2093 # @return dictionary type element - count of elements
2094 # @ingroup l1_meshinfo
2095 def GetMeshInfo(self, obj = None):
2096 if not obj: obj = self.mesh
2097 return self.smeshpyD.GetMeshInfo(obj)
2099 ## Returns the number of nodes in the mesh
2100 # @return an integer value
2101 # @ingroup l1_meshinfo
2103 return self.mesh.NbNodes()
2105 ## Returns the number of elements in the mesh
2106 # @return an integer value
2107 # @ingroup l1_meshinfo
2108 def NbElements(self):
2109 return self.mesh.NbElements()
2111 ## Returns the number of 0d elements in the mesh
2112 # @return an integer value
2113 # @ingroup l1_meshinfo
2114 def Nb0DElements(self):
2115 return self.mesh.Nb0DElements()
2117 ## Returns the number of ball discrete elements in the mesh
2118 # @return an integer value
2119 # @ingroup l1_meshinfo
2121 return self.mesh.NbBalls()
2123 ## Returns the number of edges in the mesh
2124 # @return an integer value
2125 # @ingroup l1_meshinfo
2127 return self.mesh.NbEdges()
2129 ## Returns the number of edges with the given order in the mesh
2130 # @param elementOrder the order of elements:
2131 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2132 # @return an integer value
2133 # @ingroup l1_meshinfo
2134 def NbEdgesOfOrder(self, elementOrder):
2135 return self.mesh.NbEdgesOfOrder(elementOrder)
2137 ## Returns the number of faces in the mesh
2138 # @return an integer value
2139 # @ingroup l1_meshinfo
2141 return self.mesh.NbFaces()
2143 ## Returns the number of faces with the given order in the mesh
2144 # @param elementOrder the order of elements:
2145 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2146 # @return an integer value
2147 # @ingroup l1_meshinfo
2148 def NbFacesOfOrder(self, elementOrder):
2149 return self.mesh.NbFacesOfOrder(elementOrder)
2151 ## Returns the number of triangles in the mesh
2152 # @return an integer value
2153 # @ingroup l1_meshinfo
2154 def NbTriangles(self):
2155 return self.mesh.NbTriangles()
2157 ## Returns the number of triangles with the given order in the mesh
2158 # @param elementOrder is the order of elements:
2159 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2160 # @return an integer value
2161 # @ingroup l1_meshinfo
2162 def NbTrianglesOfOrder(self, elementOrder):
2163 return self.mesh.NbTrianglesOfOrder(elementOrder)
2165 ## Returns the number of biquadratic triangles in the mesh
2166 # @return an integer value
2167 # @ingroup l1_meshinfo
2168 def NbBiQuadTriangles(self):
2169 return self.mesh.NbBiQuadTriangles()
2171 ## Returns the number of quadrangles in the mesh
2172 # @return an integer value
2173 # @ingroup l1_meshinfo
2174 def NbQuadrangles(self):
2175 return self.mesh.NbQuadrangles()
2177 ## Returns the number of quadrangles with the given order in the mesh
2178 # @param elementOrder the order of elements:
2179 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2180 # @return an integer value
2181 # @ingroup l1_meshinfo
2182 def NbQuadranglesOfOrder(self, elementOrder):
2183 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2185 ## Returns the number of biquadratic quadrangles in the mesh
2186 # @return an integer value
2187 # @ingroup l1_meshinfo
2188 def NbBiQuadQuadrangles(self):
2189 return self.mesh.NbBiQuadQuadrangles()
2191 ## Returns the number of polygons in the mesh
2192 # @return an integer value
2193 # @ingroup l1_meshinfo
2194 def NbPolygons(self):
2195 return self.mesh.NbPolygons()
2197 ## Returns the number of volumes in the mesh
2198 # @return an integer value
2199 # @ingroup l1_meshinfo
2200 def NbVolumes(self):
2201 return self.mesh.NbVolumes()
2203 ## Returns the number of volumes with the given order in the mesh
2204 # @param elementOrder the order of elements:
2205 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2206 # @return an integer value
2207 # @ingroup l1_meshinfo
2208 def NbVolumesOfOrder(self, elementOrder):
2209 return self.mesh.NbVolumesOfOrder(elementOrder)
2211 ## Returns the number of tetrahedrons in the mesh
2212 # @return an integer value
2213 # @ingroup l1_meshinfo
2215 return self.mesh.NbTetras()
2217 ## Returns the number of tetrahedrons with the given order in the mesh
2218 # @param elementOrder the order of elements:
2219 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2220 # @return an integer value
2221 # @ingroup l1_meshinfo
2222 def NbTetrasOfOrder(self, elementOrder):
2223 return self.mesh.NbTetrasOfOrder(elementOrder)
2225 ## Returns the number of hexahedrons in the mesh
2226 # @return an integer value
2227 # @ingroup l1_meshinfo
2229 return self.mesh.NbHexas()
2231 ## Returns the number of hexahedrons with the given order in the mesh
2232 # @param elementOrder the order of elements:
2233 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2234 # @return an integer value
2235 # @ingroup l1_meshinfo
2236 def NbHexasOfOrder(self, elementOrder):
2237 return self.mesh.NbHexasOfOrder(elementOrder)
2239 ## Returns the number of triquadratic hexahedrons in the mesh
2240 # @return an integer value
2241 # @ingroup l1_meshinfo
2242 def NbTriQuadraticHexas(self):
2243 return self.mesh.NbTriQuadraticHexas()
2245 ## Returns the number of pyramids in the mesh
2246 # @return an integer value
2247 # @ingroup l1_meshinfo
2248 def NbPyramids(self):
2249 return self.mesh.NbPyramids()
2251 ## Returns the number of pyramids with the given order in the mesh
2252 # @param elementOrder the order of elements:
2253 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2254 # @return an integer value
2255 # @ingroup l1_meshinfo
2256 def NbPyramidsOfOrder(self, elementOrder):
2257 return self.mesh.NbPyramidsOfOrder(elementOrder)
2259 ## Returns the number of prisms in the mesh
2260 # @return an integer value
2261 # @ingroup l1_meshinfo
2263 return self.mesh.NbPrisms()
2265 ## Returns the number of prisms with the given order in the mesh
2266 # @param elementOrder the order of elements:
2267 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2268 # @return an integer value
2269 # @ingroup l1_meshinfo
2270 def NbPrismsOfOrder(self, elementOrder):
2271 return self.mesh.NbPrismsOfOrder(elementOrder)
2273 ## Returns the number of hexagonal prisms in the mesh
2274 # @return an integer value
2275 # @ingroup l1_meshinfo
2276 def NbHexagonalPrisms(self):
2277 return self.mesh.NbHexagonalPrisms()
2279 ## Returns the number of polyhedrons in the mesh
2280 # @return an integer value
2281 # @ingroup l1_meshinfo
2282 def NbPolyhedrons(self):
2283 return self.mesh.NbPolyhedrons()
2285 ## Returns the number of submeshes in the mesh
2286 # @return an integer value
2287 # @ingroup l1_meshinfo
2288 def NbSubMesh(self):
2289 return self.mesh.NbSubMesh()
2291 ## Returns the list of mesh elements IDs
2292 # @return the list of integer values
2293 # @ingroup l1_meshinfo
2294 def GetElementsId(self):
2295 return self.mesh.GetElementsId()
2297 ## Returns the list of IDs of mesh elements with the given type
2298 # @param elementType the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2299 # @return list of integer values
2300 # @ingroup l1_meshinfo
2301 def GetElementsByType(self, elementType):
2302 return self.mesh.GetElementsByType(elementType)
2304 ## Returns the list of mesh nodes IDs
2305 # @return the list of integer values
2306 # @ingroup l1_meshinfo
2307 def GetNodesId(self):
2308 return self.mesh.GetNodesId()
2310 # Get the information about mesh elements:
2311 # ------------------------------------
2313 ## Returns the type of mesh element
2314 # @return the value from SMESH::ElementType enumeration
2315 # @ingroup l1_meshinfo
2316 def GetElementType(self, id, iselem):
2317 return self.mesh.GetElementType(id, iselem)
2319 ## Returns the geometric type of mesh element
2320 # @return the value from SMESH::EntityType enumeration
2321 # @ingroup l1_meshinfo
2322 def GetElementGeomType(self, id):
2323 return self.mesh.GetElementGeomType(id)
2325 ## Returns the shape type of mesh element
2326 # @return the value from SMESH::GeometryType enumeration
2327 # @ingroup l1_meshinfo
2328 def GetElementShape(self, id):
2329 return self.mesh.GetElementShape(id)
2331 ## Returns the list of submesh elements IDs
2332 # @param Shape a geom object(sub-shape) IOR
2333 # Shape must be the sub-shape of a ShapeToMesh()
2334 # @return the list of integer values
2335 # @ingroup l1_meshinfo
2336 def GetSubMeshElementsId(self, Shape):
2337 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2338 ShapeID = Shape.GetSubShapeIndices()[0]
2341 return self.mesh.GetSubMeshElementsId(ShapeID)
2343 ## Returns the list of submesh nodes IDs
2344 # @param Shape a geom object(sub-shape) IOR
2345 # Shape must be the sub-shape of a ShapeToMesh()
2346 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2347 # @return the list of integer values
2348 # @ingroup l1_meshinfo
2349 def GetSubMeshNodesId(self, Shape, all):
2350 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2351 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2354 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2356 ## Returns type of elements on given shape
2357 # @param Shape a geom object(sub-shape) IOR
2358 # Shape must be a sub-shape of a ShapeToMesh()
2359 # @return element type
2360 # @ingroup l1_meshinfo
2361 def GetSubMeshElementType(self, Shape):
2362 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2363 ShapeID = Shape.GetSubShapeIndices()[0]
2366 return self.mesh.GetSubMeshElementType(ShapeID)
2368 ## Gets the mesh description
2369 # @return string value
2370 # @ingroup l1_meshinfo
2372 return self.mesh.Dump()
2375 # Get the information about nodes and elements of a mesh by its IDs:
2376 # -----------------------------------------------------------
2378 ## Gets XYZ coordinates of a node
2379 # \n If there is no nodes for the given ID - returns an empty list
2380 # @return a list of double precision values
2381 # @ingroup l1_meshinfo
2382 def GetNodeXYZ(self, id):
2383 return self.mesh.GetNodeXYZ(id)
2385 ## Returns list of IDs of inverse elements for the given node
2386 # \n If there is no node for the given ID - returns an empty list
2387 # @return a list of integer values
2388 # @ingroup l1_meshinfo
2389 def GetNodeInverseElements(self, id):
2390 return self.mesh.GetNodeInverseElements(id)
2392 ## @brief Returns the position of a node on the shape
2393 # @return SMESH::NodePosition
2394 # @ingroup l1_meshinfo
2395 def GetNodePosition(self,NodeID):
2396 return self.mesh.GetNodePosition(NodeID)
2398 ## @brief Returns the position of an element on the shape
2399 # @return SMESH::ElementPosition
2400 # @ingroup l1_meshinfo
2401 def GetElementPosition(self,ElemID):
2402 return self.mesh.GetElementPosition(ElemID)
2404 ## If the given element is a node, returns the ID of shape
2405 # \n If there is no node for the given ID - returns -1
2406 # @return an integer value
2407 # @ingroup l1_meshinfo
2408 def GetShapeID(self, id):
2409 return self.mesh.GetShapeID(id)
2411 ## Returns the ID of the result shape after
2412 # FindShape() from SMESH_MeshEditor for the given element
2413 # \n If there is no element for the given ID - returns -1
2414 # @return an integer value
2415 # @ingroup l1_meshinfo
2416 def GetShapeIDForElem(self,id):
2417 return self.mesh.GetShapeIDForElem(id)
2419 ## Returns the number of nodes for the given element
2420 # \n If there is no element for the given ID - returns -1
2421 # @return an integer value
2422 # @ingroup l1_meshinfo
2423 def GetElemNbNodes(self, id):
2424 return self.mesh.GetElemNbNodes(id)
2426 ## Returns the node ID the given (zero based) index for the given element
2427 # \n If there is no element for the given ID - returns -1
2428 # \n If there is no node for the given index - returns -2
2429 # @return an integer value
2430 # @ingroup l1_meshinfo
2431 def GetElemNode(self, id, index):
2432 return self.mesh.GetElemNode(id, index)
2434 ## Returns the IDs of nodes of the given element
2435 # @return a list of integer values
2436 # @ingroup l1_meshinfo
2437 def GetElemNodes(self, id):
2438 return self.mesh.GetElemNodes(id)
2440 ## Returns true if the given node is the medium node in the given quadratic element
2441 # @ingroup l1_meshinfo
2442 def IsMediumNode(self, elementID, nodeID):
2443 return self.mesh.IsMediumNode(elementID, nodeID)
2445 ## Returns true if the given node is the medium node in one of quadratic elements
2446 # @ingroup l1_meshinfo
2447 def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2448 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2450 ## Returns the number of edges for the given element
2451 # @ingroup l1_meshinfo
2452 def ElemNbEdges(self, id):
2453 return self.mesh.ElemNbEdges(id)
2455 ## Returns the number of faces for the given element
2456 # @ingroup l1_meshinfo
2457 def ElemNbFaces(self, id):
2458 return self.mesh.ElemNbFaces(id)
2460 ## Returns nodes of given face (counted from zero) for given volumic element.
2461 # @ingroup l1_meshinfo
2462 def GetElemFaceNodes(self,elemId, faceIndex):
2463 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2465 ## Returns three components of normal of given mesh face
2466 # (or an empty array in KO case)
2467 # @ingroup l1_meshinfo
2468 def GetFaceNormal(self, faceId, normalized=False):
2469 return self.mesh.GetFaceNormal(faceId,normalized)
2471 ## Returns an element based on all given nodes.
2472 # @ingroup l1_meshinfo
2473 def FindElementByNodes(self,nodes):
2474 return self.mesh.FindElementByNodes(nodes)
2476 ## Returns true if the given element is a polygon
2477 # @ingroup l1_meshinfo
2478 def IsPoly(self, id):
2479 return self.mesh.IsPoly(id)
2481 ## Returns true if the given element is quadratic
2482 # @ingroup l1_meshinfo
2483 def IsQuadratic(self, id):
2484 return self.mesh.IsQuadratic(id)
2486 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2487 # @ingroup l1_meshinfo
2488 def GetBallDiameter(self, id):
2489 return self.mesh.GetBallDiameter(id)
2491 ## Returns XYZ coordinates of the barycenter of the given element
2492 # \n If there is no element for the given ID - returns an empty list
2493 # @return a list of three double values
2494 # @ingroup l1_meshinfo
2495 def BaryCenter(self, id):
2496 return self.mesh.BaryCenter(id)
2498 ## Passes mesh elements through the given filter and return IDs of fitting elements
2499 # @param theFilter SMESH_Filter
2500 # @return a list of ids
2501 # @ingroup l1_controls
2502 def GetIdsFromFilter(self, theFilter):
2503 theFilter.SetMesh( self.mesh )
2504 return theFilter.GetIDs()
2506 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2507 # Returns a list of special structures (borders).
2508 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2509 # @ingroup l1_controls
2510 def GetFreeBorders(self):
2511 aFilterMgr = self.smeshpyD.CreateFilterManager()
2512 aPredicate = aFilterMgr.CreateFreeEdges()
2513 aPredicate.SetMesh(self.mesh)
2514 aBorders = aPredicate.GetBorders()
2515 aFilterMgr.UnRegister()
2519 # Get mesh measurements information:
2520 # ------------------------------------
2522 ## Get minimum distance between two nodes, elements or distance to the origin
2523 # @param id1 first node/element id
2524 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2525 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2526 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2527 # @return minimum distance value
2528 # @sa GetMinDistance()
2529 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2530 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2531 return aMeasure.value
2533 ## Get measure structure specifying minimum distance data between two objects
2534 # @param id1 first node/element id
2535 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2536 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2537 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2538 # @return Measure structure
2540 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2542 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2544 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2547 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2549 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2554 aMeasurements = self.smeshpyD.CreateMeasurements()
2555 aMeasure = aMeasurements.MinDistance(id1, id2)
2556 genObjUnRegister([aMeasurements,id1, id2])
2559 ## Get bounding box of the specified object(s)
2560 # @param objects single source object or list of source objects or list of nodes/elements IDs
2561 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2562 # @c False specifies that @a objects are nodes
2563 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2564 # @sa GetBoundingBox()
2565 def BoundingBox(self, objects=None, isElem=False):
2566 result = self.GetBoundingBox(objects, isElem)
2570 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2573 ## Get measure structure specifying bounding box data of the specified object(s)
2574 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2575 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2576 # @c False specifies that @a objects are nodes
2577 # @return Measure structure
2579 def GetBoundingBox(self, IDs=None, isElem=False):
2582 elif isinstance(IDs, tuple):
2584 if not isinstance(IDs, list):
2586 if len(IDs) > 0 and isinstance(IDs[0], int):
2589 unRegister = genObjUnRegister()
2591 if isinstance(o, Mesh):
2592 srclist.append(o.mesh)
2593 elif hasattr(o, "_narrow"):
2594 src = o._narrow(SMESH.SMESH_IDSource)
2595 if src: srclist.append(src)
2597 elif isinstance(o, list):
2599 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2601 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2602 unRegister.set( srclist[-1] )
2605 aMeasurements = self.smeshpyD.CreateMeasurements()
2606 unRegister.set( aMeasurements )
2607 aMeasure = aMeasurements.BoundingBox(srclist)
2610 # Mesh edition (SMESH_MeshEditor functionality):
2611 # ---------------------------------------------
2613 ## Removes the elements from the mesh by ids
2614 # @param IDsOfElements is a list of ids of elements to remove
2615 # @return True or False
2616 # @ingroup l2_modif_del
2617 def RemoveElements(self, IDsOfElements):
2618 return self.editor.RemoveElements(IDsOfElements)
2620 ## Removes nodes from mesh by ids
2621 # @param IDsOfNodes is a list of ids of nodes to remove
2622 # @return True or False
2623 # @ingroup l2_modif_del
2624 def RemoveNodes(self, IDsOfNodes):
2625 return self.editor.RemoveNodes(IDsOfNodes)
2627 ## Removes all orphan (free) nodes from mesh
2628 # @return number of the removed nodes
2629 # @ingroup l2_modif_del
2630 def RemoveOrphanNodes(self):
2631 return self.editor.RemoveOrphanNodes()
2633 ## Add a node to the mesh by coordinates
2634 # @return Id of the new node
2635 # @ingroup l2_modif_add
2636 def AddNode(self, x, y, z):
2637 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2638 if hasVars: self.mesh.SetParameters(Parameters)
2639 return self.editor.AddNode( x, y, z)
2641 ## Creates a 0D element on a node with given number.
2642 # @param IDOfNode the ID of node for creation of the element.
2643 # @return the Id of the new 0D element
2644 # @ingroup l2_modif_add
2645 def Add0DElement(self, IDOfNode):
2646 return self.editor.Add0DElement(IDOfNode)
2648 ## Create 0D elements on all nodes of the given elements except those
2649 # nodes on which a 0D element already exists.
2650 # @param theObject an object on whose nodes 0D elements will be created.
2651 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2652 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2653 # @param theGroupName optional name of a group to add 0D elements created
2654 # and/or found on nodes of \a theObject.
2655 # @return an object (a new group or a temporary SMESH_IDSource) holding
2656 # IDs of new and/or found 0D elements. IDs of 0D elements
2657 # can be retrieved from the returned object by calling GetIDs()
2658 # @ingroup l2_modif_add
2659 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2660 unRegister = genObjUnRegister()
2661 if isinstance( theObject, Mesh ):
2662 theObject = theObject.GetMesh()
2663 if isinstance( theObject, list ):
2664 theObject = self.GetIDSource( theObject, SMESH.ALL )
2665 unRegister.set( theObject )
2666 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2668 ## Creates a ball element on a node with given ID.
2669 # @param IDOfNode the ID of node for creation of the element.
2670 # @param diameter the bal diameter.
2671 # @return the Id of the new ball element
2672 # @ingroup l2_modif_add
2673 def AddBall(self, IDOfNode, diameter):
2674 return self.editor.AddBall( IDOfNode, diameter )
2676 ## Creates a linear or quadratic edge (this is determined
2677 # by the number of given nodes).
2678 # @param IDsOfNodes the list of node IDs for creation of the element.
2679 # The order of nodes in this list should correspond to the description
2680 # of MED. \n This description is located by the following link:
2681 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2682 # @return the Id of the new edge
2683 # @ingroup l2_modif_add
2684 def AddEdge(self, IDsOfNodes):
2685 return self.editor.AddEdge(IDsOfNodes)
2687 ## Creates a linear or quadratic face (this is determined
2688 # by the number of given nodes).
2689 # @param IDsOfNodes the list of node IDs for creation of the element.
2690 # The order of nodes in this list should correspond to the description
2691 # of MED. \n This description is located by the following link:
2692 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2693 # @return the Id of the new face
2694 # @ingroup l2_modif_add
2695 def AddFace(self, IDsOfNodes):
2696 return self.editor.AddFace(IDsOfNodes)
2698 ## Adds a polygonal face to the mesh by the list of node IDs
2699 # @param IdsOfNodes the list of node IDs for creation of the element.
2700 # @return the Id of the new face
2701 # @ingroup l2_modif_add
2702 def AddPolygonalFace(self, IdsOfNodes):
2703 return self.editor.AddPolygonalFace(IdsOfNodes)
2705 ## Creates both simple and quadratic volume (this is determined
2706 # by the number of given nodes).
2707 # @param IDsOfNodes the list of node IDs for creation of the element.
2708 # The order of nodes in this list should correspond to the description
2709 # of MED. \n This description is located by the following link:
2710 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2711 # @return the Id of the new volumic element
2712 # @ingroup l2_modif_add
2713 def AddVolume(self, IDsOfNodes):
2714 return self.editor.AddVolume(IDsOfNodes)
2716 ## Creates a volume of many faces, giving nodes for each face.
2717 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2718 # @param Quantities the list of integer values, Quantities[i]
2719 # gives the quantity of nodes in face number i.
2720 # @return the Id of the new volumic element
2721 # @ingroup l2_modif_add
2722 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2723 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2725 ## Creates a volume of many faces, giving the IDs of the existing faces.
2726 # @param IdsOfFaces the list of face IDs for volume creation.
2728 # Note: The created volume will refer only to the nodes
2729 # of the given faces, not to the faces themselves.
2730 # @return the Id of the new volumic element
2731 # @ingroup l2_modif_add
2732 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2733 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2736 ## @brief Binds a node to a vertex
2737 # @param NodeID a node ID
2738 # @param Vertex a vertex or vertex ID
2739 # @return True if succeed else raises an exception
2740 # @ingroup l2_modif_add
2741 def SetNodeOnVertex(self, NodeID, Vertex):
2742 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2743 VertexID = Vertex.GetSubShapeIndices()[0]
2747 self.editor.SetNodeOnVertex(NodeID, VertexID)
2748 except SALOME.SALOME_Exception, inst:
2749 raise ValueError, inst.details.text
2753 ## @brief Stores the node position on an edge
2754 # @param NodeID a node ID
2755 # @param Edge an edge or edge ID
2756 # @param paramOnEdge a parameter on the edge where the node is located
2757 # @return True if succeed else raises an exception
2758 # @ingroup l2_modif_add
2759 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2760 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2761 EdgeID = Edge.GetSubShapeIndices()[0]
2765 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2766 except SALOME.SALOME_Exception, inst:
2767 raise ValueError, inst.details.text
2770 ## @brief Stores node position on a face
2771 # @param NodeID a node ID
2772 # @param Face a face or face ID
2773 # @param u U parameter on the face where the node is located
2774 # @param v V parameter on the face where the node is located
2775 # @return True if succeed else raises an exception
2776 # @ingroup l2_modif_add
2777 def SetNodeOnFace(self, NodeID, Face, u, v):
2778 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2779 FaceID = Face.GetSubShapeIndices()[0]
2783 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2784 except SALOME.SALOME_Exception, inst:
2785 raise ValueError, inst.details.text
2788 ## @brief Binds a node to a solid
2789 # @param NodeID a node ID
2790 # @param Solid a solid or solid ID
2791 # @return True if succeed else raises an exception
2792 # @ingroup l2_modif_add
2793 def SetNodeInVolume(self, NodeID, Solid):
2794 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2795 SolidID = Solid.GetSubShapeIndices()[0]
2799 self.editor.SetNodeInVolume(NodeID, SolidID)
2800 except SALOME.SALOME_Exception, inst:
2801 raise ValueError, inst.details.text
2804 ## @brief Bind an element to a shape
2805 # @param ElementID an element ID
2806 # @param Shape a shape or shape ID
2807 # @return True if succeed else raises an exception
2808 # @ingroup l2_modif_add
2809 def SetMeshElementOnShape(self, ElementID, Shape):
2810 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2811 ShapeID = Shape.GetSubShapeIndices()[0]
2815 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2816 except SALOME.SALOME_Exception, inst:
2817 raise ValueError, inst.details.text
2821 ## Moves the node with the given id
2822 # @param NodeID the id of the node
2823 # @param x a new X coordinate
2824 # @param y a new Y coordinate
2825 # @param z a new Z coordinate
2826 # @return True if succeed else False
2827 # @ingroup l2_modif_movenode
2828 def MoveNode(self, NodeID, x, y, z):
2829 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2830 if hasVars: self.mesh.SetParameters(Parameters)
2831 return self.editor.MoveNode(NodeID, x, y, z)
2833 ## Finds the node closest to a point and moves it to a point location
2834 # @param x the X coordinate of a point
2835 # @param y the Y coordinate of a point
2836 # @param z the Z coordinate of a point
2837 # @param NodeID if specified (>0), the node with this ID is moved,
2838 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
2839 # @return the ID of a node
2840 # @ingroup l2_modif_throughp
2841 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2842 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2843 if hasVars: self.mesh.SetParameters(Parameters)
2844 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2846 ## Finds the node closest to a point
2847 # @param x the X coordinate of a point
2848 # @param y the Y coordinate of a point
2849 # @param z the Z coordinate of a point
2850 # @return the ID of a node
2851 # @ingroup l2_modif_throughp
2852 def FindNodeClosestTo(self, x, y, z):
2853 #preview = self.mesh.GetMeshEditPreviewer()
2854 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2855 return self.editor.FindNodeClosestTo(x, y, z)
2857 ## Finds the elements where a point lays IN or ON
2858 # @param x the X coordinate of a point
2859 # @param y the Y coordinate of a point
2860 # @param z the Z coordinate of a point
2861 # @param elementType type of elements to find (SMESH.ALL type
2862 # means elements of any type excluding nodes, discrete and 0D elements)
2863 # @param meshPart a part of mesh (group, sub-mesh) to search within
2864 # @return list of IDs of found elements
2865 # @ingroup l2_modif_throughp
2866 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2868 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2870 return self.editor.FindElementsByPoint(x, y, z, elementType)
2872 # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2873 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2874 # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2876 def GetPointState(self, x, y, z):
2877 return self.editor.GetPointState(x, y, z)
2879 ## Finds the node closest to a point and moves it to a point location
2880 # @param x the X coordinate of a point
2881 # @param y the Y coordinate of a point
2882 # @param z the Z coordinate of a point
2883 # @return the ID of a moved node
2884 # @ingroup l2_modif_throughp
2885 def MeshToPassThroughAPoint(self, x, y, z):
2886 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2888 ## Replaces two neighbour triangles sharing Node1-Node2 link
2889 # with the triangles built on the same 4 nodes but having other common link.
2890 # @param NodeID1 the ID of the first node
2891 # @param NodeID2 the ID of the second node
2892 # @return false if proper faces were not found
2893 # @ingroup l2_modif_invdiag
2894 def InverseDiag(self, NodeID1, NodeID2):
2895 return self.editor.InverseDiag(NodeID1, NodeID2)
2897 ## Replaces two neighbour triangles sharing Node1-Node2 link
2898 # with a quadrangle built on the same 4 nodes.
2899 # @param NodeID1 the ID of the first node
2900 # @param NodeID2 the ID of the second node
2901 # @return false if proper faces were not found
2902 # @ingroup l2_modif_unitetri
2903 def DeleteDiag(self, NodeID1, NodeID2):
2904 return self.editor.DeleteDiag(NodeID1, NodeID2)
2906 ## Reorients elements by ids
2907 # @param IDsOfElements if undefined reorients all mesh elements
2908 # @return True if succeed else False
2909 # @ingroup l2_modif_changori
2910 def Reorient(self, IDsOfElements=None):
2911 if IDsOfElements == None:
2912 IDsOfElements = self.GetElementsId()
2913 return self.editor.Reorient(IDsOfElements)
2915 ## Reorients all elements of the object
2916 # @param theObject mesh, submesh or group
2917 # @return True if succeed else False
2918 # @ingroup l2_modif_changori
2919 def ReorientObject(self, theObject):
2920 if ( isinstance( theObject, Mesh )):
2921 theObject = theObject.GetMesh()
2922 return self.editor.ReorientObject(theObject)
2924 ## Reorient faces contained in \a the2DObject.
2925 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2926 # @param theDirection is a desired direction of normal of \a theFace.
2927 # It can be either a GEOM vector or a list of coordinates [x,y,z].
2928 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2929 # compared with theDirection. It can be either ID of face or a point
2930 # by which the face will be found. The point can be given as either
2931 # a GEOM vertex or a list of point coordinates.
2932 # @return number of reoriented faces
2933 # @ingroup l2_modif_changori
2934 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2935 unRegister = genObjUnRegister()
2937 if isinstance( the2DObject, Mesh ):
2938 the2DObject = the2DObject.GetMesh()
2939 if isinstance( the2DObject, list ):
2940 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2941 unRegister.set( the2DObject )
2942 # check theDirection
2943 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
2944 theDirection = self.smeshpyD.GetDirStruct( theDirection )
2945 if isinstance( theDirection, list ):
2946 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
2947 # prepare theFace and thePoint
2948 theFace = theFaceOrPoint
2949 thePoint = PointStruct(0,0,0)
2950 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
2951 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
2953 if isinstance( theFaceOrPoint, list ):
2954 thePoint = PointStruct( *theFaceOrPoint )
2956 if isinstance( theFaceOrPoint, PointStruct ):
2957 thePoint = theFaceOrPoint
2959 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
2961 ## Fuses the neighbouring triangles into quadrangles.
2962 # @param IDsOfElements The triangles to be fused,
2963 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2964 # choose a neighbour to fuse with.
2965 # @param MaxAngle is the maximum angle between element normals at which the fusion
2966 # is still performed; theMaxAngle is mesured in radians.
2967 # Also it could be a name of variable which defines angle in degrees.
2968 # @return TRUE in case of success, FALSE otherwise.
2969 # @ingroup l2_modif_unitetri
2970 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
2971 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2972 self.mesh.SetParameters(Parameters)
2973 if not IDsOfElements:
2974 IDsOfElements = self.GetElementsId()
2975 Functor = self.smeshpyD.GetFunctor(theCriterion)
2976 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
2978 ## Fuses the neighbouring triangles of the object into quadrangles
2979 # @param theObject is mesh, submesh or group
2980 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2981 # choose a neighbour to fuse with.
2982 # @param MaxAngle a max angle between element normals at which the fusion
2983 # is still performed; theMaxAngle is mesured in radians.
2984 # @return TRUE in case of success, FALSE otherwise.
2985 # @ingroup l2_modif_unitetri
2986 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
2987 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2988 self.mesh.SetParameters(Parameters)
2989 if isinstance( theObject, Mesh ):
2990 theObject = theObject.GetMesh()
2991 Functor = self.smeshpyD.GetFunctor(theCriterion)
2992 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
2994 ## Splits quadrangles into triangles.
2995 # @param IDsOfElements the faces to be splitted.
2996 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2997 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
2998 # value, then quadrangles will be split by the smallest diagonal.
2999 # @return TRUE in case of success, FALSE otherwise.
3000 # @ingroup l2_modif_cutquadr
3001 def QuadToTri (self, IDsOfElements, theCriterion = None):
3002 if IDsOfElements == []:
3003 IDsOfElements = self.GetElementsId()
3004 if theCriterion is None:
3005 theCriterion = FT_MaxElementLength2D
3006 Functor = self.smeshpyD.GetFunctor(theCriterion)
3007 return self.editor.QuadToTri(IDsOfElements, Functor)
3009 ## Splits quadrangles into triangles.
3010 # @param theObject the object from which the list of elements is taken,
3011 # this is mesh, submesh or group
3012 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3013 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3014 # value, then quadrangles will be split by the smallest diagonal.
3015 # @return TRUE in case of success, FALSE otherwise.
3016 # @ingroup l2_modif_cutquadr
3017 def QuadToTriObject (self, theObject, theCriterion = None):
3018 if ( isinstance( theObject, Mesh )):
3019 theObject = theObject.GetMesh()
3020 if theCriterion is None:
3021 theCriterion = FT_MaxElementLength2D
3022 Functor = self.smeshpyD.GetFunctor(theCriterion)
3023 return self.editor.QuadToTriObject(theObject, Functor)
3025 ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3027 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3028 # group or a list of face IDs. By default all quadrangles are split
3029 # @ingroup l2_modif_cutquadr
3030 def QuadTo4Tri (self, theElements=[]):
3031 unRegister = genObjUnRegister()
3032 if isinstance( theElements, Mesh ):
3033 theElements = theElements.mesh
3034 elif not theElements:
3035 theElements = self.mesh
3036 elif isinstance( theElements, list ):
3037 theElements = self.GetIDSource( theElements, SMESH.FACE )
3038 unRegister.set( theElements )
3039 return self.editor.QuadTo4Tri( theElements )
3041 ## Splits quadrangles into triangles.
3042 # @param IDsOfElements the faces to be splitted
3043 # @param Diag13 is used to choose a diagonal for splitting.
3044 # @return TRUE in case of success, FALSE otherwise.
3045 # @ingroup l2_modif_cutquadr
3046 def SplitQuad (self, IDsOfElements, Diag13):
3047 if IDsOfElements == []:
3048 IDsOfElements = self.GetElementsId()
3049 return self.editor.SplitQuad(IDsOfElements, Diag13)
3051 ## Splits quadrangles into triangles.
3052 # @param theObject the object from which the list of elements is taken,
3053 # this is mesh, submesh or group
3054 # @param Diag13 is used to choose a diagonal for splitting.
3055 # @return TRUE in case of success, FALSE otherwise.
3056 # @ingroup l2_modif_cutquadr
3057 def SplitQuadObject (self, theObject, Diag13):
3058 if ( isinstance( theObject, Mesh )):
3059 theObject = theObject.GetMesh()
3060 return self.editor.SplitQuadObject(theObject, Diag13)
3062 ## Finds a better splitting of the given quadrangle.
3063 # @param IDOfQuad the ID of the quadrangle to be splitted.
3064 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3065 # choose a diagonal for splitting.
3066 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3067 # diagonal is better, 0 if error occurs.
3068 # @ingroup l2_modif_cutquadr
3069 def BestSplit (self, IDOfQuad, theCriterion):
3070 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3072 ## Splits volumic elements into tetrahedrons
3073 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3074 # @param method flags passing splitting method:
3075 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3076 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3077 # @ingroup l2_modif_cutquadr
3078 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3079 unRegister = genObjUnRegister()
3080 if isinstance( elems, Mesh ):
3081 elems = elems.GetMesh()
3082 if ( isinstance( elems, list )):
3083 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3084 unRegister.set( elems )
3085 self.editor.SplitVolumesIntoTetra(elems, method)
3087 ## Splits hexahedra into prisms
3088 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3089 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3090 # gives a normal vector defining facets to split into triangles.
3091 # @a startHexPoint can be either a triple of coordinates or a vertex.
3092 # @param facetNormal a normal to a facet to split into triangles of a
3093 # hexahedron found by @a startHexPoint.
3094 # @a facetNormal can be either a triple of coordinates or an edge.
3095 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3096 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3097 # @param allDomains if @c False, only hexahedra adjacent to one closest
3098 # to @a startHexPoint are split, else @a startHexPoint
3099 # is used to find the facet to split in all domains present in @a elems.
3100 # @ingroup l2_modif_cutquadr
3101 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3102 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3104 unRegister = genObjUnRegister()
3105 if isinstance( elems, Mesh ):
3106 elems = elems.GetMesh()
3107 if ( isinstance( elems, list )):
3108 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3109 unRegister.set( elems )
3112 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3113 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3114 elif isinstance( startHexPoint, list ):
3115 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3118 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3119 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3120 elif isinstance( facetNormal, list ):
3121 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3124 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3126 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3128 ## Splits quadrangle faces near triangular facets of volumes
3130 # @ingroup l1_auxiliary
3131 def SplitQuadsNearTriangularFacets(self):
3132 faces_array = self.GetElementsByType(SMESH.FACE)
3133 for face_id in faces_array:
3134 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3135 quad_nodes = self.mesh.GetElemNodes(face_id)
3136 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3137 isVolumeFound = False
3138 for node1_elem in node1_elems:
3139 if not isVolumeFound:
3140 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3141 nb_nodes = self.GetElemNbNodes(node1_elem)
3142 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3143 volume_elem = node1_elem
3144 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3145 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3146 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3147 isVolumeFound = True
3148 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3149 self.SplitQuad([face_id], False) # diagonal 2-4
3150 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3151 isVolumeFound = True
3152 self.SplitQuad([face_id], True) # diagonal 1-3
3153 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3154 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3155 isVolumeFound = True
3156 self.SplitQuad([face_id], True) # diagonal 1-3
3158 ## @brief Splits hexahedrons into tetrahedrons.
3160 # This operation uses pattern mapping functionality for splitting.
3161 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3162 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3163 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3164 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3165 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3166 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3167 # @return TRUE in case of success, FALSE otherwise.
3168 # @ingroup l1_auxiliary
3169 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3170 # Pattern: 5.---------.6
3175 # (0,0,1) 4.---------.7 * |
3182 # (0,0,0) 0.---------.3
3183 pattern_tetra = "!!! Nb of points: \n 8 \n\
3193 !!! Indices of points of 6 tetras: \n\
3201 pattern = self.smeshpyD.GetPattern()
3202 isDone = pattern.LoadFromFile(pattern_tetra)
3204 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3207 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3208 isDone = pattern.MakeMesh(self.mesh, False, False)
3209 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3211 # split quafrangle faces near triangular facets of volumes
3212 self.SplitQuadsNearTriangularFacets()
3216 ## @brief Split hexahedrons into prisms.
3218 # Uses the pattern mapping functionality for splitting.
3219 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3220 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3221 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3222 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3223 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3224 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3225 # @return TRUE in case of success, FALSE otherwise.
3226 # @ingroup l1_auxiliary
3227 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3228 # Pattern: 5.---------.6
3233 # (0,0,1) 4.---------.7 |
3240 # (0,0,0) 0.---------.3
3241 pattern_prism = "!!! Nb of points: \n 8 \n\
3251 !!! Indices of points of 2 prisms: \n\
3255 pattern = self.smeshpyD.GetPattern()
3256 isDone = pattern.LoadFromFile(pattern_prism)
3258 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3261 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3262 isDone = pattern.MakeMesh(self.mesh, False, False)
3263 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3265 # Splits quafrangle faces near triangular facets of volumes
3266 self.SplitQuadsNearTriangularFacets()
3270 ## Smoothes elements
3271 # @param IDsOfElements the list if ids of elements to smooth
3272 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3273 # Note that nodes built on edges and boundary nodes are always fixed.
3274 # @param MaxNbOfIterations the maximum number of iterations
3275 # @param MaxAspectRatio varies in range [1.0, inf]
3276 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3277 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3278 # @return TRUE in case of success, FALSE otherwise.
3279 # @ingroup l2_modif_smooth
3280 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3281 MaxNbOfIterations, MaxAspectRatio, Method):
3282 if IDsOfElements == []:
3283 IDsOfElements = self.GetElementsId()
3284 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3285 self.mesh.SetParameters(Parameters)
3286 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3287 MaxNbOfIterations, MaxAspectRatio, Method)
3289 ## Smoothes elements which belong to the given object
3290 # @param theObject the object to smooth
3291 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3292 # Note that nodes built on edges and boundary nodes are always fixed.
3293 # @param MaxNbOfIterations the maximum number of iterations
3294 # @param MaxAspectRatio varies in range [1.0, inf]
3295 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3296 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3297 # @return TRUE in case of success, FALSE otherwise.
3298 # @ingroup l2_modif_smooth
3299 def SmoothObject(self, theObject, IDsOfFixedNodes,
3300 MaxNbOfIterations, MaxAspectRatio, Method):
3301 if ( isinstance( theObject, Mesh )):
3302 theObject = theObject.GetMesh()
3303 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3304 MaxNbOfIterations, MaxAspectRatio, Method)
3306 ## Parametrically smoothes the given elements
3307 # @param IDsOfElements the list if ids of elements to smooth
3308 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3309 # Note that nodes built on edges and boundary nodes are always fixed.
3310 # @param MaxNbOfIterations the maximum number of iterations
3311 # @param MaxAspectRatio varies in range [1.0, inf]
3312 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3313 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3314 # @return TRUE in case of success, FALSE otherwise.
3315 # @ingroup l2_modif_smooth
3316 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3317 MaxNbOfIterations, MaxAspectRatio, Method):
3318 if IDsOfElements == []:
3319 IDsOfElements = self.GetElementsId()
3320 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3321 self.mesh.SetParameters(Parameters)
3322 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3323 MaxNbOfIterations, MaxAspectRatio, Method)
3325 ## Parametrically smoothes the elements which belong to the given object
3326 # @param theObject the object to smooth
3327 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3328 # Note that nodes built on edges and boundary nodes are always fixed.
3329 # @param MaxNbOfIterations the maximum number of iterations
3330 # @param MaxAspectRatio varies in range [1.0, inf]
3331 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3332 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3333 # @return TRUE in case of success, FALSE otherwise.
3334 # @ingroup l2_modif_smooth
3335 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3336 MaxNbOfIterations, MaxAspectRatio, Method):
3337 if ( isinstance( theObject, Mesh )):
3338 theObject = theObject.GetMesh()
3339 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3340 MaxNbOfIterations, MaxAspectRatio, Method)
3342 ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3343 # them with quadratic with the same id.
3344 # @param theForce3d new node creation method:
3345 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3346 # 1 - the medium node lies at the middle of the line segments connecting start and end node of a mesh element
3347 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3348 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3349 # @ingroup l2_modif_tofromqu
3350 def ConvertToQuadratic(self, theForce3d, theSubMesh=None, theToBiQuad=False):
3351 if isinstance( theSubMesh, Mesh ):
3352 theSubMesh = theSubMesh.mesh
3354 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3357 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3359 self.editor.ConvertToQuadratic(theForce3d)
3360 error = self.editor.GetLastError()
3361 if error and error.comment:
3364 ## Converts the mesh from quadratic to ordinary,
3365 # deletes old quadratic elements, \n replacing
3366 # them with ordinary mesh elements with the same id.
3367 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3368 # @ingroup l2_modif_tofromqu
3369 def ConvertFromQuadratic(self, theSubMesh=None):
3371 self.editor.ConvertFromQuadraticObject(theSubMesh)
3373 return self.editor.ConvertFromQuadratic()
3375 ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3376 # @return TRUE if operation has been completed successfully, FALSE otherwise
3377 # @ingroup l2_modif_edit
3378 def Make2DMeshFrom3D(self):
3379 return self.editor. Make2DMeshFrom3D()
3381 ## Creates missing boundary elements
3382 # @param elements - elements whose boundary is to be checked:
3383 # mesh, group, sub-mesh or list of elements
3384 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3385 # @param dimension - defines type of boundary elements to create:
3386 # SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D
3387 # SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3388 # @param groupName - a name of group to store created boundary elements in,
3389 # "" means not to create the group
3390 # @param meshName - a name of new mesh to store created boundary elements in,
3391 # "" means not to create the new mesh
3392 # @param toCopyElements - if true, the checked elements will be copied into
3393 # the new mesh else only boundary elements will be copied into the new mesh
3394 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3395 # boundary elements will be copied into the new mesh
3396 # @return tuple (mesh, group) where boundary elements were added to
3397 # @ingroup l2_modif_edit
3398 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3399 toCopyElements=False, toCopyExistingBondary=False):
3400 unRegister = genObjUnRegister()
3401 if isinstance( elements, Mesh ):
3402 elements = elements.GetMesh()
3403 if ( isinstance( elements, list )):
3404 elemType = SMESH.ALL
3405 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3406 elements = self.editor.MakeIDSource(elements, elemType)
3407 unRegister.set( elements )
3408 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3409 toCopyElements,toCopyExistingBondary)
3410 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3414 # @brief Creates missing boundary elements around either the whole mesh or
3415 # groups of 2D elements
3416 # @param dimension - defines type of boundary elements to create
3417 # @param groupName - a name of group to store all boundary elements in,
3418 # "" means not to create the group
3419 # @param meshName - a name of a new mesh, which is a copy of the initial
3420 # mesh + created boundary elements; "" means not to create the new mesh
3421 # @param toCopyAll - if true, the whole initial mesh will be copied into
3422 # the new mesh else only boundary elements will be copied into the new mesh
3423 # @param groups - groups of 2D elements to make boundary around
3424 # @retval tuple( long, mesh, groups )
3425 # long - number of added boundary elements
3426 # mesh - the mesh where elements were added to
3427 # group - the group of boundary elements or None
3429 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3430 toCopyAll=False, groups=[]):
3431 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3433 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3434 return nb, mesh, group
3436 ## Renumber mesh nodes
3437 # @ingroup l2_modif_renumber
3438 def RenumberNodes(self):
3439 self.editor.RenumberNodes()
3441 ## Renumber mesh elements
3442 # @ingroup l2_modif_renumber
3443 def RenumberElements(self):
3444 self.editor.RenumberElements()
3446 ## Generates new elements by rotation of the elements around the axis
3447 # @param IDsOfElements the list of ids of elements to sweep
3448 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3449 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3450 # @param NbOfSteps the number of steps
3451 # @param Tolerance tolerance
3452 # @param MakeGroups forces the generation of new groups from existing ones
3453 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3454 # of all steps, else - size of each step
3455 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3456 # @ingroup l2_modif_extrurev
3457 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3458 MakeGroups=False, TotalAngle=False):
3459 if IDsOfElements == []:
3460 IDsOfElements = self.GetElementsId()
3461 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3462 Axis = self.smeshpyD.GetAxisStruct(Axis)
3463 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3464 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3465 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3466 self.mesh.SetParameters(Parameters)
3467 if TotalAngle and NbOfSteps:
3468 AngleInRadians /= NbOfSteps
3470 return self.editor.RotationSweepMakeGroups(IDsOfElements, Axis,
3471 AngleInRadians, NbOfSteps, Tolerance)
3472 self.editor.RotationSweep(IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance)
3475 ## Generates new elements by rotation of the elements of object around the axis
3476 # @param theObject object which elements should be sweeped.
3477 # It can be a mesh, a sub mesh or a group.
3478 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3479 # @param AngleInRadians the angle of Rotation
3480 # @param NbOfSteps number of steps
3481 # @param Tolerance tolerance
3482 # @param MakeGroups forces the generation of new groups from existing ones
3483 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3484 # of all steps, else - size of each step
3485 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3486 # @ingroup l2_modif_extrurev
3487 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3488 MakeGroups=False, TotalAngle=False):
3489 if ( isinstance( theObject, Mesh )):
3490 theObject = theObject.GetMesh()
3491 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3492 Axis = self.smeshpyD.GetAxisStruct(Axis)
3493 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3494 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3495 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3496 self.mesh.SetParameters(Parameters)
3497 if TotalAngle and NbOfSteps:
3498 AngleInRadians /= NbOfSteps
3500 return self.editor.RotationSweepObjectMakeGroups(theObject, Axis, AngleInRadians,
3501 NbOfSteps, Tolerance)
3502 self.editor.RotationSweepObject(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3505 ## Generates new elements by rotation of the elements of object around the axis
3506 # @param theObject object which elements should be sweeped.
3507 # It can be a mesh, a sub mesh or a group.
3508 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3509 # @param AngleInRadians the angle of Rotation
3510 # @param NbOfSteps number of steps
3511 # @param Tolerance tolerance
3512 # @param MakeGroups forces the generation of new groups from existing ones
3513 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3514 # of all steps, else - size of each step
3515 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3516 # @ingroup l2_modif_extrurev
3517 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3518 MakeGroups=False, TotalAngle=False):
3519 if ( isinstance( theObject, Mesh )):
3520 theObject = theObject.GetMesh()
3521 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3522 Axis = self.smeshpyD.GetAxisStruct(Axis)
3523 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3524 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3525 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3526 self.mesh.SetParameters(Parameters)
3527 if TotalAngle and NbOfSteps:
3528 AngleInRadians /= NbOfSteps
3530 return self.editor.RotationSweepObject1DMakeGroups(theObject, Axis, AngleInRadians,
3531 NbOfSteps, Tolerance)
3532 self.editor.RotationSweepObject1D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3535 ## Generates new elements by rotation of the elements of object around the axis
3536 # @param theObject object which elements should be sweeped.
3537 # It can be a mesh, a sub mesh or a group.
3538 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3539 # @param AngleInRadians the angle of Rotation
3540 # @param NbOfSteps number of steps
3541 # @param Tolerance tolerance
3542 # @param MakeGroups forces the generation of new groups from existing ones
3543 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3544 # of all steps, else - size of each step
3545 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3546 # @ingroup l2_modif_extrurev
3547 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3548 MakeGroups=False, TotalAngle=False):
3549 if ( isinstance( theObject, Mesh )):
3550 theObject = theObject.GetMesh()
3551 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3552 Axis = self.smeshpyD.GetAxisStruct(Axis)
3553 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3554 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3555 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3556 self.mesh.SetParameters(Parameters)
3557 if TotalAngle and NbOfSteps:
3558 AngleInRadians /= NbOfSteps
3560 return self.editor.RotationSweepObject2DMakeGroups(theObject, Axis, AngleInRadians,
3561 NbOfSteps, Tolerance)
3562 self.editor.RotationSweepObject2D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3565 ## Generates new elements by extrusion of the elements with given ids
3566 # @param IDsOfElements the list of elements ids for extrusion
3567 # @param StepVector vector or DirStruct or 3 vector components, defining
3568 # the direction and value of extrusion for one step (the total extrusion
3569 # length will be NbOfSteps * ||StepVector||)
3570 # @param NbOfSteps the number of steps
3571 # @param MakeGroups forces the generation of new groups from existing ones
3572 # @param IsNodes is True if elements with given ids are nodes
3573 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3574 # @ingroup l2_modif_extrurev
3575 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3576 if IDsOfElements == []:
3577 IDsOfElements = self.GetElementsId()
3578 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3579 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3580 if isinstance( StepVector, list ):
3581 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3582 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3583 Parameters = StepVector.PS.parameters + var_separator + Parameters
3584 self.mesh.SetParameters(Parameters)
3587 return self.editor.ExtrusionSweepMakeGroups0D(IDsOfElements, StepVector, NbOfSteps)
3589 return self.editor.ExtrusionSweepMakeGroups(IDsOfElements, StepVector, NbOfSteps)
3591 self.editor.ExtrusionSweep0D(IDsOfElements, StepVector, NbOfSteps)
3593 self.editor.ExtrusionSweep(IDsOfElements, StepVector, NbOfSteps)
3596 ## Generates new elements by extrusion of the elements with given ids
3597 # @param IDsOfElements is ids of elements
3598 # @param StepVector vector or DirStruct or 3 vector components, defining
3599 # the direction and value of extrusion for one step (the total extrusion
3600 # length will be NbOfSteps * ||StepVector||)
3601 # @param NbOfSteps the number of steps
3602 # @param ExtrFlags sets flags for extrusion
3603 # @param SewTolerance uses for comparing locations of nodes if flag
3604 # EXTRUSION_FLAG_SEW is set
3605 # @param MakeGroups forces the generation of new groups from existing ones
3606 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3607 # @ingroup l2_modif_extrurev
3608 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3609 ExtrFlags, SewTolerance, MakeGroups=False):
3610 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3611 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3612 if isinstance( StepVector, list ):
3613 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3615 return self.editor.AdvancedExtrusionMakeGroups(IDsOfElements, StepVector, NbOfSteps,
3616 ExtrFlags, SewTolerance)
3617 self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3618 ExtrFlags, SewTolerance)
3621 ## Generates new elements by extrusion of the elements which belong to the object
3622 # @param theObject the object which elements should be processed.
3623 # It can be a mesh, a sub mesh or a group.
3624 # @param StepVector vector or DirStruct or 3 vector components, defining
3625 # the direction and value of extrusion for one step (the total extrusion
3626 # length will be NbOfSteps * ||StepVector||)
3627 # @param NbOfSteps the number of steps
3628 # @param MakeGroups forces the generation of new groups from existing ones
3629 # @param IsNodes is True if elements which belong to the object are nodes
3630 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3631 # @ingroup l2_modif_extrurev
3632 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3633 if ( isinstance( theObject, Mesh )):
3634 theObject = theObject.GetMesh()
3635 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3636 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3637 if isinstance( StepVector, list ):
3638 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3639 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3640 Parameters = StepVector.PS.parameters + var_separator + Parameters
3641 self.mesh.SetParameters(Parameters)
3644 return self.editor.ExtrusionSweepObject0DMakeGroups(theObject, StepVector, NbOfSteps)
3646 return self.editor.ExtrusionSweepObjectMakeGroups(theObject, StepVector, NbOfSteps)
3648 self.editor.ExtrusionSweepObject0D(theObject, StepVector, NbOfSteps)
3650 self.editor.ExtrusionSweepObject(theObject, StepVector, NbOfSteps)
3653 ## Generates new elements by extrusion of the elements which belong to the object
3654 # @param theObject object which elements should be processed.
3655 # It can be a mesh, a sub mesh or a group.
3656 # @param StepVector vector or DirStruct or 3 vector components, defining
3657 # the direction and value of extrusion for one step (the total extrusion
3658 # length will be NbOfSteps * ||StepVector||)
3659 # @param NbOfSteps the number of steps
3660 # @param MakeGroups to generate new groups from existing ones
3661 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3662 # @ingroup l2_modif_extrurev
3663 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3664 if ( isinstance( theObject, Mesh )):
3665 theObject = theObject.GetMesh()
3666 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3667 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3668 if isinstance( StepVector, list ):
3669 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3670 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3671 Parameters = StepVector.PS.parameters + var_separator + Parameters
3672 self.mesh.SetParameters(Parameters)
3674 return self.editor.ExtrusionSweepObject1DMakeGroups(theObject, StepVector, NbOfSteps)
3675 self.editor.ExtrusionSweepObject1D(theObject, StepVector, NbOfSteps)
3678 ## Generates new elements by extrusion of the elements which belong to the object
3679 # @param theObject object which elements should be processed.
3680 # It can be a mesh, a sub mesh or a group.
3681 # @param StepVector vector or DirStruct or 3 vector components, defining
3682 # the direction and value of extrusion for one step (the total extrusion
3683 # length will be NbOfSteps * ||StepVector||)
3684 # @param NbOfSteps the number of steps
3685 # @param MakeGroups forces the generation of new groups from existing ones
3686 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3687 # @ingroup l2_modif_extrurev
3688 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3689 if ( isinstance( theObject, Mesh )):
3690 theObject = theObject.GetMesh()
3691 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3692 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3693 if isinstance( StepVector, list ):
3694 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3695 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3696 Parameters = StepVector.PS.parameters + var_separator + Parameters
3697 self.mesh.SetParameters(Parameters)
3699 return self.editor.ExtrusionSweepObject2DMakeGroups(theObject, StepVector, NbOfSteps)
3700 self.editor.ExtrusionSweepObject2D(theObject, StepVector, NbOfSteps)
3705 ## Generates new elements by extrusion of the given elements
3706 # The path of extrusion must be a meshed edge.
3707 # @param Base mesh or group, or submesh, or list of ids of elements for extrusion
3708 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3709 # @param NodeStart the start node from Path. Defines the direction of extrusion
3710 # @param HasAngles allows the shape to be rotated around the path
3711 # to get the resulting mesh in a helical fashion
3712 # @param Angles list of angles in radians
3713 # @param LinearVariation forces the computation of rotation angles as linear
3714 # variation of the given Angles along path steps
3715 # @param HasRefPoint allows using the reference point
3716 # @param RefPoint the point around which the elements are rotated (the mass
3717 # center of the elements by default).
3718 # The User can specify any point as the Reference Point.
3719 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
3720 # @param MakeGroups forces the generation of new groups from existing ones
3721 # @param ElemType type of elements for extrusion (if param Base is a mesh)
3722 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3723 # only SMESH::Extrusion_Error otherwise
3724 # @ingroup l2_modif_extrurev
3725 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
3726 HasAngles, Angles, LinearVariation,
3727 HasRefPoint, RefPoint, MakeGroups, ElemType):
3728 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3729 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3731 elif isinstance( RefPoint, list ):
3732 RefPoint = PointStruct(*RefPoint)
3734 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3735 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3736 self.mesh.SetParameters(Parameters)
3738 if (isinstance(Path, Mesh)): Path = Path.GetMesh()
3740 if isinstance(Base, list):
3742 if Base == []: IDsOfElements = self.GetElementsId()
3743 else: IDsOfElements = Base
3744 return self.editor.ExtrusionAlongPathX(IDsOfElements, Path, NodeStart,
3745 HasAngles, Angles, LinearVariation,
3746 HasRefPoint, RefPoint, MakeGroups, ElemType)
3748 if isinstance(Base, Mesh): Base = Base.GetMesh()
3749 if isinstance(Base, SMESH._objref_SMESH_Mesh) or isinstance(Base, SMESH._objref_SMESH_Group) or isinstance(Base, SMESH._objref_SMESH_subMesh):
3750 return self.editor.ExtrusionAlongPathObjX(Base, Path, NodeStart,
3751 HasAngles, Angles, LinearVariation,
3752 HasRefPoint, RefPoint, MakeGroups, ElemType)
3754 raise RuntimeError, "Invalid Base for ExtrusionAlongPathX"
3757 ## Generates new elements by extrusion of the given elements
3758 # The path of extrusion must be a meshed edge.
3759 # @param IDsOfElements ids of elements
3760 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
3761 # @param PathShape shape(edge) defines the sub-mesh for the path
3762 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3763 # @param HasAngles allows the shape to be rotated around the path
3764 # to get the resulting mesh in a helical fashion
3765 # @param Angles list of angles in radians
3766 # @param HasRefPoint allows using the reference point
3767 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3768 # The User can specify any point as the Reference Point.
3769 # @param MakeGroups forces the generation of new groups from existing ones
3770 # @param LinearVariation forces the computation of rotation angles as linear
3771 # variation of the given Angles along path steps
3772 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3773 # only SMESH::Extrusion_Error otherwise
3774 # @ingroup l2_modif_extrurev
3775 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
3776 HasAngles, Angles, HasRefPoint, RefPoint,
3777 MakeGroups=False, LinearVariation=False):
3778 if IDsOfElements == []:
3779 IDsOfElements = self.GetElementsId()
3780 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3781 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3783 if ( isinstance( PathMesh, Mesh )):
3784 PathMesh = PathMesh.GetMesh()
3785 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3786 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3787 self.mesh.SetParameters(Parameters)
3788 if HasAngles and Angles and LinearVariation:
3789 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3792 return self.editor.ExtrusionAlongPathMakeGroups(IDsOfElements, PathMesh,
3793 PathShape, NodeStart, HasAngles,
3794 Angles, HasRefPoint, RefPoint)
3795 return self.editor.ExtrusionAlongPath(IDsOfElements, PathMesh, PathShape,
3796 NodeStart, HasAngles, Angles, HasRefPoint, RefPoint)
3798 ## Generates new elements by extrusion of the elements which belong to the object
3799 # The path of extrusion must be a meshed edge.
3800 # @param theObject the object which elements should be processed.
3801 # It can be a mesh, a sub mesh or a group.
3802 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3803 # @param PathShape shape(edge) defines the sub-mesh for the path
3804 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3805 # @param HasAngles allows the shape to be rotated around the path
3806 # to get the resulting mesh in a helical fashion
3807 # @param Angles list of angles
3808 # @param HasRefPoint allows using the reference point
3809 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3810 # The User can specify any point as the Reference Point.
3811 # @param MakeGroups forces the generation of new groups from existing ones
3812 # @param LinearVariation forces the computation of rotation angles as linear
3813 # variation of the given Angles along path steps
3814 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3815 # only SMESH::Extrusion_Error otherwise
3816 # @ingroup l2_modif_extrurev
3817 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
3818 HasAngles, Angles, HasRefPoint, RefPoint,
3819 MakeGroups=False, LinearVariation=False):
3820 if ( isinstance( theObject, Mesh )):
3821 theObject = theObject.GetMesh()
3822 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3823 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3824 if ( isinstance( PathMesh, Mesh )):
3825 PathMesh = PathMesh.GetMesh()
3826 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3827 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3828 self.mesh.SetParameters(Parameters)
3829 if HasAngles and Angles and LinearVariation:
3830 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3833 return self.editor.ExtrusionAlongPathObjectMakeGroups(theObject, PathMesh,
3834 PathShape, NodeStart, HasAngles,
3835 Angles, HasRefPoint, RefPoint)
3836 return self.editor.ExtrusionAlongPathObject(theObject, PathMesh, PathShape,
3837 NodeStart, HasAngles, Angles, HasRefPoint,
3840 ## Generates new elements by extrusion of the elements which belong to the object
3841 # The path of extrusion must be a meshed edge.
3842 # @param theObject the object which elements should be processed.
3843 # It can be a mesh, a sub mesh or a group.
3844 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3845 # @param PathShape shape(edge) defines the sub-mesh for the path
3846 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3847 # @param HasAngles allows the shape to be rotated around the path
3848 # to get the resulting mesh in a helical fashion
3849 # @param Angles list of angles
3850 # @param HasRefPoint allows using the reference point
3851 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3852 # The User can specify any point as the Reference Point.
3853 # @param MakeGroups forces the generation of new groups from existing ones
3854 # @param LinearVariation forces the computation of rotation angles as linear
3855 # variation of the given Angles along path steps
3856 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3857 # only SMESH::Extrusion_Error otherwise
3858 # @ingroup l2_modif_extrurev
3859 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
3860 HasAngles, Angles, HasRefPoint, RefPoint,
3861 MakeGroups=False, LinearVariation=False):
3862 if ( isinstance( theObject, Mesh )):
3863 theObject = theObject.GetMesh()
3864 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3865 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3866 if ( isinstance( PathMesh, Mesh )):
3867 PathMesh = PathMesh.GetMesh()
3868 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3869 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3870 self.mesh.SetParameters(Parameters)
3871 if HasAngles and Angles and LinearVariation:
3872 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3875 return self.editor.ExtrusionAlongPathObject1DMakeGroups(theObject, PathMesh,
3876 PathShape, NodeStart, HasAngles,
3877 Angles, HasRefPoint, RefPoint)
3878 return self.editor.ExtrusionAlongPathObject1D(theObject, PathMesh, PathShape,
3879 NodeStart, HasAngles, Angles, HasRefPoint,
3882 ## Generates new elements by extrusion of the elements which belong to the object
3883 # The path of extrusion must be a meshed edge.
3884 # @param theObject the object which elements should be processed.
3885 # It can be a mesh, a sub mesh or a group.
3886 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3887 # @param PathShape shape(edge) defines the sub-mesh for the path
3888 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3889 # @param HasAngles allows the shape to be rotated around the path
3890 # to get the resulting mesh in a helical fashion
3891 # @param Angles list of angles
3892 # @param HasRefPoint allows using the reference point
3893 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3894 # The User can specify any point as the Reference Point.
3895 # @param MakeGroups forces the generation of new groups from existing ones
3896 # @param LinearVariation forces the computation of rotation angles as linear
3897 # variation of the given Angles along path steps
3898 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3899 # only SMESH::Extrusion_Error otherwise
3900 # @ingroup l2_modif_extrurev
3901 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
3902 HasAngles, Angles, HasRefPoint, RefPoint,
3903 MakeGroups=False, LinearVariation=False):
3904 if ( isinstance( theObject, Mesh )):
3905 theObject = theObject.GetMesh()
3906 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3907 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3908 if ( isinstance( PathMesh, Mesh )):
3909 PathMesh = PathMesh.GetMesh()
3910 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3911 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3912 self.mesh.SetParameters(Parameters)
3913 if HasAngles and Angles and LinearVariation:
3914 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3917 return self.editor.ExtrusionAlongPathObject2DMakeGroups(theObject, PathMesh,
3918 PathShape, NodeStart, HasAngles,
3919 Angles, HasRefPoint, RefPoint)
3920 return self.editor.ExtrusionAlongPathObject2D(theObject, PathMesh, PathShape,
3921 NodeStart, HasAngles, Angles, HasRefPoint,
3924 ## Creates a symmetrical copy of mesh elements
3925 # @param IDsOfElements list of elements ids
3926 # @param Mirror is AxisStruct or geom object(point, line, plane)
3927 # @param theMirrorType is POINT, AXIS or PLANE
3928 # If the Mirror is a geom object this parameter is unnecessary
3929 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
3930 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3931 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3932 # @ingroup l2_modif_trsf
3933 def Mirror(self, IDsOfElements, Mirror, theMirrorType, Copy=0, MakeGroups=False):
3934 if IDsOfElements == []:
3935 IDsOfElements = self.GetElementsId()
3936 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3937 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3938 self.mesh.SetParameters(Mirror.parameters)
3939 if Copy and MakeGroups:
3940 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
3941 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
3944 ## Creates a new mesh by a symmetrical copy of mesh elements
3945 # @param IDsOfElements the list of elements ids
3946 # @param Mirror is AxisStruct or geom object (point, line, plane)
3947 # @param theMirrorType is POINT, AXIS or PLANE
3948 # If the Mirror is a geom object this parameter is unnecessary
3949 # @param MakeGroups to generate new groups from existing ones
3950 # @param NewMeshName a name of the new mesh to create
3951 # @return instance of Mesh class
3952 # @ingroup l2_modif_trsf
3953 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType, MakeGroups=0, NewMeshName=""):
3954 if IDsOfElements == []:
3955 IDsOfElements = self.GetElementsId()
3956 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3957 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3958 self.mesh.SetParameters(Mirror.parameters)
3959 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
3960 MakeGroups, NewMeshName)
3961 return Mesh(self.smeshpyD,self.geompyD,mesh)
3963 ## Creates a symmetrical copy of the object
3964 # @param theObject mesh, submesh or group
3965 # @param Mirror AxisStruct or geom object (point, line, plane)
3966 # @param theMirrorType is POINT, AXIS or PLANE
3967 # If the Mirror is a geom object this parameter is unnecessary
3968 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
3969 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3970 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3971 # @ingroup l2_modif_trsf
3972 def MirrorObject (self, theObject, Mirror, theMirrorType, Copy=0, MakeGroups=False):
3973 if ( isinstance( theObject, Mesh )):
3974 theObject = theObject.GetMesh()
3975 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3976 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3977 self.mesh.SetParameters(Mirror.parameters)
3978 if Copy and MakeGroups:
3979 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
3980 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
3983 ## Creates a new mesh by a symmetrical copy of the object
3984 # @param theObject mesh, submesh or group
3985 # @param Mirror AxisStruct or geom object (point, line, plane)
3986 # @param theMirrorType POINT, AXIS or PLANE
3987 # If the Mirror is a geom object this parameter is unnecessary
3988 # @param MakeGroups forces the generation of new groups from existing ones
3989 # @param NewMeshName the name of the new mesh to create
3990 # @return instance of Mesh class
3991 # @ingroup l2_modif_trsf
3992 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType,MakeGroups=0, NewMeshName=""):
3993 if ( isinstance( theObject, Mesh )):
3994 theObject = theObject.GetMesh()
3995 if (isinstance(Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3996 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3997 self.mesh.SetParameters(Mirror.parameters)
3998 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
3999 MakeGroups, NewMeshName)
4000 return Mesh( self.smeshpyD,self.geompyD,mesh )
4002 ## Translates the elements
4003 # @param IDsOfElements list of elements ids
4004 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4005 # @param Copy allows copying the translated elements
4006 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4007 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4008 # @ingroup l2_modif_trsf
4009 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4010 if IDsOfElements == []:
4011 IDsOfElements = self.GetElementsId()
4012 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4013 Vector = self.smeshpyD.GetDirStruct(Vector)
4014 if isinstance( Vector, list ):
4015 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4016 self.mesh.SetParameters(Vector.PS.parameters)
4017 if Copy and MakeGroups:
4018 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4019 self.editor.Translate(IDsOfElements, Vector, Copy)
4022 ## Creates a new mesh of translated elements
4023 # @param IDsOfElements list of elements ids
4024 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4025 # @param MakeGroups forces the generation of new groups from existing ones
4026 # @param NewMeshName the name of the newly created mesh
4027 # @return instance of Mesh class
4028 # @ingroup l2_modif_trsf
4029 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4030 if IDsOfElements == []:
4031 IDsOfElements = self.GetElementsId()
4032 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4033 Vector = self.smeshpyD.GetDirStruct(Vector)
4034 if isinstance( Vector, list ):
4035 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4036 self.mesh.SetParameters(Vector.PS.parameters)
4037 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4038 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4040 ## Translates the object
4041 # @param theObject the object to translate (mesh, submesh, or group)
4042 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4043 # @param Copy allows copying the translated elements
4044 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4045 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4046 # @ingroup l2_modif_trsf
4047 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4048 if ( isinstance( theObject, Mesh )):
4049 theObject = theObject.GetMesh()
4050 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4051 Vector = self.smeshpyD.GetDirStruct(Vector)
4052 if isinstance( Vector, list ):
4053 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4054 self.mesh.SetParameters(Vector.PS.parameters)
4055 if Copy and MakeGroups:
4056 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4057 self.editor.TranslateObject(theObject, Vector, Copy)
4060 ## Creates a new mesh from the translated object
4061 # @param theObject the object to translate (mesh, submesh, or group)
4062 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4063 # @param MakeGroups forces the generation of new groups from existing ones
4064 # @param NewMeshName the name of the newly created mesh
4065 # @return instance of Mesh class
4066 # @ingroup l2_modif_trsf
4067 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4068 if isinstance( theObject, Mesh ):
4069 theObject = theObject.GetMesh()
4070 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4071 Vector = self.smeshpyD.GetDirStruct(Vector)
4072 if isinstance( Vector, list ):
4073 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4074 self.mesh.SetParameters(Vector.PS.parameters)
4075 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4076 return Mesh( self.smeshpyD, self.geompyD, mesh )
4080 ## Scales the object
4081 # @param theObject - the object to translate (mesh, submesh, or group)
4082 # @param thePoint - base point for scale
4083 # @param theScaleFact - list of 1-3 scale factors for axises
4084 # @param Copy - allows copying the translated elements
4085 # @param MakeGroups - forces the generation of new groups from existing
4087 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4088 # empty list otherwise
4089 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4090 unRegister = genObjUnRegister()
4091 if ( isinstance( theObject, Mesh )):
4092 theObject = theObject.GetMesh()
4093 if ( isinstance( theObject, list )):
4094 theObject = self.GetIDSource(theObject, SMESH.ALL)
4095 unRegister.set( theObject )
4096 if ( isinstance( theScaleFact, float )):
4097 theScaleFact = [theScaleFact]
4098 if ( isinstance( theScaleFact, int )):
4099 theScaleFact = [ float(theScaleFact)]
4101 self.mesh.SetParameters(thePoint.parameters)
4103 if Copy and MakeGroups:
4104 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4105 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4108 ## Creates a new mesh from the translated object
4109 # @param theObject - the object to translate (mesh, submesh, or group)
4110 # @param thePoint - base point for scale
4111 # @param theScaleFact - list of 1-3 scale factors for axises
4112 # @param MakeGroups - forces the generation of new groups from existing ones
4113 # @param NewMeshName - the name of the newly created mesh
4114 # @return instance of Mesh class
4115 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4116 unRegister = genObjUnRegister()
4117 if (isinstance(theObject, Mesh)):
4118 theObject = theObject.GetMesh()
4119 if ( isinstance( theObject, list )):
4120 theObject = self.GetIDSource(theObject,SMESH.ALL)
4121 unRegister.set( theObject )
4122 if ( isinstance( theScaleFact, float )):
4123 theScaleFact = [theScaleFact]
4124 if ( isinstance( theScaleFact, int )):
4125 theScaleFact = [ float(theScaleFact)]
4127 self.mesh.SetParameters(thePoint.parameters)
4128 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4129 MakeGroups, NewMeshName)
4130 return Mesh( self.smeshpyD, self.geompyD, mesh )
4134 ## Rotates the elements
4135 # @param IDsOfElements list of elements ids
4136 # @param Axis the axis of rotation (AxisStruct or geom line)
4137 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4138 # @param Copy allows copying the rotated elements
4139 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4140 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4141 # @ingroup l2_modif_trsf
4142 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4143 if IDsOfElements == []:
4144 IDsOfElements = self.GetElementsId()
4145 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4146 Axis = self.smeshpyD.GetAxisStruct(Axis)
4147 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4148 Parameters = Axis.parameters + var_separator + Parameters
4149 self.mesh.SetParameters(Parameters)
4150 if Copy and MakeGroups:
4151 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4152 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4155 ## Creates a new mesh of rotated elements
4156 # @param IDsOfElements list of element ids
4157 # @param Axis the axis of rotation (AxisStruct or geom line)
4158 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4159 # @param MakeGroups forces the generation of new groups from existing ones
4160 # @param NewMeshName the name of the newly created mesh
4161 # @return instance of Mesh class
4162 # @ingroup l2_modif_trsf
4163 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4164 if IDsOfElements == []:
4165 IDsOfElements = self.GetElementsId()
4166 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4167 Axis = self.smeshpyD.GetAxisStruct(Axis)
4168 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4169 Parameters = Axis.parameters + var_separator + Parameters
4170 self.mesh.SetParameters(Parameters)
4171 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4172 MakeGroups, NewMeshName)
4173 return Mesh( self.smeshpyD, self.geompyD, mesh )
4175 ## Rotates the object
4176 # @param theObject the object to rotate( mesh, submesh, or group)
4177 # @param Axis the axis of rotation (AxisStruct or geom line)
4178 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4179 # @param Copy allows copying the rotated elements
4180 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4181 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4182 # @ingroup l2_modif_trsf
4183 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4184 if (isinstance(theObject, Mesh)):
4185 theObject = theObject.GetMesh()
4186 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4187 Axis = self.smeshpyD.GetAxisStruct(Axis)
4188 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4189 Parameters = Axis.parameters + ":" + Parameters
4190 self.mesh.SetParameters(Parameters)
4191 if Copy and MakeGroups:
4192 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4193 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4196 ## Creates a new mesh from the rotated object
4197 # @param theObject the object to rotate (mesh, submesh, or group)
4198 # @param Axis the axis of rotation (AxisStruct or geom line)
4199 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4200 # @param MakeGroups forces the generation of new groups from existing ones
4201 # @param NewMeshName the name of the newly created mesh
4202 # @return instance of Mesh class
4203 # @ingroup l2_modif_trsf
4204 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4205 if (isinstance( theObject, Mesh )):
4206 theObject = theObject.GetMesh()
4207 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4208 Axis = self.smeshpyD.GetAxisStruct(Axis)
4209 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4210 Parameters = Axis.parameters + ":" + Parameters
4211 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4212 MakeGroups, NewMeshName)
4213 self.mesh.SetParameters(Parameters)
4214 return Mesh( self.smeshpyD, self.geompyD, mesh )
4216 ## Finds groups of adjacent nodes within Tolerance.
4217 # @param Tolerance the value of tolerance
4218 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4219 # @ingroup l2_modif_trsf
4220 def FindCoincidentNodes (self, Tolerance):
4221 return self.editor.FindCoincidentNodes(Tolerance)
4223 ## Finds groups of ajacent nodes within Tolerance.
4224 # @param Tolerance the value of tolerance
4225 # @param SubMeshOrGroup SubMesh or Group
4226 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4227 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4228 # @ingroup l2_modif_trsf
4229 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance, exceptNodes=[]):
4230 unRegister = genObjUnRegister()
4231 if (isinstance( SubMeshOrGroup, Mesh )):
4232 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4233 if not isinstance( exceptNodes, list):
4234 exceptNodes = [ exceptNodes ]
4235 if exceptNodes and isinstance( exceptNodes[0], int):
4236 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE)]
4237 unRegister.set( exceptNodes )
4238 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,exceptNodes)
4241 # @param GroupsOfNodes a list of pairs of nodes IDs for merging (e.g. [[1,12],[25,4]])
4242 # @ingroup l2_modif_trsf
4243 def MergeNodes (self, GroupsOfNodes):
4244 self.editor.MergeNodes(GroupsOfNodes)
4246 ## Finds the elements built on the same nodes.
4247 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4248 # @return the list of pairs of equal elements IDs (e.g. [[1,12],[25,4]])
4249 # @ingroup l2_modif_trsf
4250 def FindEqualElements (self, MeshOrSubMeshOrGroup):
4251 if ( isinstance( MeshOrSubMeshOrGroup, Mesh )):
4252 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4253 return self.editor.FindEqualElements(MeshOrSubMeshOrGroup)
4255 ## Merges elements in each given group.
4256 # @param GroupsOfElementsID a list of pairs of elements IDs for merging (e.g. [[1,12],[25,4]])
4257 # @ingroup l2_modif_trsf
4258 def MergeElements(self, GroupsOfElementsID):
4259 self.editor.MergeElements(GroupsOfElementsID)
4261 ## Leaves one element and removes all other elements built on the same nodes.
4262 # @ingroup l2_modif_trsf
4263 def MergeEqualElements(self):
4264 self.editor.MergeEqualElements()
4266 ## Sews free borders
4267 # @return SMESH::Sew_Error
4268 # @ingroup l2_modif_trsf
4269 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4270 FirstNodeID2, SecondNodeID2, LastNodeID2,
4271 CreatePolygons, CreatePolyedrs):
4272 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4273 FirstNodeID2, SecondNodeID2, LastNodeID2,
4274 CreatePolygons, CreatePolyedrs)
4276 ## Sews conform free borders
4277 # @return SMESH::Sew_Error
4278 # @ingroup l2_modif_trsf
4279 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4280 FirstNodeID2, SecondNodeID2):
4281 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4282 FirstNodeID2, SecondNodeID2)
4284 ## Sews border to side
4285 # @return SMESH::Sew_Error
4286 # @ingroup l2_modif_trsf
4287 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4288 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4289 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4290 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4292 ## Sews two sides of a mesh. The nodes belonging to Side1 are
4293 # merged with the nodes of elements of Side2.
4294 # The number of elements in theSide1 and in theSide2 must be
4295 # equal and they should have similar nodal connectivity.
4296 # The nodes to merge should belong to side borders and
4297 # the first node should be linked to the second.
4298 # @return SMESH::Sew_Error
4299 # @ingroup l2_modif_trsf
4300 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4301 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4302 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4303 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4304 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4305 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4307 ## Sets new nodes for the given element.
4308 # @param ide the element id
4309 # @param newIDs nodes ids
4310 # @return If the number of nodes does not correspond to the type of element - returns false
4311 # @ingroup l2_modif_edit
4312 def ChangeElemNodes(self, ide, newIDs):
4313 return self.editor.ChangeElemNodes(ide, newIDs)
4315 ## If during the last operation of MeshEditor some nodes were
4316 # created, this method returns the list of their IDs, \n
4317 # if new nodes were not created - returns empty list
4318 # @return the list of integer values (can be empty)
4319 # @ingroup l1_auxiliary
4320 def GetLastCreatedNodes(self):
4321 return self.editor.GetLastCreatedNodes()
4323 ## If during the last operation of MeshEditor some elements were
4324 # created this method returns the list of their IDs, \n
4325 # if new elements were not created - returns empty list
4326 # @return the list of integer values (can be empty)
4327 # @ingroup l1_auxiliary
4328 def GetLastCreatedElems(self):
4329 return self.editor.GetLastCreatedElems()
4331 ## Clears sequences of nodes and elements created by mesh edition oparations
4332 # @ingroup l1_auxiliary
4333 def ClearLastCreated(self):
4334 self.editor.ClearLastCreated()
4336 ## Creates Duplicates given elements, i.e. creates new elements based on the
4337 # same nodes as the given ones.
4338 # @param theElements - container of elements to duplicate. It can be a Mesh,
4339 # sub-mesh, group, filter or a list of element IDs.
4340 # @param theGroupName - a name of group to contain the generated elements.
4341 # If a group with such a name already exists, the new elements
4342 # are added to the existng group, else a new group is created.
4343 # If \a theGroupName is empty, new elements are not added
4345 # @return a group where the new elements are added. None if theGroupName == "".
4346 # @ingroup l2_modif_edit
4347 def DoubleElements(self, theElements, theGroupName=""):
4348 unRegister = genObjUnRegister()
4349 if isinstance( theElements, Mesh ):
4350 theElements = theElements.mesh
4351 elif isinstance( theElements, list ):
4352 theElements = self.GetIDSource( theElements, SMESH.ALL )
4353 unRegister.set( theElements )
4354 return self.editor.DoubleElements(theElements, theGroupName)
4356 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4357 # @param theNodes identifiers of nodes to be doubled
4358 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4359 # nodes. If list of element identifiers is empty then nodes are doubled but
4360 # they not assigned to elements
4361 # @return TRUE if operation has been completed successfully, FALSE otherwise
4362 # @ingroup l2_modif_edit
4363 def DoubleNodes(self, theNodes, theModifiedElems):
4364 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4366 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4367 # This method provided for convenience works as DoubleNodes() described above.
4368 # @param theNodeId identifiers of node to be doubled
4369 # @param theModifiedElems identifiers of elements to be updated
4370 # @return TRUE if operation has been completed successfully, FALSE otherwise
4371 # @ingroup l2_modif_edit
4372 def DoubleNode(self, theNodeId, theModifiedElems):
4373 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4375 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4376 # This method provided for convenience works as DoubleNodes() described above.
4377 # @param theNodes group of nodes to be doubled
4378 # @param theModifiedElems group of elements to be updated.
4379 # @param theMakeGroup forces the generation of a group containing new nodes.
4380 # @return TRUE or a created group if operation has been completed successfully,
4381 # FALSE or None otherwise
4382 # @ingroup l2_modif_edit
4383 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4385 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4386 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4388 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4389 # This method provided for convenience works as DoubleNodes() described above.
4390 # @param theNodes list of groups of nodes to be doubled
4391 # @param theModifiedElems list of groups of elements to be updated.
4392 # @param theMakeGroup forces the generation of a group containing new nodes.
4393 # @return TRUE if operation has been completed successfully, FALSE otherwise
4394 # @ingroup l2_modif_edit
4395 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4397 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4398 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4400 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4401 # @param theElems - the list of elements (edges or faces) to be replicated
4402 # The nodes for duplication could be found from these elements
4403 # @param theNodesNot - list of nodes to NOT replicate
4404 # @param theAffectedElems - the list of elements (cells and edges) to which the
4405 # replicated nodes should be associated to.
4406 # @return TRUE if operation has been completed successfully, FALSE otherwise
4407 # @ingroup l2_modif_edit
4408 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4409 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4411 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4412 # @param theElems - the list of elements (edges or faces) to be replicated
4413 # The nodes for duplication could be found from these elements
4414 # @param theNodesNot - list of nodes to NOT replicate
4415 # @param theShape - shape to detect affected elements (element which geometric center
4416 # located on or inside shape).
4417 # The replicated nodes should be associated to affected elements.
4418 # @return TRUE if operation has been completed successfully, FALSE otherwise
4419 # @ingroup l2_modif_edit
4420 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4421 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4423 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4424 # This method provided for convenience works as DoubleNodes() described above.
4425 # @param theElems - group of of elements (edges or faces) to be replicated
4426 # @param theNodesNot - group of nodes not to replicated
4427 # @param theAffectedElems - group of elements to which the replicated nodes
4428 # should be associated to.
4429 # @param theMakeGroup forces the generation of a group containing new elements.
4430 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4431 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4432 # FALSE or None otherwise
4433 # @ingroup l2_modif_edit
4434 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4435 theMakeGroup=False, theMakeNodeGroup=False):
4436 if theMakeGroup or theMakeNodeGroup:
4437 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4439 theMakeGroup, theMakeNodeGroup)
4440 if theMakeGroup and theMakeNodeGroup:
4443 return twoGroups[ int(theMakeNodeGroup) ]
4444 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4446 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4447 # This method provided for convenience works as DoubleNodes() described above.
4448 # @param theElems - group of of elements (edges or faces) to be replicated
4449 # @param theNodesNot - group of nodes not to replicated
4450 # @param theShape - shape to detect affected elements (element which geometric center
4451 # located on or inside shape).
4452 # The replicated nodes should be associated to affected elements.
4453 # @ingroup l2_modif_edit
4454 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4455 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4457 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4458 # This method provided for convenience works as DoubleNodes() described above.
4459 # @param theElems - list of groups of elements (edges or faces) to be replicated
4460 # @param theNodesNot - list of groups of nodes not to replicated
4461 # @param theAffectedElems - group of elements to which the replicated nodes
4462 # should be associated to.
4463 # @param theMakeGroup forces the generation of a group containing new elements.
4464 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4465 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4466 # FALSE or None otherwise
4467 # @ingroup l2_modif_edit
4468 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4469 theMakeGroup=False, theMakeNodeGroup=False):
4470 if theMakeGroup or theMakeNodeGroup:
4471 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4473 theMakeGroup, theMakeNodeGroup)
4474 if theMakeGroup and theMakeNodeGroup:
4477 return twoGroups[ int(theMakeNodeGroup) ]
4478 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4480 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4481 # This method provided for convenience works as DoubleNodes() described above.
4482 # @param theElems - list of groups of elements (edges or faces) to be replicated
4483 # @param theNodesNot - list of groups of nodes not to replicated
4484 # @param theShape - shape to detect affected elements (element which geometric center
4485 # located on or inside shape).
4486 # The replicated nodes should be associated to affected elements.
4487 # @return TRUE if operation has been completed successfully, FALSE otherwise
4488 # @ingroup l2_modif_edit
4489 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4490 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4492 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4493 # This method is the first step of DoubleNodeElemGroupsInRegion.
4494 # @param theElems - list of groups of elements (edges or faces) to be replicated
4495 # @param theNodesNot - list of groups of nodes not to replicated
4496 # @param theShape - shape to detect affected elements (element which geometric center
4497 # located on or inside shape).
4498 # The replicated nodes should be associated to affected elements.
4499 # @return groups of affected elements
4500 # @ingroup l2_modif_edit
4501 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4502 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4504 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4505 # The list of groups must describe a partition of the mesh volumes.
4506 # The nodes of the internal faces at the boundaries of the groups are doubled.
4507 # In option, the internal faces are replaced by flat elements.
4508 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4509 # @param theDomains - list of groups of volumes
4510 # @param createJointElems - if TRUE, create the elements
4511 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4512 # the boundary between \a theDomains and the rest mesh
4513 # @return TRUE if operation has been completed successfully, FALSE otherwise
4514 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4515 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4517 ## Double nodes on some external faces and create flat elements.
4518 # Flat elements are mainly used by some types of mechanic calculations.
4520 # Each group of the list must be constituted of faces.
4521 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4522 # @param theGroupsOfFaces - list of groups of faces
4523 # @return TRUE if operation has been completed successfully, FALSE otherwise
4524 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4525 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4527 ## identify all the elements around a geom shape, get the faces delimiting the hole
4529 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4530 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4532 def _getFunctor(self, funcType ):
4533 fn = self.functors[ funcType._v ]
4535 fn = self.smeshpyD.GetFunctor(funcType)
4536 fn.SetMesh(self.mesh)
4537 self.functors[ funcType._v ] = fn
4540 def _valueFromFunctor(self, funcType, elemId):
4541 fn = self._getFunctor( funcType )
4542 if fn.GetElementType() == self.GetElementType(elemId, True):
4543 val = fn.GetValue(elemId)
4548 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4549 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4550 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4551 # @ingroup l1_measurements
4552 def GetLength(self, elemId=None):
4555 length = self.smeshpyD.GetLength(self)
4557 length = self._valueFromFunctor(SMESH.FT_Length, elemId)
4560 ## Get area of 2D element or sum of areas of all 2D mesh elements
4561 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4562 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4563 # @ingroup l1_measurements
4564 def GetArea(self, elemId=None):
4567 area = self.smeshpyD.GetArea(self)
4569 area = self._valueFromFunctor(SMESH.FT_Area, elemId)
4572 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4573 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4574 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4575 # @ingroup l1_measurements
4576 def GetVolume(self, elemId=None):
4579 volume = self.smeshpyD.GetVolume(self)
4581 volume = self._valueFromFunctor(SMESH.FT_Volume3D, elemId)
4584 ## Get maximum element length.
4585 # @param elemId mesh element ID
4586 # @return element's maximum length value
4587 # @ingroup l1_measurements
4588 def GetMaxElementLength(self, elemId):
4589 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4590 ftype = SMESH.FT_MaxElementLength3D
4592 ftype = SMESH.FT_MaxElementLength2D
4593 return self._valueFromFunctor(ftype, elemId)
4595 ## Get aspect ratio of 2D or 3D element.
4596 # @param elemId mesh element ID
4597 # @return element's aspect ratio value
4598 # @ingroup l1_measurements
4599 def GetAspectRatio(self, elemId):
4600 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4601 ftype = SMESH.FT_AspectRatio3D
4603 ftype = SMESH.FT_AspectRatio
4604 return self._valueFromFunctor(ftype, elemId)
4606 ## Get warping angle of 2D element.
4607 # @param elemId mesh element ID
4608 # @return element's warping angle value
4609 # @ingroup l1_measurements
4610 def GetWarping(self, elemId):
4611 return self._valueFromFunctor(SMESH.FT_Warping, elemId)
4613 ## Get minimum angle of 2D element.
4614 # @param elemId mesh element ID
4615 # @return element's minimum angle value
4616 # @ingroup l1_measurements
4617 def GetMinimumAngle(self, elemId):
4618 return self._valueFromFunctor(SMESH.FT_MinimumAngle, elemId)
4620 ## Get taper of 2D element.
4621 # @param elemId mesh element ID
4622 # @return element's taper value
4623 # @ingroup l1_measurements
4624 def GetTaper(self, elemId):
4625 return self._valueFromFunctor(SMESH.FT_Taper, elemId)
4627 ## Get skew of 2D element.
4628 # @param elemId mesh element ID
4629 # @return element's skew value
4630 # @ingroup l1_measurements
4631 def GetSkew(self, elemId):
4632 return self._valueFromFunctor(SMESH.FT_Skew, elemId)
4634 ## Return minimal and maximal value of a given functor.
4635 # @param funType a functor type, an item of SMESH.FunctorType enum
4636 # (one of SMESH.FunctorType._items)
4637 # @param meshPart a part of mesh (group, sub-mesh) to treat
4638 # @return tuple (min,max)
4639 # @ingroup l1_measurements
4640 def GetMinMax(self, funType, meshPart=None):
4641 unRegister = genObjUnRegister()
4642 if isinstance( meshPart, list ):
4643 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
4644 unRegister.set( meshPart )
4645 if isinstance( meshPart, Mesh ):
4646 meshPart = meshPart.mesh
4647 fun = self._getFunctor( funType )
4650 hist = fun.GetLocalHistogram( 1, False, meshPart )
4652 hist = fun.GetHistogram( 1, False )
4654 return hist[0].min, hist[0].max
4657 pass # end of Mesh class
4659 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
4661 class Pattern(SMESH._objref_SMESH_Pattern):
4663 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4664 decrFun = lambda i: i-1
4665 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4666 theMesh.SetParameters(Parameters)
4667 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4669 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4670 decrFun = lambda i: i-1
4671 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4672 theMesh.SetParameters(Parameters)
4673 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4675 # Registering the new proxy for Pattern
4676 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4678 ## Private class used to bind methods creating algorithms to the class Mesh
4683 self.defaultAlgoType = ""
4684 self.algoTypeToClass = {}
4686 # Stores a python class of algorithm
4687 def add(self, algoClass):
4688 if type( algoClass ).__name__ == 'classobj' and \
4689 hasattr( algoClass, "algoType"):
4690 self.algoTypeToClass[ algoClass.algoType ] = algoClass
4691 if not self.defaultAlgoType and \
4692 hasattr( algoClass, "isDefault") and algoClass.isDefault:
4693 self.defaultAlgoType = algoClass.algoType
4694 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
4696 # creates a copy of self and assign mesh to the copy
4697 def copy(self, mesh):
4698 other = algoCreator()
4699 other.defaultAlgoType = self.defaultAlgoType
4700 other.algoTypeToClass = self.algoTypeToClass
4704 # creates an instance of algorithm
4705 def __call__(self,algo="",geom=0,*args):
4706 algoType = self.defaultAlgoType
4707 for arg in args + (algo,geom):
4708 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
4710 if isinstance( arg, str ) and arg:
4712 if not algoType and self.algoTypeToClass:
4713 algoType = self.algoTypeToClass.keys()[0]
4714 if self.algoTypeToClass.has_key( algoType ):
4715 #print "Create algo",algoType
4716 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
4717 raise RuntimeError, "No class found for algo type %s" % algoType
4720 # Private class used to substitute and store variable parameters of hypotheses.
4722 class hypMethodWrapper:
4723 def __init__(self, hyp, method):
4725 self.method = method
4726 #print "REBIND:", method.__name__
4729 # call a method of hypothesis with calling SetVarParameter() before
4730 def __call__(self,*args):
4732 return self.method( self.hyp, *args ) # hypothesis method with no args
4734 #print "MethWrapper.__call__",self.method.__name__, args
4736 parsed = ParseParameters(*args) # replace variables with their values
4737 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
4738 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
4739 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
4740 # maybe there is a replaced string arg which is not variable
4741 result = self.method( self.hyp, *args )
4742 except ValueError, detail: # raised by ParseParameters()
4744 result = self.method( self.hyp, *args )
4745 except omniORB.CORBA.BAD_PARAM:
4746 raise ValueError, detail # wrong variable name
4751 # A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
4752 class genObjUnRegister:
4754 def __init__(self, genObj=None):
4755 self.genObjList = []
4759 def set(self, genObj):
4760 "Store one or a list of of SALOME.GenericObj'es"
4761 if isinstance( genObj, list ):
4762 self.genObjList.extend( genObj )
4764 self.genObjList.append( genObj )
4768 for genObj in self.genObjList:
4769 if genObj and hasattr( genObj, "UnRegister" ):
4772 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
4774 #print "pluginName: ", pluginName
4775 pluginBuilderName = pluginName + "Builder"
4777 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
4778 except Exception, e:
4779 from salome_utils import verbose
4780 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
4782 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
4783 plugin = eval( pluginBuilderName )
4784 #print " plugin:" , str(plugin)
4786 # add methods creating algorithms to Mesh
4787 for k in dir( plugin ):
4788 if k[0] == '_': continue
4789 algo = getattr( plugin, k )
4790 #print " algo:", str(algo)
4791 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
4792 #print " meshMethod:" , str(algo.meshMethod)
4793 if not hasattr( Mesh, algo.meshMethod ):
4794 setattr( Mesh, algo.meshMethod, algoCreator() )
4796 getattr( Mesh, algo.meshMethod ).add( algo )